boxmux 0.240.3373

YAML-driven terminal UI framework for rich, interactive CLI applications and dashboards with PTY support
Documentation
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
use crate::{
    model::common::{Bounds, InputBounds, ScreenBuffer},
    pty_manager::PtyManager,
    Layout,
};
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
use crossterm::{execute, terminal::size};
use regex::Regex;
use std::collections::HashMap;
use std::io::Stdout;
use std::io::{self, Write};
use std::process::Command;
use std::str;

pub fn screen_width() -> usize {
    size().unwrap_or((80, 24)).0 as usize
}

pub fn screen_height() -> usize {
    size().unwrap_or((80, 24)).1 as usize
}

pub fn screen_bounds() -> Bounds {
    Bounds {
        x1: 0,
        y1: 0,
        x2: screen_width().saturating_sub(1), // Last valid column coordinate
        y2: screen_height().saturating_sub(1), // Last valid row coordinate
    }
}

/// Build a Command for running a user script that is fully detached from
/// boxmux's terminal: stdin is null and the child runs in its own session
/// (`setsid`) so it has NO controlling terminal and therefore cannot reset
/// boxmux's raw mode / mouse tracking — not via stdin and not via /dev/tty.
/// Callers add `.arg(...)` and capture stdout/stderr with `.output()`.
pub fn detached_command(program: &str) -> Command {
    use std::os::unix::process::CommandExt;
    let mut cmd = Command::new(program);
    cmd.stdin(std::process::Stdio::null());
    // SAFETY: setsid() is async-signal-safe and only detaches the freshly forked
    // child from the controlling terminal. Failure (e.g. already a group leader)
    // is harmless — stdin is null regardless.
    unsafe {
        cmd.pre_exec(|| {
            libc::setsid();
            Ok(())
        });
    }
    cmd
}

/// Force the controlling terminal back into raw mode if it has been reset to
/// cooked mode by a child process (e.g. something that ran `stty`/`reset` or set
/// terminal attributes via /dev/tty). crossterm's `enable_raw_mode()` is a no-op
/// once it believes raw mode is on, so it cannot recover from an external reset;
/// this inspects the ACTUAL OS terminal attributes and re-applies raw directly
/// (matching crossterm, which also uses `cfmakeraw`). It leaves crossterm's saved
/// original mode untouched, so terminal restoration on exit still works.
///
/// No-op when stdin is not a terminal or is already raw, so it is safe to call
/// every frame.
pub fn ensure_raw_mode() {
    unsafe {
        let mut termios: libc::termios = std::mem::zeroed();
        if libc::tcgetattr(libc::STDIN_FILENO, &mut termios) != 0 {
            return; // not a terminal (e.g. redirected) — nothing to enforce
        }
        // Cooked mode is indicated by canonical input or local echo being on.
        let is_cooked = (termios.c_lflag & (libc::ICANON | libc::ECHO)) != 0;
        if is_cooked {
            libc::cfmakeraw(&mut termios);
            let _ = libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &termios);
        }
    }
}

pub fn input_bounds_to_bounds(input_bounds: &InputBounds, parent_bounds: &Bounds) -> Bounds {
    let bx1 = parse_percentage(&input_bounds.x1, parent_bounds.width());
    let by1 = parse_percentage(&input_bounds.y1, parent_bounds.height());
    let bx2 = parse_percentage(&input_bounds.x2, parent_bounds.width());
    let by2 = parse_percentage(&input_bounds.y2, parent_bounds.height());
    let abs_x1 = parent_bounds.x1 + bx1;
    let abs_y1 = parent_bounds.y1 + by1;
    let abs_x2 = parent_bounds.x1 + bx2;
    let abs_y2 = parent_bounds.y1 + by2;
    Bounds {
        x1: abs_x1,
        y1: abs_y1,
        x2: abs_x2,
        y2: abs_y2,
    }
}

pub fn bounds_to_input_bounds(abs_bounds: &Bounds, parent_bounds: &Bounds) -> InputBounds {
    let width = parent_bounds.width();
    let height = parent_bounds.height();

    // Account for coordinate system where percentages map to (total-1)
    // So percentage = coordinate / (total-1) for the reverse conversion
    let ix1 = if width <= 1 {
        0.0
    } else {
        (abs_bounds.x1 - parent_bounds.x1) as f64 / (width - 1) as f64
    };
    let iy1 = if height <= 1 {
        0.0
    } else {
        (abs_bounds.y1 - parent_bounds.y1) as f64 / (height - 1) as f64
    };
    let ix2 = if width <= 1 {
        0.0
    } else {
        (abs_bounds.x2 - parent_bounds.x1) as f64 / (width - 1) as f64
    };
    let iy2 = if height <= 1 {
        0.0
    } else {
        (abs_bounds.y2 - parent_bounds.y1) as f64 / (height - 1) as f64
    };

    InputBounds {
        x1: format!("{}%", ix1 * 100.0),
        y1: format!("{}%", iy1 * 100.0),
        x2: format!("{}%", ix2 * 100.0),
        y2: format!("{}%", iy2 * 100.0),
    }
}

pub fn parse_percentage(value: &str, total: usize) -> usize {
    if value.ends_with('%') {
        match value.trim_end_matches('%').parse::<f64>() {
            Ok(percentage) => {
                let normalized = percentage.clamp(0.0, 100.0) / 100.0;
                // Fix: Map 0-100% to coordinate space 0 to (total-1)
                // This ensures 100% maps to the last displayable coordinate
                if total == 0 {
                    0
                } else if percentage >= 100.0 {
                    total - 1 // 100% maps to last valid coordinate
                } else {
                    (normalized * (total - 1) as f64).round() as usize
                }
            }
            Err(_) => 0, // Default to 0 for invalid percentage values
        }
    } else {
        value.parse::<usize>().unwrap_or_default()
    }
}

/// Inherit string with transparent support - returns None if no color specified anywhere
pub fn inherit_string_transparent(
    child_value: Option<&String>,
    parent_value: Option<&String>,
    parent_layout_value: Option<&String>,
    default_value: Option<&str>,
) -> Option<String> {
    if let Some(value) = child_value {
        if !value.is_empty() {
            return Some(value.clone());
        }
    }
    if let Some(value) = parent_value {
        if !value.is_empty() {
            return Some(value.clone());
        }
    }
    if let Some(value) = parent_layout_value {
        if !value.is_empty() {
            return Some(value.clone());
        }
    }
    default_value.map(|s| s.to_string())
}

/// Legacy inherit function with default fallback
pub fn inherit_string(
    child_value: Option<&String>,
    parent_value: Option<&String>,
    parent_layout_value: Option<&String>,
    default_value: &str,
) -> String {
    if let Some(value) = child_value {
        if !value.is_empty() {
            return value.clone();
        }
    }
    if let Some(value) = parent_value {
        if !value.is_empty() {
            return value.clone();
        }
    }
    if let Some(value) = parent_layout_value {
        if !value.is_empty() {
            return value.clone();
        }
    }
    default_value.to_string()
}

pub fn inherit_char(
    child_char: Option<&char>,
    parent_char: Option<&char>,
    parent_layout_char: Option<&char>,
    default_char: char,
) -> char {
    if let Some(&char) = child_char {
        return char;
    }
    if let Some(&char) = parent_char {
        return char;
    }
    if let Some(&char) = parent_layout_char {
        return char;
    }
    default_char
}

