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
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
#![allow(clippy::collapsible_if)]
mod ansi_handler;
mod button;
mod charset;
mod cli;
mod clipboard_manager;
mod config;
mod config_manager;
mod config_window;
mod context_menu;
#[cfg(target_os = "linux")]
mod gpm_handler;
mod info_window;
mod prompt;
mod selection;
mod term_grid;
mod terminal_emulator;
mod terminal_window;
mod theme;
mod video_buffer;
mod window;
mod window_manager;
use button::Button;
use charset::Charset;
use chrono::{Datelike, Local, NaiveDate};
use clipboard_manager::ClipboardManager;
use config_manager::AppConfig;
use config_window::{ConfigAction, ConfigWindow};
use context_menu::{ContextMenu, MenuAction};
use crossterm::{
cursor,
event::{self, Event, KeyCode, KeyModifiers, MouseButton, MouseEventKind},
execute,
style::Color,
terminal::{self, ClearType},
};
use info_window::InfoWindow;
use prompt::{Prompt, PromptAction, PromptButton, PromptType};
use selection::SelectionType;
use std::io::{self, Write};
use std::time::{Duration, Instant};
use std::{thread, time};
use theme::Theme;
use video_buffer::{Cell, VideoBuffer};
use window_manager::{FocusState, WindowManager};
// Calendar state structure
struct CalendarState {
year: i32,
month: u32,
today: NaiveDate,
}
impl CalendarState {
fn new() -> Self {
let today = Local::now().date_naive();
Self {
year: today.year(),
month: today.month(),
today,
}
}
fn next_month(&mut self) {
if self.month == 12 {
self.month = 1;
self.year += 1;
} else {
self.month += 1;
}
}
fn previous_month(&mut self) {
if self.month == 1 {
self.month = 12;
self.year -= 1;
} else {
self.month -= 1;
}
}
fn next_year(&mut self) {
self.year += 1;
}
fn previous_year(&mut self) {
self.year -= 1;
}
fn reset_to_today(&mut self) {
self.year = self.today.year();
self.month = self.today.month();
}
fn month_name(&self) -> &'static str {
match self.month {
1 => "January",
2 => "February",
3 => "March",
4 => "April",
5 => "May",
6 => "June",
7 => "July",
8 => "August",
9 => "September",
10 => "October",
11 => "November",
12 => "December",
_ => "Unknown",
}
}
}
fn main() -> io::Result<()> {
// Parse command-line arguments
let cli_args = cli::Cli::parse_args();
// Create charset based on CLI arguments
let mut charset = if cli_args.ascii {
Charset::ascii()
} else {
Charset::unicode()
};
// Load application configuration
let mut app_config = AppConfig::load();
// Set the background character from config
charset.set_background(app_config.get_background_char());
// Use theme from CLI args (takes precedence over config)
let theme_name = &cli_args.theme;
let mut theme = Theme::from_name(theme_name);
let mut stdout = io::stdout();
// Enter raw mode for low-level terminal control
terminal::enable_raw_mode()?;
// Hide cursor and enable mouse capture
execute!(stdout, cursor::Hide, event::EnableMouseCapture)?;
// Initialize GPM (General Purpose Mouse) for Linux console if available
#[cfg(target_os = "linux")]
let gpm_connection = gpm_handler::GpmConnection::open();
// Clear the screen
execute!(stdout, terminal::Clear(ClearType::All))?;
// Initialize video buffer
let (cols, rows) = terminal::size()?;
let mut video_buffer = VideoBuffer::new(cols, rows);
// Initialize window manager
let mut window_manager = WindowManager::new();
// Create the "New Terminal" button
let mut new_terminal_button = Button::new(1, 0, "+New Terminal".to_string());
// Create clipboard-related buttons (centered in top bar)
let (initial_cols, initial_rows) = terminal::size()?;
// Paste button
let paste_label = "Paste".to_string();
let paste_button_width = (paste_label.len() as u16) + 4; // "[ Label ]"
let paste_x = (initial_cols.saturating_sub(paste_button_width + 5)) / 2; // +5 for [ X ] button
let mut paste_button = Button::new(paste_x, 0, paste_label);
// Clear clipboard button (X)
let clear_label = "X".to_string();
let mut clear_clipboard_button = Button::new(paste_x + paste_button_width, 0, clear_label);
// Copy button (shows when text is selected)
let copy_label = "Copy".to_string();
let mut copy_button = Button::new(0, 0, copy_label);
// Clear selection button (X) (shows when text is selected)
let clear_selection_label = "X".to_string();
let mut clear_selection_button = Button::new(0, 0, clear_selection_label);
// Auto-tiling toggle state and button (initialized from config)
// Button is on bottom bar (rows - 1), left side
let mut auto_tiling_enabled = app_config.auto_tiling_on_startup;
let auto_tiling_text = if auto_tiling_enabled {
"â–ˆ on] Auto Tiling"
} else {
"off â–‘] Auto Tiling"
};
let mut auto_tiling_button = Button::new(1, initial_rows - 1, auto_tiling_text.to_string());
// Terminal tinting toggle state (initialized from CLI args)
let mut tint_terminal = cli_args.tint_terminal;
// Prompt state (None when no prompt is active)
let mut active_prompt: Option<Prompt> = None;
// Calendar state (None when calendar is not shown)
let mut active_calendar: Option<CalendarState> = None;
// Config window state (None when not shown)
let mut active_config_window: Option<ConfigWindow> = None;
// Help window state (None when not shown)
let mut active_help_window: Option<InfoWindow> = None;
// About window state (None when not shown)
let mut active_about_window: Option<InfoWindow> = None;
// Clipboard manager
let mut clipboard_manager = ClipboardManager::new();
// Context menu state (None when not shown)
let mut context_menu = ContextMenu::new(0, 0);
// Selection state
let mut selection_active = false;
let mut last_click_time: Option<Instant> = None;
let mut click_count = 0;
// Show splash screen for 1 second
show_splash_screen(&mut video_buffer, &mut stdout, &charset, &theme)?;
// Start with desktop focused - no windows yet
// User can press 't' to create windows
// Main loop
loop {
// Get current terminal size
let (cols, rows) = terminal::size()?;
// Check if terminal was resized and recreate buffer if needed
let (buffer_cols, buffer_rows) = video_buffer.dimensions();
if cols != buffer_cols || rows != buffer_rows {
// Clear the terminal screen to remove artifacts
execute!(stdout, terminal::Clear(ClearType::All))?;
video_buffer = VideoBuffer::new(cols, rows);
}
// Render the background (every frame for consistency)
render_background(&mut video_buffer, &charset, &theme);
// Update clipboard buttons state and position
let has_clipboard_content = clipboard_manager.has_content();
let has_selection = window_manager.focused_window_has_meaningful_selection();
paste_button.enabled = has_clipboard_content;
clear_clipboard_button.enabled = has_clipboard_content;
copy_button.enabled = has_selection;
clear_selection_button.enabled = has_selection;
// Calculate button positions (centered)
let paste_width = paste_button.width();
let clear_clip_width = clear_clipboard_button.width();
let copy_width = copy_button.width();
let clear_sel_width = clear_selection_button.width();
// Position paste and clear clipboard buttons together in center
let paste_clear_total_width = paste_width + clear_clip_width;
let paste_x = (cols.saturating_sub(paste_clear_total_width)) / 2;
paste_button.x = paste_x;
clear_clipboard_button.x = paste_x + paste_width;
// Position copy and clear selection buttons
if has_selection && has_clipboard_content {
// Both visible: put copy[X] to the left of paste[X]
let copy_clear_sel_width = copy_width + clear_sel_width;
let total_width = copy_clear_sel_width + 1 + paste_clear_total_width; // +1 for gap
let start_x = (cols.saturating_sub(total_width)) / 2;
copy_button.x = start_x;
clear_selection_button.x = start_x + copy_width;
paste_button.x = start_x + copy_clear_sel_width + 1;
clear_clipboard_button.x = paste_button.x + paste_width;
} else if has_selection {
// Only copy[X] visible: center it
let copy_clear_sel_width = copy_width + clear_sel_width;
let start_x = (cols.saturating_sub(copy_clear_sel_width)) / 2;
copy_button.x = start_x;
clear_selection_button.x = start_x + copy_width;
}
// Render the top bar
let focus = window_manager.get_focus();
render_top_bar(
&mut video_buffer,
focus,
&new_terminal_button,
&paste_button,
&clear_clipboard_button,
©_button,
&clear_selection_button,
&app_config,
&theme,
);
// Render all windows (returns true if any were closed)
let windows_closed =
window_manager.render_all(&mut video_buffer, &charset, &theme, tint_terminal);
// Auto-reposition remaining windows if any were closed
if windows_closed && auto_tiling_enabled {
let (cols, rows) = terminal::size()?;
window_manager.auto_position_windows(cols, rows);
}
// Render snap preview overlay (if dragging and snap zone is active)
window_manager.render_snap_preview(&mut video_buffer, &charset, &theme);
// Render the button bar
render_button_bar(
&mut video_buffer,
&window_manager,
&auto_tiling_button,
auto_tiling_enabled,
&theme,
);
// Render active prompt (if any) on top of everything
if let Some(ref prompt) = active_prompt {
prompt.render(&mut video_buffer, &charset, &theme);
}
// Render active calendar (if any) on top of everything
if let Some(ref calendar) = active_calendar {
render_calendar(&mut video_buffer, calendar, &charset, &theme, cols, rows);
}
// Render active config window (if any) on top of everything
if let Some(ref config_win) = active_config_window {
config_win.render(
&mut video_buffer,
&charset,
&theme,
&app_config,
tint_terminal,
);
}
// Render active help window (if any)
if let Some(ref help_win) = active_help_window {
help_win.render(&mut video_buffer, &charset, &theme);
}
// Render active about window (if any)
if let Some(ref about_win) = active_about_window {
about_win.render(&mut video_buffer, &charset, &theme);
}
// Render context menu (if visible)
if context_menu.visible {
context_menu.render(&mut video_buffer, &charset);
}
// Present buffer to screen
video_buffer.present(&mut stdout)?;
stdout.flush()?;
// Check for GPM events first (Linux console mouse support)
#[cfg(target_os = "linux")]
let gpm_event = if let Some(ref gpm) = gpm_connection {
if gpm.has_event() {
gpm.get_event()
} else {
None
}
} else {
None
};
// Process GPM event if available
#[cfg(target_os = "linux")]
if let Some(gpm_evt) = gpm_event {
// Convert GPM event to crossterm MouseEvent format
use crossterm::event::{MouseButton, MouseEvent, MouseEventKind};
let mouse_event = match gpm_evt.event_type {
gpm_handler::GpmEventType::Down => {
let button = match gpm_evt.button {
Some(gpm_handler::GpmButton::Left) => MouseButton::Left,
Some(gpm_handler::GpmButton::Middle) => MouseButton::Middle,
Some(gpm_handler::GpmButton::Right) => MouseButton::Right,
None => MouseButton::Left,
};
MouseEvent {
kind: MouseEventKind::Down(button),
column: gpm_evt.x,
row: gpm_evt.y,
modifiers: KeyModifiers::empty(),
}
}
gpm_handler::GpmEventType::Up => {
let button = match gpm_evt.button {
Some(gpm_handler::GpmButton::Left) => MouseButton::Left,
Some(gpm_handler::GpmButton::Middle) => MouseButton::Middle,
Some(gpm_handler::GpmButton::Right) => MouseButton::Right,
None => MouseButton::Left,
};
MouseEvent {
kind: MouseEventKind::Up(button),
column: gpm_evt.x,
row: gpm_evt.y,
modifiers: KeyModifiers::empty(),
}
}
gpm_handler::GpmEventType::Drag => {
let button = match gpm_evt.button {
Some(gpm_handler::GpmButton::Left) => MouseButton::Left,
Some(gpm_handler::GpmButton::Middle) => MouseButton::Middle,
Some(gpm_handler::GpmButton::Right) => MouseButton::Right,
None => MouseButton::Left,
};
MouseEvent {
kind: MouseEventKind::Drag(button),
column: gpm_evt.x,
row: gpm_evt.y,
modifiers: KeyModifiers::empty(),
}
}
gpm_handler::GpmEventType::Move => MouseEvent {
kind: MouseEventKind::Moved,
column: gpm_evt.x,
row: gpm_evt.y,
modifiers: KeyModifiers::empty(),
},
};
// Process the mouse event (reuse existing mouse handling code)
// For now, we'll just pass it to the window manager
// This duplicates the mouse handling logic below, but we'll refactor it later
if active_prompt.is_none() {
let window_closed =
window_manager.handle_mouse_event(&mut video_buffer, mouse_event);
if window_closed && auto_tiling_enabled {
let (cols, rows) = terminal::size()?;
window_manager.auto_position_windows(cols, rows);
}
}
// Continue to next frame to avoid processing crossterm events in same frame
continue;
}
// Check for input (non-blocking with ~60fps)
if event::poll(Duration::from_millis(16))? {
match event::read()? {
Event::Key(key_event) => {
let current_focus = window_manager.get_focus();
// Handle prompt keyboard navigation if a prompt is active
if let Some(ref mut prompt) = active_prompt {
match key_event.code {
KeyCode::Tab => {
// Tab or Shift+Tab to navigate buttons
if key_event.modifiers.contains(KeyModifiers::SHIFT) {
prompt.select_previous_button();
} else {
prompt.select_next_button();
}
continue;
}
KeyCode::Left => {
// Left arrow - previous button
prompt.select_previous_button();
continue;
}
KeyCode::Right => {
// Right arrow - next button
prompt.select_next_button();
continue;
}
KeyCode::Enter => {
// Enter - activate selected button
if let Some(action) = prompt.get_selected_action() {
match action {
PromptAction::Confirm => {
// Exit confirmed
break;
}
PromptAction::Cancel => {
// Dismiss prompt
active_prompt = None;
}
_ => {}
}
}
continue;
}
KeyCode::Esc => {
// ESC dismisses the prompt
active_prompt = None;
continue;
}
_ => {
// Ignore other keys when prompt is active
continue;
}
}
}
// Handle calendar keyboard navigation if calendar is active
if let Some(ref mut calendar) = active_calendar {
match key_event.code {
KeyCode::Char('<') | KeyCode::Char(',') | KeyCode::Left => {
// Previous month
calendar.previous_month();
continue;
}
KeyCode::Char('>') | KeyCode::Char('.') | KeyCode::Right => {
// Next month
calendar.next_month();
continue;
}
KeyCode::Up => {
// Previous year
calendar.previous_year();
continue;
}
KeyCode::Down => {
// Next year
calendar.next_year();
continue;
}
KeyCode::Char('t') | KeyCode::Home => {
// Reset to today
calendar.reset_to_today();
continue;
}
KeyCode::Esc => {
// ESC dismisses the calendar
active_calendar = None;
continue;
}
_ => {
// Ignore other keys when calendar is active
continue;
}
}
}
// Handle help window keyboard events if help window is active
if active_help_window.is_some() {
match key_event.code {
KeyCode::Esc => {
// ESC dismisses the help window
active_help_window = None;
continue;
}
_ => {
// Ignore other keys when help window is active
continue;
}
}
}
// Handle about window keyboard events if about window is active
if active_about_window.is_some() {
match key_event.code {
KeyCode::Esc => {
// ESC dismisses the about window
active_about_window = None;
continue;
}
_ => {
// Ignore other keys when about window is active
continue;
}
}
}
// Handle config window keyboard events if config window is active
if active_config_window.is_some() {
match key_event.code {
KeyCode::Esc => {
// ESC dismisses the config window
active_config_window = None;
continue;
}
_ => {
// Ignore other keys when config window is active
continue;
}
}
}
// Handle ALT+TAB for window cycling
if key_event.code == KeyCode::Tab
&& key_event.modifiers.contains(KeyModifiers::ALT)
{
window_manager.cycle_to_next_window();
continue;
}
// Handle CTRL+L to clear the terminal (like 'clear' command)
// Check for both Ctrl+L and the control character form
if key_event.code == KeyCode::Char('l')
&& key_event.modifiers.contains(KeyModifiers::CONTROL)
{
if current_focus != FocusState::Desktop {
// Send Ctrl+L (form feed, 0x0c) to the shell
// Most shells (bash, zsh, etc.) interpret this as "clear screen"
let _ = window_manager.send_to_focused("\x0c");
}
continue;
}
// Handle Ctrl+Shift+C to copy selection
if key_event.code == KeyCode::Char('C')
&& key_event.modifiers.contains(KeyModifiers::CONTROL)
&& key_event.modifiers.contains(KeyModifiers::SHIFT)
{
if let FocusState::Window(window_id) = current_focus {
if let Some(text) = window_manager.get_selected_text(window_id) {
if clipboard_manager.copy(text).is_ok() {
// Clear selection after copying
window_manager.clear_selection(window_id);
}
}
}
continue;
}
// Handle Ctrl+Shift+V to paste
if key_event.code == KeyCode::Char('V')
&& key_event.modifiers.contains(KeyModifiers::CONTROL)
&& key_event.modifiers.contains(KeyModifiers::SHIFT)
{
if let FocusState::Window(window_id) = current_focus {
if let Ok(text) = clipboard_manager.paste() {
let _ = window_manager.paste_to_window(window_id, &text);
// Clear selection after paste
window_manager.clear_selection(window_id);
}
}
continue;
}
match key_event.code {
KeyCode::Esc => {
// ESC exits only from desktop (prompts are handled above)
if current_focus == FocusState::Desktop {
// If windows are open, show confirmation
if window_manager.window_count() > 0 {
let (cols, rows) = terminal::size()?;
active_prompt = Some(Prompt::new(
PromptType::Danger,
"Exit with open windows?\nAll terminal sessions will be closed.".to_string(),
vec![
PromptButton::new("Exit".to_string(), PromptAction::Confirm, true),
PromptButton::new("Cancel".to_string(), PromptAction::Cancel, false),
],
cols,
rows,
));
} else {
// No windows open, just exit
break;
}
} else {
// Send ESC to terminal
let _ = window_manager.send_to_focused("\x1b");
}
}
KeyCode::Char('q') => {
// Only exit if desktop is focused (prompts are handled above)
if current_focus == FocusState::Desktop {
// If windows are open, show confirmation
if window_manager.window_count() > 0 {
let (cols, rows) = terminal::size()?;
active_prompt = Some(Prompt::new(
PromptType::Danger,
"Exit with open windows?\nAll terminal sessions will be closed.".to_string(),
vec![
PromptButton::new("Exit".to_string(), PromptAction::Confirm, true),
PromptButton::new("Cancel".to_string(), PromptAction::Cancel, false),
],
cols,
rows,
));
} else {
// No windows open, just exit
break;
}
} else {
// Send 'q' to terminal
let _ = window_manager.send_char_to_focused('q');
}
}
KeyCode::Char('h') => {
// Show help if desktop is focused (prompts are handled above)
if current_focus == FocusState::Desktop {
let (cols, rows) = terminal::size()?;
let help_message = "{C}KEYBOARD SHORTCUTS{W}\n\
\n\
{Y}'t'{W} - Create new terminal window\n\
{Y}'T'{W} - Create new maximized terminal window\n\
{Y}'q'/ESC{W} - Exit application (from desktop)\n\
{Y}'h'{W} - Show this help screen\n\
{Y}'l'{W} - Show license and about information\n\
{Y}'s'{W} - Show settings/configuration window\n\
{Y}'c'{W} - Show calendar ({Y}\u{2190}\u{2192}{W} months, {Y}\u{2191}\u{2193}{W} years, {Y}t{W} today)\n\
{Y}CTRL+L{W} - Clear terminal (like 'clear' command)\n\
{Y}ALT+TAB{W} - Switch between windows\n\
\n\
{C}POPUP DIALOG CONTROLS{W}\n\
\n\
{Y}TAB/Arrow keys{W} - Navigate between buttons\n\
{Y}ENTER{W} - Activate selected button\n\
{Y}ESC{W} - Close dialog\n\
\n\
{C}MOUSE CONTROLS{W}\n\
\n\
{Y}Click title bar{W} - Drag window\n\
{Y}CTRL+Drag{W} - Drag without snap\n\
{Y}Click [X]{W} - Close window\n\
{Y}Drag ╬ handle{W} - Resize window\n\
{Y}Click window{W} - Focus window\n\
{Y}Click bottom bar{W} - Switch windows";
active_help_window = Some(InfoWindow::new(
"Help".to_string(),
help_message,
cols,
rows,
));
} else if current_focus != FocusState::Desktop {
// Send 'h' to terminal
let _ = window_manager.send_char_to_focused('h');
}
}
KeyCode::Char('l') => {
// Show license and about if desktop is focused
if current_focus == FocusState::Desktop {
let (cols, rows) = terminal::size()?;
let license_message = format!(
"TERM39 - Terminal UI Windows Manager\n\
\n\
A low-level terminal UI windows manager built with Rust.\n\
\n\
Version: {}\n\
Author: {}\n\
Repository: {}\n\
\n\
LICENSE\n\
\n\
This software is licensed under the MIT License.\n\
See LICENSE file or visit the repository for details.\n\
\n\
BUILT WITH\n\
\n\
This project uses the following open source packages:\n\
\n\
- crossterm - Cross-platform terminal manipulation\n\
- portable-pty - Portable pseudo-terminal support\n\
- vte - Virtual terminal emulator parser\n\
- chrono - Date and time library\n\
\n\
All dependencies are used under their respective licenses.",
config::VERSION,
config::AUTHORS,
config::REPOSITORY
);
active_about_window = Some(InfoWindow::new(
"About".to_string(),
&license_message,
cols,
rows,
));
} else if current_focus != FocusState::Desktop {
// Send 'l' to terminal
let _ = window_manager.send_char_to_focused('l');
}
}
KeyCode::Char('c') => {
// Show calendar if desktop is focused
if current_focus == FocusState::Desktop {
active_calendar = Some(CalendarState::new());
} else if current_focus != FocusState::Desktop {
// Send 'c' to terminal
let _ = window_manager.send_char_to_focused('c');
}
}
KeyCode::Char('s') => {
// Show settings/config window if desktop is focused
if current_focus == FocusState::Desktop {
let (cols, rows) = terminal::size()?;
active_config_window = Some(ConfigWindow::new(cols, rows));
} else if current_focus != FocusState::Desktop {
// Send 's' to terminal
let _ = window_manager.send_char_to_focused('s');
}
}
KeyCode::Char('t') => {
// Only create new window if desktop is focused
if current_focus == FocusState::Desktop {
// Create a new terminal window
let (cols, rows) = terminal::size()?;
// Window size: 2.5x larger (60*2.5=150, 20*2.5=50)
let width = 150;
let height = 50;
// Center the window (ensuring y >= 1 to avoid overlapping top bar)
let x = (cols.saturating_sub(width)) / 2;
let y = ((rows.saturating_sub(height)) / 2).max(1);
window_manager.create_window(
x,
y,
width,
height,
format!("Terminal {}", window_manager.window_count() + 1),
);
// Auto-position all windows based on the snap pattern
if auto_tiling_enabled {
window_manager.auto_position_windows(cols, rows);
}
} else {
// Send 't' to terminal
let _ = window_manager.send_char_to_focused('t');
}
}
KeyCode::Char('T') => {
// Only create maximized window if desktop is focused
if current_focus == FocusState::Desktop {
// Create a new terminal window
let (cols, rows) = terminal::size()?;
// Window size: 2.5x larger (60*2.5=150, 20*2.5=50)
let width = 150;
let height = 50;
// Center the window (will be maximized immediately, ensuring y >= 1)
let x = (cols.saturating_sub(width)) / 2;
let y = ((rows.saturating_sub(height)) / 2).max(1);
let window_id = window_manager.create_window(
x,
y,
width,
height,
format!("Terminal {}", window_manager.window_count() + 1),
);
// Maximize the newly created window
window_manager.maximize_window(window_id, cols, rows);
} else {
// Send 'T' to terminal
let _ = window_manager.send_char_to_focused('T');
}
}
KeyCode::Char(c) => {
// Send character to focused terminal
if current_focus != FocusState::Desktop {
let _ = window_manager.send_char_to_focused(c);
}
}
KeyCode::Enter => {
if current_focus != FocusState::Desktop {
let _ = window_manager.send_to_focused("\r");
}
}
KeyCode::Backspace => {
if current_focus != FocusState::Desktop {
let _ = window_manager.send_to_focused("\x7f");
}
}
KeyCode::Tab => {
if current_focus != FocusState::Desktop {
let _ = window_manager.send_to_focused("\t");
}
}
KeyCode::Up => {
if current_focus != FocusState::Desktop {
let _ = window_manager.send_to_focused("\x1b[A");
}
}
KeyCode::Down => {
if current_focus != FocusState::Desktop {
let _ = window_manager.send_to_focused("\x1b[B");
}
}
KeyCode::Right => {
if current_focus != FocusState::Desktop {
let _ = window_manager.send_to_focused("\x1b[C");
}
}
KeyCode::Left => {
if current_focus != FocusState::Desktop {
let _ = window_manager.send_to_focused("\x1b[D");
}
}
KeyCode::Home => {
if current_focus != FocusState::Desktop {
let _ = window_manager.send_to_focused("\x1b[H");
}
}
KeyCode::End => {
if current_focus != FocusState::Desktop {
let _ = window_manager.send_to_focused("\x1b[F");
}
}
KeyCode::PageUp => {
if current_focus != FocusState::Desktop {
let _ = window_manager.send_to_focused("\x1b[5~");
}
}
KeyCode::PageDown => {
if current_focus != FocusState::Desktop {
let _ = window_manager.send_to_focused("\x1b[6~");
}
}
KeyCode::Delete => {
if current_focus != FocusState::Desktop {
let _ = window_manager.send_to_focused("\x1b[3~");
}
}
KeyCode::Insert => {
if current_focus != FocusState::Desktop {
let _ = window_manager.send_to_focused("\x1b[2~");
}
}
_ => {}
}
}
Event::Mouse(mouse_event) => {
let (_, rows) = terminal::size()?;
let bar_y = rows - 1;
let mut handled = false;
// Check if there's an active prompt - it takes priority
#[allow(clippy::collapsible_if)]
if let Some(ref prompt) = active_prompt {
if mouse_event.kind == MouseEventKind::Down(MouseButton::Left) {
if let Some(action) =
prompt.handle_click(mouse_event.column, mouse_event.row)
{
match action {
PromptAction::Confirm => {
// Exit confirmed
break;
}
PromptAction::Cancel => {
// Dismiss prompt
active_prompt = None;
}
_ => {}
}
handled = true;
} else if prompt.contains_point(mouse_event.column, mouse_event.row) {
// Click inside prompt but not on a button - consume the event
handled = true;
}
}
}
// Check if there's an active config window (after prompt, before other events)
#[allow(clippy::collapsible_if)]
if !handled {
if let Some(ref config_win) = active_config_window {
if mouse_event.kind == MouseEventKind::Down(MouseButton::Left) {
let action =
config_win.handle_click(mouse_event.column, mouse_event.row);
match action {
ConfigAction::Close => {
active_config_window = None;
handled = true;
}
ConfigAction::ToggleAutoTiling => {
app_config.toggle_auto_tiling_on_startup();
// Update runtime state to match config
auto_tiling_enabled = app_config.auto_tiling_on_startup;
// Update button text
let (_, rows) = terminal::size()?;
let auto_tiling_text = if auto_tiling_enabled {
"â–ˆ on] Auto Tiling"
} else {
"off â–‘] Auto Tiling"
};
auto_tiling_button =
Button::new(1, rows - 1, auto_tiling_text.to_string());
handled = true;
}
ConfigAction::ToggleShowDate => {
app_config.toggle_show_date_in_clock();
handled = true;
}
ConfigAction::CycleTheme => {
// Cycle through themes: classic -> monochrome -> dark -> green_phosphor -> amber -> classic
let next_theme = match app_config.theme.as_str() {
"classic" => "monochrome",
"monochrome" => "dark",
"dark" => "green_phosphor",
"green_phosphor" => "amber",
"amber" => "classic",
_ => "classic",
};
app_config.theme = next_theme.to_string();
let _ = app_config.save();
// Reload theme
theme = Theme::from_name(&app_config.theme);
handled = true;
}
ConfigAction::CycleBackgroundChar => {
// Cycle to the next background character
app_config.cycle_background_char();
// Update charset with new background character
charset.set_background(app_config.get_background_char());
handled = true;
}
ConfigAction::ToggleTintTerminal => {
// Toggle terminal tinting
tint_terminal = !tint_terminal;
handled = true;
}
ConfigAction::None => {
// Check if click is inside config window
if config_win
.contains_point(mouse_event.column, mouse_event.row)
{
// Click inside config window but not on an option - consume the event
handled = true;
}
}
}
}
}
}
// Update button hover state on mouse movement (always active)
if !handled {
if new_terminal_button.contains(mouse_event.column, mouse_event.row) {
new_terminal_button.set_state(button::ButtonState::Hovered);
} else {
new_terminal_button.set_state(button::ButtonState::Normal);
}
// Clipboard buttons hover state
if paste_button.contains(mouse_event.column, mouse_event.row) {
paste_button.set_state(button::ButtonState::Hovered);
} else {
paste_button.set_state(button::ButtonState::Normal);
}
if clear_clipboard_button.contains(mouse_event.column, mouse_event.row) {
clear_clipboard_button.set_state(button::ButtonState::Hovered);
} else {
clear_clipboard_button.set_state(button::ButtonState::Normal);
}
if copy_button.contains(mouse_event.column, mouse_event.row) {
copy_button.set_state(button::ButtonState::Hovered);
} else {
copy_button.set_state(button::ButtonState::Normal);
}
if clear_selection_button.contains(mouse_event.column, mouse_event.row) {
clear_selection_button.set_state(button::ButtonState::Hovered);
} else {
clear_selection_button.set_state(button::ButtonState::Normal);
}
// Calculate position for toggle button hover detection (bottom bar, left side)
let (_, rows) = terminal::size()?;
let bar_y = rows - 1;
let button_start_x = 1u16;
let button_text_width = auto_tiling_button.label.len() as u16 + 3; // +1 for "[", +1 for label, +1 for " "
let button_end_x = button_start_x + button_text_width;
if mouse_event.row == bar_y
&& mouse_event.column >= button_start_x
&& mouse_event.column < button_end_x
{
auto_tiling_button.set_state(button::ButtonState::Hovered);
} else {
auto_tiling_button.set_state(button::ButtonState::Normal);
}
}
// Check if click is on the New Terminal button in the top bar (only if no prompt)
if !handled
&& active_prompt.is_none()
&& mouse_event.kind == MouseEventKind::Down(MouseButton::Left)
&& new_terminal_button.contains(mouse_event.column, mouse_event.row)
{
new_terminal_button.set_state(button::ButtonState::Pressed);
// Create a new terminal window (same as pressing 't')
let (cols, rows) = terminal::size()?;
let width = 150;
let height = 50;
let x = (cols.saturating_sub(width)) / 2;
let y = ((rows.saturating_sub(height)) / 2).max(1);
window_manager.create_window(
x,
y,
width,
height,
format!("Terminal {}", window_manager.window_count() + 1),
);
// Auto-position all windows based on the snap pattern
if auto_tiling_enabled {
window_manager.auto_position_windows(cols, rows);
}
handled = true;
}
// Check if click is on the Copy button in the top bar (only if no prompt)
if !handled
&& active_prompt.is_none()
&& mouse_event.kind == MouseEventKind::Down(MouseButton::Left)
&& copy_button.contains(mouse_event.column, mouse_event.row)
{
copy_button.set_state(button::ButtonState::Pressed);
// Copy selected text to clipboard and clear selection
if let FocusState::Window(window_id) = window_manager.get_focus() {
if let Some(text) = window_manager.get_selected_text(window_id) {
let _ = clipboard_manager.copy(text);
// Clear selection after copying
window_manager.clear_selection(window_id);
}
}
handled = true;
}
// Check if click is on the Clear Selection (X) button in the top bar
if !handled
&& active_prompt.is_none()
&& mouse_event.kind == MouseEventKind::Down(MouseButton::Left)
&& clear_selection_button.contains(mouse_event.column, mouse_event.row)
{
clear_selection_button.set_state(button::ButtonState::Pressed);
// Clear the selection
if let FocusState::Window(window_id) = window_manager.get_focus() {
window_manager.clear_selection(window_id);
}
handled = true;
}
// Check if click is on the Paste button in the top bar (only if no prompt)
if !handled
&& active_prompt.is_none()
&& mouse_event.kind == MouseEventKind::Down(MouseButton::Left)
&& paste_button.contains(mouse_event.column, mouse_event.row)
{
paste_button.set_state(button::ButtonState::Pressed);
// Paste clipboard content to focused window
if let FocusState::Window(window_id) = window_manager.get_focus() {
if let Ok(text) = clipboard_manager.paste() {
let _ = window_manager.paste_to_window(window_id, &text);
}
}
handled = true;
}
// Check if click is on the Clear (X) button in the top bar (only if no prompt)
if !handled
&& active_prompt.is_none()
&& mouse_event.kind == MouseEventKind::Down(MouseButton::Left)
&& clear_clipboard_button.contains(mouse_event.column, mouse_event.row)
{
clear_clipboard_button.set_state(button::ButtonState::Pressed);
// Clear the clipboard
clipboard_manager.clear();
handled = true;
}
// Check if click is on the clock in the top bar (only if no prompt)
if !handled
&& active_prompt.is_none()
&& mouse_event.kind == MouseEventKind::Down(MouseButton::Left)
&& mouse_event.row == 0
{
// Calculate clock position (same logic as render_top_bar)
let (cols, _) = terminal::size()?;
let now = Local::now();
let time_str = if app_config.show_date_in_clock {
now.format("%a %b %d, %H:%M").to_string()
} else {
now.format("%H:%M:%S").to_string()
};
let clock_with_separator = format!("| {} ", time_str);
let clock_width = clock_with_separator.len() as u16;
let time_pos = cols.saturating_sub(clock_width);
// Check if click is within clock area
if mouse_event.column >= time_pos && mouse_event.column < cols {
// Show calendar (same as pressing 'c')
active_calendar = Some(CalendarState::new());
handled = true;
}
}
// Check if click is on the Auto-Tiling toggle button (only if no prompt)
if !handled
&& active_prompt.is_none()
&& mouse_event.kind == MouseEventKind::Down(MouseButton::Left)
{
// Calculate position for toggle button click detection (bottom bar, left side)
let (_, rows) = terminal::size()?;
let bar_y = rows - 1;
let button_start_x = 1u16;
let button_text_width = auto_tiling_button.label.len() as u16 + 3; // +1 for "[", +1 for label, +1 for " "
let button_end_x = button_start_x + button_text_width;
if mouse_event.row == bar_y
&& mouse_event.column >= button_start_x
&& mouse_event.column < button_end_x
{
auto_tiling_button.set_state(button::ButtonState::Pressed);
// Toggle the auto-tiling state
auto_tiling_enabled = !auto_tiling_enabled;
// Update button label to reflect new state
let new_label = if auto_tiling_enabled {
"â–ˆ on] Auto Tiling".to_string()
} else {
"off â–‘] Auto Tiling".to_string()
};
auto_tiling_button = Button::new(1, bar_y, new_label);
handled = true;
}
}
// Check if click is on button bar (only if no prompt)
if !handled
&& active_prompt.is_none()
&& mouse_event.kind == MouseEventKind::Down(MouseButton::Left)
{
// Calculate where window buttons start (after auto-tiling button)
// Format: "[label ]" + 2 spaces
let window_buttons_start =
1 + 1 + auto_tiling_button.label.len() as u16 + 1 + 2;
handled = window_manager
.button_bar_click(
mouse_event.column,
bar_y,
mouse_event.row,
window_buttons_start,
)
.is_some();
}
// Handle right-click for context menu
if !handled
&& active_prompt.is_none()
&& mouse_event.kind == MouseEventKind::Down(MouseButton::Right)
{
if let FocusState::Window(_) = window_manager.get_focus() {
context_menu.show(mouse_event.column, mouse_event.row);
handled = true;
}
}
// Handle context menu interactions
if !handled && context_menu.visible {
if mouse_event.kind == MouseEventKind::Down(MouseButton::Left) {
if context_menu.contains_point(mouse_event.column, mouse_event.row) {
if let Some(action) = context_menu.get_selected_action() {
if let FocusState::Window(window_id) =
window_manager.get_focus()
{
match action {
MenuAction::Copy => {
if let Some(text) =
window_manager.get_selected_text(window_id)
{
let _ = clipboard_manager.copy(text);
// Clear selection after copying
window_manager.clear_selection(window_id);
}
}
MenuAction::Paste => {
if let Ok(text) = clipboard_manager.paste() {
let _ = window_manager
.paste_to_window(window_id, &text);
}
}
MenuAction::SelectAll => {
// TODO: Implement select all
}
MenuAction::CopyWindow => {
// TODO: Implement copy window
}
MenuAction::Close => {}
}
}
}
context_menu.hide();
handled = true;
} else {
// Clicked outside menu - hide it
context_menu.hide();
}
} else if mouse_event.kind == MouseEventKind::Moved {
// Update menu selection on hover
if context_menu.contains_point(mouse_event.column, mouse_event.row) {
// TODO: Update hover state if needed
}
}
}
// Handle selection events (left-click, drag)
if !handled && active_prompt.is_none() && !context_menu.visible {
match mouse_event.kind {
MouseEventKind::Down(MouseButton::Left) => {
// Check if click is in a window content area
if let FocusState::Window(window_id) = window_manager.get_focus() {
// Track click timing for double/triple-click detection
let now = Instant::now();
let is_multi_click = if let Some(last_time) = last_click_time {
now.duration_since(last_time).as_millis() < 500
} else {
false
};
if is_multi_click {
click_count += 1;
} else {
click_count = 1;
}
last_click_time = Some(now);
// Start or expand selection based on click count
let selection_type = match click_count {
2 => {
window_manager.start_selection(
window_id,
mouse_event.column,
mouse_event.row,
SelectionType::Character,
);
window_manager.expand_selection_to_word(window_id);
window_manager.complete_selection(window_id);
SelectionType::Word
}
3 => {
window_manager.start_selection(
window_id,
mouse_event.column,
mouse_event.row,
SelectionType::Character,
);
window_manager.expand_selection_to_line(window_id);
window_manager.complete_selection(window_id);
SelectionType::Line
}
_ => {
let sel_type = if mouse_event
.modifiers
.contains(KeyModifiers::ALT)
{
SelectionType::Block
} else {
SelectionType::Character
};
window_manager.start_selection(
window_id,
mouse_event.column,
mouse_event.row,
sel_type,
);
sel_type
}
};
if click_count <= 1 || selection_type == SelectionType::Block {
selection_active = true;
}
}
}
MouseEventKind::Drag(MouseButton::Left) => {
if selection_active {
if let FocusState::Window(window_id) =
window_manager.get_focus()
{
window_manager.update_selection(
window_id,
mouse_event.column,
mouse_event.row,
);
}
}
}
MouseEventKind::Up(MouseButton::Left) => {
if selection_active {
if let FocusState::Window(window_id) =
window_manager.get_focus()
{
window_manager.complete_selection(window_id);
}
selection_active = false;
}
}
_ => {}
}
}
// If not handled by buttons, let window manager handle it (only if no prompt)
if !handled && active_prompt.is_none() && !context_menu.visible {
let window_closed =
window_manager.handle_mouse_event(&mut video_buffer, mouse_event);
// Auto-reposition remaining windows if a window was closed
if window_closed && auto_tiling_enabled {
let (cols, rows) = terminal::size()?;
window_manager.auto_position_windows(cols, rows);
}
}
}
_ => {}
}
}
}
// Cleanup: restore terminal
cleanup(&mut stdout)?;
Ok(())
}
fn render_background(buffer: &mut VideoBuffer, charset: &Charset, theme: &Theme) {
let (cols, rows) = buffer.dimensions();
// Use the background character from charset configuration
let background_cell = Cell::new(charset.background, theme.desktop_fg, theme.desktop_bg);
// Fill entire screen with the background character
for y in 0..rows {
for x in 0..cols {
buffer.set(x, y, background_cell);
}
}
}
#[allow(clippy::too_many_arguments)]
fn render_top_bar(
buffer: &mut VideoBuffer,
focus: FocusState,
new_terminal_button: &Button,
paste_button: &Button,
clear_clipboard_button: &Button,
copy_button: &Button,
clear_selection_button: &Button,
app_config: &AppConfig,
theme: &Theme,
) {
let (cols, _rows) = buffer.dimensions();
// Change background color based on focus
let bg_color = match focus {
FocusState::Desktop => theme.topbar_bg_desktop,
FocusState::Window(_) => theme.topbar_bg_window,
};
let bar_cell = Cell::new(' ', theme.topbar_fg, bg_color);
// Create a blank top bar
for x in 0..cols {
buffer.set(x, 0, bar_cell);
}
// Left section - New Terminal button (always visible)
new_terminal_button.render(buffer, theme);
// Center section - Copy/Paste/Clear buttons (visible based on state)
copy_button.render(buffer, theme);
clear_selection_button.render(buffer, theme);
paste_button.render(buffer, theme);
clear_clipboard_button.render(buffer, theme);
// Right section - Clock with dark background
let now = Local::now();
// Format clock based on configuration
let time_str = if app_config.show_date_in_clock {
// Show date and time: "Tue Nov 11, 09:21"
now.format("%a %b %d, %H:%M").to_string()
} else {
// Show time only with seconds: "09:21:45"
now.format("%H:%M:%S").to_string()
};
// Format: "| Tue Nov 11, 09:21 " or "| 09:21:45 " (with separator and trailing space)
let clock_with_separator = format!("| {} ", time_str);
let clock_width = clock_with_separator.len() as u16;
let time_pos = cols.saturating_sub(clock_width);
// Render clock with dark background
for (i, ch) in clock_with_separator.chars().enumerate() {
buffer.set(
time_pos + i as u16,
0,
Cell::new(ch, theme.clock_fg, theme.clock_bg),
);
}
}
fn show_splash_screen(
buffer: &mut VideoBuffer,
stdout: &mut io::Stdout,
charset: &Charset,
theme: &Theme,
) -> io::Result<()> {
let (cols, rows) = buffer.dimensions();
// Clear screen to black
let black_cell = Cell::new(' ', theme.splash_fg, Color::Black);
for y in 0..rows {
for x in 0..cols {
buffer.set(x, y, black_cell);
}
}
// Choose ASCII art based on charset mode
let ascii_art = match charset.mode {
charset::CharsetMode::Unicode => vec![
" ███████████ ██████████ ███████████ ██████ ██████ ████████ ████████ ",
"░█░░░███░░░█░░███░░░░░█░░███░░░░░███ ░░██████ ██████ ███░░░░███ ███░░░░███",
"░ ░███ ░ ░███ █ ░ ░███ ░███ ░███░█████░███ ░░░ ░███░███ ░███",
" ░███ ░██████ ░██████████ ░███░░███ ░███ ██████░ ░░█████████",
" ░███ ░███░░█ ░███░░░░░███ ░███ ░░░ ░███ ░░░░░░███ ░░░░░░░███",
" ░███ ░███ ░ █ ░███ ░███ ░███ ░███ ███ ░███ ███ ░███",
" █████ ██████████ █████ █████ █████ █████░░████████ ░░████████ ",
" â–‘â–‘â–‘â–‘â–‘ â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘ â–‘â–‘â–‘â–‘â–‘ â–‘â–‘â–‘â–‘â–‘ â–‘â–‘â–‘â–‘â–‘ â–‘â–‘â–‘â–‘â–‘ â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘ â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘ ",
],
charset::CharsetMode::Ascii => vec![
"TTTTTTT EEEEEEE RRRRRR M M 333333 999999 ",
" TTT EE RR RR MM MM 33 99 99",
" TTT EEEEE RRRRRR M M M M 333333 9999999",
" TTT EE RR RR M M M 33 99",
" TTT EEEEEEE RR RR M M 333333 99999 ",
],
};
// License information to display below ASCII art
let license_lines = [
"",
&format!("Version {}", config::VERSION),
"MIT License",
&format!("Copyright (c) 2025 {}", config::AUTHORS),
];
// Calculate window dimensions
let art_width = ascii_art[0].chars().count() as u16;
let art_height = ascii_art.len() as u16;
let license_height = license_lines.len() as u16;
let total_content_height = art_height + license_height;
let window_width = art_width + 6; // 2 for borders + 4 for padding
let window_height = total_content_height + 4; // Top border + padding + content + padding + bottom border
// Center the window
let window_x = (cols.saturating_sub(window_width)) / 2;
let window_y = (rows.saturating_sub(window_height)) / 2;
let border_color = theme.splash_border;
let content_bg = theme.splash_bg;
// Draw top border using charset
buffer.set(
window_x,
window_y,
Cell::new(charset.border_top_left, border_color, content_bg),
);
for x in 1..window_width - 1 {
buffer.set(
window_x + x,
window_y,
Cell::new(charset.border_horizontal, border_color, content_bg),
);
}
buffer.set(
window_x + window_width - 1,
window_y,
Cell::new(charset.border_top_right, border_color, content_bg),
);
// Draw middle rows (content area)
for y in 1..window_height - 1 {
// Left border
buffer.set(
window_x,
window_y + y,
Cell::new(charset.border_vertical, border_color, content_bg),
);
// Content
for x in 1..window_width - 1 {
buffer.set(
window_x + x,
window_y + y,
Cell::new(' ', theme.splash_fg, content_bg),
);
}
// Right border
buffer.set(
window_x + window_width - 1,
window_y + y,
Cell::new(charset.border_vertical, border_color, content_bg),
);
}
// Draw bottom border using charset
buffer.set(
window_x,
window_y + window_height - 1,
Cell::new(charset.border_bottom_left, border_color, content_bg),
);
for x in 1..window_width - 1 {
buffer.set(
window_x + x,
window_y + window_height - 1,
Cell::new(charset.border_horizontal, border_color, content_bg),
);
}
buffer.set(
window_x + window_width - 1,
window_y + window_height - 1,
Cell::new(charset.border_bottom_right, border_color, content_bg),
);
// Draw shadow (right and bottom) using shared function
video_buffer::render_shadow(
buffer,
window_x,
window_y,
window_width,
window_height,
charset,
theme,
);
// Render ASCII art centered in the window
let content_start_y = window_y + 2; // Start after top border and padding
let content_x = window_x + 3; // Left padding
for (i, line) in ascii_art.iter().enumerate() {
for (j, ch) in line.chars().enumerate() {
buffer.set(
content_x + j as u16,
content_start_y + i as u16,
Cell::new(ch, theme.splash_fg, content_bg),
);
}
}
// Render license information below ASCII art
let license_start_y = content_start_y + art_height;
for (i, line) in license_lines.iter().enumerate() {
// Center each license line
let line_len = line.chars().count() as u16;
let line_x = if line_len < art_width {
content_x + (art_width - line_len) / 2
} else {
content_x
};
for (j, ch) in line.chars().enumerate() {
buffer.set(
line_x + j as u16,
license_start_y + i as u16,
Cell::new(ch, theme.splash_fg, content_bg),
);
}
}
// Present to screen
buffer.present(stdout)?;
stdout.flush()?;
// Wait for 1 second
thread::sleep(time::Duration::from_secs(1));
Ok(())
}
fn render_button_bar(
buffer: &mut VideoBuffer,
window_manager: &WindowManager,
auto_tiling_button: &Button,
auto_tiling_enabled: bool,
theme: &Theme,
) {
let (cols, rows) = buffer.dimensions();
let bar_y = rows - 1;
// Fill button bar with black background
let bar_cell = Cell::new(' ', theme.bottombar_fg, theme.bottombar_bg);
for x in 0..cols {
buffer.set(x, bar_y, bar_cell);
}
// Render Auto Tiling toggle on the left side
let toggle_color = if auto_tiling_enabled {
theme.toggle_enabled_fg
} else {
theme.toggle_disabled_fg
};
let toggle_bg = match auto_tiling_button.state {
button::ButtonState::Normal => {
if auto_tiling_enabled {
theme.toggle_enabled_bg_normal
} else {
theme.toggle_disabled_bg_normal
}
}
button::ButtonState::Hovered => {
if auto_tiling_enabled {
theme.toggle_enabled_bg_hovered
} else {
theme.toggle_disabled_bg_hovered
}
}
button::ButtonState::Pressed => {
if auto_tiling_enabled {
theme.toggle_enabled_bg_pressed
} else {
theme.toggle_disabled_bg_pressed
}
}
};
let mut current_x = 1u16;
// Render "[ "
buffer.set(current_x, bar_y, Cell::new('[', toggle_color, toggle_bg));
current_x += 1;
// Render label
for ch in auto_tiling_button.label.chars() {
buffer.set(current_x, bar_y, Cell::new(ch, toggle_color, toggle_bg));
current_x += 1;
}
// Render " ]"
buffer.set(current_x, bar_y, Cell::new(' ', toggle_color, toggle_bg));
current_x += 1;
// Add spacing after toggle
current_x += 2;
// Render help text on the right side
let help_text = " > 'h' Help | 's' Settings < ";
let help_text_len = help_text.len() as u16;
if cols > help_text_len {
let help_x = cols - help_text_len - 1;
for (i, ch) in help_text.chars().enumerate() {
buffer.set(
help_x + i as u16,
bar_y,
Cell::new(ch, theme.bottombar_fg, theme.bottombar_bg),
);
}
}
// Get list of windows
let windows = window_manager.get_window_list();
if windows.is_empty() {
return;
}
for (_id, title, is_focused, is_minimized) in windows {
// Max button width is 18 chars total
let max_title_len = 14;
let button_title = if title.len() > max_title_len {
&title[..max_title_len]
} else {
title
};
// Button format: [ Title ] for normal, ( Title ) for minimized
// Use different brackets and colors for minimized windows
let (open_bracket, close_bracket, button_bg, button_fg) = if is_minimized {
// Minimized windows: use parentheses and grey color
(
'(',
')',
theme.bottombar_button_minimized_bg,
theme.bottombar_button_minimized_fg,
)
} else if is_focused {
// Focused window: cyan background
(
'[',
']',
theme.bottombar_button_focused_bg,
theme.bottombar_button_focused_fg,
)
} else {
// Normal unfocused window: white text
(
'[',
']',
theme.bottombar_button_normal_bg,
theme.bottombar_button_normal_fg,
)
};
// Render opening bracket and space
buffer.set(
current_x,
bar_y,
Cell::new(open_bracket, button_fg, button_bg),
);
current_x += 1;
buffer.set(current_x, bar_y, Cell::new(' ', button_fg, button_bg));
current_x += 1;
// Render title
for ch in button_title.chars() {
if current_x >= cols - 1 {
break;
}
buffer.set(current_x, bar_y, Cell::new(ch, button_fg, button_bg));
current_x += 1;
}
// Render space and closing bracket
if current_x < cols - 1 {
buffer.set(current_x, bar_y, Cell::new(' ', button_fg, button_bg));
current_x += 1;
}
if current_x < cols - 1 {
buffer.set(
current_x,
bar_y,
Cell::new(close_bracket, button_fg, button_bg),
);
current_x += 1;
}
// Add space between buttons
current_x += 1;
// Stop if we've run out of space
if current_x >= cols - 1 {
break;
}
}
}
fn render_calendar(
buffer: &mut VideoBuffer,
calendar: &CalendarState,
charset: &Charset,
theme: &Theme,
cols: u16,
rows: u16,
) {
// Calendar dimensions
let width = 42u16;
let height = 18u16;
let x = (cols.saturating_sub(width)) / 2;
let y = (rows.saturating_sub(height)) / 2;
// Get the first day of the month
let first_day = match NaiveDate::from_ymd_opt(calendar.year, calendar.month, 1) {
Some(date) => date,
None => return, // Invalid date, don't render
};
// Get the number of days in the month
let days_in_month = if calendar.month == 12 {
match NaiveDate::from_ymd_opt(calendar.year + 1, 1, 1) {
Some(next_month) => (next_month - chrono::Duration::days(1)).day(),
None => 31,
}
} else {
match NaiveDate::from_ymd_opt(calendar.year, calendar.month + 1, 1) {
Some(next_month) => (next_month - chrono::Duration::days(1)).day(),
None => 31,
}
};
// Get the weekday of the first day (0 = Sunday, 6 = Saturday)
let first_weekday = first_day.weekday().num_days_from_sunday() as u16;
// Colors
let bg_color = theme.calendar_bg;
let fg_color = theme.calendar_fg;
let title_color = theme.calendar_title_color;
let today_bg = theme.calendar_today_bg;
let today_fg = theme.calendar_today_fg;
// Fill calendar background
for cy in 0..height {
for cx in 0..width {
buffer.set(x + cx, y + cy, Cell::new(' ', fg_color, bg_color));
}
}
// Render title (Month Year)
let title = format!("{} {}", calendar.month_name(), calendar.year);
let title_len = title.len() as u16;
let title_x = if title_len < width {
x + (width - title_len) / 2
} else {
x + 1
};
for (i, ch) in title.chars().enumerate() {
let char_x = title_x + i as u16;
if char_x < x + width {
buffer.set(char_x, y + 1, Cell::new(ch, title_color, bg_color));
}
}
// Render day headers (Su Mo Tu We Th Fr Sa)
let day_headers = "Su Mo Tu We Th Fr Sa";
let header_len = day_headers.len() as u16;
let header_x = if header_len < width {
x + (width - header_len) / 2
} else {
x + 1
};
for (i, ch) in day_headers.chars().enumerate() {
let char_x = header_x + i as u16;
if char_x < x + width {
buffer.set(char_x, y + 3, Cell::new(ch, fg_color, bg_color));
}
}
// Render calendar days
let mut day = 1u32;
let calendar_start_y = y + 5;
for week in 0..6 {
for weekday in 0..7 {
let day_x = header_x + (weekday * 5);
let day_y = calendar_start_y + (week * 2);
if (week == 0 && weekday < first_weekday) || day > days_in_month {
continue;
}
// Check if this is today
let is_today = calendar.today.year() == calendar.year
&& calendar.today.month() == calendar.month
&& calendar.today.day() == day;
let (day_fg, day_bg) = if is_today {
(today_fg, today_bg)
} else {
(fg_color, bg_color)
};
// Render day number (right-aligned in 2-char space)
let day_str = format!("{:>2}", day);
for (i, ch) in day_str.chars().enumerate() {
buffer.set(day_x + i as u16, day_y, Cell::new(ch, day_fg, day_bg));
}
day += 1;
}
}
// Render navigation hints at bottom
let hint = "\u{2190}\u{2192} Month | \u{2191}\u{2193} Year | T Today | ESC Close";
let hint_len = hint.chars().count() as u16;
let hint_x = if hint_len < width {
x + (width - hint_len) / 2
} else {
x + 1
};
for (i, ch) in hint.chars().enumerate() {
let char_x = hint_x + i as u16;
if char_x < x + width {
buffer.set(
char_x,
y + height - 1,
Cell::new(ch, theme.config_instructions_fg, bg_color),
);
}
}
// Add shadow effect
let shadow_char = charset.shadow;
for sy in 1..height {
buffer.set(
x + width,
y + sy,
Cell::new(shadow_char, theme.window_shadow_color, Color::Black),
);
}
for sx in 1..=width {
buffer.set(
x + sx,
y + height,
Cell::new(shadow_char, theme.window_shadow_color, Color::Black),
);
}
}
fn cleanup(stdout: &mut io::Stdout) -> io::Result<()> {
// Disable mouse capture
execute!(stdout, event::DisableMouseCapture)?;
// Clear screen
execute!(stdout, terminal::Clear(ClearType::All))?;
// Show cursor
execute!(stdout, cursor::Show)?;
// Disable raw mode
terminal::disable_raw_mode()?;
Ok(())
}