返回 CodeWhale
paste_burst.rs
根目录 / crates / tui-kit / src / paste_burst.rs
1 //! Paste-burst detection for terminals without reliable bracketed paste.
2
3 use std::time::{Duration, Instant};
4
5 const PASTE_BURST_MIN_CHARS: u16 = 3;
6 const PASTE_BURST_MAX_BYTES: usize = 64 * 1024;
7 const PASTE_BURST_CHAR_INTERVAL: Duration = Duration::from_millis(8);
8 const PASTE_ENTER_SUPPRESS_WINDOW: Duration = Duration::from_millis(120);
9 #[cfg(not(windows))]
10 const PASTE_BURST_ACTIVE_IDLE_TIMEOUT: Duration = Duration::from_millis(8);
11 #[cfg(windows)]
12 const PASTE_BURST_ACTIVE_IDLE_TIMEOUT: Duration = Duration::from_millis(60);
13 #[cfg(not(windows))]
14 const PASTE_BURST_STREAM_WINDOW: Duration = PASTE_BURST_CHAR_INTERVAL;
15 #[cfg(windows)]
16 const PASTE_BURST_STREAM_WINDOW: Duration = Duration::from_millis(60);
17 const PASTE_BURST_STREAM_CHAR_INTERVAL: Duration = if cfg!(windows) {
18 Duration::from_millis(30)
19 } else {
20 PASTE_BURST_STREAM_WINDOW
21 };
22
23 #[derive(Default)]
24 pub struct PasteBurst {
25 last_plain_char_time: Option<Instant>,
26 consecutive_plain_char_burst: u16,
27 stream_chars: u16,
28 burst_window_until: Option<Instant>,
29 buffer: String,
30 chunk_emitted: bool,
31 active: bool,
32 pending_first_char: Option<(char, Instant)>,
33 }
34
35 pub enum CharDecision {
36 BeginBuffer,
37 BufferAppend,
38 RetainFirstChar,
39 BeginBufferFromPending,
40 }
41
42 pub enum FlushResult {
43 Paste(String),
44 TextContinuation(String),
45 Typed(char),
46 /// Enter can submit again even though the composer text has not changed.
47 SuppressionExpired,
48 None,
49 }
50
51 impl PasteBurst {
52 #[cfg(any(test, feature = "test-support"))]
53 pub fn recommended_flush_delay() -> Duration {
54 PASTE_BURST_CHAR_INTERVAL + Duration::from_millis(1)
55 }
56
57 #[cfg(any(test, feature = "test-support"))]
58 pub fn recommended_active_flush_delay() -> Duration {
59 PASTE_BURST_ACTIVE_IDLE_TIMEOUT + Duration::from_millis(1)
60 }
61
62 fn push_bounded(&mut self, ch: char) {
63 self.buffer.push(ch);
64 }
65
66 pub fn take_chunk_if_full(&mut self) -> Option<String> {
67 if self.buffer.len() >= PASTE_BURST_MAX_BYTES {
68 self.chunk_emitted = true;
69 Some(std::mem::take(&mut self.buffer))
70 } else {
71 None
72 }
73 }
74
75 pub fn on_plain_char(&mut self, ch: char, now: Instant) -> CharDecision {
76 self.note_plain_char(now);
77
78 if self.active {
79 self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
80 return CharDecision::BufferAppend;
81 }
82
83 if let Some((held, held_at)) = self.pending_first_char
84 && now.duration_since(held_at) <= PASTE_BURST_CHAR_INTERVAL
85 {
86 self.active = true;
87 let _ = self.pending_first_char.take();
88 self.push_bounded(held);
89 self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
90 return CharDecision::BeginBufferFromPending;
91 }
92
93 if self.consecutive_plain_char_burst >= PASTE_BURST_MIN_CHARS {
94 return CharDecision::BeginBuffer;
95 }
96
97 self.pending_first_char = Some((ch, now));
98 CharDecision::RetainFirstChar
99 }
100
101 pub fn note_plain_char(&mut self, now: Instant) -> u16 {
102 match self.last_plain_char_time {
103 Some(prev) => {
104 let gap = now.duration_since(prev);
105 if gap <= PASTE_BURST_CHAR_INTERVAL {
106 self.consecutive_plain_char_burst =
107 self.consecutive_plain_char_burst.saturating_add(1);
108 } else {
109 self.consecutive_plain_char_burst = 1;
110 }
111 self.stream_chars = if gap <= PASTE_BURST_STREAM_CHAR_INTERVAL {
112 self.stream_chars.saturating_add(1)
113 } else {
114 1
115 };
116 }
117 _ => {
118 self.consecutive_plain_char_burst = 1;
119 self.stream_chars = 1;
120 }
121 }
122 self.last_plain_char_time = Some(now);
123 self.consecutive_plain_char_burst
124 }
125
126 pub fn flush_if_due(&mut self, now: Instant) -> FlushResult {
127 let suppression_expired = self.burst_window_until.is_some_and(|until| now > until);
128 if suppression_expired {
129 self.burst_window_until = None;
130 }
131 let unchanged = if suppression_expired {
132 FlushResult::SuppressionExpired
133 } else {
134 FlushResult::None
135 };
136 let timeout = if self.is_active_internal() {
137 PASTE_BURST_ACTIVE_IDLE_TIMEOUT
138 } else {
139 PASTE_BURST_CHAR_INTERVAL
140 };
141 let timed_out = self
142 .last_plain_char_time
143 .is_some_and(|t| now.duration_since(t) > timeout);
144
145 if timed_out && self.is_active_internal() {
146 self.active = false;
147 let out = std::mem::take(&mut self.buffer);
148 // `burst_window_until` intentionally survives the flush: the idle
149 // timeout is only 8ms, and a paste's trailing newline can land
150 // just after it over a laggy link (SSH/tmux). Dropping the window
151 // here would let that pasted newline submit a partial paste
152 // (#1073). The window stays *bounded* instead: absorbing an Enter
153 // outside an active burst no longer re-arms it, so suppression
154 // always ends `PASTE_ENTER_SUPPRESS_WINDOW` after the last real
155 // keystroke.
156 if std::mem::take(&mut self.chunk_emitted) {
157 FlushResult::TextContinuation(out)
158 } else {
159 FlushResult::Paste(out)
160 }
161 } else if timed_out {
162 if let Some((ch, _)) = self.pending_first_char.take() {
163 FlushResult::Typed(ch)
164 } else {
165 unchanged
166 }
167 } else {
168 unchanged
169 }
170 }
171
172 /// Wake for pending input or the one redraw that re-enables submission.
173 /// Once both are settled, typing must not leave a zero-delay poll loop.
174 #[must_use]
175 pub fn next_flush_delay(&self, now: Instant) -> Option<Duration> {
176 if self.is_active() {
177 let last = self.last_plain_char_time?;
178 let timeout = if self.is_active_internal() {
179 PASTE_BURST_ACTIVE_IDLE_TIMEOUT
180 } else {
181 PASTE_BURST_CHAR_INTERVAL
182 };
183 return Some(timeout.saturating_sub(now.duration_since(last)));
184 }
185 self.burst_window_until
186 .map(|until| (until + Duration::from_millis(1)).saturating_duration_since(now))
187 }
188
189 pub fn append_newline_if_active(&mut self, now: Instant) -> bool {
190 if self.is_active() {
191 // A held first char precedes this newline in arrival order; move
192 // it into the burst first or it would land after the newline
193 // ("a\nb" became "\nab").
194 if let Some((held, _)) = self.pending_first_char.take() {
195 self.push_bounded(held);
196 self.active = true;
197 }
198 self.push_bounded('\n');
199 self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
200 true
201 } else {
202 false
203 }
204 }
205
206 pub fn newline_should_insert_instead_of_submit(&self, now: Instant) -> bool {
207 let in_burst_window = self.burst_window_until.is_some_and(|until| now <= until);
208 let stream_recent = self.stream_chars >= PASTE_BURST_MIN_CHARS
209 && self
210 .last_plain_char_time
211 .is_some_and(|t| now.duration_since(t) <= PASTE_BURST_STREAM_WINDOW);
212 self.is_active() || in_burst_window || stream_recent
213 }
214
215 pub fn extend_window(&mut self, now: Instant) {
216 self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
217 }
218
219 /// Begin buffering from the current char, leaving already-typed text
220 /// untouched. The burst never rewrites the composer (Y-7): chars before
221 /// the burst stay exactly as the user typed them.
222 pub fn begin_buffer_from_now(&mut self, ch: char, now: Instant) {
223 self.push_bounded(ch);
224 self.active = true;
225 self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
226 }
227
228 /// The text the heuristic currently holds on the user's behalf: the
229 /// held first char plus the burst buffer, in arrival order. Command
230 /// context must be judged on this — while a burst is held the composer
231 /// can be empty even though the user is mid-command (Y-7).
232 pub fn held_text(&self) -> String {
233 let mut out = String::new();
234 if let Some((ch, _)) = self.pending_first_char {
235 out.push(ch);
236 }
237 out.push_str(&self.buffer);
238 out
239 }
240
241 pub fn append_char_to_buffer(&mut self, ch: char, now: Instant) {
242 self.push_bounded(ch);
243 self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
244 }
245
246 pub fn flush_before_modified_input(&mut self) -> Option<String> {
247 if !self.is_active() {
248 return None;
249 }
250 self.active = false;
251 self.chunk_emitted = false;
252 let mut out = std::mem::take(&mut self.buffer);
253 if let Some((ch, _)) = self.pending_first_char.take() {
254 out.push(ch);
255 }
256 Some(out)
257 }
258
259 /// Reset burst-accumulation state without clearing the suppression window.
260 ///
261 /// Used when a non-char key (Tab, etc.) arrives during an active burst as
262 /// part of table-data paste. The buffer was flushed upstream; only the
263 /// active state is reset so `burst_window_until` stays alive and a trailing
264 /// Enter is still absorbed as a newline (#2134).
265 ///
266 /// # Panics
267 ///
268 /// Panics in debug builds if `buffer` is non-empty — the caller must flush
269 /// via `flush_before_modified_input` first.
270 pub fn deactivate_keep_window(&mut self) {
271 debug_assert!(
272 self.buffer.is_empty(),
273 "buffer must be flushed before deactivating"
274 );
275 self.consecutive_plain_char_burst = 0;
276 self.active = false;
277 self.chunk_emitted = false;
278 self.pending_first_char = None;
279 // burst_window_until, stream_chars and last_plain_char_time are
280 // intentionally NOT cleared: a trailing Enter a stream-window after
281 // a table cell boundary is still pasted payload.
282 }
283
284 pub fn is_active(&self) -> bool {
285 self.is_active_internal() || self.pending_first_char.is_some()
286 }
287
288 /// True while a burst buffer holds pasted text. Unlike [`Self::is_active`]
289 /// a lone held first char does not count: it precedes anything appended
290 /// now in arrival order, so callers flush it before buffering.
291 pub fn is_buffering(&self) -> bool {
292 self.is_active_internal()
293 }
294
295 fn is_active_internal(&self) -> bool {
296 self.active || !self.buffer.is_empty()
297 }
298
299 pub fn clear_after_explicit_paste(&mut self) {
300 self.last_plain_char_time = None;
301 self.consecutive_plain_char_burst = 0;
302 self.stream_chars = 0;
303 self.burst_window_until = None;
304 self.active = false;
305 self.chunk_emitted = false;
306 self.buffer.clear();
307 self.pending_first_char = None;
308 }
309
310 /// Arm the Enter-suppression window for a non-ASCII character that was
311 /// inserted straight into the composer instead of being buffered (the
312 /// IME / raw-CJK path in `tui::paste`).
313 ///
314 /// `rapid_chars` is the run length reported by [`Self::note_plain_char`].
315 ///
316 /// A *lone* commit only earns a burst-interval window. An IME candidate
317 /// commit is ordinary typing: the user may press Enter to send a
318 /// message ending in a CJK character tens of milliseconds later, and the
319 /// full 120ms window turned that Enter into a stray newline. A real raw
320 /// paste delivers its trailing newline within microseconds of the last
321 /// character, so the short window still absorbs it — including the
322 /// single-character first line of a CJK paste (#1302).
323 ///
324 /// Two or more characters at paste speed mean the stream *is* a paste,
325 /// so the full window applies and later lines stay absorbed.
326 pub fn arm_window_for_direct_char(&mut self, now: Instant, rapid_chars: u16) {
327 if rapid_chars >= 2 {
328 self.extend_window(now);
329 } else {
330 self.burst_window_until = Some(now + PASTE_BURST_CHAR_INTERVAL);
331 }
332 }
333 }
334
335 #[cfg(test)]
336 mod tests {
337 use super::*;
338
339 #[test]
340 fn ascii_first_char_is_held_then_flushes_as_typed() {
341 let mut burst = PasteBurst::default();
342 let t0 = Instant::now();
343 assert!(matches!(
344 burst.on_plain_char('a', t0),
345 CharDecision::RetainFirstChar
346 ));
347
348 let t1 = t0 + PasteBurst::recommended_flush_delay() + Duration::from_millis(1);
349 assert!(matches!(burst.flush_if_due(t1), FlushResult::Typed('a')));
350 assert!(!burst.is_active());
351 }
352
353 #[test]
354 fn ascii_two_fast_chars_start_buffer_from_pending_and_flush_as_paste() {
355 let mut burst = PasteBurst::default();
356 let t0 = Instant::now();
357 assert!(matches!(
358 burst.on_plain_char('a', t0),
359 CharDecision::RetainFirstChar
360 ));
361
362 let t1 = t0 + Duration::from_millis(1);
363 assert!(matches!(
364 burst.on_plain_char('b', t1),
365 CharDecision::BeginBufferFromPending
366 ));
367 burst.append_char_to_buffer('b', t1);
368
369 let t2 = t1 + PasteBurst::recommended_active_flush_delay() + Duration::from_millis(1);
370 assert!(matches!(
371 burst.flush_if_due(t2),
372 FlushResult::Paste(ref s) if s == "ab"
373 ));
374 }
375
376 #[test]
377 fn newline_after_held_first_char_keeps_arrival_order() {
378 let mut burst = PasteBurst::default();
379 let t0 = Instant::now();
380 assert!(matches!(
381 burst.on_plain_char('1', t0),
382 CharDecision::RetainFirstChar
383 ));
384 let t1 = t0 + Duration::from_millis(1);
385 assert!(burst.append_newline_if_active(t1));
386 let t2 = t1 + Duration::from_millis(1);
387 let decision = burst.on_plain_char('2', t2);
388 assert!(matches!(
389 decision,
390 CharDecision::BufferAppend | CharDecision::BeginBufferFromPending
391 ));
392 burst.append_char_to_buffer('2', t2);
393 let t3 = t2 + PasteBurst::recommended_active_flush_delay() + Duration::from_millis(1);
394 assert!(matches!(
395 burst.flush_if_due(t3),
396 FlushResult::Paste(ref s) if s == "1\n2"
397 ));
398 }
399
400 #[test]
401 fn flush_before_modified_input_includes_pending_first_char() {
402 let mut burst = PasteBurst::default();
403 let t0 = Instant::now();
404 assert!(matches!(
405 burst.on_plain_char('a', t0),
406 CharDecision::RetainFirstChar
407 ));
408
409 assert_eq!(burst.flush_before_modified_input(), Some("a".to_string()));
410 assert!(!burst.is_active());
411 }
412
413 #[test]
414 fn settled_input_stops_polling_and_expiry_requests_one_redraw() {
415 let mut burst = PasteBurst::default();
416 let now = Instant::now();
417 let _ = burst.on_plain_char('a', now);
418 assert!(matches!(
419 burst.flush_if_due(now + Duration::from_millis(20)),
420 FlushResult::Typed('a')
421 ));
422 assert_eq!(
423 burst.next_flush_delay(now + Duration::from_millis(20)),
424 None
425 );
426
427 burst.extend_window(now);
428 let inside = now + Duration::from_millis(100);
429 assert!(burst.newline_should_insert_instead_of_submit(inside));
430 assert_eq!(
431 burst.next_flush_delay(inside),
432 Some(Duration::from_millis(21))
433 );
434 let expired = now + Duration::from_millis(121);
435 assert!(matches!(
436 burst.flush_if_due(expired),
437 FlushResult::SuppressionExpired
438 ));
439 assert!(!burst.newline_should_insert_instead_of_submit(expired));
440 assert_eq!(burst.next_flush_delay(expired), None);
441 assert!(matches!(burst.flush_if_due(expired), FlushResult::None));
442 }
443
444 #[test]
445 fn next_flush_delay_counts_down_to_zero() {
446 let mut burst = PasteBurst::default();
447 let t0 = Instant::now();
448 let _ = burst.on_plain_char('a', t0);
449
450 let almost_due = t0 + Duration::from_millis(7);
451 let remaining = burst
452 .next_flush_delay(almost_due)
453 .expect("delay should exist");
454 assert!(remaining <= Duration::from_millis(1));
455
456 let due = t0 + Duration::from_millis(20);
457 assert_eq!(burst.next_flush_delay(due), Some(Duration::ZERO));
458 }
459
460 /// Simulate #2134: when a non-char key (Tab) arrives during table-data
461 /// paste, `deactivate_keep_window` resets accumulation state but
462 /// preserves the Enter-suppression window so a trailing newline is still
463 /// absorbed instead of submitting the partial input.
464 #[test]
465 fn deactivate_keep_window_preserves_enter_suppression_window() {
466 let mut burst = PasteBurst::default();
467 let t0 = Instant::now();
468
469 assert!(matches!(
470 burst.on_plain_char('a', t0),
471 CharDecision::RetainFirstChar
472 ));
473 let t1 = t0 + Duration::from_millis(1);
474 assert!(matches!(
475 burst.on_plain_char('b', t1),
476 CharDecision::BeginBufferFromPending
477 ));
478 burst.append_char_to_buffer('b', t1);
479 assert!(burst.is_active());
480 assert!(burst.newline_should_insert_instead_of_submit(t1));
481
482 let flushed = burst.flush_before_modified_input();
483 assert!(flushed.is_some());
484 assert!(!burst.is_active());
485
486 burst.deactivate_keep_window();
487
488 assert!(!burst.is_active());
489
490 let t_tab = t1 + Duration::from_millis(2);
491 assert!(
492 burst.newline_should_insert_instead_of_submit(t_tab),
493 "Enter within suppression window should insert newline, not submit"
494 );
495
496 let t_expired = t_tab + PASTE_ENTER_SUPPRESS_WINDOW + Duration::from_millis(1);
497 assert!(
498 !burst.newline_should_insert_instead_of_submit(t_expired),
499 "Enter after suppression window expires should submit"
500 );
501 }
502
503 /// The idle flush must NOT drop the Enter-suppression window. The active
504 /// idle timeout is only 8ms, so a paste's trailing newline can easily
505 /// land just after the flush on a laggy link — dropping the window there
506 /// would submit a partial paste (#1073).
507 #[test]
508 fn idle_flush_keeps_enter_suppression_window_alive() {
509 let mut burst = PasteBurst::default();
510 let t0 = Instant::now();
511
512 let _ = burst.on_plain_char('a', t0);
513 let t1 = t0 + Duration::from_millis(1);
514 assert!(matches!(
515 burst.on_plain_char('b', t1),
516 CharDecision::BeginBufferFromPending
517 ));
518 burst.append_char_to_buffer('b', t1);
519
520 let t_flush = t1 + PasteBurst::recommended_active_flush_delay();
521 assert!(matches!(
522 burst.flush_if_due(t_flush),
523 FlushResult::Paste(ref s) if s == "ab"
524 ));
525 assert!(!burst.is_active());
526 assert!(
527 burst.newline_should_insert_instead_of_submit(t_flush),
528 "a trailing pasted newline arriving right after the idle flush \
529 must still be absorbed instead of submitting"
530 );
531 }
532
533 /// …but the window is *bounded*: it expires 120ms after the last real
534 /// keystroke and nothing about the flush re-arms it, so the user's next
535 /// Enter submits.
536 #[test]
537 fn enter_suppression_window_expires_after_the_last_keystroke() {
538 let mut burst = PasteBurst::default();
539 let t0 = Instant::now();
540
541 let _ = burst.on_plain_char('a', t0);
542 let t1 = t0 + Duration::from_millis(1);
543 let _ = burst.on_plain_char('b', t1);
544 burst.append_char_to_buffer('b', t1);
545 let t_flush = t1 + PasteBurst::recommended_active_flush_delay();
546 let _ = burst.flush_if_due(t_flush);
547
548 let t_late = t1 + PASTE_ENTER_SUPPRESS_WINDOW + Duration::from_millis(1);
549 assert!(
550 !burst.newline_should_insert_instead_of_submit(t_late),
551 "Enter more than the suppression window after the paste must submit"
552 );
553 }
554
555 /// A lone IME candidate commit is ordinary typing: it may only hold Enter
556 /// for one burst interval, so a user finishing a CJK sentence and
557 /// pressing Enter actually sends.
558 #[test]
559 fn lone_non_ascii_commit_arms_only_a_burst_interval_window() {
560 let mut burst = PasteBurst::default();
561 let t0 = Instant::now();
562
563 let rapid = burst.note_plain_char(t0);
564 assert_eq!(rapid, 1, "an isolated commit is a run of one");
565 burst.arm_window_for_direct_char(t0, rapid);
566
567 assert!(
568 burst.newline_should_insert_instead_of_submit(t0 + PASTE_BURST_CHAR_INTERVAL),
569 "a raw paste delivers its trailing newline within the burst \
570 interval and must still be absorbed (#1302)"
571 );
572 assert!(
573 !burst.newline_should_insert_instead_of_submit(
574 t0 + PASTE_BURST_CHAR_INTERVAL + Duration::from_millis(1)
575 ),
576 "an IME commit must not swallow the Enter a human presses \
577 tens of milliseconds later"
578 );
579 }
580
581 /// Two non-ASCII characters at paste speed mean the stream is a paste,
582 /// so the full suppression window applies to later lines.
583 #[test]
584 fn rapid_non_ascii_run_arms_the_full_suppression_window() {
585 let mut burst = PasteBurst::default();
586 let t0 = Instant::now();
587
588 let rapid = burst.note_plain_char(t0);
589 burst.arm_window_for_direct_char(t0, rapid);
590 let t1 = t0 + Duration::from_millis(1);
591 let rapid = burst.note_plain_char(t1);
592 assert_eq!(rapid, 2);
593 burst.arm_window_for_direct_char(t1, rapid);
594
595 assert!(
596 burst.newline_should_insert_instead_of_submit(t1 + PASTE_ENTER_SUPPRESS_WINDOW),
597 "a raw CJK paste must keep absorbing its embedded newlines"
598 );
599 assert!(
600 !burst.newline_should_insert_instead_of_submit(
601 t1 + PASTE_ENTER_SUPPRESS_WINDOW + Duration::from_millis(1)
602 ),
603 "even a paste-speed run releases Enter once the window lapses"
604 );
605 }
606
607 /// A slow IME sequence never accumulates a rapid run, so every commit
608 /// re-arms only the short window and Enter stays available throughout.
609 /// Known limitation: typing at the stream cadence is indistinguishable
610 /// from raw paste; slower raw paste without an earlier burst is typing.
611 /// Bracketed paste supplies the independent signal that resolves this.
612 #[test]
613 fn slow_ime_sequence_never_holds_enter() {
614 let mut burst = PasteBurst::default();
615 let t0 = Instant::now();
616
617 // "你好世界" committed one character at a time with human gaps.
618 for i in 0..4u64 {
619 let now = t0 + Duration::from_millis(200 * i);
620 let rapid = burst.note_plain_char(now);
621 assert_eq!(rapid, 1, "200ms gaps are never a paste-speed run");
622 burst.arm_window_for_direct_char(now, rapid);
623 }
624
625 let last = t0 + Duration::from_millis(600);
626 assert!(
627 !burst.newline_should_insert_instead_of_submit(last + Duration::from_millis(30)),
628 "Enter after an IME-typed CJK message must submit"
629 );
630 }
631
632 /// Windows Terminal injects pasted console records at its own pace —
633 /// tens of ms apart on a loaded runner, past the 8ms burst-forming
634 /// interval. Such a paste never buffers, but its embedded Enters are
635 /// still payload, not submits. The stream counter (>=3 plain chars each
636 /// within 30ms) is stronger cadence evidence than the trailing-Enter
637 /// window, which bounds how stale the last char may be. The 60ms window is
638 /// Windows-only; elsewhere the bound is the burst interval.
639 #[cfg(windows)]
640 #[test]
641 fn enter_inside_a_slow_paced_raw_paste_inserts_a_newline() {
642 let mut burst = PasteBurst::default();
643 let t0 = Instant::now();
644
645 // "line 1\n…" arriving one record every 30ms: too slow to form a
646 // burst (consecutive never reaches 3), so every char rides the
647 // pending→Typed path.
648 for (i, ch) in "line 1".chars().enumerate() {
649 let now = t0 + Duration::from_millis(30 * i as u64);
650 let _ = burst.flush_if_due(now);
651 let _ = burst.on_plain_char(ch, now);
652 }
653 let t_enter = t0 + Duration::from_millis(30 * 6);
654 let _ = burst.flush_if_due(t_enter);
655 assert!(
656 burst.newline_should_insert_instead_of_submit(t_enter),
657 "the trailing Enter of a slow-paced raw paste is paste payload, \
658 not a submit — it must insert a newline"
659 );
660 }
661
662 /// The same stream releases Enter once the last char is stale: a
663 /// deliberate submit lands past the 60ms stream window.
664 #[cfg(windows)]
665 #[test]
666 fn enter_after_a_slow_stream_gone_still_submits() {
667 let mut burst = PasteBurst::default();
668 let t0 = Instant::now();
669
670 for (i, ch) in "line 1".chars().enumerate() {
671 let now = t0 + Duration::from_millis(30 * i as u64);
672 let _ = burst.on_plain_char(ch, now);
673 }
674 let last = t0 + Duration::from_millis(30 * 5);
675 let _ = burst.flush_if_due(last + Duration::from_millis(40));
676 assert!(
677 !burst.newline_should_insert_instead_of_submit(
678 last + PASTE_BURST_STREAM_WINDOW + Duration::from_millis(1)
679 ),
680 "Enter more than the stream window after the last char submits"
681 );
682 }
683
684 #[cfg(windows)]
685 #[test]
686 fn established_windows_burst_preserves_fifty_ms_tail_and_enter() {
687 let mut burst = PasteBurst::default();
688 let start = Instant::now();
689 let payload = "ab你好\n";
690 let mut last = start;
691 for (i, ch) in payload.chars().enumerate() {
692 last = start + Duration::from_millis(if i == 0 { 0 } else { 1 + 50 * (i as u64 - 1) });
693 assert!(matches!(burst.flush_if_due(last), FlushResult::None));
694 if ch == '\n' {
695 assert!(burst.append_newline_if_active(last));
696 } else {
697 match burst.on_plain_char(ch, last) {
698 CharDecision::RetainFirstChar => {}
699 CharDecision::BeginBuffer => burst.begin_buffer_from_now(ch, last),
700 CharDecision::BeginBufferFromPending | CharDecision::BufferAppend => {
701 burst.append_char_to_buffer(ch, last);
702 }
703 }
704 }
705 }
706 assert!(matches!(
707 burst.flush_if_due(last + PasteBurst::recommended_active_flush_delay()),
708 FlushResult::Paste(text) if text == payload
709 ));
710 }
711
712 #[cfg(windows)]
713 #[test]
714 fn fifty_ms_typing_and_ime_commits_do_not_establish_a_paste_stream() {
715 for text in ["abc", "你好啊", "hello world", "你好世界你好世界"] {
716 let mut burst = PasteBurst::default();
717 let start = Instant::now();
718 let mut last = start;
719 for (i, ch) in text.chars().enumerate() {
720 last = start + Duration::from_millis(50 * i as u64);
721 let _ = burst.flush_if_due(last);
722 if ch.is_ascii() {
723 assert!(matches!(
724 burst.on_plain_char(ch, last),
725 CharDecision::RetainFirstChar
726 ));
727 } else {
728 let rapid = burst.note_plain_char(last);
729 burst.arm_window_for_direct_char(last, rapid);
730 }
731 }
732 let enter = last + Duration::from_millis(30);
733 let _ = burst.flush_if_due(enter);
734 assert!(
735 !burst.newline_should_insert_instead_of_submit(enter),
736 "{text}"
737 );
738 }
739 }
740
741 #[test]
742 fn large_raw_cjk_multiline_paste_preserves_every_char_and_newline_via_chunks() {
743 let mut burst = PasteBurst::default();
744 let t0 = Instant::now();
745 let line = "漢字テスト🐳line\n";
746 let payload: String = line.repeat(6_000);
747 assert!(payload.len() > PASTE_BURST_MAX_BYTES * 2);
748
749 let mut assembled = String::new();
750 let mut chunk_count = 0usize;
751 let mut now = t0;
752 for ch in payload.chars() {
753 now += Duration::from_micros(100);
754 if ch == '\n' {
755 assert!(burst.append_newline_if_active(now));
756 } else {
757 match burst.on_plain_char(ch, now) {
758 CharDecision::RetainFirstChar => {}
759 CharDecision::BeginBuffer => burst.begin_buffer_from_now(ch, now),
760 CharDecision::BeginBufferFromPending | CharDecision::BufferAppend => {
761 burst.append_char_to_buffer(ch, now);
762 }
763 }
764 }
765 if let Some(chunk) = burst.take_chunk_if_full() {
766 assembled.push_str(&chunk);
767 chunk_count += 1;
768 }
769 }
770 let flush_at = now + PasteBurst::recommended_active_flush_delay();
771 match burst.flush_if_due(flush_at) {
772 FlushResult::TextContinuation(rest) => assembled.push_str(&rest),
773 _ => panic!("expected final Paste flush"),
774 }
775 assert!(chunk_count >= 2);
776 assert_eq!(assembled.len(), payload.len());
777 assert_eq!(assembled, payload);
778 }
779 }
780
780 lines RUST