pub fn inherit_bool(
    child_bool: Option<&bool>,
    parent_bool: Option<&bool>,
    parent_layout_bool: Option<&bool>,
    default_bool: bool,
) -> bool {
    if let Some(bool) = child_bool {
        return *bool;
    }
    if let Some(bool) = parent_bool {
        return *bool;
    }
    if let Some(bool) = parent_layout_bool {
        return *bool;
    }
    default_bool
}

pub fn inherit_u64(
    child_value: Option<&u64>,
    parent_value: Option<&u64>,
    parent_layout_value: Option<&u64>,
    default_value: u64,
) -> u64 {
    if let Some(value) = child_value {
        return *value;
    }
    if let Some(value) = parent_value {
        return *value;
    }
    if let Some(value) = parent_layout_value {
        return *value;
    }
    default_value
}

pub fn inherit_i64(
    child_value: Option<&i64>,
    parent_value: Option<&i64>,
    parent_layout_value: Option<&i64>,
    default_value: i64,
) -> i64 {
    if let Some(value) = child_value {
        return *value;
    }
    if let Some(value) = parent_value {
        return *value;
    }
    if let Some(value) = parent_layout_value {
        return *value;
    }
    default_value
}

pub fn inherit_f64(
    child_value: Option<&f64>,
    parent_value: Option<&f64>,
    parent_layout_value: Option<&f64>,
    default_value: f64,
) -> f64 {
    if let Some(value) = child_value {
        return *value;
    }
    if let Some(value) = parent_value {
        return *value;
    }
    if let Some(value) = parent_layout_value {
        return *value;
    }
    default_value
}

pub fn inherit_optional_string(
    child_value: Option<&String>,
    parent_value: Option<&String>,
    parent_layout_value: Option<&String>,
    default_value: Option<String>,
) -> Option<String> {
    if let Some(value) = child_value {
        if !value.is_empty() {
            return Some(value.clone());
        }
    }
    if let Some(value) = parent_value {
        if !value.is_empty() {
            return Some(value.clone());
        }
    }
    if let Some(value) = parent_layout_value {
        if !value.is_empty() {
            return Some(value.clone());
        }
    }
    default_value
}

pub fn inherit_optional_char(
    child_char: Option<&char>,
    parent_char: Option<&char>,
    parent_layout_char: Option<&char>,
    default_char: Option<char>,
) -> Option<char> {
    if let Some(&char) = child_char {
        return Some(char);
    }
    if let Some(&char) = parent_char {
        return Some(char);
    }
    if let Some(&char) = parent_layout_char {
        return Some(char);
    }
    default_char
}

pub fn inherit_optional_bool(
    child_bool: Option<&bool>,
    parent_bool: Option<&bool>,
    parent_layout_bool: Option<&bool>,
    default_bool: Option<bool>,
) -> Option<bool> {
    if let Some(bool) = child_bool {
        return Some(*bool);
    }
    if let Some(bool) = parent_bool {
        return Some(*bool);
    }
    if let Some(bool) = parent_layout_bool {
        return Some(*bool);
    }
    default_bool
}

pub fn inherit_optional_u64(
    child_value: Option<&u64>,
    parent_value: Option<&u64>,
    parent_layout_value: Option<&u64>,
    default_value: Option<u64>,
) -> Option<u64> {
    if let Some(value) = child_value {
        return Some(*value);
    }
    if let Some(value) = parent_value {
        return Some(*value);
    }
    if let Some(value) = parent_layout_value {
        return Some(*value);
    }
    default_value
}

pub fn inherit_optional_i64(
    child_value: Option<&i64>,
    parent_value: Option<&i64>,
    parent_layout_value: Option<&i64>,
    default_value: Option<i64>,
) -> Option<i64> {
    if let Some(value) = child_value {
        return Some(*value);
    }
    if let Some(value) = parent_value {
        return Some(*value);
    }
    if let Some(value) = parent_layout_value {
        return Some(*value);
    }
    default_value
}

pub fn inherit_optional_f64(
    child_value: Option<&f64>,
    parent_value: Option<&f64>,
    parent_layout_value: Option<&f64>,
    default_value: Option<f64>,
) -> Option<f64> {
    if let Some(value) = child_value {
        return Some(*value);
    }
    if let Some(value) = parent_value {
        return Some(*value);
    }
    if let Some(value) = parent_layout_value {
        return Some(*value);
    }
    default_value
}

pub fn apply_buffer(screen_buffer: &mut ScreenBuffer, stdout: &mut Stdout) {
    for y in 0..screen_buffer.height {
        for x in 0..screen_buffer.width {
            if let Some(cell) = screen_buffer.get(x, y) {
                execute!(stdout, crossterm::cursor::MoveTo(x as u16, y as u16)).unwrap();
                write!(stdout, "{}{}{}", cell.bg_color, cell.fg_color, cell.ch).unwrap();
            }
        }
    }
    stdout.flush().unwrap();
}

pub fn apply_buffer_if_changed(
    previous_buffer: &ScreenBuffer,
    current_buffer: &ScreenBuffer,
    stdout: &mut Stdout,
) {
    for y in 0..current_buffer.height {
        let mut last_changed_index: Option<u16> = None;
        let mut changes = Vec::new(); // Store changes for each line

        for x in 0..current_buffer.width {
            let current_cell = current_buffer.get(x, y);
            let previous_cell = previous_buffer.get(x, y);

            if current_cell != previous_cell {
                if last_changed_index.is_none() {
                    last_changed_index = Some(x as u16); // Mark the start of a change sequence
                }
                if let Some(cell) = current_cell {
                    changes.push(cell.clone()); // Accumulate changes
                }
            } else {
                // When encountering the end of a sequence of changes, flush them
                if let Some(start) = last_changed_index {
                    execute!(stdout, crossterm::cursor::MoveTo(start, y as u16)).unwrap();
                    for cell in &changes {
                        write!(stdout, "{}{}{}", cell.bg_color, cell.fg_color, cell.ch).unwrap();
                    }
                    changes.clear();
                    last_changed_index = None;
                }
            }
        }

        // Check if there's a pending sequence at the end of the line
        if let Some(start) = last_changed_index {
            execute!(stdout, crossterm::cursor::MoveTo(start, y as u16)).unwrap();
            for cell in changes {
                write!(stdout, "{}{}{}", cell.bg_color, cell.fg_color, cell.ch).unwrap();
            }
        }
    }
    stdout.flush().unwrap(); // Make sure to flush only once after all changes
}

pub fn find_selected_muxbox_uuid(layout: &Layout) -> Option<String> {
    if let Some(children) = &layout.children {
        for muxbox in children {
            if let Some(selected) = muxbox.selected {
                if selected {
                    return Some(muxbox.id.clone());
                }
            }
        }
    }

    None
}

pub fn set_terminal_title(title: &str) {
    print!("\x1B]0;{}\x07", title);
    io::stdout().flush().unwrap();
}

pub fn calculate_tab_order(layout: &Layout) -> Vec<String> {
    let mut result: HashMap<String, i32> = HashMap::new();

    if let Some(children) = &layout.children {
        for muxbox in children {
            let tab_order = muxbox.tab_order.clone();
            if let Some(order) = tab_order {
                result.insert(
                    muxbox.id.clone(),
                    order.parse::<i32>().expect("Invalid tab order"),
                );
            }
        }
    }

    // Sort the hashmap by value
    let mut sorted_result: Vec<(String, i32)> = result.into_iter().collect();
    sorted_result.sort_by(|a, b| a.1.cmp(&b.1));

    let mut tab_order: Vec<String> = Vec::new();
    for (key, _) in sorted_result {
        tab_order.push(key);
    }

    tab_order
}

