Repository navigation
Expand file tree
/
Copy pathmod.rs
More file actions
2757 lines (2525 loc) · 114 KB
/
Copy pathmod.rs
File metadata and controls
2757 lines (2525 loc) · 114 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
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub(crate) mod actions;
pub(crate) mod auto_close;
pub(crate) mod formatted_buffer;
mod ui;
use crate::subshell_ipc::{self, IpcStatus, SubshellHandle};
use nix::sys::wait::{WaitPidFlag, WaitStatus, waitpid};
pub(crate) use ui::DrawnContent;
#[derive(Debug, Clone)]
pub struct LastKeyPress {
pub key: KeyEvent,
pub display: String,
pub context: String,
pub actions: Vec<KeyEventAction>,
pub sequence_number: u64,
}
#[derive(Debug, Clone)]
pub struct LastMouseEvent {
pub mouse: MouseEvent,
pub matches: Vec<(String, String)>,
pub time: std::time::Instant,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RightClickCopyTarget {
Selection(String),
Buffer(String),
HistoryEntry(String, Option<crate::history::HistoryEntry>),
Cwd(String),
Suggestion(String),
AiResult(String),
Clipboard(String),
}
use crate::LongLived;
use crate::active_suggestions::{ActiveSuggestions, ActiveSuggestionsBuilder, COLUMN_PADDING};
use crate::agent_mode::{AiOutputSelection, parse_ai_output};
use crate::app::actions::KeyEventAction;
use crate::app::formatted_buffer::{FormattedBuffer, format_agent_buffer, format_buffer};
use crate::content::{Contents, Coord, SpanTag, Tag, TaggedLine, TaggedSpan};
use crate::cursor::{Cursor, CursorBackend};
use crate::dparser::{AnnotatedToken, ToInclusiveRange};
use crate::grammar::TokenKind;
use crate::history::{HistoryEntry, HistoryEntryFormatted, HistoryManager};
use crate::iter_first_last::FirstLast;
use crate::kill_on_drop_child::KillOnDropChild;
use crate::mouse_state::{MouseState, mouse_state};
use crate::palette::{ButtonState, Palette};
use crate::prompt_manager::PromptManager;
use crate::settings::{self, MatrixAnimation, MouseMode};
use crate::shell_integration;
use crate::{command_acceptance, dparser};
use crate::{shell, tab_completion_context};
use flybuffer::{SubString, TextBuffer};
use itertools::Itertools;
use ratatui::prelude::*;
use ratatui::text::StyledGrapheme;
use ratatui::{TerminalOptions, Viewport};
use std::boxed::Box;
use std::io::{Error, ErrorKind, IsTerminal};
use std::time::Duration;
use std::vec;
use termina::escape::csi::{
Csi, Cursor as CsiCursor, DecPrivateMode, DecPrivateModeCode, Keyboard, KittyKeyboardFlags,
Mode as DecMode,
};
use termina::event::{
KeyCode, KeyEvent, Modifiers as KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use termina::{Event as TerminaEvent, Terminal};
use std::io::Write;
use std::sync::LazyLock;
/// The reason for the global event reader is that it often buffers events
/// and if we drop it, those buffered events are lost.
/// This is apparent when you type `sleep 5\necho foo\necho bar\n`.
pub static GLOBAL_EVENT_READER: LazyLock<termina::EventReader> = LazyLock::new(|| {
let temp_terminal = termina::PlatformTerminal::new().unwrap();
temp_terminal.event_reader()
});
/// After this duration of inactivity the frame rate drops to `idle_frame_rate` and the
/// cursor is rendered in the unfocused (dim, non-animated) state.
const IDLE_TIMEOUT: Duration = Duration::from_secs(30);
fn restore_terminal(write: &mut impl std::io::Write) {
let reset = |code| Csi::Mode(DecMode::ResetDecPrivateMode(DecPrivateMode::Code(code)));
let _ = write!(
write,
"{}{}{}",
reset(DecPrivateModeCode::BracketedPaste),
reset(DecPrivateModeCode::FocusTracking),
Csi::Keyboard(Keyboard::PopFlags(1))
);
mouse_state(|m| m.disable());
let _ = write.flush();
}
/// Drains in-flight trailing events from stdin after restoring the terminal (such as SGR mouse coordinates
/// or focus reports) to prevent them from leaking into the parent shell prompt.
fn drain_shutdown_events(timeout: Duration) {
use termina::escape::csi::Device as CsiDevice;
let start = std::time::Instant::now();
let is_drainable_event = |event: &TerminaEvent| {
matches!(
event,
TerminaEvent::Mouse(_)
| TerminaEvent::FocusIn
| TerminaEvent::FocusOut
| TerminaEvent::Csi(Csi::Cursor(CsiCursor::ActivePositionReport { .. }))
| TerminaEvent::Csi(Csi::Device(CsiDevice::DeviceAttributes(_)))
)
};
while start.elapsed() < timeout {
let remaining = timeout.saturating_sub(start.elapsed());
match GLOBAL_EVENT_READER.poll(Some(remaining), is_drainable_event) {
Ok(true) => match GLOBAL_EVENT_READER.read(is_drainable_event) {
Ok(TerminaEvent::FocusIn) => {
log::trace!("Drained FocusIn event during shutdown");
}
Ok(TerminaEvent::FocusOut) => {
log::trace!("Drained FocusOut event during shutdown");
}
Ok(event) => {
log::trace!("Drained shutdown event: {:?}", event);
}
Err(e) => {
log::debug!("Error reading event during shutdown drain: {}", e);
break;
}
},
Ok(false) => {
break;
}
Err(e) => {
log::debug!("Error polling during shutdown drain: {}", e);
break;
}
}
}
}
fn configure_terminal(extended_key_codes: bool, mouse_mode: &crate::settings::MouseMode) {
let set_mode = |code| Csi::Mode(DecMode::SetDecPrivateMode(DecPrivateMode::Code(code)));
let flags = if extended_key_codes {
// Enabling REPORT_ALL_KEYS_AS_ESCAPE_CODES causes Ctrl+C to not copy to clipboard in VS Code with default settings
// because it causes the press of Ctrl to be sent as a key code thus clearing the selection before 'c' is pressed.
// https://blog.fsck.com/releases/2026/02/26/terminal-keyboard-protocol/ is a good reference for understanding the terminal key code problem.
KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES | KittyKeyboardFlags::REPORT_ALTERNATE_KEYS
} else {
KittyKeyboardFlags::empty()
};
let _ = crate::flush_stdout!(
"{}{}",
set_mode(DecPrivateModeCode::BracketedPaste),
Csi::Keyboard(Keyboard::PushFlags(flags))
);
MouseState::enable_mode(mouse_mode);
}
fn stdin_unavailable_reason() -> Option<&'static str> {
// I was finding bash processes were often spinning trying to read from stdin
// When the terminal emulator closed.
// I believe this problem was fixed by setting `use-dev-tty` in crossterm.
// The following are defensive checks to avoid calling crossterm poll when the terminal closes.
// If stdin has been closed outright, bail out before crossterm enters its
// Unix event loop. In crossterm 0.29 that path can spin on closed input.
if unsafe { libc::fcntl(libc::STDIN_FILENO, libc::F_GETFD) } == -1
&& Error::last_os_error().raw_os_error() == Some(libc::EBADF)
{
return Some("stdin file descriptor is closed");
}
if !std::io::stdin().is_terminal() {
return Some("stdin is no longer attached to a terminal");
}
// On macOS, when the terminal emulator closes its end of the PTY (the
// master), the slave PTY fd (stdin) remains valid and isatty() continues to
// return true. The is_terminal() check above therefore does NOT fire on
// macOS after the terminal is closed, so crossterm is called even though
// input is gone.
//
// Crossterm uses mio, which on macOS uses kqueue. kqueue registers
// EVFILT_READ on the slave PTY fd. After the PTY master closes, kqueue
// immediately marks the fd readable (it reports the EOF/hangup condition as
// a read-ready event). Crossterm's inner read loop then calls read(2),
// which returns 0 bytes (macOS PTY slave returns EOF rather than EIO when
// the master closes). Since read_count == 0 is not treated as WouldBlock,
// the loop never breaks and spins at 100% CPU indefinitely.
//
// On Linux the is_terminal() guard above is sufficient: after the PTY
// master closes, Linux updates the slave's session state so that isatty()
// returns 0, which is caught above. If isatty() somehow still returns 1,
// Linux's epoll reports EPOLLHUP without EPOLLIN, so mio's poll times out
// normally. And when Linux read() does return EIO the same inner-loop
// fall-through occurs, but the earlier guards prevent reaching that point.
//
// The reliable cross-platform guard is to call poll(2) with a zero timeout
// and check for POLLHUP. POSIX guarantees that POLLHUP is set in revents
// whenever a hang-up has occurred on the fd, regardless of which events
// were requested. A set POLLHUP therefore means we should not call
// crossterm.
let mut pfd = libc::pollfd {
fd: libc::STDIN_FILENO,
events: libc::POLLIN,
revents: 0,
};
// SAFETY: pfd is a valid, stack-allocated pollfd. Passing its address with
// nfds=1 and timeout=0 is a standard non-blocking poll probe.
// poll(2) returns -1 on error, 0 on timeout, or a positive count of ready
// fds. We check > 0 so that we only inspect revents when poll actually
// reported an event; a return of 0 (timeout) leaves revents as 0.
if unsafe { libc::poll(&raw mut pfd, 1, 0) } > 0 && (pfd.revents & libc::POLLHUP) != 0 {
return Some("stdin PTY has hung up (POLLHUP)");
}
None
}
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum ExitState {
WithCommand(String),
WithoutCommand,
Eof,
}
#[derive(PartialEq, Eq, Debug, Clone)]
pub(crate) enum AppRunningState {
Running,
Exiting(ExitState),
}
impl AppRunningState {
pub fn is_running(&self) -> bool {
*self == AppRunningState::Running
}
}
pub fn get_command(long_lived: &mut LongLived) -> ExitState {
// If stdin is closed, bash expects us to just return EOF a few times
if let Some(reason) = stdin_unavailable_reason() {
log::error!(
"Standard input is not available: {}. Exiting without command.",
reason
);
return ExitState::Eof;
}
let app = time_it!("startup: app creation", App::new(long_lived));
let exit_state = app.run();
log::debug!("Final state: {:?}", exit_state);
exit_state
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FuzzyHistorySource {
PastCommands,
CancelledCommands,
AgentPrompts,
}
impl FuzzyHistorySource {
fn label(&self) -> &'static str {
match self {
FuzzyHistorySource::PastCommands => "Fuzzy search",
FuzzyHistorySource::CancelledCommands => "Cancelled commands",
FuzzyHistorySource::AgentPrompts => "Agent prompts",
}
}
}
/// Guard that owns the tab-completion background process and the result channel.
/// Killing the process (on drop) ensures it does not outlive the app.
pub(crate) type TabCompletionPayload = Option<(ActiveSuggestionsBuilder, std::time::Duration)>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) enum FlycompPromptSelection {
Yes,
No,
DontAsk,
}
#[derive(Debug)]
pub(crate) enum ContentMode {
Normal,
FuzzyHistorySearch(FuzzyHistorySource),
TabCompletion(Box<ActiveSuggestions>),
/// Tab completion is running in a background thread. The handle owns both
/// the result channel receiver and the thread join-handle so that cleanup
/// happens automatically when the mode transitions.
TabCompletionWaiting {
handle: SubshellHandle<TabCompletionPayload>,
wuc_substring: SubString,
start_time: std::time::Instant,
auto_started: bool,
last_active_suggestions: Option<Box<ActiveSuggestions>>,
},
/// AI command is running as a child process. The child is polled each
/// event-loop iteration with `try_wait`; on drop it is killed and reaped.
AgentModeWaiting {
child: KillOnDropChild,
command_display: String,
start_time: std::time::Instant,
},
/// AI output has been parsed; user is selecting a suggestion from the list.
AgentOutputSelection(AiOutputSelection),
/// AI command or JSON parsing failed; stores the error message and any raw output.
/// When `suggested_setup_command` is set, an agent from the example file was found on PATH;
/// pressing Enter will run that `flyline set-agent-mode ...` command to configure it.
AgentError {
message: String,
raw_output: String,
suggested_setup_command: Option<String>,
},
/// User is navigating the CWD path segments displayed in the prompt.
/// The inner value is the currently highlighted segment index (0 = rightmost/current dir).
PromptDirSelect(usize),
TabCompletionAskForFlycomp {
command_word: String,
word_under_cursor: String,
selection: FlycompPromptSelection,
dump_path: String,
forced: bool,
},
TabCompletionRunningFlycomp {
command_word: String,
_word_under_cursor: String,
start_time: std::time::Instant,
handle: SubshellHandle<String>,
},
TabCompletionFlycompResult {
command_word: String,
error_message: String,
},
}
pub(crate) struct App<'a> {
pub(super) long_lived: &'a mut LongLived,
pub(super) terminal:
ratatui::Terminal<ratatui::backend::TerminaBackend<termina::PlatformTerminal>>,
pub(super) mode: AppRunningState,
pub(super) buffer: TextBuffer,
pub(super) formatted_buffer_cache: FormattedBuffer,
/// Cached annotated tokens from the last dparser run, including `is_auto_inserted` flags.
pub(super) dparser_tokens_cache: Vec<AnnotatedToken>,
pub(super) cursor: Cursor,
/// Whether the terminal currently has focus. Used to control cursor animation intensity.
pub(super) term_has_focus: bool,
pub(super) unfinished_from_prev_command: bool,
pub(super) prompt_manager: PromptManager,
pub(super) buffer_before_history_navigation: Option<String>,
pub(super) inline_history_suggestion: Option<(Option<HistoryEntry>, String)>,
/// Buffer contents at the time the user last dismissed the inline suggestion.
/// While the buffer equals this value the suggestion is suppressed.
pub(super) dismissed_inline_suggestion_buffer: Option<String>,
/// Word-under-cursor at the time the user dismissed tab completion with Escape.
/// While the new word-under-cursor equals this value, auto-suggest is suppressed.
pub(super) dismissed_tab_completion_wuc: Option<String>,
/// Buffer contents at the time the user last dismissed the agent prompts fuzzy history search.
pub(super) dismissed_agent_mode_buffer: Option<String>,
pub(super) content_mode: ContentMode,
pub(super) last_contents: Option<DrawnContent>,
pub(super) tooltip: Option<String>,
/// Terminal row (absolute) where the inline viewport starts; used by smart mouse mode.
/// Timestamp of the last draw operation.
pub(super) last_draw_time: std::time::Instant,
pub(super) needs_screen_cleared: bool,
pub(super) needs_full_redraw: bool,
/// Last key event, context expression, and action dispatched.
pub(super) last_key: Option<LastKeyPress>,
/// Last mouse event received.
pub(super) last_mouse: Option<LastMouseEvent>,
/// Last processed key event sequence number for triggers.
pub(super) last_processed_key_sequence: u64,
/// Position of the right click popup, if active.
pub(super) right_click_popup_pos: Option<Coord>,
/// Target content to copy/cut determined at right-click depress time.
pub(super) right_click_copy_target: Option<RightClickCopyTarget>,
pub(super) last_activity_time: std::time::Instant,
pub(super) leader_key_active_at: Option<std::time::Instant>,
pub(super) app_start_time: std::time::Instant,
pub(super) has_run_delayed_startup: Option<std::time::Instant>,
pub(super) last_resize_time: Option<std::time::Instant>,
pub(super) path_warming_subshell: Option<SubshellHandle<shell::PathScanPayload>>,
pub(super) git_warming_subshell: Option<SubshellHandle<Option<crate::git::GitRepoPayload>>>,
pub(super) fuzzy_history_session_filter_active: bool,
}
impl<'a> App<'a> {
fn new(long_lived: &'a mut LongLived) -> Self {
let settings = crate::settings();
long_lived
.history_manager
.set_jsonl_history_path(settings.history_jsonl_path.clone());
let unfinished_from_prev_command = shell::backend().multiline_command_count() > 0;
let initial_buf_val = settings.initial_buffer.take().unwrap_or_default();
let buffer = TextBuffer::new(&initial_buf_val);
let formatted_buffer_cache = FormattedBuffer::default();
time_it!("startup: reload history", {
match settings.history_backend {
crate::settings::HistoryBackend::Bash => {
let zsh_history_path = settings.zsh_history_path.clone();
long_lived
.history_manager
.reload_from_bash_history(zsh_history_path.as_deref());
}
crate::settings::HistoryBackend::Flyline => {
// We dont refresh it here often so that when we press Up
// we search through the history entires from this session
if long_lived.history_manager.is_empty() {
long_lived.history_manager.refresh_jsonl_backend();
}
long_lived.history_manager.reset_navigation();
}
}
});
shell::backend().reset_caches();
time_it!("startup: warm bash caches", {
shell::backend().warm_completion_caches();
});
let path_env = shell::backend().env_var("PATH");
let path_warming_subshell = subshell_ipc::spawn_subshell(move || {
Some(shell::ExecutablesOnPath::scan_path_updates(path_env))
});
let git_warming_subshell = if settings.git_ref_mtime {
let cwd_str = shell::backend().cwd();
log::info!("Spawning background git warming subshell for {:?}", cwd_str);
subshell_ipc::spawn_subshell(move || {
if cwd_str.is_empty() {
None
} else {
Some(crate::git::scan_git_repo_payload(std::path::Path::new(
&cwd_str,
)))
}
})
} else {
None
};
let mut terminal = time_it!("startup: terminal setup", {
let event_reader = GLOBAL_EVENT_READER.clone();
let mut platform_terminal =
termina::PlatformTerminal::with_reader(event_reader).unwrap();
platform_terminal.enter_raw_mode().unwrap();
platform_terminal.set_panic_hook(restore_terminal);
configure_terminal(settings.enable_extended_key_codes, &settings.mouse_mode);
let backend = ratatui::backend::TerminaBackend::new(platform_terminal);
use ratatui::backend::Backend;
if let Some(width) = backend.size().ok().map(|s| s.width as usize) {
let (formatted_marker, marker_width) = crate::content::format_newline_marker(
settings.newline_marker.as_str(),
termina::style::Stylized::is_ansi_color_disabled(),
width,
);
use termina::escape::csi::{Csi, Edit, EraseInLine};
let clear_to_eol =
Csi::Edit(Edit::EraseInLine(EraseInLine::EraseToEndOfLine)).to_string();
let spaces = " ".repeat(width - marker_width);
let _ = crate::flush_stdout!("{}{}\r{}", formatted_marker, spaces, clear_to_eol);
}
ratatui::Terminal::with_options(
backend,
TerminalOptions {
viewport: Viewport::Inline(0),
},
)
.expect("Failed to create terminal")
});
// clear from cursor pos to end of terminal
terminal.clear().unwrap_or_else(|e| {
log::error!("Failed to clear terminal on startup: {}", e);
});
let mut app = App {
long_lived,
terminal,
mode: AppRunningState::Running,
buffer,
formatted_buffer_cache,
dparser_tokens_cache: Vec::new(),
cursor: Cursor::new(),
term_has_focus: true,
unfinished_from_prev_command,
prompt_manager: time_it!(
"startup: prompt manager",
PromptManager::new(
unfinished_from_prev_command,
&settings
.custom_animations
.values()
.cloned()
.collect::<Vec<_>>(),
&settings
.custom_prompt_widgets
.values()
.cloned()
.collect::<Vec<_>>(),
settings.last_app_closed_at,
)
),
buffer_before_history_navigation: None,
inline_history_suggestion: None,
dismissed_inline_suggestion_buffer: None,
dismissed_tab_completion_wuc: None,
dismissed_agent_mode_buffer: None,
content_mode: ContentMode::Normal,
last_contents: None,
tooltip: None,
last_draw_time: std::time::Instant::now(),
needs_screen_cleared: false,
needs_full_redraw: false,
last_key: None,
last_mouse: None,
last_processed_key_sequence: 0,
right_click_popup_pos: None,
right_click_copy_target: None,
last_activity_time: std::time::Instant::now(),
leader_key_active_at: None,
app_start_time: std::time::Instant::now(),
has_run_delayed_startup: None,
last_resize_time: None,
path_warming_subshell,
git_warming_subshell,
fuzzy_history_session_filter_active: false,
};
app.on_possible_buffer_change();
app
}
fn sync_viewport_top_from_cpr(&mut self) {
let req_csi = Csi::Cursor(CsiCursor::RequestActivePositionReport);
let _ = crate::flush_stdout!("{req_csi}");
let is_apr_event = |event: &TerminaEvent| {
matches!(
event,
TerminaEvent::Csi(Csi::Cursor(CsiCursor::ActivePositionReport { .. }))
)
};
match GLOBAL_EVENT_READER.poll(Some(Duration::from_millis(500)), is_apr_event) {
Ok(true) => match GLOBAL_EVENT_READER.read(is_apr_event) {
Ok(TerminaEvent::Csi(Csi::Cursor(CsiCursor::ActivePositionReport {
line,
..
}))) => {
let abs_row = line.get_zero_based();
let top = abs_row.saturating_sub(self.terminal.inline_cursor_y());
self.terminal.set_viewport_top(top);
if let Some(ref mut drawn) = self.last_contents {
drawn.viewport_start = Some(top);
}
}
Ok(other) => {
log::error!(
"Failed to receive CPR response: unexpected event {:?}",
other
);
}
Err(e) => {
log::error!("Failed to read CPR response: {}", e);
}
},
Ok(false) => {
log::error!("Timed out waiting for CPR response (500ms)");
}
Err(e) => {
log::error!("Failed polling for CPR response: {}", e);
}
}
}
/// Computes the number of terminal rows occupied by the lines up to the cursor
/// after a window resize to `new_width` columns, based on `resize_logic`.
pub fn compute_wrapped_rows_up(
&mut self,
new_width: u16,
resize_logic: settings::ResizeLogic,
) -> u16 {
let inline_cursor_y = self.terminal.inline_cursor_y();
let inline_cursor_x = self.terminal.inline_cursor_x();
let buffer = self.terminal.previous_buffer_mut();
Self::compute_wrapped_rows_up_from_buffer(
buffer,
inline_cursor_x,
inline_cursor_y,
new_width,
resize_logic,
)
}
/// Computes the display width of line `y` in `buffer` by finding the rightmost non-empty cell.
#[allow(dead_code)]
pub fn compute_line_width_from_buffer(buffer: &ratatui::buffer::Buffer, y: u16) -> u16 {
Self::compute_line_width_from_buffer_opts(buffer, y, false)
}
/// Computes the display width of line `y` in `buffer`, optionally trimming trailing whitespace.
pub fn compute_line_width_from_buffer_opts(
buffer: &ratatui::buffer::Buffer,
y: u16,
trim_whitespace: bool,
) -> u16 {
let old_width = buffer.area.width;
let mut line_width = 0u16;
for x in (0..old_width).rev() {
if let Some(cell) = buffer.cell(ratatui::layout::Position { x, y }) {
let is_empty = cell.symbol_opt().is_none_or(|s| {
if trim_whitespace {
s.trim().is_empty()
} else {
s.is_empty()
}
});
if !is_empty {
log::info!(
"[LineWidth] Line {} (old_width={}, trim_ws={}) rightmost non-empty cell at x={} with symbol {:?}",
y,
old_width,
trim_whitespace,
x,
cell.symbol_opt()
);
let sym_width = cell
.symbol_opt()
.map(|s| unicode_width::UnicodeWidthStr::width(s) as u16)
.unwrap_or(1);
line_width = (x + sym_width.max(1)).min(old_width);
break;
}
}
}
line_width
}
/// Computes the number of terminal rows occupied by the lines up to the cursor
/// after a window resize to `new_width` columns, based on `resize_logic`.
pub fn compute_wrapped_rows_up_from_buffer(
buffer: &ratatui::buffer::Buffer,
inline_cursor_x: u16,
inline_cursor_y: u16,
new_width: u16,
resize_logic: settings::ResizeLogic,
) -> u16 {
if new_width == 0 {
return 0;
}
if resize_logic == settings::ResizeLogic::DontMoveCursor {
return 0;
}
if resize_logic == settings::ResizeLogic::AutoCleared {
// ghostty seems to clear the text we wrote but it doesnt move the cursor back to the start.
// Because the text was cleared, it doesnt wrap.
return inline_cursor_y;
}
let trim_whitespace = resize_logic == settings::ResizeLogic::ReflowedAllWhitespaceTrimmed;
let mut total_rows = 0u16;
// Calculate rows for each line above the cursor (y < inline_cursor_y)
for y in 0..inline_cursor_y {
let line_width = Self::compute_line_width_from_buffer_opts(buffer, y, trim_whitespace);
log::info!(
"Line {} width before resize: {}, new width: {}",
y,
line_width,
new_width
);
if line_width == 0 {
total_rows += 1;
} else {
let rows = line_width.div_ceil(new_width);
total_rows += rows.max(1);
}
}
// Add offset for the cursor line itself and lines below the cursor according to the resize strategy
match resize_logic {
settings::ResizeLogic::ReflowedApartFromCursor => {
// Account for extra wrapped rows generated by lines below the cursor (y > inline_cursor_y).
// Terminal reflow engines (such as xterm.js) process buffer lines bottom-to-top and increment
// the cursor screen Y position for each extra row added below the cursor.
let total_buffer_height = buffer.area.height;
for y in (inline_cursor_y + 1)..total_buffer_height {
let line_width =
Self::compute_line_width_from_buffer_opts(buffer, y, trim_whitespace);
if line_width > new_width {
let extra_rows = line_width.div_ceil(new_width) - 1;
log::info!(
"Line {} below cursor width: {}, extra rows added: {}",
y,
line_width,
extra_rows
);
total_rows += extra_rows;
}
}
}
settings::ResizeLogic::ReflowedAll
| settings::ResizeLogic::ReflowedAllWhitespaceTrimmed => {
// Cursor row wraps at new_width; cursor is offset by inline_cursor_x / new_width
let cursor_row_offset = inline_cursor_x / new_width;
total_rows += cursor_row_offset;
}
settings::ResizeLogic::AutoCleared => {}
settings::ResizeLogic::DontMoveCursor => {}
settings::ResizeLogic::Default => {}
}
total_rows
}
/// Return a mutable reference to the history manager for the given fuzzy source.
pub(crate) fn select_fuzzy_history_manager_mut(
&mut self,
source: &FuzzyHistorySource,
) -> &mut HistoryManager {
match source {
FuzzyHistorySource::PastCommands => &mut self.long_lived.history_manager,
FuzzyHistorySource::CancelledCommands => {
&mut self.long_lived.cancelled_command_history_manager
}
FuzzyHistorySource::AgentPrompts => &mut self.long_lived.agent_prompt_history_manager,
}
}
/// Return an immutable reference to the history manager for the given fuzzy source.
pub(crate) fn select_fuzzy_history_manager(
&self,
source: &FuzzyHistorySource,
) -> &HistoryManager {
match source {
FuzzyHistorySource::PastCommands => &self.long_lived.history_manager,
FuzzyHistorySource::CancelledCommands => {
&self.long_lived.cancelled_command_history_manager
}
FuzzyHistorySource::AgentPrompts => &self.long_lived.agent_prompt_history_manager,
}
}
pub fn run(mut self) -> ExitState {
// Send execution finished escape codes (previous command has completed).
time_it!("startup: escape codes", {
if crate::settings().send_shell_integration_codes
== settings::ShellIntegrationLevel::Full
{
let last_command_exit_value = shell::backend().last_command_exit_status();
let hostname = shell::backend().hostname();
let cwd = shell::backend().cwd();
shell_integration::write_startup_codes(last_command_exit_value, &hostname, &cwd)
.unwrap_or_else(|e| {
log::error!("Failed to write execution finished escape codes: {}", e);
});
}
});
shell::backend().prep_terminal();
let event_reader = self.terminal.backend_mut().terminal_mut().event_reader();
let poll_terminal_event = |event_reader: &termina::EventReader,
timeout: Duration|
-> std::io::Result<Option<TerminaEvent>> {
if let Some(reason) = stdin_unavailable_reason() {
log::error!("Cannot read terminal events: {}", reason);
return Err(Error::new(ErrorKind::UnexpectedEof, reason));
}
if event_reader.poll(Some(timeout), |_| true)? {
return event_reader.read(|_| true).map(Some);
}
Ok(None)
};
let mut redraw = true;
let mut last_terminal_size = self.terminal.size().unwrap();
'main_loop: loop {
if let Some(resize_time) = self.last_resize_time {
// Getting cursor pos can be slow via ssh
// and resizes can happen in quick succession, so we wait a bit before requesting the cursor pos
if resize_time.elapsed() >= std::time::Duration::from_millis(150) {
self.last_resize_time = None;
self.sync_viewport_top_from_cpr();
if self.terminal.viewport_top().is_none() {
log::warn!("[Resize] CPR returned None for viewport_top");
}
}
}
self.handle_delayed_startup();
if self.poll_agent() {
redraw = true;
}
if self.poll_tab_completion(0) {
redraw = true;
}
if self.poll_flycomp() {
redraw = true;
}
if self.poll_path_warming() {
redraw = true;
}
if self.poll_git_warming() {
redraw = true;
}
if self
.leader_key_active_at
.is_some_and(|t| t.elapsed() >= std::time::Duration::from_millis(1000))
{
self.leader_key_active_at = None;
redraw = true;
}
if redraw {
if self.needs_full_redraw
&& let Err(e) = self.terminal.resize(last_terminal_size.into())
{
log::error!("Failed to resync inline viewport after bash command: {}", e);
}
let frame_area = self.terminal.get_frame().area();
let content =
self.create_content(frame_area.width, frame_area.y, last_terminal_size.height);
let was_screen_cleared = self.needs_screen_cleared;
if self.needs_screen_cleared {
self.needs_screen_cleared = false;
let _ = self.terminal.clear_screen();
}
let desired_height = content.height().min(last_terminal_size.height);
// This helps to reduce flicker.
// Each time we call set_viewport_height, there is a chance it flickers.
if desired_height > frame_area.height {
log::info!(
"Resizing inline viewport from {} to {} rows",
frame_area.height,
desired_height
);
self.terminal
.set_viewport_height(desired_height)
.unwrap_or_else(|e| {
log::error!("Failed to set viewport height: {}", e);
});
}
let prev_contents = std::mem::take(&mut self.last_contents);
let show_terminal_cursor = (crate::settings().cursor_config.backend()
== crate::cursor::CursorBackend::Terminal
|| !self.mode.is_running())
&& !(mouse_state(|m| m.is_left_button_down())
&& self.buffer.selection_range().is_some()
&& matches!(
mouse_state(|m| m.last_mouse_over_cell_semantic),
Some(Tag::Command(_))
));
let needs_full_redraw = self.needs_full_redraw;
if self.needs_full_redraw {
self.needs_full_redraw = false;
}
let set_mode =
|code| Csi::Mode(DecMode::SetDecPrivateMode(DecPrivateMode::Code(code)));
let reset_mode =
|code| Csi::Mode(DecMode::ResetDecPrivateMode(DecPrivateMode::Code(code)));
let current_viewport_top = self.terminal.viewport_top();
let mut drawn_content: Option<DrawnContent> = None;
let _ =
crate::flush_stdout!("{}", set_mode(DecPrivateModeCode::SynchronizedOutput));
let draw_result = {
let _timer = crate::perf::PerfTimer::start("draw");
self.terminal.draw(|f| {
drawn_content = Some(Self::ui(
f,
content,
needs_full_redraw,
show_terminal_cursor,
current_viewport_top,
));
})
};
self.last_contents = drawn_content;
match draw_result {
Ok(_) => {
self.last_draw_time = std::time::Instant::now();
if let Some(top) = self.terminal.viewport_top()
&& let Some(ref mut drawn) = self.last_contents
{
drawn.viewport_start = Some(top);
}
if matches!(
crate::settings().send_shell_integration_codes,
settings::ShellIntegrationLevel::OnlyPromptPos
| settings::ShellIntegrationLevel::Full
) {
let force_resend_prompt_codes = was_screen_cleared || needs_full_redraw;
let prev_start = if force_resend_prompt_codes {
None
} else {
prev_contents
.as_ref()
.and_then(|c| c.prompt_start_relative())
};
let prev_end = if force_resend_prompt_codes {
None
} else {
prev_contents.as_ref().and_then(|c| c.prompt_end_relative())
};
shell_integration::write_after_rendering_codes(
prev_start,
prev_end,
self.last_contents
.as_ref()
.and_then(|c| c.prompt_start_relative()),
self.last_contents
.as_ref()
.and_then(|c| c.prompt_end_relative()),
self.mode.is_running(),
)
.unwrap_or_else(|e| {
log::error!("Failed to write prompt position escape codes: {}", e);
});
}
}
Err(e) => {
log::error!("Failed to draw terminal UI: {}", e);
self.mode = AppRunningState::Exiting(ExitState::WithoutCommand);
}
}
let _ =
crate::flush_stdout!("{}", reset_mode(DecPrivateModeCode::SynchronizedOutput));
self.reevaluate_pointer_shape();
}
if !self.mode.is_running() {
break;
}
let is_idle = self.last_activity_time.elapsed() >= IDLE_TIMEOUT;
let effective_fps = if is_idle {
crate::settings()
.idle_frame_rate
.min(crate::settings().frame_rate as f64)
} else {
crate::settings().frame_rate as f64
};
let min_refresh_rate: Duration = Duration::from_millis((1000.0 / effective_fps) as u64);
redraw = match poll_terminal_event(&event_reader, min_refresh_rate) {
Ok(Some(event)) => {
match event {
TerminaEvent::Key(key) => {
self.last_activity_time = std::time::Instant::now();
self.handle_key_event(key);
true