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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
use super::base::Window;
use crate::app::app_state::AutoScrollDirection;
use crate::rendering::{Cell, Charset, CharsetMode, Theme, VideoBuffer};
use crate::term_emu::{
Color as TermColor, NamedColor, Position, Selection, SelectionType, ShellConfig, TerminalCell,
TerminalEmulator, TerminalGrid, TerminalRenderer,
};
use crate::ui::prompt::{Prompt, PromptAction, PromptButton, PromptType, TextAlign};
use crossterm::event::{KeyCode, KeyEvent};
use crossterm::style::Color;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Instant;
/// Mouse position relative to the terminal content area
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MouseContentPosition {
/// Mouse is inside the content area
Inside,
/// Mouse is above the content area (should scroll up)
Above,
/// Mouse is below the content area (should scroll down)
Below,
/// Mouse is outside horizontally (left or right)
Outside,
}
/// Close confirmation dialog for a terminal window
pub(crate) struct CloseConfirmation {
prompt: Prompt,
}
impl CloseConfirmation {
fn new(content_x: u16, content_y: u16, content_width: u16, content_height: u16) -> Self {
// Create buttons for the dialog
let buttons = vec![
PromptButton::new("Cancel".to_string(), PromptAction::Cancel, false),
PromptButton::new("Close".to_string(), PromptAction::Confirm, true),
];
// Create the prompt centered in the terminal content area
let prompt = Prompt::new_with_alignment(
PromptType::Danger,
"Close this terminal?\n\nActive content may be lost.".to_string(),
buttons,
content_width,
content_height,
TextAlign::Center,
)
.with_selection_indicators(true)
.centered_in_region(content_x, content_y, content_width, content_height)
.with_selected_button(0); // Default to Cancel (safe choice)
Self { prompt }
}
}
/// Emulator mode: Local (owns PTY) or Remote (daemon owns PTY)
pub enum EmulatorMode {
/// Standalone mode: terminal emulator with local PTY
Local(TerminalEmulator),
/// Client mode: rendering only, PTY owned by persist daemon
Remote {
renderer: TerminalRenderer,
window_id: u32,
},
}
/// A window containing a terminal emulator
pub struct TerminalWindow {
pub window: Window,
mode: EmulatorMode,
scroll_offset: usize, // For scrollback navigation
selection: Option<Selection>, // Current text selection
// Cached foreground process name to avoid spawning ps every frame
cached_process_name: Option<String>,
process_name_last_update: Instant,
// Close confirmation state
pub(crate) pending_close_confirmation: Option<CloseConfirmation>,
// Track user input (for dirty state detection)
created_at: Instant,
has_user_input: bool,
/// Last rendered grid generation (for change detection optimization)
/// When this matches the grid's generation, we can skip re-rendering content
last_rendered_generation: u64,
/// Pending bytes to send to daemon (buffered from Remote mode mouse events)
pending_remote_bytes: Vec<u8>,
/// Pending resize notification for daemon (cols, rows)
pending_resize: Option<(u16, u16)>,
}
/// Mouse tracking state - all flags retrieved with a single mutex lock
/// Used internally to avoid multiple lock acquisitions in hot path
struct MouseTrackingState {
/// Whether any mouse tracking mode is enabled
tracking_enabled: bool,
/// Whether button/drag tracking is enabled (1002 or 1003)
button_tracking: bool,
/// SGR extended mouse mode (1006)
sgr_mode: bool,
/// URXVT mouse mode (1015)
urxvt_mode: bool,
}
impl TerminalWindow {
/// Create a new terminal window with a local PTY (standalone mode)
#[allow(clippy::too_many_arguments)]
pub fn new(
id: u32,
x: u16,
y: u16,
width: u16,
height: u16,
title: String,
initial_command: Option<String>,
shell_config: &ShellConfig,
) -> std::io::Result<Self> {
// Calculate content area (excluding 2-char borders and title bar)
let content_width = width.saturating_sub(4).max(1); // -2 left, -2 right
let content_height = height.saturating_sub(2).max(1); // -1 title, -1 bottom
let window = Window::new(id, x, y, width, height, title);
// Parse initial_command into program + args for direct execution
let parsed_command = initial_command.as_ref().map(|cmd| Self::parse_command(cmd));
let emulator = TerminalEmulator::new(
content_width as usize,
content_height as usize,
1000, // 1000 lines of scrollback
parsed_command,
shell_config,
)?;
Ok(Self {
window,
mode: EmulatorMode::Local(emulator),
scroll_offset: 0,
selection: None,
cached_process_name: None,
process_name_last_update: Instant::now(),
pending_close_confirmation: None,
created_at: Instant::now(),
has_user_input: false,
last_rendered_generation: 0,
pending_remote_bytes: Vec::new(),
pending_resize: None,
})
}
/// Create a new terminal window in remote mode (persist client)
/// PTY is owned by the daemon; this window only renders output
#[allow(dead_code)]
pub fn new_remote(
id: u32,
x: u16,
y: u16,
width: u16,
height: u16,
title: String,
daemon_window_id: u32,
) -> Self {
let content_width = width.saturating_sub(4).max(1);
let content_height = height.saturating_sub(2).max(1);
let window = Window::new(id, x, y, width, height, title);
let renderer = TerminalRenderer::new(content_width as usize, content_height as usize, 1000);
Self {
window,
mode: EmulatorMode::Remote {
renderer,
window_id: daemon_window_id,
},
scroll_offset: 0,
selection: None,
cached_process_name: None,
process_name_last_update: Instant::now(),
pending_close_confirmation: None,
created_at: Instant::now(),
has_user_input: false,
last_rendered_generation: 0,
pending_remote_bytes: Vec::new(),
pending_resize: None,
}
}
/// Get the grid Arc regardless of mode
fn grid_arc(&self) -> Arc<Mutex<TerminalGrid>> {
match &self.mode {
EmulatorMode::Local(emu) => emu.grid(),
EmulatorMode::Remote { renderer, .. } => renderer.grid(),
}
}
/// Check if this window is in remote (persist client) mode
#[allow(dead_code)]
pub fn is_remote(&self) -> bool {
matches!(self.mode, EmulatorMode::Remote { .. })
}
/// Get the daemon window ID (only valid in Remote mode)
#[allow(dead_code)]
pub fn remote_window_id(&self) -> Option<u32> {
match &self.mode {
EmulatorMode::Remote { window_id, .. } => Some(*window_id),
EmulatorMode::Local(_) => None,
}
}
/// Feed raw PTY output from daemon into the renderer (Remote mode only)
pub fn feed_remote_output(&mut self, data: &[u8]) {
if let EmulatorMode::Remote { renderer, .. } = &mut self.mode {
renderer.feed_output(data);
}
}
/// Drain any pending bytes buffered from Remote mode (mouse events, etc.)
/// Returns the bytes that need to be sent to the daemon as PtyInput
pub fn drain_pending_remote_bytes(&mut self) -> Option<Vec<u8>> {
if self.pending_remote_bytes.is_empty() {
None
} else {
Some(std::mem::take(&mut self.pending_remote_bytes))
}
}
/// Take pending resize notification (cols, rows) if any
pub fn take_pending_resize(&mut self) -> Option<(u16, u16)> {
self.pending_resize.take()
}
/// Parse a command string into (program, args)
/// Simple shell-like parsing: splits on whitespace, respects quotes
fn parse_command(cmd: &str) -> (String, Vec<String>) {
let mut parts = Vec::new();
let mut current = String::new();
let mut in_quotes = false;
for ch in cmd.chars() {
match ch {
'"' | '\'' => {
in_quotes = !in_quotes;
}
' ' | '\t' if !in_quotes => {
if !current.is_empty() {
parts.push(current.clone());
current.clear();
}
}
_ => {
current.push(ch);
}
}
}
if !current.is_empty() {
parts.push(current);
}
if parts.is_empty() {
// Empty command, return a safe default
("sh".to_string(), vec![])
} else {
let program = parts[0].clone();
let args = parts.into_iter().skip(1).collect();
(program, args)
}
}
/// Process terminal output (call this regularly in the event loop)
/// In Remote mode, returns Ok(true) (output is fed externally via feed_remote_output)
pub fn process_output(&mut self) -> std::io::Result<bool> {
match &mut self.mode {
EmulatorMode::Local(emu) => emu.process_output(),
EmulatorMode::Remote { .. } => Ok(true), // Always alive; output fed externally
}
}
/// Send input to the terminal
/// In Remote mode, this is a no-op (WindowManager routes input via daemon)
pub fn send_str(&mut self, s: &str) -> std::io::Result<()> {
// Only track user input after initial shell setup (1 second grace period)
if self.created_at.elapsed().as_secs() >= 1 {
self.has_user_input = true;
}
match &mut self.mode {
EmulatorMode::Local(emu) => emu.send_str(s),
EmulatorMode::Remote { .. } => Ok(()), // Routed by WindowManager
}
}
/// Send a character to the terminal
/// In Remote mode, this is a no-op (WindowManager routes input via daemon)
pub fn send_char(&mut self, c: char) -> std::io::Result<()> {
// Only track user input after initial shell setup (1 second grace period)
if self.created_at.elapsed().as_secs() >= 1 {
self.has_user_input = true;
}
match &mut self.mode {
EmulatorMode::Local(emu) => emu.send_char(c),
EmulatorMode::Remote { .. } => Ok(()),
}
}
/// Flush any buffered terminal input
/// Call this after processing a batch of keyboard events
pub fn flush_input(&mut self) -> std::io::Result<()> {
match &mut self.mode {
EmulatorMode::Local(emu) => emu.flush_input(),
EmulatorMode::Remote { .. } => Ok(()),
}
}
/// Resize the window (also resizes the terminal)
pub fn resize(&mut self, new_width: u16, new_height: u16) -> std::io::Result<()> {
self.window.width = new_width;
self.window.height = new_height;
// Calculate new content dimensions (accounting for 2-char borders)
let content_width = new_width.saturating_sub(4).max(1); // -2 left, -2 right
let content_height = new_height.saturating_sub(2).max(1); // -1 title, -1 bottom
// Invalidate render cache since window dimensions changed
self.invalidate_render_cache();
match &mut self.mode {
EmulatorMode::Local(emu) => emu.resize(content_width as usize, content_height as usize),
EmulatorMode::Remote { renderer, .. } => {
renderer.resize(content_width as usize, content_height as usize);
self.pending_resize = Some((content_width, content_height));
Ok(())
}
}
}
/// Invalidate the render cache to force re-rendering on next frame
/// Call this when window state changes that affect rendering (resize, focus, selection)
#[inline]
fn invalidate_render_cache(&mut self) {
self.last_rendered_generation = u64::MAX;
}
/// Scroll up in the scrollback buffer
#[allow(dead_code)]
pub fn scroll_up(&mut self, lines: usize) {
let grid = self.grid_arc();
let grid = grid.lock().unwrap();
let max_offset = grid.scrollback_len();
self.scroll_offset = (self.scroll_offset + lines).min(max_offset);
}
/// Scroll down in the scrollback buffer
#[allow(dead_code)]
pub fn scroll_down(&mut self, lines: usize) {
self.scroll_offset = self.scroll_offset.saturating_sub(lines);
}
/// Reset scroll to bottom (showing current output)
#[allow(dead_code)]
pub fn scroll_to_bottom(&mut self) {
self.scroll_offset = 0;
}
/// Render the terminal window
/// If keyboard_mode_active is true and window is focused, uses keyboard mode colors
pub fn render(
&mut self,
buffer: &mut VideoBuffer,
charset: &Charset,
theme: &Theme,
tint_terminal: bool,
keyboard_mode_active: bool,
) {
// Get dynamic title with cached process name
let dynamic_title = self.get_dynamic_title_cached();
// Render the window frame and title bar with dynamic title
self.window.render_with_title(
buffer,
charset,
theme,
Some(&dynamic_title),
keyboard_mode_active,
);
// Acquire grid lock once for both content and scrollbar rendering
let grid_arc = self.grid_arc();
let grid = grid_arc.lock().unwrap();
// Render the terminal content
self.render_terminal_content_with_grid(buffer, theme, tint_terminal, &grid);
// Render the scrollbar
self.render_scrollbar_with_grid(buffer, charset, theme, &grid);
// Render close confirmation on top of window content (if active)
self.render_close_confirmation(buffer, charset, theme);
}
fn render_terminal_content_with_grid(
&self,
buffer: &mut VideoBuffer,
theme: &Theme,
tint_terminal: bool,
grid: &MutexGuard<'_, TerminalGrid>,
) {
if self.window.is_minimized {
return;
}
// Content area starts after 2-char left border and title bar
let content_x = self.window.x + 2; // After 2-char left border
let content_y = self.window.y + 1; // After title bar
let content_width = self.window.width.saturating_sub(4); // -2 left, -2 right
let content_height = self.window.height.saturating_sub(2); // -1 title, -1 bottom
let scrollback_len = grid.scrollback_len();
let visible_rows = grid.rows();
// Render terminal grid cells
for row in 0..content_height {
for col in 0..content_width {
let grid_col = col as usize;
let row_idx = row as usize;
// Calculate which line to display based on scroll offset
let term_cell = if self.scroll_offset > 0 {
// We're scrolled back, need to fetch from scrollback or visible rows
let total_lines = scrollback_len + visible_rows;
let line_idx =
total_lines.saturating_sub(self.scroll_offset + visible_rows) + row_idx;
if line_idx < scrollback_len {
// Fetch from scrollback
grid.get_scrollback_line(line_idx)
.and_then(|line| line.get(grid_col))
} else {
// Fetch from visible rows
let visible_row = line_idx - scrollback_len;
grid.get_cell(grid_col, visible_row)
}
} else {
// Not scrolled, show current visible rows
// Use get_render_cell to respect synchronized output snapshot
grid.get_render_cell(grid_col, row_idx)
};
// Render the cell
let mut cell = if let Some(term_cell) = term_cell {
convert_terminal_cell(term_cell, theme, tint_terminal)
} else {
// Grid doesn't have data for this cell (window is larger than grid)
// Use default terminal background to maintain visual consistency
Cell::new_unchecked(' ', theme.window_content_fg, theme.window_content_bg)
};
// Apply selection highlighting if this cell is selected
// Selection uses absolute buffer coordinates, so convert viewport row to absolute
if let Some(selection) = &self.selection {
let absolute_row =
Self::viewport_to_absolute_row(row, scrollback_len, self.scroll_offset);
let pos = Position::new(col, absolute_row);
if selection.contains(pos) {
// Invert colors for DOS-style selection
cell = cell.inverted();
}
}
buffer.set(content_x + col, content_y + row, cell);
}
}
// Render cursor if visible and not scrolled
// Applications like Claude hide the cursor to draw their own
// Use get_render_cursor to respect synchronized output snapshot
let render_cursor = grid.get_render_cursor();
if render_cursor.visible && self.scroll_offset == 0 {
let cursor_x = content_x + render_cursor.x as u16;
let cursor_y = content_y + render_cursor.y as u16;
// Check if cursor is within window bounds
if cursor_x < content_x + content_width && cursor_y < content_y + content_height {
// Get the current cell at cursor position
if let Some(current_cell) = buffer.get(cursor_x, cursor_y) {
// Create cursor based on cursor shape
let cursor_cell = match render_cursor.shape {
crate::term_emu::CursorShape::Block => {
// For block cursor, show as inverted colors
if current_cell.character == ' ' || current_cell.character == '\0' {
// For empty space, show a solid block using the foreground color
// This makes the cursor visible as a colored block
Cell::new('â–ˆ', current_cell.fg_color, current_cell.bg_color)
} else {
// For text, invert the colors (swap fg and bg)
Cell::new(
current_cell.character,
current_cell.bg_color, // Use bg as fg (inverted)
current_cell.fg_color, // Use fg as bg (inverted)
)
}
}
crate::term_emu::CursorShape::Underline => {
// For underline cursor, show underscore in foreground color
Cell::new('_', current_cell.fg_color, current_cell.bg_color)
}
crate::term_emu::CursorShape::Bar => {
// For bar cursor, show vertical bar in foreground color
Cell::new('│', current_cell.fg_color, current_cell.bg_color)
}
};
buffer.set(cursor_x, cursor_y, cursor_cell);
}
}
}
}
fn render_scrollbar_with_grid(
&self,
buffer: &mut VideoBuffer,
charset: &Charset,
theme: &Theme,
grid: &MutexGuard<'_, TerminalGrid>,
) {
if self.window.is_minimized {
return;
}
let scrollback_len = grid.scrollback_len();
// Only show scrollbar if there's scrollback content
if scrollback_len == 0 {
return;
}
let scrollbar_x = self.window.x + self.window.width - 2; // Inner char of 2-char right border
let (track_start, track_end) = self.get_scrollbar_bounds();
// Calculate thumb bounds inline to avoid re-locking the grid
let visible_rows = grid.rows();
let total_lines = scrollback_len + visible_rows;
let (thumb_start, thumb_end) = if total_lines <= visible_rows {
(0, 0)
} else {
let track_height = (track_end - track_start) as usize;
let thumb_size = ((visible_rows as f64 / total_lines as f64) * track_height as f64)
.max(1.0) as usize;
let max_scroll = total_lines.saturating_sub(visible_rows);
// Invert the scroll ratio so thumb is at bottom when at current output (scroll_offset=0)
let scroll_ratio = if max_scroll > 0 {
(max_scroll - self.scroll_offset) as f64 / max_scroll as f64
} else {
1.0
};
let thumb_offset = (scroll_ratio * (track_height - thumb_size) as f64) as usize;
let thumb_start = track_start + thumb_offset as u16;
let thumb_end = thumb_start + thumb_size as u16;
(thumb_start, thumb_end)
};
// Choose characters based on charset mode
let track_char = match charset.mode {
CharsetMode::Unicode | CharsetMode::UnicodeSingleLine => 'â–‘', // Light shade for track
CharsetMode::Ascii => '.',
};
let thumb_char = match charset.mode {
CharsetMode::Unicode | CharsetMode::UnicodeSingleLine => 'â–ˆ',
CharsetMode::Ascii => '#',
};
// Render the scrollbar track and thumb
for y in track_start..track_end {
let (ch, fg_color) = if y >= thumb_start && y < thumb_end {
// Scrollbar thumb
(thumb_char, theme.scrollbar_thumb_fg)
} else {
// Scrollbar track
(track_char, theme.scrollbar_track_fg)
};
let cell = Cell::new(ch, fg_color, theme.window_content_bg);
buffer.set(scrollbar_x, y, cell);
}
}
/// Render close confirmation dialog centered in window
fn render_close_confirmation(
&self,
buffer: &mut VideoBuffer,
charset: &Charset,
theme: &Theme,
) {
if let Some(confirmation) = &self.pending_close_confirmation {
confirmation.prompt.render(buffer, charset, theme);
}
}
/// Get the window's ID
pub fn id(&self) -> u32 {
self.window.id
}
/// Set focus state
pub fn set_focused(&mut self, focused: bool) {
if self.window.is_focused != focused {
self.window.is_focused = focused;
// Invalidate render cache since cursor visibility changes with focus
self.invalidate_render_cache();
}
}
/// Check if a point is within the window
pub fn contains_point(&self, x: u16, y: u16) -> bool {
if self.window.is_minimized {
return false;
}
self.window.contains_point(x, y)
}
/// Check if point is in title bar
pub fn is_in_title_bar(&self, x: u16, y: u16) -> bool {
if self.window.is_minimized {
return false;
}
self.window.is_in_title_bar(x, y)
}
/// Check if point is in close button
pub fn is_in_close_button(&self, x: u16, y: u16) -> bool {
if self.window.is_minimized {
return false;
}
self.window.is_in_close_button(x, y)
}
/// Check if window has unsaved work (user input or non-shell process running)
/// Ignores shell processes and common shell helpers
pub fn is_dirty(&self) -> bool {
// Check if user has typed anything (after initial 1 second grace period)
if self.has_user_input {
return true;
}
// Check if there's a non-shell process running
if let Some(process_name) = self.get_foreground_process_name() {
// List of shell processes and common shell-related tools to ignore
let ignore_list = [
// Shells (regular and login shell variants with - prefix)
"bash",
"-bash",
"zsh",
"-zsh",
"sh",
"-sh",
"fish",
"-fish",
"dash",
"-dash",
"ksh",
"-ksh",
"csh",
"-csh",
"tcsh",
"-tcsh",
"nu",
"-nu",
"elvish",
"-elvish",
"xonsh",
"-xonsh",
// Shell prompt tools
"starship",
"gitstatus",
"powerlevel10k",
// Environment tools
"direnv",
"asdf",
"mise",
"rtx",
"fnm",
"nvm",
// Common shell integrations
"zsh-autocomplete",
"zsh-autosuggestions",
"zsh-syntax-highlighting",
];
!ignore_list.contains(&process_name.as_str())
} else {
false
}
}
/// Check if close confirmation dialog is currently shown
pub fn has_close_confirmation(&self) -> bool {
self.pending_close_confirmation.is_some()
}
/// Show the close confirmation dialog
pub fn show_close_confirmation(&mut self) {
// Calculate content area for centering the dialog
let content_x = self.window.x + 2;
let content_y = self.window.y + 1;
let content_width = self.window.width.saturating_sub(4);
let content_height = self.window.height.saturating_sub(2);
self.pending_close_confirmation = Some(CloseConfirmation::new(
content_x,
content_y,
content_width,
content_height,
));
}
/// Get total number of lines (scrollback + visible)
#[allow(dead_code)]
pub fn get_total_lines(&self) -> usize {
let grid = self.grid_arc();
let grid = grid.lock().unwrap();
grid.scrollback_len() + grid.rows()
}
/// Get the bounds of the scrollbar track (y_start, y_end)
pub fn get_scrollbar_bounds(&self) -> (u16, u16) {
let y_start = self.window.y + 1; // After title bar
let y_end = self.window.y + self.window.height - 1; // Before bottom border
(y_start, y_end)
}
/// Get the bounds of the scrollbar thumb (y_start, y_end)
pub fn get_scrollbar_thumb_bounds(&self) -> (u16, u16) {
let grid = self.grid_arc();
let grid = grid.lock().unwrap();
let scrollback_len = grid.scrollback_len();
let visible_rows = grid.rows();
let total_lines = scrollback_len + visible_rows;
if total_lines <= visible_rows {
// No scrollbar needed
return (0, 0);
}
let (track_start, track_end) = self.get_scrollbar_bounds();
let track_height = (track_end - track_start) as usize;
// Calculate thumb size (proportional to visible area)
let thumb_size =
((visible_rows as f64 / total_lines as f64) * track_height as f64).max(1.0) as usize;
// Calculate thumb position based on scroll offset
// Invert the scroll ratio so thumb is at bottom when at current output (scroll_offset=0)
let max_scroll = total_lines.saturating_sub(visible_rows);
let scroll_ratio = if max_scroll > 0 {
(max_scroll - self.scroll_offset) as f64 / max_scroll as f64
} else {
1.0
};
let thumb_offset = (scroll_ratio * (track_height - thumb_size) as f64) as usize;
let thumb_start = track_start + thumb_offset as u16;
let thumb_end = thumb_start + thumb_size as u16;
(thumb_start, thumb_end)
}
/// Check if a point is on the scrollbar
pub fn is_point_on_scrollbar(&self, x: u16, y: u16) -> bool {
if self.window.is_minimized {
return false;
}
let scrollbar_x = self.window.x + self.window.width - 2; // Inner char of 2-char right border
let (y_start, y_end) = self.get_scrollbar_bounds();
x == scrollbar_x && y >= y_start && y < y_end
}
/// Check if a point is on the scrollbar thumb
pub fn is_point_on_scrollbar_thumb(&self, x: u16, y: u16) -> bool {
if self.window.is_minimized {
return false;
}
if !self.is_point_on_scrollbar(x, y) {
return false;
}
let (thumb_start, thumb_end) = self.get_scrollbar_thumb_bounds();
y >= thumb_start && y < thumb_end
}
/// Scroll to a specific offset based on mouse position on scrollbar
pub fn scroll_to_position(&mut self, y: u16) {
let (track_start, track_end) = self.get_scrollbar_bounds();
let track_height = (track_end - track_start) as usize;
if track_height == 0 {
return;
}
let grid = self.grid_arc();
let grid = grid.lock().unwrap();
let total_lines = grid.scrollback_len() + grid.rows();
let visible_rows = grid.rows();
let max_scroll = total_lines.saturating_sub(visible_rows);
// Calculate position ratio (inverted: top = old content, bottom = current)
let click_offset = y.saturating_sub(track_start) as usize;
let ratio = click_offset as f64 / track_height as f64;
// Invert the ratio so clicking at bottom shows current output (scroll_offset=0)
self.scroll_offset = ((1.0 - ratio) * max_scroll as f64) as usize;
self.scroll_offset = self.scroll_offset.min(max_scroll);
}
/// Get the current scroll offset
pub fn get_scroll_offset(&self) -> usize {
self.scroll_offset
}
/// Convert screen coordinates to terminal grid position
fn screen_to_grid_pos(&self, screen_x: u16, screen_y: u16) -> Option<Position> {
let content_x = self.window.x + 2; // After 2-char left border
let content_y = self.window.y + 1; // After title bar
let content_width = self.window.width.saturating_sub(4); // -2 left, -2 right
let content_height = self.window.height.saturating_sub(2); // -1 title, -1 bottom
// Check if coordinates are within content area
if screen_x < content_x
|| screen_x >= content_x + content_width
|| screen_y < content_y
|| screen_y >= content_y + content_height
{
return None;
}
let col = screen_x - content_x;
let row = screen_y - content_y;
Some(Position::new(col, row))
}
/// Convert a viewport row to absolute buffer row
/// Absolute row = scrollback_len - scroll_offset + viewport_row
fn viewport_to_absolute_row(
viewport_row: u16,
scrollback_len: usize,
scroll_offset: usize,
) -> u16 {
let absolute = scrollback_len as i32 - scroll_offset as i32 + viewport_row as i32;
absolute.max(0) as u16
}
/// Get a cell from the buffer using absolute row coordinates
/// Returns the character at the given absolute position
fn get_cell_at_absolute(
grid: &MutexGuard<'_, TerminalGrid>,
col: u16,
absolute_row: u16,
scrollback_len: usize,
) -> Option<char> {
let abs_row = absolute_row as usize;
if abs_row < scrollback_len {
// Position is in scrollback buffer
grid.get_scrollback_line(abs_row)
.and_then(|line| line.get(col as usize))
.map(|cell| cell.c)
} else {
// Position is in visible grid
let visible_row = abs_row - scrollback_len;
grid.get_cell(col as usize, visible_row).map(|cell| cell.c)
}
}
/// Check if a screen position is above, below, or inside the content area
pub fn get_mouse_content_position(&self, screen_x: u16, screen_y: u16) -> MouseContentPosition {
let content_x = self.window.x + 2; // After 2-char left border
let content_y = self.window.y + 1; // After title bar
let content_width = self.window.width.saturating_sub(4); // -2 left, -2 right
let content_height = self.window.height.saturating_sub(2); // -1 title, -1 bottom
// Check if within horizontal bounds (within window width)
let in_horizontal = screen_x >= content_x && screen_x < content_x + content_width;
if !in_horizontal {
return MouseContentPosition::Outside;
}
if screen_y < content_y {
MouseContentPosition::Above
} else if screen_y >= content_y + content_height {
MouseContentPosition::Below
} else {
MouseContentPosition::Inside
}
}
/// Update selection at edge during auto-scroll (uses absolute coordinates)
pub fn update_selection_at_edge(&mut self, direction: AutoScrollDirection) {
// Get grid before borrowing selection to avoid borrow conflict
let grid = self.grid_arc();
let scrollback_len = {
let g = grid.lock().unwrap();
g.scrollback_len()
};
if let Some(selection) = &mut self.selection {
let content_height = self.window.height.saturating_sub(2);
let content_width = self.window.width.saturating_sub(4);
let (viewport_row, col) = match direction {
AutoScrollDirection::Up => (0, 0), // Top-left for scrolling up
AutoScrollDirection::Down => (
content_height.saturating_sub(1),
content_width.saturating_sub(1),
), // Bottom-right for scrolling down
};
// Convert viewport row to absolute row
let absolute_row =
Self::viewport_to_absolute_row(viewport_row, scrollback_len, self.scroll_offset);
selection.update_end(Position::new(col, absolute_row));
}
}
/// Start a new selection (uses absolute coordinates for scroll-aware selection)
pub fn start_selection(&mut self, screen_x: u16, screen_y: u16, selection_type: SelectionType) {
if let Some(pos) = self.screen_to_grid_pos(screen_x, screen_y) {
// Convert viewport row to absolute row
let grid = self.grid_arc();
let scrollback_len = {
let grid = grid.lock().unwrap();
grid.scrollback_len()
};
let absolute_row =
Self::viewport_to_absolute_row(pos.row, scrollback_len, self.scroll_offset);
let absolute_pos = Position::new(pos.col, absolute_row);
self.selection = Some(Selection::new(absolute_pos, selection_type));
}
}
/// Update selection end position (uses absolute coordinates for scroll-aware selection)
pub fn update_selection(&mut self, screen_x: u16, screen_y: u16) {
if let Some(pos) = self.screen_to_grid_pos(screen_x, screen_y) {
// Convert viewport row to absolute row - get scrollback_len and scroll_offset before borrowing selection
let grid = self.grid_arc();
let scrollback_len = {
let grid = grid.lock().unwrap();
grid.scrollback_len()
};
let scroll_offset = self.scroll_offset;
if let Some(selection) = &mut self.selection {
let absolute_row =
Self::viewport_to_absolute_row(pos.row, scrollback_len, scroll_offset);
let absolute_pos = Position::new(pos.col, absolute_row);
selection.update_end(absolute_pos);
}
}
}
/// Complete the selection
/// Clears the selection if it's too small (less than 2 characters)
pub fn complete_selection(&mut self) {
if let Some(selection) = &mut self.selection {
// Clear selection if it's too small (single character click)
if selection.is_too_small() {
self.selection = None;
} else {
selection.complete();
}
}
}
/// Clear the selection
pub fn clear_selection(&mut self) {
self.selection = None;
}
/// Expand selection to word boundaries (handles absolute coordinates)
pub fn expand_selection_to_word(&mut self) {
// Get grid before borrowing selection to avoid borrow conflict
let grid_arc = self.grid_arc();
let grid = grid_arc.lock().unwrap();
let scrollback_len = grid.scrollback_len();
if let Some(selection) = &mut self.selection {
selection.expand_to_word(|pos| {
// Selection uses absolute coordinates, so use absolute-aware cell access
Self::get_cell_at_absolute(&grid, pos.col, pos.row, scrollback_len)
});
}
}
/// Expand selection to line
pub fn expand_selection_to_line(&mut self) {
if let Some(selection) = &mut self.selection {
let content_width = self.window.width.saturating_sub(4); // -2 left, -2 right
selection.expand_to_line(content_width);
}
}
/// Select all content in the terminal (uses absolute coordinates)
pub fn select_all(&mut self) {
let content_width = self.window.width.saturating_sub(4); // -2 left, -2 right
let content_height = self.window.height.saturating_sub(2); // -1 title, -1 bottom border
// Get scrollback length for absolute coordinate calculation
let grid = self.grid_arc();
let scrollback_len = {
let grid = grid.lock().unwrap();
grid.scrollback_len()
};
// Convert viewport positions to absolute positions
let start_row = Self::viewport_to_absolute_row(0, scrollback_len, self.scroll_offset);
let end_row = Self::viewport_to_absolute_row(
content_height.saturating_sub(1),
scrollback_len,
self.scroll_offset,
);
let start = Position::new(0, start_row);
let end = Position::new(content_width.saturating_sub(1), end_row);
let mut selection = Selection::new(start, SelectionType::Character);
selection.update_end(end);
selection.complete();
self.selection = Some(selection);
}
/// Get selected text (handles absolute coordinates)
pub fn get_selected_text(&self) -> Option<String> {
let selection = self.selection.as_ref()?;
if selection.is_empty() {
return None;
}
let grid = self.grid_arc();
let grid = grid.lock().unwrap();
let scrollback_len = grid.scrollback_len();
let (start, end) = selection.normalized_bounds();
let mut result = String::new();
match selection.selection_type {
SelectionType::Block => {
// Rectangle selection
let min_col = start.col.min(end.col);
let max_col = start.col.max(end.col);
let min_row = start.row.min(end.row);
let max_row = start.row.max(end.row);
for row in min_row..=max_row {
for col in min_col..=max_col {
if let Some(c) = Self::get_cell_at_absolute(&grid, col, row, scrollback_len)
{
result.push(c);
}
}
if row < max_row {
result.push('\n');
}
}
}
_ => {
// Linear selection (character, word, line)
if start.row == end.row {
// Single line
for col in start.col..=end.col {
if let Some(c) =
Self::get_cell_at_absolute(&grid, col, start.row, scrollback_len)
{
result.push(c);
}
}
} else {
// Multiple lines
// First line (from start.col to end of line)
let content_width = self.window.width.saturating_sub(4); // -2 left, -2 right
for col in start.col..content_width {
if let Some(c) =
Self::get_cell_at_absolute(&grid, col, start.row, scrollback_len)
{
result.push(c);
}
}
result.push('\n');
// Middle lines (full lines)
for row in (start.row + 1)..end.row {
for col in 0..content_width {
if let Some(c) =
Self::get_cell_at_absolute(&grid, col, row, scrollback_len)
{
result.push(c);
}
}
result.push('\n');
}
// Last line (from start to end.col)
for col in 0..=end.col {
if let Some(c) =
Self::get_cell_at_absolute(&grid, col, end.row, scrollback_len)
{
result.push(c);
}
}
}
}
}
// Clean up trailing spaces and return
let result = result.trim_end().to_string();
if result.is_empty() {
None
} else {
Some(result)
}
}
/// Paste text to terminal (with bracketed paste mode support)
/// In Remote mode, this is a no-op (WindowManager routes via daemon)
pub fn paste_text(&mut self, text: &str) -> std::io::Result<()> {
match &mut self.mode {
EmulatorMode::Local(emu) => emu.send_paste(text),
EmulatorMode::Remote { .. } => Ok(()),
}
}
/// Check if there's an active selection
pub fn has_selection(&self) -> bool {
self.selection.is_some()
}
/// Get the content area bounds (for hit testing)
#[allow(dead_code)]
pub fn get_content_bounds(&self) -> (u16, u16, u16, u16) {
let content_x = self.window.x + 2; // After 2-char left border
let content_y = self.window.y + 1; // After title bar
let content_width = self.window.width.saturating_sub(4); // -2 left, -2 right
let content_height = self.window.height.saturating_sub(2); // -1 title, -1 bottom
(content_x, content_y, content_width, content_height)
}
/// Set scroll offset (for session restoration)
pub fn set_scroll_offset(&mut self, offset: usize) {
self.scroll_offset = offset;
}
/// Extract terminal content for session persistence
pub fn get_terminal_content(
&self,
) -> (
Vec<crate::app::session::SerializableTerminalLine>,
crate::app::session::SerializableCursor,
) {
match &self.mode {
EmulatorMode::Local(emu) => emu.get_terminal_content(),
EmulatorMode::Remote { .. } => {
// Remote mode: return empty content (daemon owns the data)
(
Vec::new(),
crate::app::session::SerializableCursor {
x: 0,
y: 0,
visible: true,
shape: crate::app::session::SerializableCursorShape::Block,
},
)
}
}
}
/// Restore terminal content from session
pub fn restore_terminal_content(
&mut self,
lines: Vec<crate::app::session::SerializableTerminalLine>,
cursor: &crate::app::session::SerializableCursor,
) {
if let EmulatorMode::Local(emu) = &mut self.mode {
emu.restore_terminal_content(lines, cursor);
}
}
/// Get the name of the foreground process running in the terminal
pub fn get_foreground_process_name(&self) -> Option<String> {
match &self.mode {
EmulatorMode::Local(emu) => emu.get_foreground_process_name(),
EmulatorMode::Remote { .. } => None,
}
}
/// Get the cached foreground process name, updating cache every 500ms
/// This avoids spawning ps processes every frame (60fps = 60 times/second)
fn get_foreground_process_name_cached(&mut self) -> Option<String> {
use std::time::Duration;
// Update cache every 500ms (2 times per second instead of 60)
let elapsed = self.process_name_last_update.elapsed();
if elapsed >= Duration::from_millis(500) || self.cached_process_name.is_none() {
self.cached_process_name = self.get_foreground_process_name();
self.process_name_last_update = Instant::now();
}
self.cached_process_name.clone()
}
/// Get the dynamic title including the running process name (with caching)
/// Format: "Terminal N [ > process ]" where > is a running indicator
fn get_dynamic_title_cached(&mut self) -> String {
if let Some(process_name) = self.get_foreground_process_name_cached() {
// Use '>' as an ASCII-compatible "running" indicator with spacing
format!("{} [ > {} ]", self.window.title, process_name)
} else {
self.window.title.clone()
}
}
/// Get the dynamic title including the running process name
/// Format: "Terminal N [ > process ]" where > is a running indicator
#[allow(dead_code)]
pub fn get_dynamic_title(&self) -> String {
if let Some(process_name) = self.get_foreground_process_name() {
// Use '>' as an ASCII-compatible "running" indicator with spacing
format!("{} [ > {} ]", self.window.title, process_name)
} else {
self.window.title.clone()
}
}
/// Update the window's display title with process info
#[allow(dead_code)]
pub fn update_title_with_process(&mut self) {
// Store the base title if not already stored
if !self.window.title.contains(" [>") {
// Title is still the base title, keep it
}
}
/// Get the base title (without process info)
#[allow(dead_code)]
pub fn get_base_title(&self) -> &str {
// If the title contains process info, extract base title
if let Some(idx) = self.window.title.find(" [>") {
&self.window.title[..idx]
} else {
&self.window.title
}
}
/// Get application cursor keys mode state (DECCKM)
pub fn get_application_cursor_keys(&self) -> bool {
let grid = self.grid_arc();
let grid = grid.lock().unwrap();
grid.application_cursor_keys
}
/// Handle keyboard input for close confirmation dialog
/// Returns Some(true) if should close, Some(false) if canceled, None if not handled
pub fn handle_close_confirmation_key(&mut self, key: KeyEvent) -> Option<bool> {
let confirmation = self.pending_close_confirmation.as_mut()?;
match key.code {
KeyCode::Left | KeyCode::Char('h') => {
confirmation.prompt.select_previous_button();
None // Just update UI, don't trigger action
}
KeyCode::Right | KeyCode::Char('l') | KeyCode::Tab => {
confirmation.prompt.select_next_button();
None // Just update UI, don't trigger action
}
KeyCode::Enter => {
let action = confirmation.prompt.get_selected_action();
self.pending_close_confirmation = None;
Some(matches!(action, Some(PromptAction::Confirm)))
}
KeyCode::Esc | KeyCode::Char('q') => {
self.pending_close_confirmation = None;
Some(false) // Cancel
}
_ => None, // Ignore other keys
}
}
/// Handle mouse click for close confirmation dialog
/// Returns Some(true) if should close, Some(false) if canceled, None if not in dialog
pub fn handle_close_confirmation_click(
&mut self,
x: u16,
y: u16,
charset: &Charset,
) -> Option<bool> {
let confirmation = self.pending_close_confirmation.as_ref()?;
// Check if click is within dialog bounds
if !confirmation.prompt.contains_point(x, y) {
return None; // Click outside dialog
}
// Check if click is on a button
if let Some(action) = confirmation.prompt.handle_click(x, y, charset) {
self.pending_close_confirmation = None;
Some(matches!(action, PromptAction::Confirm))
} else {
None // Click inside dialog but not on a button
}
}
/// Get all mouse tracking state with a single mutex lock acquisition
/// This is more efficient than separate calls that each acquire the lock
fn get_mouse_tracking_state(&self) -> MouseTrackingState {
let grid = self.grid_arc();
let grid = grid.lock().unwrap();
MouseTrackingState {
tracking_enabled: grid.mouse_normal_tracking
|| grid.mouse_button_tracking
|| grid.mouse_any_event_tracking,
button_tracking: grid.mouse_button_tracking || grid.mouse_any_event_tracking,
sgr_mode: grid.mouse_sgr_mode,
urxvt_mode: grid.mouse_urxvt_mode,
}
}
/// Check if the terminal has mouse tracking enabled
/// Returns true if the child process has requested mouse events
pub fn has_mouse_tracking_enabled(&self) -> bool {
let grid = self.grid_arc();
let grid = grid.lock().unwrap();
grid.mouse_normal_tracking || grid.mouse_button_tracking || grid.mouse_any_event_tracking
}
/// Convert screen coordinates to terminal-relative coordinates
/// Returns None if the point is outside the content area
pub fn screen_to_terminal_coords(&self, screen_x: u16, screen_y: u16) -> Option<(u16, u16)> {
// Content area starts after 2-char left border and title bar
let content_x = self.window.x + 2;
let content_y = self.window.y + 1;
// Content area ends before 2-char right border and bottom border
// But we need to account for the scrollbar on the right side
let content_width = self.window.width.saturating_sub(5); // -2 left, -2 right, -1 scrollbar
let content_height = self.window.height.saturating_sub(2); // -1 title, -1 bottom
// Check if point is within content area
if screen_x >= content_x
&& screen_x < content_x + content_width
&& screen_y >= content_y
&& screen_y < content_y + content_height
{
let term_x = screen_x - content_x;
let term_y = screen_y - content_y;
Some((term_x, term_y))
} else {
None
}
}
/// Send a mouse event to the terminal using pre-fetched tracking state
/// Uses stack-allocated buffer to avoid heap allocation in hot path
/// button: 0=left, 1=middle, 2=right, 3=release, 64=scroll up, 65=scroll down
/// action: 0=press, 1=release, 2=drag/motion
/// term_x, term_y: 0-indexed terminal coordinates
fn send_mouse_event_with_state(
&mut self,
state: &MouseTrackingState,
button: u8,
action: u8,
term_x: u16,
term_y: u16,
) -> std::io::Result<()> {
// Terminal coordinates are 1-indexed for mouse reporting
let x = term_x + 1;
let y = term_y + 1;
// Stack-allocated buffer - 24 bytes is sufficient for any mouse sequence
// SGR max: \x1b[<999;999;999M = ~18 bytes
// URXVT max: \x1b[999;999;999M = ~17 bytes
// Normal: \x1b[Mccc = 6 bytes
let mut buf = [0u8; 24];
let len = if state.sgr_mode {
// SGR extended mouse mode (CSI < Cb ; Cx ; Cy M/m)
// Cb = button number (0-2 for press, +32 for motion)
// M for press, m for release
let cb = match action {
1 => button, // release
2 => button + 32, // motion/drag
_ => button, // press
};
let suffix = if action == 1 { b'm' } else { b'M' };
// Write escape sequence manually to avoid format! allocation
let mut pos = 0;
buf[pos..pos + 3].copy_from_slice(b"\x1b[<");
pos += 3;
pos += write_u16_to_buf(&mut buf[pos..], cb as u16);
buf[pos] = b';';
pos += 1;
pos += write_u16_to_buf(&mut buf[pos..], x);
buf[pos] = b';';
pos += 1;
pos += write_u16_to_buf(&mut buf[pos..], y);
buf[pos] = suffix;
pos + 1
} else if state.urxvt_mode {
// URXVT mouse mode (CSI Cb ; Cx ; Cy M)
// Cb = 32 + button + modifiers
let cb = 32
+ match action {
1 => 3, // release (button 3 means release)
2 => button + 32, // motion
_ => button, // press
};
let mut pos = 0;
buf[pos..pos + 2].copy_from_slice(b"\x1b[");
pos += 2;
pos += write_u16_to_buf(&mut buf[pos..], cb as u16);
buf[pos] = b';';
pos += 1;
pos += write_u16_to_buf(&mut buf[pos..], x);
buf[pos] = b';';
pos += 1;
pos += write_u16_to_buf(&mut buf[pos..], y);
buf[pos] = b'M';
pos + 1
} else {
// Normal X10/X11 mouse mode (CSI M Cb Cx Cy)
// Cb = 32 + button, Cx/Cy = 32 + coordinate
// Coordinates are limited to 223 (255-32)
let cb = 32
+ match action {
1 => 3, // release
2 => button + 32, // motion
_ => button, // press
};
buf[0..3].copy_from_slice(b"\x1b[M");
buf[3] = cb;
buf[4] = (32 + x.min(223)) as u8;
buf[5] = (32 + y.min(223)) as u8;
6
};
match &mut self.mode {
EmulatorMode::Local(emu) => emu.write_input(&buf[..len]),
EmulatorMode::Remote { .. } => {
// Buffer bytes for WindowManager to forward to daemon
self.pending_remote_bytes.extend_from_slice(&buf[..len]);
Ok(())
}
}
}
/// Handle a mouse event from the parent application
/// Returns true if the event was consumed (forwarded to terminal)
pub fn handle_mouse_for_terminal(
&mut self,
screen_x: u16,
screen_y: u16,
button: u8,
action: u8,
) -> bool {
// Get all mouse tracking state with a single mutex lock
let state = self.get_mouse_tracking_state();
// Check if this terminal wants mouse events
if !state.tracking_enabled {
return false;
}
// For motion events, check if motion tracking is enabled
if action == 2 && !state.button_tracking {
return false;
}
// Convert to terminal coordinates
if let Some((term_x, term_y)) = self.screen_to_terminal_coords(screen_x, screen_y) {
// Send the event using pre-fetched state (no additional lock needed)
if self
.send_mouse_event_with_state(&state, button, action, term_x, term_y)
.is_ok()
{
return true;
}
}
false
}
}
/// Write a u16 value as decimal ASCII to a buffer, returning bytes written
/// This avoids format! allocation for number formatting
#[inline]
fn write_u16_to_buf(buf: &mut [u8], value: u16) -> usize {
if value == 0 {
buf[0] = b'0';
return 1;
}
let mut n = value;
let mut digits = [0u8; 5]; // u16 max is 65535 = 5 digits
let mut len = 0;
while n > 0 {
digits[len] = b'0' + (n % 10) as u8;
n /= 10;
len += 1;
}
// Reverse digits into buffer
for i in 0..len {
buf[i] = digits[len - 1 - i];
}
len
}
/// Convert a terminal cell to a video buffer cell
fn convert_terminal_cell(term_cell: &TerminalCell, theme: &Theme, tint_terminal: bool) -> Cell {
let mut fg = convert_fg_color(&term_cell.fg);
let mut bg = convert_bg_color(&term_cell.bg);
// Handle reverse video attribute - swap fg and bg
if term_cell.attrs.reverse {
std::mem::swap(&mut fg, &mut bg);
}
// Apply theme-based tinting if enabled
if tint_terminal {
fg = apply_theme_tint(fg, theme, true);
bg = apply_theme_tint(bg, theme, false);
}
// Use unchecked cell creation - theme tints are pre-designed with contrast in mind
Cell::new_unchecked(term_cell.c, fg, bg)
}
/// Convert terminal color to crossterm color for foreground
fn convert_fg_color(color: &TermColor) -> Color {
match color {
// Default foreground: light grey (standard terminal default)
TermColor::Default => Color::Grey,
TermColor::Named(named) => convert_named_color(named),
TermColor::Indexed(idx) => Color::AnsiValue(*idx),
TermColor::Rgb(r, g, b) => Color::Rgb {
r: *r,
g: *g,
b: *b,
},
}
}
/// Convert terminal color to crossterm color for background
fn convert_bg_color(color: &TermColor) -> Color {
match color {
// Default background: black (standard terminal default)
TermColor::Default => Color::Black,
TermColor::Named(named) => convert_named_color(named),
TermColor::Indexed(idx) => Color::AnsiValue(*idx),
TermColor::Rgb(r, g, b) => Color::Rgb {
r: *r,
g: *g,
b: *b,
},
}
}
/// Convert named ANSI color to crossterm color
fn convert_named_color(named: &NamedColor) -> Color {
match named {
NamedColor::Black => Color::Black,
NamedColor::Red => Color::DarkRed,
NamedColor::Green => Color::DarkGreen,
NamedColor::Yellow => Color::DarkYellow,
NamedColor::Blue => Color::DarkBlue,
NamedColor::Magenta => Color::DarkMagenta,
NamedColor::Cyan => Color::DarkCyan,
NamedColor::White => Color::Grey,
NamedColor::BrightBlack => Color::DarkGrey,
NamedColor::BrightRed => Color::Red,
NamedColor::BrightGreen => Color::Green,
NamedColor::BrightYellow => Color::Yellow,
NamedColor::BrightBlue => Color::Blue,
NamedColor::BrightMagenta => Color::Magenta,
NamedColor::BrightCyan => Color::Cyan,
NamedColor::BrightWhite => Color::White,
}
}
/// Apply theme-based color tinting to terminal colors
fn apply_theme_tint(color: Color, theme: &Theme, is_foreground: bool) -> Color {
// Map terminal colors to theme colors
match color {
// Reset/default colors - map to theme defaults
Color::Reset => {
if is_foreground {
theme.window_content_fg
} else {
theme.window_content_bg
}
}
// Background colors - map to theme background
Color::Black | Color::DarkGrey if !is_foreground => theme.window_content_bg,
// Foreground colors - map to theme foreground variations
Color::Black | Color::DarkGrey if is_foreground => {
// Dark colors map to a darker version of foreground
darken_color(theme.window_content_fg, 0.6)
}
// Bright colors - keep as foreground
Color::White | Color::Grey => theme.window_content_fg,
// Red colors - map to theme button close or a red-ish tint
Color::Red | Color::DarkRed => theme.button_close_color,
// Green colors - map to theme button maximize or a green-ish tint
Color::Green | Color::DarkGreen => theme.button_maximize_color,
// Yellow colors - improve contrast for monochrome theme
Color::Yellow | Color::DarkYellow => {
// Monochrome uses DarkGrey which has poor contrast on Black
// Use Grey instead for better visibility
match theme.button_minimize_color {
Color::DarkGrey => Color::Grey,
_ => theme.button_minimize_color,
}
}
// Blue colors - use border color for visibility (avoid mapping to Black)
// This ensures blue text is visible across all themes
Color::Blue | Color::DarkBlue => theme.window_border_unfocused_fg,
// Cyan colors - map to content foreground for differentiation from blue
Color::Cyan | Color::DarkCyan => theme.window_content_fg,
// Magenta colors - map to a magenta-ish variation
Color::Magenta | Color::DarkMagenta => theme.resize_handle_active_fg,
// RGB colors - apply a theme-based tint transformation
Color::Rgb { r, g, b } => {
if is_foreground {
// For foreground, blend with theme foreground color
// Use 0.3 blend factor: 30% original color, 70% theme color for strong tinting
blend_with_theme_color(Color::Rgb { r, g, b }, theme.window_content_fg, 0.3)
} else {
// For background, blend with theme background color
// Use 0.3 blend factor: 30% original color, 70% theme color for strong tinting
blend_with_theme_color(Color::Rgb { r, g, b }, theme.window_content_bg, 0.3)
}
}
// Indexed colors (256-color palette)
Color::AnsiValue(idx) => {
// Map 256-color palette to theme colors based on brightness
if idx < 8 {
// Standard colors (0-7): map to theme colors
match idx {
0 => theme.window_content_bg, // Black
1 => theme.button_close_color, // Red
2 => theme.button_maximize_color, // Green
3 => {
// Yellow - improve contrast for monochrome theme
match theme.button_minimize_color {
Color::DarkGrey => Color::Grey,
_ => theme.button_minimize_color,
}
}
4 => theme.window_border_unfocused_fg, // Blue - use border for visibility
5 => theme.resize_handle_active_fg, // Magenta
6 => theme.window_content_fg, // Cyan - differentiate from blue
7 => theme.window_content_fg, // White
_ => color,
}
} else if idx < 16 {
// Bright colors (8-15): map to brighter theme variations
theme.window_content_fg
} else {
// Extended colors: blend with theme
if is_foreground {
theme.window_content_fg
} else {
theme.window_content_bg
}
}
}
// Catch-all: tint any unhandled colors to prevent full-brightness rendering
// This ensures consistent tinting across all color types
_ => {
if is_foreground {
theme.window_content_fg
} else {
theme.window_content_bg
}
}
}
}
/// Darken a color by a factor (0.0 = black, 1.0 = original)
fn darken_color(color: Color, factor: f32) -> Color {
match color {
Color::Rgb { r, g, b } => Color::Rgb {
r: (r as f32 * factor) as u8,
g: (g as f32 * factor) as u8,
b: (b as f32 * factor) as u8,
},
_ => color,
}
}
/// Blend a color with a theme color
fn blend_with_theme_color(original: Color, theme_color: Color, blend_factor: f32) -> Color {
// Convert both colors to RGB for blending
let (r1, g1, b1) = color_to_rgb(original);
let (r2, g2, b2) = color_to_rgb(theme_color);
Color::Rgb {
r: (r1 as f32 * blend_factor + r2 as f32 * (1.0 - blend_factor)) as u8,
g: (g1 as f32 * blend_factor + g2 as f32 * (1.0 - blend_factor)) as u8,
b: (b1 as f32 * blend_factor + b2 as f32 * (1.0 - blend_factor)) as u8,
}
}
/// Convert any Color to RGB values
fn color_to_rgb(color: Color) -> (u8, u8, u8) {
match color {
Color::Rgb { r, g, b } => (r, g, b),
Color::Black => (0, 0, 0),
Color::DarkGrey => (128, 128, 128),
Color::Red => (255, 0, 0),
Color::DarkRed => (128, 0, 0),
Color::Green => (0, 255, 0),
Color::DarkGreen => (0, 128, 0),
Color::Yellow => (255, 255, 0),
Color::DarkYellow => (128, 128, 0),
Color::Blue => (0, 0, 255),
Color::DarkBlue => (0, 0, 128),
Color::Magenta => (255, 0, 255),
Color::DarkMagenta => (128, 0, 128),
Color::Cyan => (0, 255, 255),
Color::DarkCyan => (0, 128, 128),
Color::White => (255, 255, 255),
Color::Grey => (192, 192, 192),
// For indexed colors, use approximate RGB values
Color::AnsiValue(idx) => ansi_to_rgb(idx),
// Default to white for reset and unknown
_ => (255, 255, 255),
}
}
/// Convert ANSI 256-color palette index to approximate RGB
fn ansi_to_rgb(idx: u8) -> (u8, u8, u8) {
match idx {
// Standard 16 colors (0-15)
0 => (0, 0, 0), // Black
1 => (128, 0, 0), // Dark Red
2 => (0, 128, 0), // Dark Green
3 => (128, 128, 0), // Dark Yellow
4 => (0, 0, 128), // Dark Blue
5 => (128, 0, 128), // Dark Magenta
6 => (0, 128, 128), // Dark Cyan
7 => (192, 192, 192), // Grey
8 => (128, 128, 128), // Dark Grey
9 => (255, 0, 0), // Red
10 => (0, 255, 0), // Green
11 => (255, 255, 0), // Yellow
12 => (0, 0, 255), // Blue
13 => (255, 0, 255), // Magenta
14 => (0, 255, 255), // Cyan
15 => (255, 255, 255), // White
// 216-color cube (16-231): 6x6x6 RGB cube
16..=231 => {
let idx = idx - 16;
let r = (idx / 36) % 6;
let g = (idx / 6) % 6;
let b = idx % 6;
(
if r > 0 { 55 + r * 40 } else { 0 },
if g > 0 { 55 + g * 40 } else { 0 },
if b > 0 { 55 + b * 40 } else { 0 },
)
}
// Grayscale ramp (232-255): 24 shades of gray
232..=255 => {
let gray = 8 + (idx - 232) * 10;
(gray, gray, gray)
}
}
}