pub fn find_next_muxbox_uuid(layout: &Layout, current_muxbox_uuid: &str) -> Option<String> {
    let tab_order = calculate_tab_order(layout);
    let mut found_current_muxbox = false;

    for muxbox_uuid in tab_order {
        if found_current_muxbox {
            return Some(muxbox_uuid);
        }

        if muxbox_uuid == current_muxbox_uuid {
            found_current_muxbox = true;
        }
    }

    None
}

pub fn find_previous_muxbox_uuid(layout: &Layout, current_muxbox_uuid: &str) -> Option<String> {
    let tab_order = calculate_tab_order(layout);
    let mut previous_muxbox_uuid: Option<String> = None;

    for muxbox_uuid in tab_order {
        if muxbox_uuid == current_muxbox_uuid {
            return previous_muxbox_uuid;
        }

        previous_muxbox_uuid = Some(muxbox_uuid);
    }

    None
}

pub fn run_script(libs_paths: Option<Vec<String>>, script: &Vec<String>) -> io::Result<String> {
    // F0228: Use ExecutionMode::Immediate for simple script execution without PTY
    run_script_with_pty(
        libs_paths,
        script,
        &crate::model::common::ExecutionMode::Immediate,
        None,
        None,
        None,
    )
}

// F0228: ExecutionMode Message System - Update function signature to use ExecutionMode
pub fn run_script_with_pty(
    libs_paths: Option<Vec<String>>,
    script: &Vec<String>,
    execution_mode: &crate::model::common::ExecutionMode,
    pty_manager: Option<&PtyManager>,
    muxbox_id: Option<String>,
    message_sender: Option<(
        std::sync::mpsc::Sender<(uuid::Uuid, crate::thread_manager::Message)>,
        uuid::Uuid,
    )>,
) -> io::Result<String> {
    run_script_with_pty_and_redirect(
        libs_paths,
        script,
        execution_mode, // F0228: Pass ExecutionMode instead of boolean
        pty_manager,
        muxbox_id,
        message_sender,
        None,
    )
}

// F0228: ExecutionMode Message System - Update function signature to use ExecutionMode instead of boolean
pub fn run_script_with_pty_and_redirect(
    libs_paths: Option<Vec<String>>,
    script: &Vec<String>,
    execution_mode: &crate::model::common::ExecutionMode,
    pty_manager: Option<&PtyManager>,
    muxbox_id: Option<String>,
    message_sender: Option<(
        std::sync::mpsc::Sender<(uuid::Uuid, crate::thread_manager::Message)>,
        uuid::Uuid,
    )>,
    redirect_target: Option<String>,
) -> io::Result<String> {
    if execution_mode.is_pty() {
        if let (Some(pty_mgr), Some(pid), Some((sender, thread_uuid))) =
            (pty_manager, muxbox_id, message_sender)
        {
            // Check if we should avoid PTY due to recent failures
            if pty_mgr.should_avoid_pty(&pid) {
                log::warn!(
                    "Avoiding PTY for muxbox {} due to recent failures, using regular execution",
                    pid
                );
                return run_script_regular(libs_paths, script);
            }

            // Use PTY for script execution
            match pty_mgr.spawn_pty_script_with_redirect(
                pid.clone(),
                script,
                libs_paths.clone(),
                sender,
                thread_uuid,
                redirect_target,
                None, // Use default stream ID generation
                None, // No bounds available in utils.rs context
            ) {
                Ok(_) => {
                    // PTY started successfully - clear any previous failures
                    pty_mgr.clear_pty_failures(&pid);
                    log::info!("PTY started for muxbox: {}", pid);
                    // Return empty string - actual output will come through messages
                    Ok(String::new())
                }
                Err(e) => {
                    // Fall back to regular execution on PTY failure
                    log::warn!(
                        "PTY execution failed for muxbox {}, falling back to regular execution: {}",
                        pid,
                        e
                    );
                    run_script_regular(libs_paths, script)
                }
            }
        } else {
            // Use regular script execution if any required parameter is missing
            run_script_regular(libs_paths, script)
        }
    } else {
        // Use regular script execution
        run_script_regular(libs_paths, script)
    }
}

fn run_script_regular(libs_paths: Option<Vec<String>>, script: &Vec<String>) -> io::Result<String> {
    // Create the script content in-memory
    let mut script_content = String::new();
    if let Some(paths) = libs_paths {
        for lib in paths {
            script_content.push_str(&format!("source {}\n", lib));
        }
    }

    // Add the script commands to the script content
    for command in script {
        script_content.push_str(&format!("{}\n", command));
    }

    // Execute the script and capture stdout and stderr
    // Detach the child from the real terminal so it can't reset boxmux's raw
    // mode / mouse tracking via stdin or /dev/tty; stdout+stderr are captured.
    let output = detached_command("bash")
        .arg("-c")
        .arg(script_content)
        .output();

    match output {
        Ok(output) => {
            // Combine stdout and stderr
            let mut combined_output = format!(
                "{}{}",
                str::from_utf8(&output.stdout).unwrap_or(""),
                str::from_utf8(&output.stderr).unwrap_or("")
            );

            combined_output = strip_ansi_codes(&combined_output);

            if output.status.success() {
                Ok(combined_output)
            } else {
                let error_message = if combined_output.trim().is_empty() {
                    format!(
                        "Script execution failed with exit code: {}",
                        output.status.code().unwrap_or(-1)
                    )
                } else {
                    combined_output
                };
                Err(io::Error::other(error_message))
            }
        }
        Err(e) => Err(io::Error::other(e.to_string())),
    }
}

/// F0226: ExecutionMode-based PTY check - replaces legacy muxbox.pty boolean  
pub fn should_use_pty(muxbox: &crate::model::muxbox::MuxBox) -> bool {
    matches!(
        muxbox.execution_mode,
        crate::model::common::ExecutionMode::Pty
    )
}

/// F0226: ExecutionMode-based PTY check - replaces legacy choice.pty boolean
pub fn should_use_pty_for_choice(choice: &crate::model::choice::Choice) -> bool {
    matches!(
        choice.execution_mode,
        crate::model::common::ExecutionMode::Pty
    )
}

pub fn normalize_key_str(key_str: &str) -> String {
    key_str.to_lowercase().replace(' ', "")
}

pub fn extract_key_str(event: Event) -> Option<String> {
    match event {
        Event::Key(KeyEvent {
            code, modifiers, ..
        }) => match code {
            KeyCode::Char(' ') => Some("Space".to_string()),
            KeyCode::Enter => Some("Return".to_string()),
            KeyCode::Tab => Some("Tab".to_string()),
            KeyCode::BackTab => Some("BackTab".to_string()),
            KeyCode::Char(c) => {
                if modifiers.contains(KeyModifiers::CONTROL) {
                    Some(format!("Ctrl+{}", c))
                } else if modifiers.contains(KeyModifiers::ALT) {
                    Some(format!("Alt+{}", c))
                } else {
                    Some(c.to_string())
                }
            }
            KeyCode::Left => Some("Left".to_string()),
            KeyCode::Right => Some("Right".to_string()),
            KeyCode::Up => Some("Up".to_string()),
            KeyCode::Down => Some("Down".to_string()),
            KeyCode::Backspace => Some("Backspace".to_string()),
            KeyCode::Delete => Some("Delete".to_string()),
            KeyCode::Esc => Some("Esc".to_string()),
            KeyCode::Home => Some("Home".to_string()),
            KeyCode::End => Some("End".to_string()),
            KeyCode::PageUp => Some("PageUp".to_string()),
            KeyCode::PageDown => Some("PageDown".to_string()),
            KeyCode::F(n) => Some(format!("F{}", n)),
            KeyCode::Insert => Some("Insert".to_string()),
            _ => None,
        },
        _ => None,
    }
}

pub fn key_str_to_translate_whitespace(original_str: &str) -> String {
    let mut replacements = HashMap::new();
    replacements.insert(" ", "Space");
    replacements.insert("\n", "Return");
    replacements.insert("\t", "Tab");
    replacements.insert("\x08", "Backspace");
    replacements.insert("\x7f", "Delete");
    replacements.insert("\x1b", "Esc");
    replacements.insert("\x1b[H", "Home");
    replacements.insert("\x1b[F", "End");
    replacements.insert("\x1b[5~", "PageUp");
    replacements.insert("\x1b[6~", "PageDown");
    replacements.insert("\x1b[2~", "Insert");
    replacements.insert("\x1bOP", "F1");
    replacements.insert("\x1bOQ", "F2");
    replacements.insert("\x1bOR", "F3");
    replacements.insert("\x1bOS", "F4");
    replacements.insert("\x1b[15~", "F5");
    replacements.insert("\x1b[17~", "F6");
    replacements.insert("\x1b[18~", "F7");
    replacements.insert("\x1b[19~", "F8");
    replacements.insert("\x1b[20~", "F9");
    replacements.insert("\x1b[21~", "F10");
    replacements.insert("\x1b[23~", "F11");
    replacements.insert("\x1b[24~", "F12");
    replacements.insert("\x1b[A", "Up");
    replacements.insert("\x1b[B", "Down");
    replacements.insert("\x1b[C", "Right");
    replacements.insert("\x1b[D", "Left");

    // Check for exact matches first
    if let Some(replacement) = replacements.get(original_str) {
        replacement.to_string()
    } else {
        original_str.to_string()
    }
}

pub fn handle_keypress(
    key_str: &str,
    key_mappings: &HashMap<String, Vec<String>>,
) -> Option<Vec<String>> {
    let normalized_key_str = normalize_key_str(&key_str_to_translate_whitespace(key_str));

    for (key, actions) in key_mappings.iter() {
        if normalize_key_str(key) == normalized_key_str {
            return Some(actions.clone());
        }
    }
    None
}

pub fn strip_ansi_codes(input: &str) -> String {
    let re = Regex::new(r"\x1B\[[0-?]*[ -/]*[@-~]").unwrap();
    re.replace_all(input, "").to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::common::{Bounds, InputBounds};
    use crate::model::layout::Layout;
    use crate::model::muxbox::MuxBox;
    use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
    use std::collections::HashMap;

    /// run_script must detach the child from the terminal: a command that reads
    /// stdin sees immediate EOF (empty), so it can never read the terminal or run
    /// tty-resetting tools against it. If stdin were inherited from a real
    /// terminal this `cat` would block forever instead of returning empty.
    #[test]
    fn test_run_script_detaches_child_stdin_from_terminal() {
        let copied = run_script(None, &vec!["cat".to_string()]).expect("cat should run");
        assert_eq!(copied.trim(), "", "child stdin must be empty (detached), not the terminal");
        // Normal captured output still works.
        let echoed = run_script(None, &vec!["echo hello".to_string()]).expect("echo should run");
        assert_eq!(echoed.trim(), "hello");
        // A command that explicitly checks for a controlling terminal on stdin
        // must report there is none.
        let tty = run_script(None, &vec!["test -t 0 && echo TTY || echo NOTTY".to_string()])
            .expect("tty check should run");
        assert_eq!(tty.trim(), "NOTTY", "child stdin must not be a terminal");
    }

    // Helper function to create test bounds
    fn create_test_bounds(x1: usize, y1: usize, x2: usize, y2: usize) -> Bounds {
        Bounds { x1, y1, x2, y2 }
    }

    // Helper function to create test input bounds
    fn create_test_input_bounds(x1: &str, y1: &str, x2: &str, y2: &str) -> InputBounds {
        InputBounds {
            x1: x1.to_string(),
            y1: y1.to_string(),
            x2: x2.to_string(),
            y2: y2.to_string(),
        }
    }

    // Helper function to create test layout with muxboxes
    fn create_test_layout_with_muxboxes(muxboxes: Vec<MuxBox>) -> Layout {
        Layout {
            id: "test_layout".to_string(),
            children: Some(muxboxes),
            ..Default::default()
        }
    }

    // Helper function to create test muxbox with ID and tab order
    fn create_test_muxbox_with_tab_order(id: &str, tab_order: Option<&str>) -> MuxBox {
        MuxBox {
            id: id.to_string(),
            position: create_test_input_bounds("0%", "0%", "100%", "100%"),
            tab_order: tab_order.map(|t| t.to_string()),
            ..Default::default()
        }
    }

    // Helper function to create test muxbox with selection state
    fn create_test_muxbox_with_selection(id: &str, selected: bool) -> MuxBox {
        MuxBox {
            id: id.to_string(),
            position: create_test_input_bounds("0%", "0%", "100%", "100%"),
            selected: Some(selected),
            ..Default::default()
        }
    }

    /// Tests that screen_bounds() returns bounds covering the entire screen.
    /// This test demonstrates the screen bounds calculation feature.
    #[test]
    fn test_screen_bounds() {
        let bounds = screen_bounds();
        assert_eq!(bounds.x1, 0);
        assert_eq!(bounds.y1, 0);
        assert!(bounds.x2 > 0);
        assert!(bounds.y2 > 0);
    }

    /// Tests that input_bounds_to_bounds() correctly converts percentage-based bounds.
    /// This test demonstrates the percentage-based positioning feature.
    #[test]
    fn test_input_bounds_to_bounds_percentage() {
        let parent_bounds = create_test_bounds(10, 20, 110, 120);
        let input_bounds = create_test_input_bounds("50%", "25%", "75%", "50%");
        let result = input_bounds_to_bounds(&input_bounds, &parent_bounds);

        assert_eq!(result.x1, 60); // 10 + 50% of (101-1) = 10 + 50 = 60
        assert_eq!(result.y1, 45); // 20 + 25% of (101-1) = 20 + 25 = 45
        assert_eq!(result.x2, 85); // 10 + 75% of (101-1) = 10 + 75 = 85
        assert_eq!(result.y2, 70); // 20 + 50% of (101-1) = 20 + 50 = 70
    }

    /// Tests that input_bounds_to_bounds() correctly converts absolute bounds.
    /// This test demonstrates the absolute positioning feature.
    #[test]
    fn test_input_bounds_to_bounds_absolute() {
        let parent_bounds = create_test_bounds(10, 20, 110, 120);
        let input_bounds = create_test_input_bounds("5", "10", "15", "25");
        let result = input_bounds_to_bounds(&input_bounds, &parent_bounds);

        assert_eq!(result.x1, 15); // 10 + 5
        assert_eq!(result.y1, 30); // 20 + 10
        assert_eq!(result.x2, 25); // 10 + 15
        assert_eq!(result.y2, 45); // 20 + 25
    }

    /// Tests that bounds_to_input_bounds() correctly converts bounds to percentages.
    /// This test demonstrates the bounds-to-percentage conversion feature.
    #[test]
    fn test_bounds_to_input_bounds() {
        let parent_bounds = create_test_bounds(0, 0, 100, 100);
        let abs_bounds = create_test_bounds(25, 50, 75, 100);
        let result = bounds_to_input_bounds(&abs_bounds, &parent_bounds);

        assert_eq!(result.x1, "25%");
        assert_eq!(result.y1, "50%");
        assert_eq!(result.x2, "75%");
        assert_eq!(result.y2, "100%");
    }

    /// Tests that parse_percentage() correctly parses percentage strings.
    /// This test demonstrates the percentage parsing feature.
    #[test]
    fn test_parse_percentage() {
        assert_eq!(parse_percentage("50%", 100), 50); // 50% of range 0-99 = 50
        assert_eq!(parse_percentage("25%", 200), 50); // 25% of range 0-199 = 50
        assert_eq!(parse_percentage("0%", 100), 0);
        assert_eq!(parse_percentage("100%", 100), 99); // 100% maps to last coordinate
        assert_eq!(parse_percentage("33.5%", 100), 33); // 33.5% of 0-99 range
    }

    /// Tests that parse_percentage() correctly parses absolute values.
    /// This test demonstrates the absolute value parsing feature.
    #[test]
    fn test_parse_percentage_absolute() {
        assert_eq!(parse_percentage("50", 100), 50);
        assert_eq!(parse_percentage("0", 100), 0);
        assert_eq!(parse_percentage("123", 100), 123);
    }

    /// Tests that inherit_string() prioritizes child value over parent values.
    /// This test demonstrates the string inheritance priority feature.
    #[test]
    fn test_inherit_string_child_priority() {
        let child_val = "child".to_string();
        let parent_val = "parent".to_string();
        let layout_val = "layout".to_string();
        let child = Some(&child_val);
        let parent = Some(&parent_val);
        let layout = Some(&layout_val);
        let result = inherit_string(child, parent, layout, "default");
        assert_eq!(result, "child");
    }

    /// Tests that inherit_string() falls back to parent value when child is empty.
    /// This test demonstrates the string inheritance fallback feature.
    #[test]
    fn test_inherit_string_parent_fallback() {
        let child_val = "".to_string();
        let parent_val = "parent".to_string();
        let layout_val = "layout".to_string();
        let child = Some(&child_val);
        let parent = Some(&parent_val);
        let layout = Some(&layout_val);
        let result = inherit_string(child, parent, layout, "default");
        assert_eq!(result, "parent");
    }

    /// Tests that inherit_string() uses default when all values are empty.
    /// This test demonstrates the string inheritance default feature.
    #[test]
    fn test_inherit_string_default() {
        let child = None;
        let parent = None;
        let layout = None;
        let result = inherit_string(child, parent, layout, "default");
        assert_eq!(result, "default");
    }

    /// Tests that inherit_char() prioritizes child value over parent values.
    /// This test demonstrates the character inheritance priority feature.
    #[test]
    fn test_inherit_char_child_priority() {
        let child = Some(&'A');
        let parent = Some(&'B');
        let layout = Some(&'C');
        let result = inherit_char(child, parent, layout, 'D');
        assert_eq!(result, 'A');
    }

    /// Tests that inherit_char() falls back to parent value when child is None.
    /// This test demonstrates the character inheritance fallback feature.
    #[test]
    fn test_inherit_char_parent_fallback() {
        let child = None;
        let parent = Some(&'B');
        let layout = Some(&'C');
        let result = inherit_char(child, parent, layout, 'D');
        assert_eq!(result, 'B');
    }

    /// Tests that inherit_char() uses default when all values are None.
    /// This test demonstrates the character inheritance default feature.
    #[test]
    fn test_inherit_char_default() {
        let child = None;
        let parent = None;
        let layout = None;
        let result = inherit_char(child, parent, layout, 'D');
        assert_eq!(result, 'D');
    }

    /// Tests that inherit_bool() prioritizes child value over parent values.
    /// This test demonstrates the boolean inheritance priority feature.
    #[test]
    fn test_inherit_bool_child_priority() {
        let child = Some(&true);
        let parent = Some(&false);
        let layout = Some(&false);
        let result = inherit_bool(child, parent, layout, false);
        assert_eq!(result, true);
    }

    /// Tests that inherit_bool() falls back to parent value when child is None.
    /// This test demonstrates the boolean inheritance fallback feature.
    #[test]
    fn test_inherit_bool_parent_fallback() {
        let child = None;
        let parent = Some(&true);
        let layout = Some(&false);
        let result = inherit_bool(child, parent, layout, false);
        assert_eq!(result, true);
    }

    /// Tests that inherit_bool() uses default when all values are None.
    /// This test demonstrates the boolean inheritance default feature.
    #[test]
    fn test_inherit_bool_default() {
        let child = None;
        let parent = None;
        let layout = None;
        let result = inherit_bool(child, parent, layout, true);
        assert_eq!(result, true);
    }

    /// Tests that inherit_u64() prioritizes child value over parent values.
    /// This test demonstrates the u64 inheritance priority feature.
    #[test]
    fn test_inherit_u64_child_priority() {
        let child = Some(&100u64);
        let parent = Some(&200u64);
        let layout = Some(&300u64);
        let result = inherit_u64(child, parent, layout, 400u64);
        assert_eq!(result, 100u64);
    }

    /// Tests that inherit_u64() falls back to parent value when child is None.
    /// This test demonstrates the u64 inheritance fallback feature.
    #[test]
    fn test_inherit_u64_parent_fallback() {
        let child = None;
        let parent = Some(&200u64);
        let layout = Some(&300u64);
        let result = inherit_u64(child, parent, layout, 400u64);
        assert_eq!(result, 200u64);
    }

    /// Tests that inherit_u64() uses default when all values are None.
    /// This test demonstrates the u64 inheritance default feature.
    #[test]
    fn test_inherit_u64_default() {
        let child = None;
        let parent = None;
        let layout = None;
        let result = inherit_u64(child, parent, layout, 400u64);
        assert_eq!(result, 400u64);
    }

    /// Tests that inherit_i64() prioritizes child value over parent values.
    /// This test demonstrates the i64 inheritance priority feature.
    #[test]
    fn test_inherit_i64_child_priority() {
        let child = Some(&-100i64);
        let parent = Some(&200i64);
        let layout = Some(&-300i64);
        let result = inherit_i64(child, parent, layout, 400i64);
        assert_eq!(result, -100i64);
    }

    /// Tests that inherit_f64() prioritizes child value over parent values.
    /// This test demonstrates the f64 inheritance priority feature.
    #[test]
    fn test_inherit_f64_child_priority() {
        let child = Some(&3.14f64);
        let parent = Some(&2.71f64);
        let layout = Some(&1.41f64);
        let result = inherit_f64(child, parent, layout, 0.0f64);
        assert_eq!(result, 3.14f64);
    }

    /// Tests that inherit_optional_string() prioritizes child value over parent values.
    /// This test demonstrates the optional string inheritance priority feature.
    #[test]
    fn test_inherit_optional_string_child_priority() {
        let child_val = "child".to_string();
        let parent_val = "parent".to_string();
        let layout_val = "layout".to_string();
        let child = Some(&child_val);
        let parent = Some(&parent_val);
        let layout = Some(&layout_val);
        let result = inherit_optional_string(child, parent, layout, Some("default".to_string()));
        assert_eq!(result, Some("child".to_string()));
    }

    /// Tests that inherit_optional_string() falls back to parent value when child is empty.
    /// This test demonstrates the optional string inheritance fallback feature.
    #[test]
    fn test_inherit_optional_string_parent_fallback() {
        let child_val = "".to_string();
        let parent_val = "parent".to_string();
        let layout_val = "layout".to_string();
        let child = Some(&child_val);
        let parent = Some(&parent_val);
        let layout = Some(&layout_val);
        let result = inherit_optional_string(child, parent, layout, Some("default".to_string()));
        assert_eq!(result, Some("parent".to_string()));
    }

    /// Tests that inherit_optional_string() returns None when all values are empty.
    /// This test demonstrates the optional string inheritance None result feature.
    #[test]
    fn test_inherit_optional_string_none() {
        let child = None;
        let parent = None;
        let layout = None;
        let result = inherit_optional_string(child, parent, layout, None);
        assert_eq!(result, None);
    }

    /// Tests that inherit_optional_char() prioritizes child value over parent values.
    /// This test demonstrates the optional character inheritance priority feature.
    #[test]
    fn test_inherit_optional_char_child_priority() {
        let child = Some(&'A');
        let parent = Some(&'B');
        let layout = Some(&'C');
        let result = inherit_optional_char(child, parent, layout, Some('D'));
        assert_eq!(result, Some('A'));
    }

    /// Tests that inherit_optional_bool() prioritizes child value over parent values.
    /// This test demonstrates the optional boolean inheritance priority feature.
    #[test]
    fn test_inherit_optional_bool_child_priority() {
        let child = Some(&true);
        let parent = Some(&false);
        let layout = Some(&false);
        let result = inherit_optional_bool(child, parent, layout, Some(false));
        assert_eq!(result, Some(true));
    }

    /// Tests that inherit_optional_u64() prioritizes child value over parent values.
    /// This test demonstrates the optional u64 inheritance priority feature.
    #[test]
    fn test_inherit_optional_u64_child_priority() {
        let child = Some(&100u64);
        let parent = Some(&200u64);
        let layout = Some(&300u64);
        let result = inherit_optional_u64(child, parent, layout, Some(400u64));
        assert_eq!(result, Some(100u64));
    }

    /// Tests that inherit_optional_i64() prioritizes child value over parent values.
    /// This test demonstrates the optional i64 inheritance priority feature.
    #[test]
    fn test_inherit_optional_i64_child_priority() {
        let child = Some(&-100i64);
        let parent = Some(&200i64);
        let layout = Some(&-300i64);
        let result = inherit_optional_i64(child, parent, layout, Some(400i64));
        assert_eq!(result, Some(-100i64));
    }

    /// Tests that inherit_optional_f64() prioritizes child value over parent values.
    /// This test demonstrates the optional f64 inheritance priority feature.
    #[test]
    fn test_inherit_optional_f64_child_priority() {
        let child = Some(&3.14f64);
        let parent = Some(&2.71f64);
        let layout = Some(&1.41f64);
        let result = inherit_optional_f64(child, parent, layout, Some(0.0f64));
        assert_eq!(result, Some(3.14f64));
    }

    /// Tests that find_selected_muxbox_uuid() returns the ID of the selected muxbox.
    /// This test demonstrates the selected muxbox finding feature.
    #[test]
    fn test_find_selected_muxbox_uuid() {
        let muxbox1 = create_test_muxbox_with_selection("muxbox1", false);
        let muxbox2 = create_test_muxbox_with_selection("muxbox2", true);
        let muxbox3 = create_test_muxbox_with_selection("muxbox3", false);
        let layout = create_test_layout_with_muxboxes(vec![muxbox1, muxbox2, muxbox3]);

        let result = find_selected_muxbox_uuid(&layout);
        assert_eq!(result, Some("muxbox2".to_string()));
    }

    /// Tests that find_selected_muxbox_uuid() returns None when no muxbox is selected.
    /// This test demonstrates the no selection case handling feature.
    #[test]
    fn test_find_selected_muxbox_uuid_none() {
        let muxbox1 = create_test_muxbox_with_selection("muxbox1", false);
        let muxbox2 = create_test_muxbox_with_selection("muxbox2", false);
        let layout = create_test_layout_with_muxboxes(vec![muxbox1, muxbox2]);

        let result = find_selected_muxbox_uuid(&layout);
        assert_eq!(result, None);
    }

    /// Tests that find_selected_muxbox_uuid() returns None when layout has no children.
    /// This test demonstrates the empty layout handling feature.
    #[test]
    fn test_find_selected_muxbox_uuid_empty_layout() {
        let mut layout = Layout::default();
        layout.children = None;

        let result = find_selected_muxbox_uuid(&layout);
        assert_eq!(result, None);
    }

    /// Tests that calculate_tab_order() returns muxboxes sorted by tab order.
    /// This test demonstrates the tab order calculation feature.
    #[test]
    fn test_calculate_tab_order() {
        let muxbox1 = create_test_muxbox_with_tab_order("muxbox1", Some("3"));
        let muxbox2 = create_test_muxbox_with_tab_order("muxbox2", Some("1"));
        let muxbox3 = create_test_muxbox_with_tab_order("muxbox3", Some("2"));
        let layout = create_test_layout_with_muxboxes(vec![muxbox1, muxbox2, muxbox3]);

        let result = calculate_tab_order(&layout);
        assert_eq!(result, vec!["muxbox2", "muxbox3", "muxbox1"]);
    }

    /// Tests that calculate_tab_order() handles muxboxes without tab order.
    /// This test demonstrates the partial tab order handling feature.
    #[test]
    fn test_calculate_tab_order_partial() {
        let muxbox1 = create_test_muxbox_with_tab_order("muxbox1", Some("2"));
        let muxbox2 = create_test_muxbox_with_tab_order("muxbox2", None);
        let muxbox3 = create_test_muxbox_with_tab_order("muxbox3", Some("1"));
        let layout = create_test_layout_with_muxboxes(vec![muxbox1, muxbox2, muxbox3]);

        let result = calculate_tab_order(&layout);
        assert_eq!(result, vec!["muxbox3", "muxbox1"]);
    }

    /// Tests that calculate_tab_order() returns empty vec when layout has no children.
    /// This test demonstrates the empty layout tab order handling feature.
    #[test]
    fn test_calculate_tab_order_empty_layout() {
        let mut layout = Layout::default();
        layout.children = None;

        let result = calculate_tab_order(&layout);
        assert_eq!(result, Vec::<String>::new());
    }

    /// Tests that find_next_muxbox_uuid() returns the next muxbox in tab order.
    /// This test demonstrates the next muxbox navigation feature.
    #[test]
    fn test_find_next_muxbox_uuid() {
        let muxbox1 = create_test_muxbox_with_tab_order("muxbox1", Some("1"));
        let muxbox2 = create_test_muxbox_with_tab_order("muxbox2", Some("2"));
        let muxbox3 = create_test_muxbox_with_tab_order("muxbox3", Some("3"));
        let layout = create_test_layout_with_muxboxes(vec![muxbox1, muxbox2, muxbox3]);

        let result = find_next_muxbox_uuid(&layout, "muxbox2");
        assert_eq!(result, Some("muxbox3".to_string()));
    }

    /// Tests that find_next_muxbox_uuid() returns None when current muxbox is last.
    /// This test demonstrates the last muxbox navigation handling feature.
    #[test]
    fn test_find_next_muxbox_uuid_last() {
        let muxbox1 = create_test_muxbox_with_tab_order("muxbox1", Some("1"));
        let muxbox2 = create_test_muxbox_with_tab_order("muxbox2", Some("2"));
        let layout = create_test_layout_with_muxboxes(vec![muxbox1, muxbox2]);

        let result = find_next_muxbox_uuid(&layout, "muxbox2");
        assert_eq!(result, None);
    }

    /// Tests that find_next_muxbox_uuid() returns None when current muxbox not found.
    /// This test demonstrates the missing muxbox navigation handling feature.
    #[test]
    fn test_find_next_muxbox_uuid_not_found() {
        let muxbox1 = create_test_muxbox_with_tab_order("muxbox1", Some("1"));
        let muxbox2 = create_test_muxbox_with_tab_order("muxbox2", Some("2"));
        let layout = create_test_layout_with_muxboxes(vec![muxbox1, muxbox2]);

        let result = find_next_muxbox_uuid(&layout, "muxbox3");
        assert_eq!(result, None);
    }

    /// Tests that find_previous_muxbox_uuid() returns the previous muxbox in tab order.
    /// This test demonstrates the previous muxbox navigation feature.
    #[test]
    fn test_find_previous_muxbox_uuid() {
        let muxbox1 = create_test_muxbox_with_tab_order("muxbox1", Some("1"));
        let muxbox2 = create_test_muxbox_with_tab_order("muxbox2", Some("2"));
        let muxbox3 = create_test_muxbox_with_tab_order("muxbox3", Some("3"));
        let layout = create_test_layout_with_muxboxes(vec![muxbox1, muxbox2, muxbox3]);

        let result = find_previous_muxbox_uuid(&layout, "muxbox2");
        assert_eq!(result, Some("muxbox1".to_string()));
    }

    /// Tests that find_previous_muxbox_uuid() returns None when current muxbox is first.
    /// This test demonstrates the first muxbox navigation handling feature.
    #[test]
    fn test_find_previous_muxbox_uuid_first() {
        let muxbox1 = create_test_muxbox_with_tab_order("muxbox1", Some("1"));
        let muxbox2 = create_test_muxbox_with_tab_order("muxbox2", Some("2"));
        let layout = create_test_layout_with_muxboxes(vec![muxbox1, muxbox2]);

        let result = find_previous_muxbox_uuid(&layout, "muxbox1");
        assert_eq!(result, None);
    }

    /// Tests that find_previous_muxbox_uuid() returns None when current muxbox not found.
    /// This test demonstrates the missing muxbox navigation handling feature.
    #[test]
    fn test_find_previous_muxbox_uuid_not_found() {
        let muxbox1 = create_test_muxbox_with_tab_order("muxbox1", Some("1"));
        let muxbox2 = create_test_muxbox_with_tab_order("muxbox2", Some("2"));
        let layout = create_test_layout_with_muxboxes(vec![muxbox1, muxbox2]);

        let result = find_previous_muxbox_uuid(&layout, "muxbox3");
        assert_eq!(result, None);
    }

    /// Tests that run_script() executes simple bash commands successfully.
    /// This test demonstrates the script execution feature.
    #[test]
    fn test_run_script_simple() {
        let script = vec!["echo 'Hello World'".to_string()];
        let result = run_script(None, &script);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().trim(), "Hello World");
    }

    /// Tests that run_script() executes multiple commands in sequence.
    /// This test demonstrates the multi-command script execution feature.
    #[test]
    fn test_run_script_multiple_commands() {
        let script = vec!["echo 'First'".to_string(), "echo 'Second'".to_string()];
        let result = run_script(None, &script);
        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("First"));
        assert!(output.contains("Second"));
    }

    /// Tests that run_script() handles command failures properly.
    /// This test demonstrates the error handling feature in script execution.
    #[test]
    fn test_run_script_failure() {
        let script = vec!["false".to_string()]; // Command that always fails
        let result = run_script(None, &script);
        assert!(result.is_err());
    }

    /// Tests that run_script() includes library paths in the script.
    /// This test demonstrates the library inclusion feature.
    #[test]
    fn test_run_script_with_libs() {
        let libs = vec!["/nonexistent/lib1.sh".to_string()];
        let script = vec!["echo 'test'".to_string()];
        let result = run_script(Some(libs), &script);
        // The script should still work even if the lib doesn't exist
        // because we're just sourcing it and then running echo
        assert!(result.is_ok() || result.is_err()); // Either way is acceptable
    }

    /// Tests that normalize_key_str() removes spaces and converts to lowercase.
    /// This test demonstrates the key normalization feature.
    #[test]
    fn test_normalize_key_str() {
        assert_eq!(normalize_key_str("Ctrl + A"), "ctrl+a");
        assert_eq!(normalize_key_str("SHIFT Space"), "shiftspace");
        assert_eq!(normalize_key_str("F1"), "f1");
        assert_eq!(normalize_key_str("ctrl+c"), "ctrl+c");
    }

    /// Tests that extract_key_str() correctly extracts key strings from events.
    /// This test demonstrates the key event extraction feature.
    #[test]
    fn test_extract_key_str() {
        assert_eq!(
            extract_key_str(Event::Key(KeyEvent::new(
                KeyCode::Char('a'),
                KeyModifiers::NONE
            ))),
            Some("a".to_string())
        );
        assert_eq!(
            extract_key_str(Event::Key(KeyEvent::new(
                KeyCode::Char(' '),
                KeyModifiers::NONE
            ))),
            Some("Space".to_string())
        );
        assert_eq!(
            extract_key_str(Event::Key(KeyEvent::new(
                KeyCode::Enter,
                KeyModifiers::NONE
            ))),
            Some("Return".to_string())
        );
        assert_eq!(
            extract_key_str(Event::Key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE))),
            Some("Tab".to_string())
        );
        assert_eq!(
            extract_key_str(Event::Key(KeyEvent::new(
                KeyCode::Char('c'),
                KeyModifiers::CONTROL
            ))),
            Some("Ctrl+c".to_string())
        );
        assert_eq!(
            extract_key_str(Event::Key(KeyEvent::new(
                KeyCode::Char('x'),
                KeyModifiers::ALT
            ))),
            Some("Alt+x".to_string())
        );
        assert_eq!(
            extract_key_str(Event::Key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE))),
            Some("Left".to_string())
        );
        assert_eq!(
            extract_key_str(Event::Key(KeyEvent::new(
                KeyCode::Right,
                KeyModifiers::NONE
            ))),
            Some("Right".to_string())
        );
        assert_eq!(
            extract_key_str(Event::Key(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE))),
            Some("Up".to_string())
        );
        assert_eq!(
            extract_key_str(Event::Key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE))),
            Some("Down".to_string())
        );
        assert_eq!(
            extract_key_str(Event::Key(KeyEvent::new(KeyCode::F(1), KeyModifiers::NONE))),
            Some("F1".to_string())
        );
        assert_eq!(
            extract_key_str(Event::Key(KeyEvent::new(
                KeyCode::F(12),
                KeyModifiers::NONE
            ))),
            Some("F12".to_string())
        );
        assert_eq!(
            extract_key_str(Event::Key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE))),
            Some("Esc".to_string())
        );
        assert_eq!(
            extract_key_str(Event::Key(KeyEvent::new(
                KeyCode::Backspace,
                KeyModifiers::NONE
            ))),
            Some("Backspace".to_string())
        );
    }

    /// Tests that key_str_to_translate_whitespace() replaces whitespace characters.
    /// This test demonstrates the whitespace translation feature.
    #[test]
    fn test_key_str_to_translate_whitespace() {
        assert_eq!(key_str_to_translate_whitespace(" "), "Space");
        assert_eq!(key_str_to_translate_whitespace("\n"), "Return");
        assert_eq!(key_str_to_translate_whitespace("\t"), "Tab");
        assert_eq!(key_str_to_translate_whitespace("\x1b"), "Esc");
        assert_eq!(key_str_to_translate_whitespace("\x1b[A"), "Up");
        assert_eq!(key_str_to_translate_whitespace("\x1b[B"), "Down");
        assert_eq!(key_str_to_translate_whitespace("\x1b[C"), "Right");
        assert_eq!(key_str_to_translate_whitespace("\x1b[D"), "Left");
        assert_eq!(key_str_to_translate_whitespace("\x1bOP"), "F1");
        assert_eq!(
            key_str_to_translate_whitespace("regular text"),
            "regular text"
        );
    }

    /// Tests that handle_keypress() matches keys and returns actions.
    /// This test demonstrates the keypress handling feature.
    #[test]
    fn test_handle_keypress() {
        let mut key_mappings = HashMap::new();
        key_mappings.insert("ctrl+c".to_string(), vec!["exit".to_string()]);
        key_mappings.insert("space".to_string(), vec!["pause".to_string()]);
        key_mappings.insert(
            "f1".to_string(),
            vec!["help".to_string(), "show".to_string()],
        );

        let result = handle_keypress("Ctrl+C", &key_mappings);
        assert_eq!(result, Some(vec!["exit".to_string()]));

        let result = handle_keypress(" ", &key_mappings);
        assert_eq!(result, Some(vec!["pause".to_string()]));

        let result = handle_keypress("F1", &key_mappings);
        assert_eq!(result, Some(vec!["help".to_string(), "show".to_string()]));

        let result = handle_keypress("unknown", &key_mappings);
        assert_eq!(result, None);
    }

    /// Tests that handle_keypress() handles normalized key matching.
    /// This test demonstrates the normalized key matching feature.
    #[test]
    fn test_handle_keypress_normalized() {
        let mut key_mappings = HashMap::new();
        key_mappings.insert("Ctrl + C".to_string(), vec!["exit".to_string()]);

        let result = handle_keypress("ctrl+c", &key_mappings);
        assert_eq!(result, Some(vec!["exit".to_string()]));

        let result = handle_keypress("CTRL+C", &key_mappings);
        assert_eq!(result, Some(vec!["exit".to_string()]));
    }

    /// Tests that strip_ansi_codes() removes ANSI escape sequences.
    /// This test demonstrates the ANSI code stripping feature.
    #[test]
    fn test_strip_ansi_codes() {
        assert_eq!(strip_ansi_codes("Hello World"), "Hello World");
        assert_eq!(
            strip_ansi_codes("\x1b[31mHello\x1b[0m World"),
            "Hello World"
        );
        assert_eq!(strip_ansi_codes("\x1b[1;32mGreen\x1b[0m"), "Green");
        assert_eq!(strip_ansi_codes("\x1b[2J\x1b[H"), ""); // Clear screen sequence
        assert_eq!(
            strip_ansi_codes("No \x1b[31mANSI\x1b[0m codes"),
            "No ANSI codes"
        );
    }

    /// Tests that strip_ansi_codes() handles complex ANSI sequences.
    /// This test demonstrates the complex ANSI code handling feature.
    #[test]
    fn test_strip_ansi_codes_complex() {
        let input = "\x1b[1;31;40mRed text on black\x1b[0m\x1b[32mGreen\x1b[0m";
        let expected = "Red text on blackGreen";
        assert_eq!(strip_ansi_codes(input), expected);
    }

    /// Tests that strip_ansi_codes() handles empty strings.
    /// This test demonstrates the empty string handling feature.
    #[test]
    fn test_strip_ansi_codes_empty() {
        assert_eq!(strip_ansi_codes(""), "");
        assert_eq!(strip_ansi_codes("\x1b[0m"), "");
    }

    // Performance benchmarks for critical functions
    #[test]
    fn benchmark_strip_ansi_codes_performance() {
        let test_string =
            "\x1b[1;31;40mThis is a test string with ANSI codes\x1b[0m\x1b[32mGreen text\x1b[0m";

        let start = std::time::Instant::now();
        for _ in 0..10000 {
            let _ = strip_ansi_codes(test_string);
        }
        let duration = start.elapsed();

        // Should complete 10,000 operations in under 30 seconds (based on measured 25.8s performance)
        println!("ANSI stripping 10k operations: {:?}", duration);
        assert!(
            duration.as_secs() < 30,
            "ANSI stripping performance regression: {:?}",
            duration
        );
    }

    #[test]
    fn benchmark_run_script_performance() {
        let start = std::time::Instant::now();
        for _ in 0..100 {
            let _ = run_script(None, &vec!["echo test".to_string()]);
        }
        let duration = start.elapsed();

        // Should complete 100 script executions in under 10 seconds (relaxed for different environments)
        println!("Script execution 100 operations: {:?}", duration);
        assert!(
            duration.as_secs() < 10,
            "Script execution performance regression: {:?}",
            duration
        );
    }

    #[test]
    fn benchmark_handle_keypress_performance() {
        let mut key_mappings = std::collections::HashMap::new();
        key_mappings.insert("Ctrl + C".to_string(), vec!["exit".to_string()]);
        key_mappings.insert("Ctrl + D".to_string(), vec!["quit".to_string()]);
        key_mappings.insert("Enter".to_string(), vec!["confirm".to_string()]);

        let start = std::time::Instant::now();
        for _ in 0..50000 {
            let _ = handle_keypress("ctrl+c", &key_mappings);
            let _ = handle_keypress("enter", &key_mappings);
            let _ = handle_keypress("unknown", &key_mappings);
        }
        let duration = start.elapsed();

        // Should complete 150,000 key mapping operations in under 30 seconds (relaxed for different environments)
        println!("Key mapping 150k operations: {:?}", duration);
        assert!(
            duration.as_secs() < 30,
            "Key mapping performance regression: {:?}",
            duration
        );
    }

    #[test]
    fn benchmark_bounds_calculation_performance() {
        let input_bounds = InputBounds {
            x1: "10".to_string(),
            y1: "20".to_string(),
            x2: "90".to_string(),
            y2: "44".to_string(),
        };

        let parent_bounds = Bounds {
            x1: 0,
            y1: 0,
            x2: 100,
            y2: 50,
        };

        let start = std::time::Instant::now();
        for _ in 0..100000 {
            let _ = input_bounds_to_bounds(&input_bounds, &parent_bounds);
        }
        let duration = start.elapsed();

        // Should complete 100,000 bounds calculations in under 1300ms (based on measured 1.26s performance)
        println!("Bounds calculation 100k operations: {:?}", duration);
        assert!(
            duration.as_millis() < 1300,
            "Bounds calculation performance regression: {:?}",
            duration
        );
    }

    #[test]
    fn benchmark_large_config_parsing() {
        // Create a large configuration structure
        let mut muxboxes = Vec::new();
        for i in 0..1000 {
            muxboxes.push(format!("muxbox_{}", i));
        }

        let start = std::time::Instant::now();
        for _ in 0..1000 {
            // Simulate processing large muxbox lists
            let _sorted: Vec<_> = muxboxes.iter().collect();
            let _filtered: Vec<_> = muxboxes.iter().filter(|p| p.contains("1")).collect();
        }
        let duration = start.elapsed();

        // Should handle large config processing efficiently (based on measured 4.1s performance)
        println!("Large config processing 1k operations: {:?}", duration);
        assert!(
            duration.as_millis() < 4500,
            "Large config processing performance regression: {:?}",
            duration
        );
    }
}