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
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
use crate::color_utils::get_bg_color;
use crate::draw_utils::{draw_app, draw_muxbox};
use crate::model::app::{
save_active_layout_to_yaml, save_complete_state_to_yaml, save_muxbox_bounds_to_yaml,
save_muxbox_content_to_yaml, save_muxbox_scroll_to_yaml,
};
use crate::model::choice::Choice;
use crate::model::common::{InputBounds, StreamSourceTrait, StreamType};
use crate::thread_manager::Runnable;
use crate::{
apply_buffer, apply_buffer_if_changed, handle_keypress, AppContext, MuxBox, ScreenBuffer,
};
use crate::{thread_manager::*, FieldUpdate};
// use crossbeam_channel::Sender; // T311: Removed with ChoiceThreadManager
use crossterm::{
terminal::{enable_raw_mode, EnterAlternateScreen},
ExecutableCommand,
};
use std::io::stdout;
use std::io::Stdout;
use std::sync::{mpsc, Mutex};
use uuid::Uuid;
// F0188: Drag state tracking for draggable scroll knobs
#[derive(Debug, Clone)]
struct DragState {
muxbox_id: String,
is_vertical: bool, // true for vertical scrollbar, false for horizontal
start_x: u16,
start_y: u16,
start_scroll_percentage: f64,
}
// F0189: MuxBox resize state tracking for draggable muxbox borders
#[derive(Debug, Clone)]
struct MuxBoxResizeState {
muxbox_id: String,
resize_edge: ResizeEdge,
start_x: u16,
start_y: u16,
original_bounds: InputBounds,
}
// F0191: MuxBox move state tracking for draggable muxbox titles/top borders
#[derive(Debug, Clone)]
struct MuxBoxMoveState {
muxbox_id: String,
start_x: u16,
start_y: u16,
original_bounds: InputBounds,
}
// Hover state tracking for sensitive zones
#[derive(Debug, Clone)]
struct HoverState {
current_zone: Option<String>, // Currently hovered zone ID
current_muxbox: Option<String>, // MuxBox containing hovered zone
last_position: Option<(u16, u16)>, // Last mouse position
hover_start_time: Option<std::time::SystemTime>, // When current hover started
}
#[derive(Debug, Clone, PartialEq)]
pub enum ResizeEdge {
BottomRight, // Only corner resize allowed
}
static DRAG_STATE: Mutex<Option<DragState>> = Mutex::new(None);
static MUXBOX_RESIZE_STATE: Mutex<Option<MuxBoxResizeState>> = Mutex::new(None);
static MUXBOX_MOVE_STATE: Mutex<Option<MuxBoxMoveState>> = Mutex::new(None);
static HOVER_STATE: Mutex<HoverState> = Mutex::new(HoverState {
current_zone: None,
current_muxbox: None,
last_position: None,
hover_start_time: None,
});
/// Signature (hash of render-relevant app state + terminal size) of the last
/// full render, used to skip rebuilding the screen buffer and recomputing
/// sensitive zones when nothing observable has changed.
static LAST_RENDER_SIGNATURE: Mutex<Option<u64>> = Mutex::new(None);
/// When the last full render happened, for a periodic liveness backstop so any
/// state not captured by the signature still appears within ~1s.
static LAST_RENDER_AT: Mutex<Option<std::time::Instant>> = Mutex::new(None);
/// Compute the render signature: everything that affects the drawn frame.
fn compute_render_signature(app_context: &AppContext) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
app_context.app.hash(&mut hasher);
// Terminal size affects layout even without an explicit resize message.
let screen = crate::utils::screen_bounds();
screen.x2.hash(&mut hasher);
screen.y2.hash(&mut hasher);
hasher.finish()
}
pub fn apply_calibration_cursor_overlay_at(
layout: &crate::Layout,
buffer: &mut ScreenBuffer,
x: u16,
y: u16,
root_bounds: &crate::Bounds,
) -> bool {
if layout
.find_muxbox_at_coordinates_with_bounds(x, y, root_bounds)
.is_none()
{
return false;
}
let x = x as usize;
let y = y as usize;
if let Some(cell) = buffer.get(x, y).cloned() {
let mut calibrated_cell = cell;
calibrated_cell.bg_color = get_bg_color("red");
buffer.update(x, y, calibrated_cell);
true
} else {
false
}
}
fn apply_calibration_cursor_overlay(app_context: &AppContext, buffer: &mut ScreenBuffer) {
if !app_context.config.calibrate {
return;
}
let last_position = HOVER_STATE.lock().unwrap().last_position;
let Some((x, y)) = last_position else {
return;
};
if let Some(active_layout) = app_context.app.get_active_layout() {
let root_bounds = crate::utils::screen_bounds();
apply_calibration_cursor_overlay_at(active_layout, buffer, x, y, &root_bounds);
}
}
/// Last mouse position that hover reconciliation has already processed.
static LAST_HOVER_POS: Mutex<Option<(u16, u16)>> = Mutex::new(None);
/// When hover was last reconciled, for the periodic self-heal timer.
static LAST_HOVER_CHECK_AT: Mutex<Option<std::time::Instant>> = Mutex::new(None);
/// Detect which interactive zone (tab target or choice) is under the screen
/// coordinate (x, y). Returns (muxbox_id, zone_id) or None. This is the single
/// source of truth for "what is hoverable here", shared by every hover update.
fn detect_hover_zone(
app_context: &AppContext,
app_graph: &crate::model::app::AppGraph,
x: u16,
y: u16,
) -> Option<(String, String)> {
let active_layout = app_context.app.get_active_layout()?;
let hovered_muxbox = active_layout.find_muxbox_at_coordinates(x, y)?;
let screen_x = x as usize;
let screen_y = y as usize;
let muxbox_bounds = hovered_muxbox.bounds();
// Tab bar / close button / nav arrow row (top border of the box).
if screen_y == muxbox_bounds.top() {
let tab_labels = hovered_muxbox.get_tab_labels();
if !tab_labels.is_empty() {
if let Some(tab_target) = crate::draw_utils::calculate_tab_hover_target(
screen_x,
muxbox_bounds.left(),
muxbox_bounds.right(),
&tab_labels,
&hovered_muxbox.get_tab_close_buttons(),
hovered_muxbox.tab_scroll_offset,
&hovered_muxbox.calc_border_color(app_context, app_graph),
&hovered_muxbox.bg_color,
) {
let zone = match tab_target {
crate::draw_utils::TabHoverTarget::Tab(i) => format!("tab_{}", i),
crate::draw_utils::TabHoverTarget::CloseButton(i) => format!("tab_close_{}", i),
crate::draw_utils::TabHoverTarget::NavigationLeft => "tab_nav_left".to_string(),
crate::draw_utils::TabHoverTarget::NavigationRight => {
"tab_nav_right".to_string()
}
};
return Some((hovered_muxbox.id.clone(), zone));
}
}
}
// Choice rows.
if let Some(stream) = hovered_muxbox.get_selected_stream() {
if let Some(choices) = stream.choices.as_ref() {
if !choices.is_empty() {
use crate::components::box_renderer::{BoxDimensions, BoxRenderer};
use crate::components::choice_menu::ChoiceMenu;
use crate::components::renderable_content::RenderableContent;
let box_renderer =
BoxRenderer::new(hovered_muxbox, format!("{}_hover", hovered_muxbox.id));
let choice_menu =
ChoiceMenu::new(format!("{}_choice_menu", hovered_muxbox.id), choices)
.with_selection(hovered_muxbox.selected_choice_index())
.with_focus(hovered_muxbox.focused_choice_index());
let bounds = hovered_muxbox.bounds();
let (content_width, content_height) = choice_menu.get_dimensions();
let dimensions =
BoxDimensions::new(hovered_muxbox, &bounds, content_width, content_height);
let zones = box_renderer.translate_box_relative_zones_to_absolute(
&choice_menu.get_box_relative_sensitive_zones(),
&bounds,
content_width,
content_height,
dimensions.viewable_width,
dimensions.viewable_height,
dimensions.horizontal_scroll,
dimensions.vertical_scroll,
false,
);
if let Some(zone) = zones
.iter()
.find(|z| z.bounds.contains_point(screen_x, screen_y))
{
return Some((hovered_muxbox.id.clone(), zone.content_id.clone()));
}
}
}
}
None
}
/// Remove every hover flag everywhere (all choice rows in every stream and every
/// tab hover target, across all boxes and nested children). Returns whether any
/// hover flag was actually cleared.
fn clear_all_hover(app: &mut crate::model::app::App) -> bool {
fn clear_in(muxboxes: &mut [MuxBox]) -> bool {
let mut changed = false;
for muxbox in muxboxes {
if muxbox.hovered_tab_target.is_some() {
muxbox.hovered_tab_target = None;
changed = true;
}
for stream in muxbox.streams.values_mut() {
if let Some(choices) = stream.choices.as_mut() {
for choice in choices.iter_mut() {
if choice.hovered {
choice.hovered = false;
changed = true;
}
}
}
}
if let Some(children) = muxbox.children.as_mut() {
changed |= clear_in(children);
}
}
changed
}
let mut changed = false;
for layout in &mut app.layouts {
if let Some(children) = layout.children.as_mut() {
changed |= clear_in(children);
}
}
changed
}
/// Apply a single hover target (tab target or choice) to the named box.
fn apply_hover_target(app: &mut crate::model::app::App, muxbox_id: &str, zone: &str) {
let Some(muxbox) = app.get_muxbox_by_id_mut(muxbox_id) else {
return;
};
if zone == "tab_nav_left" {
muxbox.hovered_tab_target = Some(crate::draw_utils::TabHoverTarget::NavigationLeft);
} else if zone == "tab_nav_right" {
muxbox.hovered_tab_target = Some(crate::draw_utils::TabHoverTarget::NavigationRight);
} else if let Some(i) = zone
.strip_prefix("tab_close_")
.and_then(|s| s.parse::<usize>().ok())
{
muxbox.hovered_tab_target = Some(crate::draw_utils::TabHoverTarget::CloseButton(i));
} else if let Some(i) = zone.strip_prefix("tab_").and_then(|s| s.parse::<usize>().ok()) {
muxbox.hovered_tab_target = Some(crate::draw_utils::TabHoverTarget::Tab(i));
} else if let Some(i) = zone
.strip_prefix("choice_")
.and_then(|s| s.parse::<usize>().ok())
{
if let Some(choices) = muxbox.get_selected_stream_choices_mut() {
if let Some(choice) = choices.get_mut(i) {
choice.hovered = true;
}
}
}
}
/// Reconcile the app's hover state to exactly match the zone under (x, y):
/// clear every existing highlight and set only the one under the cursor
/// (mutual exclusivity). Returns true if the highlighted target changed (i.e. a
/// redraw is warranted). Cheap no-op when the target is unchanged.
fn reconcile_hover(
app_context: &mut AppContext,
app_graph: &crate::model::app::AppGraph,
x: u16,
y: u16,
) -> bool {
let target = detect_hover_zone(app_context, app_graph, x, y);
let (new_muxbox, new_zone) = match &target {
Some((muxbox_id, zone)) => (Some(muxbox_id.clone()), Some(zone.clone())),
None => (None, None),
};
{
let mut hover_state = HOVER_STATE.lock().unwrap();
if hover_state.current_muxbox == new_muxbox && hover_state.current_zone == new_zone {
return false;
}
hover_state.current_muxbox = new_muxbox;
hover_state.current_zone = new_zone;
}
// A new highlight always clears all others first.
clear_all_hover(&mut app_context.app);
if let Some((muxbox_id, zone)) = &target {
apply_hover_target(&mut app_context.app, muxbox_id, zone);
}
true
}
/// Direction for mouse-wheel scrolling of the hovered box.
#[derive(Clone, Copy)]
enum WheelDirection {
Up,
Down,
Left,
Right,
}
/// Scroll the box UNDER the cursor (hovered), regardless of focus. Returns the
/// scrolled box's id if a box was found at (x, y). Scrolls content/view only —
/// it never changes choice selection (that stays a focus/keyboard action).
fn scroll_hovered_box(
app_context: &mut AppContext,
x: u16,
y: u16,
root_bounds: &crate::Bounds,
direction: WheelDirection,
) -> Option<String> {
let id = {
let layout = app_context.app.get_active_layout()?;
layout
.find_muxbox_at_coordinates_with_bounds(x, y, root_bounds)?
.id
.clone()
};
let muxbox = app_context.app.get_muxbox_by_id_mut(&id)?;
match direction {
WheelDirection::Up => muxbox.scroll_up(Some(1.0)),
WheelDirection::Down => muxbox.scroll_down(Some(1.0)),
WheelDirection::Left => muxbox.scroll_left(Some(1.0)),
WheelDirection::Right => muxbox.scroll_right(Some(1.0)),
}
Some(id)
}
// F0189: Helper functions to detect muxbox border resize areas (corner-only)
pub fn detect_resize_edge(muxbox: &MuxBox, click_x: u16, click_y: u16) -> Option<ResizeEdge> {
let bounds = muxbox.bounds();
let x = click_x as usize;
let y = click_y as usize;
// Check for corner resize (bottom-right only) with tolerance for easier clicking
// Allow clicking within 1 pixel of the exact corner to make it easier to grab
let corner_tolerance = 1;
// Standard detection zone - same for all panels including 100% width
if (x >= bounds.x2.saturating_sub(corner_tolerance) && x <= bounds.x2)
&& (y >= bounds.y2.saturating_sub(corner_tolerance) && y <= bounds.y2)
{
return Some(ResizeEdge::BottomRight);
}
None
}
// F0191: Helper function to detect muxbox title/top border for movement
pub fn detect_move_area(muxbox: &MuxBox, click_x: u16, click_y: u16) -> bool {
let bounds = muxbox.bounds();
let x = click_x as usize;
let y = click_y as usize;
// Check for title area or top border (y1 coordinate across muxbox width)
y == bounds.y1 && x >= bounds.x1 && x <= bounds.x2
}
pub fn calculate_new_bounds(
original_bounds: &InputBounds,
resize_edge: &ResizeEdge,
start_x: u16,
start_y: u16,
current_x: u16,
current_y: u16,
terminal_width: usize,
terminal_height: usize,
) -> InputBounds {
let delta_x = (current_x as i32) - (start_x as i32);
let delta_y = (current_y as i32) - (start_y as i32);
let mut new_bounds = original_bounds.clone();
// F0197: Minimum resize constraints - prevent boxes smaller than 2x2 characters
let min_width_percent = (2.0 / terminal_width as f32) * 100.0;
let min_height_percent = (2.0 / terminal_height as f32) * 100.0;
match resize_edge {
ResizeEdge::BottomRight => {
// Update both x2 and y2 coordinates for corner resize
if let Ok(current_x2_percent) = new_bounds.x2.replace('%', "").parse::<f32>() {
if let Ok(current_x1_percent) = new_bounds.x1.replace('%', "").parse::<f32>() {
let pixel_delta_x = delta_x as f32;
let percent_delta_x = (pixel_delta_x / terminal_width as f32) * 100.0;
let new_x2_percent = (current_x2_percent + percent_delta_x).clamp(10.0, 100.0);
// Enforce minimum width constraint
let min_x2_for_width = current_x1_percent + min_width_percent;
let constrained_x2 = new_x2_percent.max(min_x2_for_width);
new_bounds.x2 = format!("{}%", constrained_x2.round() as i32);
}
}
// Also update y2 coordinate for corner resize
if let Ok(current_y2_percent) = new_bounds.y2.replace('%', "").parse::<f32>() {
if let Ok(current_y1_percent) = new_bounds.y1.replace('%', "").parse::<f32>() {
let pixel_delta_y = delta_y as f32;
let percent_delta_y = (pixel_delta_y / terminal_height as f32) * 100.0;
let new_y2_percent = (current_y2_percent + percent_delta_y).clamp(10.0, 100.0);
// Enforce minimum height constraint
let min_y2_for_height = current_y1_percent + min_height_percent;
let constrained_y2 = new_y2_percent.max(min_y2_for_height);
new_bounds.y2 = format!("{}%", constrained_y2.round() as i32);
}
}
}
}
new_bounds
}
// F0191: Calculate new muxbox position during drag move
pub fn calculate_new_position(
original_bounds: &InputBounds,
start_x: u16,
start_y: u16,
current_x: u16,
current_y: u16,
terminal_width: usize,
terminal_height: usize,
) -> InputBounds {
let delta_x = (current_x as i32) - (start_x as i32);
let delta_y = (current_y as i32) - (start_y as i32);
let mut new_bounds = original_bounds.clone();
// Convert pixel deltas to percentage deltas and update position
let pixel_delta_x = delta_x as f32;
let percent_delta_x = (pixel_delta_x / terminal_width as f32) * 100.0;
let pixel_delta_y = delta_y as f32;
let percent_delta_y = (pixel_delta_y / terminal_height as f32) * 100.0;
// Update x1 and x2 (maintain width)
if let (Ok(current_x1), Ok(current_x2)) = (
new_bounds.x1.replace('%', "").parse::<f32>(),
new_bounds.x2.replace('%', "").parse::<f32>(),
) {
let new_x1 = (current_x1 + percent_delta_x).clamp(0.0, 90.0);
let new_x2 = (current_x2 + percent_delta_x).clamp(10.0, 100.0);
// Ensure we don't go beyond boundaries while maintaining muxbox width
if new_x2 <= 100.0 && new_x1 >= 0.0 {
new_bounds.x1 = format!("{}%", new_x1.round() as i32);
new_bounds.x2 = format!("{}%", new_x2.round() as i32);
}
}
// Update y1 and y2 (maintain height)
if let (Ok(current_y1), Ok(current_y2)) = (
new_bounds.y1.replace('%', "").parse::<f32>(),
new_bounds.y2.replace('%', "").parse::<f32>(),
) {
let new_y1 = (current_y1 + percent_delta_y).clamp(0.0, 90.0);
let new_y2 = (current_y2 + percent_delta_y).clamp(10.0, 100.0);
// Ensure we don't go beyond boundaries while maintaining muxbox height
if new_y2 <= 100.0 && new_y1 >= 0.0 {
new_bounds.y1 = format!("{}%", new_y1.round() as i32);
new_bounds.y2 = format!("{}%", new_y2.round() as i32);
}
}
new_bounds
}
// F0188: Helper functions to determine if click is on scroll knob (not just track)
fn is_on_vertical_knob(muxbox: &MuxBox, click_y: usize) -> bool {
let muxbox_bounds = muxbox.bounds();
let viewable_height = muxbox_bounds.height().saturating_sub(4);
// Get content dimensions to calculate knob position and size
// F0214: Stream-Based Scrollbar Calculations - Use active stream content
let stream_content = muxbox
.get_selected_stream()
.map_or(Vec::new(), |s| s.content.clone());
let stream_choices = muxbox.get_selected_stream_choices();
let max_content_height = if !stream_content.is_empty() {
let mut total_height = stream_content.len();
// Add choices height if active stream has choices
if let Some(choices) = stream_choices {
total_height += choices.len();
}
total_height
} else if let Some(choices) = stream_choices {
choices.len()
} else {
viewable_height // No scrolling needed
};
if max_content_height <= viewable_height {
return false; // No scrollbar needed
}
let track_height = viewable_height.saturating_sub(2);
if track_height == 0 {
return false;
}
// Calculate knob position and size (matching draw_utils.rs logic)
let content_ratio = viewable_height as f64 / max_content_height as f64;
let knob_size = std::cmp::max(1, (track_height as f64 * content_ratio).round() as usize);
let available_track = track_height.saturating_sub(knob_size);
let vertical_scroll = muxbox.vertical_scroll.unwrap_or(0.0);
let knob_position = if available_track > 0 {
((vertical_scroll / 100.0) * available_track as f64).round() as usize
} else {
0
};
// Check if click is within knob bounds
let knob_start_y = muxbox_bounds.top() + 1 + knob_position;
let knob_end_y = knob_start_y + knob_size;
click_y >= knob_start_y && click_y < knob_end_y
}
fn is_on_horizontal_knob(muxbox: &MuxBox, click_x: usize) -> bool {
let muxbox_bounds = muxbox.bounds();
let viewable_width = muxbox_bounds.width().saturating_sub(4);
// Get content width to calculate knob position and size
// F0214: Stream-Based Scrollbar Calculations - Use active stream content
let stream_content = muxbox
.get_selected_stream()
.map_or(Vec::new(), |s| s.content.clone());
let stream_choices = muxbox.get_selected_stream_choices();
let max_content_width = if !stream_content.is_empty() {
stream_content
.iter()
.map(|line| line.len())
.max()
.unwrap_or(0)
} else if let Some(choices) = stream_choices {
choices
.iter()
.map(|choice| choice.content.as_ref().map(|c| c.len()).unwrap_or(0))
.max()
.unwrap_or(0)
} else {
viewable_width // No scrolling needed
};
if max_content_width <= viewable_width {
return false; // No scrollbar needed
}
let track_width = viewable_width.saturating_sub(2);
if track_width == 0 {
return false;
}
// Calculate knob position and size (matching draw_utils.rs logic)
let content_ratio = viewable_width as f64 / max_content_width as f64;
let knob_size = std::cmp::max(1, (track_width as f64 * content_ratio).round() as usize);
let available_track = track_width.saturating_sub(knob_size);
let horizontal_scroll = muxbox.horizontal_scroll.unwrap_or(0.0);
let knob_position = if available_track > 0 {
((horizontal_scroll / 100.0) * available_track as f64).round() as usize
} else {
0
};
// Check if click is within knob bounds
let knob_start_x = muxbox_bounds.left() + 1 + knob_position;
let knob_end_x = knob_start_x + knob_size;
click_x >= knob_start_x && click_x < knob_end_x
}
lazy_static! {
static ref GLOBAL_SCREEN: Mutex<Option<Stdout>> = Mutex::new(None);
static ref GLOBAL_BUFFER: Mutex<Option<ScreenBuffer>> = Mutex::new(None);
}
create_runnable!(
DrawLoop,
|inner: &mut RunnableImpl, app_context: AppContext, _messages: Vec<Message>| -> bool {
let mut global_screen = GLOBAL_SCREEN.lock().unwrap();
let mut global_buffer = GLOBAL_BUFFER.lock().unwrap();
let mut app_context_unwrapped = app_context.clone();
let is_first_render = global_screen.is_none();
// Hover reconciliation: derive the highlight purely from the current mouse
// position so highlights are mutually exclusive and never get stuck. Runs
// when the pointer moved since last time, plus on a ~150ms timer that
// re-checks and removes any stale highlight (the "still needed?" check).
{
let last_position = HOVER_STATE.lock().unwrap().last_position;
let now = std::time::Instant::now();
let position_changed = *LAST_HOVER_POS.lock().unwrap() != last_position;
let timer_due = LAST_HOVER_CHECK_AT
.lock()
.unwrap()
.map(|t| now.duration_since(t) >= std::time::Duration::from_millis(150))
.unwrap_or(true);
if position_changed || timer_due {
*LAST_HOVER_POS.lock().unwrap() = last_position;
*LAST_HOVER_CHECK_AT.lock().unwrap() = Some(now);
let app_graph = app_context_unwrapped.app.generate_graph();
let changed = match last_position {
Some((mx, my)) => {
reconcile_hover(&mut app_context_unwrapped, &app_graph, mx, my)
}
// No known pointer position: ensure nothing is left highlighted.
None => {
let mut hover_state = HOVER_STATE.lock().unwrap();
let had = hover_state.current_zone.is_some();
hover_state.current_zone = None;
hover_state.current_muxbox = None;
drop(hover_state);
clear_all_hover(&mut app_context_unwrapped.app) || had
}
};
if changed {
inner.app_context = app_context_unwrapped.clone();
}
}
}
// Skip the (expensive) full rebuild + sensitive-zone recomputation when
// nothing observable has changed since the last render. Calibration mode
// tracks the live cursor cell, so it always renders. A ~1s periodic
// backstop guarantees liveness for any state the signature can't capture.
let signature = compute_render_signature(&app_context_unwrapped);
let now = std::time::Instant::now();
let mut last_signature = LAST_RENDER_SIGNATURE.lock().unwrap();
let mut last_render_at = LAST_RENDER_AT.lock().unwrap();
let periodic_due = last_render_at
.map(|t| now.duration_since(t) >= std::time::Duration::from_millis(1000))
.unwrap_or(true);
let must_render = is_first_render
|| app_context_unwrapped.config.calibrate
|| *last_signature != Some(signature)
|| periodic_due;
if !must_render {
return true;
}
if is_first_render {
let mut stdout = stdout();
enable_raw_mode().unwrap();
stdout.execute(EnterAlternateScreen).unwrap();
*global_screen = Some(stdout);
*global_buffer = Some(ScreenBuffer::new());
}
let (adjusted_bounds, app_graph) = app_context_unwrapped
.app
.get_adjusted_bounds_and_app_graph(Some(true));
if let (Some(ref mut screen), Some(ref mut buffer)) =
(&mut *global_screen, &mut *global_buffer)
{
// Re-assert the terminal modes boxmux relies on every render. A child
// process (or anything else) can reset raw mode / mouse tracking on the
// tty; without this, that leaves the terminal echoing raw mouse escape
// codes to the screen. `ensure_raw_mode` inspects the real OS terminal
// state and re-applies raw mode when it has been reset (crossterm's own
// enable_raw_mode is a no-op after an external reset). EnableMouseCapture
// re-enables mouse tracking. Both are no-ops/emit nothing when already
// set, so the UI self-heals within a frame (the ~1s backstop covers idle).
crate::utils::ensure_raw_mode();
let _ = screen.execute(crossterm::event::EnableMouseCapture);
let mut new_buffer = ScreenBuffer::new();
draw_app(
&app_context_unwrapped,
&app_graph,
&adjusted_bounds,
&mut new_buffer,
);
apply_calibration_cursor_overlay(&app_context_unwrapped, &mut new_buffer);
if is_first_render {
// Force full render on first run to ensure everything is drawn
apply_buffer(&mut new_buffer, screen);
} else {
apply_buffer_if_changed(buffer, &new_buffer, screen);
}
*buffer = new_buffer;
}
*last_signature = Some(signature);
*last_render_at = Some(now);
true
},
|inner: &mut RunnableImpl,
app_context: AppContext,
messages: Vec<Message>|
-> (bool, AppContext) {
let mut global_screen = GLOBAL_SCREEN.lock().unwrap();
let mut global_buffer = GLOBAL_BUFFER.lock().unwrap();
let mut should_continue = true;
if let (Some(ref mut screen), Some(ref mut buffer)) =
(&mut *global_screen, &mut *global_buffer)
{
let mut new_buffer;
let mut app_context_unwrapped = app_context.clone();
let (adjusted_bounds, app_graph) = app_context_unwrapped
.app
.get_adjusted_bounds_and_app_graph(Some(true));
// T311: choice_ids_now_waiting removed - no longer needed with unified threading
if !messages.is_empty() {
log::info!("DrawLoop processing {} messages", messages.len());
}
for message in &messages {
log::trace!("Processing message: {:?}", message);
match message {
Message::MuxBoxEventRefresh(_) => {
log::trace!("MuxBoxEventRefresh");
}
// ExecuteScript messages sent back from ThreadManager for stream creation + execution
Message::ExecuteScriptMessage(execute_script) => {
log::info!("Processing ExecuteScript from ThreadManager for target_box_id: {}, execution_mode: {:?}",
execute_script.target_box_id, execute_script.execution_mode);
// ExecuteScript already contains the stream_id from source registry
let stream_id = execute_script.stream_id.clone();
let source_id = execute_script.source.source_id.clone();
if let Some(target_muxbox) = app_context_unwrapped
.app
.get_muxbox_by_id_mut(&execute_script.target_box_id)
{
// Create stream label based on source type
let stream_label = match &execute_script.source.source_type {
crate::model::common::SourceType::Choice(choice_id) => {
choice_id.clone()
}
crate::model::common::SourceType::StaticScript => {
"Script".to_string()
}
crate::model::common::SourceType::PeriodicRefresh => {
"Content".to_string()
} // Periodic refresh shows as "Content" tab
crate::model::common::SourceType::SocketUpdate => {
"Socket".to_string()
}
crate::model::common::SourceType::RedirectedScript => {
"Redirect".to_string()
}
crate::model::common::SourceType::HotkeyScript => {
"Hotkey".to_string()
}
crate::model::common::SourceType::ScheduledScript => {
"Scheduled".to_string()
}
};
// Create execution stream with appropriate type
let stream_type = match execute_script.execution_mode {
crate::model::common::ExecutionMode::Immediate => {
StreamType::ChoiceExecution(source_id.clone())
}
crate::model::common::ExecutionMode::Thread => {
StreamType::ChoiceExecution(source_id.clone())
}
crate::model::common::ExecutionMode::Pty => {
StreamType::PtySession(format!("PTY-{}", source_id))
}
};
let new_stream = crate::model::common::Stream::new(
stream_id.clone(),
stream_type,
stream_label,
Vec::new(),
None,
None,
);
// Set new execution stream as selected so it renders
target_muxbox.selected_stream_id = Some(stream_id.clone());
// Add stream to target muxbox streams HashMap
target_muxbox.streams.insert(stream_id.clone(), new_stream);
log::info!(
"Created stream {} in box {} for execution",
stream_id,
execute_script.target_box_id
);
// T0700: Route ALL execution through ThreadManager for unified architecture
// Send ExecuteScript to ThreadManager for consistent handling across all execution modes
let mut execute_script_with_stream = execute_script.clone();
execute_script_with_stream.stream_id = stream_id;
log::info!("T0700: Unified execution - sending {:?} ExecuteScript to ThreadManager",
execute_script.execution_mode);
inner.send_message(Message::ExecuteScriptMessage(
execute_script_with_stream,
));
} else {
log::error!(
"Target box {} not found for ExecuteScript",
execute_script.target_box_id
);
}
}
Message::StreamUpdateMessage(stream_update) => {
log::info!("Processing StreamUpdate for stream_id: {}, target_box: {}, execution_mode: {:?}",
stream_update.stream_id, stream_update.target_box_id, stream_update.execution_mode);
// T0308 ENHANCED: StreamUpdate handler with auto-creation - find or create stream
let mut stream_found = false;
// First, try to find existing stream across all muxboxes
for layout in &mut app_context_unwrapped.app.layouts {
if let Some(children) = &mut layout.children {
for muxbox in children {
if let Some(stream) =
muxbox.streams.get_mut(&stream_update.stream_id)
{
// Handle replace vs append based on content prefix
if !stream_update.content_update.is_empty() {
if stream_update.content_update.starts_with("REPLACE:")
{
// Replace content for full-screen programs
let new_content = stream_update
.content_update
.strip_prefix("REPLACE:")
.unwrap_or(&stream_update.content_update);
stream.content = vec![new_content.to_string()];
log::info!("Replaced content in existing stream {}: {} characters",
stream_update.stream_id, new_content.len());
} else {
// Normal append behavior
stream
.content
.push(stream_update.content_update.clone());
log::info!("Appended content to existing stream {}: {} characters",
stream_update.stream_id, stream_update.content_update.len());
}
}
stream_found = true;
// AUTO_SCROLL_BOTTOM FIX: Apply auto-scroll when stream content is updated
if muxbox.auto_scroll_bottom == Some(true) {
muxbox.vertical_scroll = Some(100.0);
log::debug!("Applied auto-scroll to bottom for muxbox {} after stream update", muxbox.id);
}
inner
.send_message(Message::RedrawMuxBox(muxbox.id.clone()));
break;
}
}
if stream_found {
break;
}
}
}
// If stream not found, create it in the target box
if !stream_found {
if let Some(target_muxbox) = app_context_unwrapped
.app
.get_muxbox_by_id_mut(&stream_update.target_box_id)
{
log::info!(
"AUTO-CREATING stream {} in target box {}",
stream_update.stream_id,
stream_update.target_box_id
);
// Create execution stream with content
let stream_label = match stream_update.execution_mode {
crate::model::common::ExecutionMode::Immediate => "Immediate",
crate::model::common::ExecutionMode::Thread => "Thread",
crate::model::common::ExecutionMode::Pty => "PTY",
};
let stream_id = target_muxbox.add_stream_with_source(
crate::model::common::StreamType::ChoiceExecution(stream_update.stream_id.clone()),
stream_label.to_string(),
crate::model::common::StreamSource::create_immediate_execution_source(
stream_update.stream_id.clone(),
stream_update.target_box_id.clone(),
vec!["executed".to_string()],
)
);
// Add the content to the newly created stream
if let Some(stream) = target_muxbox.streams.get_mut(&stream_id) {
if !stream_update.content_update.is_empty() {
if stream_update.content_update.starts_with("REPLACE:") {
// Replace content for full-screen programs
let new_content = stream_update
.content_update
.strip_prefix("REPLACE:")
.unwrap_or(&stream_update.content_update);
stream.content = vec![new_content.to_string()];
log::info!("Set initial content in new stream {}: {} characters",
stream_id, new_content.len());
} else {
// Normal append behavior
stream
.content
.push(stream_update.content_update.clone());
log::info!(
"Added content to new stream {}: {} characters",
stream_id,
stream_update.content_update.len()
);
}
}
}
// Set the newly created stream as the selected stream so it's visible
target_muxbox.selected_stream_id = Some(stream_id.clone());
log::info!(
"Set stream {} as selected stream for box {}",
stream_id,
target_muxbox.id
);
// AUTO_SCROLL_BOTTOM FIX: Apply auto-scroll when new stream content is added
if target_muxbox.auto_scroll_bottom == Some(true) {
target_muxbox.vertical_scroll = Some(100.0);
log::debug!("Applied auto-scroll to bottom for muxbox {} after new stream content", target_muxbox.id);
}
inner.send_message(Message::RedrawMuxBox(target_muxbox.id.clone()));
} else {
log::error!(
"Target box {} not found for stream creation",
stream_update.target_box_id
);
}
}
// Clear waiting state for any choices that were executed (visual feedback completion)
for layout in &mut app_context_unwrapped.app.layouts {
if let Some(children) = &mut layout.children {
for muxbox in children {
if let Some(choices) = muxbox.get_selected_stream_choices_mut()
{
for choice in choices.iter_mut() {
if choice.waiting {
choice.waiting = false;
log::info!(
"Cleared waiting state for choice: {}",
choice.id
);
}
}
}
}
}
}
// CRITICAL FIX: Update app context to persist all stream changes
inner.update_app_context(app_context_unwrapped.clone());
}
Message::SourceActionMessage(source_action) => {
log::info!(
"Processing SourceAction: {:?} for source_id: {}, execution_mode: {:?}",
source_action.action,
source_action.source_id,
source_action.execution_mode
);
// T0320: SourceAction handler - Phase 4 source lifecycle management implementation
match source_action.action {
crate::model::common::ActionType::Kill => {
log::info!(
"Kill action for source {} (mode: {:?})",
source_action.source_id,
source_action.execution_mode
);
// Find and terminate the source based on execution mode
let mut source_terminated = false;
let mut stream_to_update: Option<(String, String)> = None; // (stream_id, muxbox_id)
// Search all muxboxes for streams with this source_id (read-only first)
for layout in &app_context_unwrapped.app.layouts {
for muxbox in layout.get_all_muxboxes() {
for (stream_id, stream) in &muxbox.streams {
// Check if this stream matches the source_id
let stream_source_id = match &stream.stream_type {
StreamType::ChoiceExecution(id) => Some(id.clone()),
StreamType::PtySession(id) => {
// Extract source_id from PTY session format "PTY-{source_id}"
if let Some(stripped) = id.strip_prefix("PTY-")
{
Some(stripped.to_string())
} else {
Some(id.clone())
}
}
_ => None,
};
if let Some(stream_src_id) = stream_source_id {
if stream_src_id == source_action.source_id {
log::info!("Found stream {} with source_id {} for termination", stream_id, source_action.source_id);
stream_to_update = Some((
stream_id.clone(),
muxbox.id.clone(),
));
source_terminated = true;
break;
}
}
}
if source_terminated {
break;
}
}
if source_terminated {
break;
}
}
// Now perform the actual cleanup if we found the stream
if let Some((stream_id, muxbox_id)) = stream_to_update {
// Get mutable access to perform cleanup
if let Some(target_muxbox) =
app_context_unwrapped.app.get_muxbox_by_id_mut(&muxbox_id)
{
if let Some(stream) = target_muxbox.streams.get(&stream_id)
{
// Attempt source cleanup based on execution mode
if let Some(ref stream_source) = stream.source {
match source_action.execution_mode {
crate::model::common::ExecutionMode::Immediate => {
// Batch mode - attempt to cancel queued task
if let Err(e) = stream_source.cleanup() {
log::warn!("Failed to cleanup batch source {}: {}", source_action.source_id, e);
} else {
log::info!("Successfully terminated batch source {}", source_action.source_id);
}
}
crate::model::common::ExecutionMode::Thread => {
// Thread mode - interrupt thread execution
if let Err(e) = stream_source.cleanup() {
log::warn!("Failed to cleanup thread source {}: {}", source_action.source_id, e);
} else {
log::info!("Successfully terminated thread source {}", source_action.source_id);
}
}
crate::model::common::ExecutionMode::Pty => {
// PTY mode - kill PTY process
if let Err(e) = stream_source.cleanup() {
log::warn!("Failed to cleanup PTY source {}: {}", source_action.source_id, e);
} else {
log::info!("Successfully terminated PTY source {}", source_action.source_id);
}
}
}
} else {
log::info!("Stream {} source already terminated or inactive", stream_id);
}
// Send StreamUpdate with terminated status
let terminated_state = match source_action.execution_mode {
crate::model::common::ExecutionMode::Immediate => {
crate::model::common::SourceState::Batch(
crate::model::common::BatchSourceState {
task_id: source_action.source_id.clone(),
queue_wait_time: std::time::Duration::from_secs(0),
execution_time: std::time::Duration::from_secs(0),
exit_code: Some(1),
status: crate::model::common::BatchStatus::Failed("Killed by user".to_string())
}
)
}
crate::model::common::ExecutionMode::Thread => {
crate::model::common::SourceState::Thread(
crate::model::common::ThreadSourceState {
thread_id: source_action.source_id.clone(),
execution_time: std::time::Duration::from_secs(0),
exit_code: Some(1),
status: crate::model::common::ExecutionThreadStatus::Failed("Killed by user".to_string())
}
)
}
crate::model::common::ExecutionMode::Pty => {
crate::model::common::SourceState::Pty(
crate::model::common::PtySourceState {
process_id: 0, // Will be updated by actual PTY termination
runtime: std::time::Duration::from_secs(0),
exit_code: Some(1),
status: crate::model::common::ExecutionPtyStatus::Terminated
}
)
}
};
let termination_update =
crate::model::common::StreamUpdate {
stream_id: stream_id.clone(),
target_box_id: muxbox_id.clone(),
content_update:
"\n[Process terminated by user]".to_string(),
source_state: terminated_state,
execution_mode: source_action
.execution_mode
.clone(),
};
inner.send_message(Message::StreamUpdateMessage(
termination_update,
));
}
}
} else {
log::warn!(
"Source {} not found for kill action",
source_action.source_id
);
}
}
crate::model::common::ActionType::Query => {
log::info!(
"Query action for source {} (mode: {:?})",
source_action.source_id,
source_action.execution_mode
);
// Find source and return status information
let mut found_source = false;
for layout in &app_context_unwrapped.app.layouts {
for muxbox in layout.get_all_muxboxes() {
for (stream_id, stream) in &muxbox.streams {
let stream_source_id = match &stream.stream_type {
StreamType::ChoiceExecution(id) => Some(id.clone()),
StreamType::PtySession(id) => {
if let Some(stripped) = id.strip_prefix("PTY-")
{
Some(stripped.to_string())
} else {
Some(id.clone())
}
}
_ => None,
};
if let Some(stream_src_id) = stream_source_id {
if stream_src_id == source_action.source_id {
log::info!(
"Source {} status: stream_id={}, active={}",
source_action.source_id,
stream_id,
stream.source.is_some()
);
found_source = true;
break;
}
}
}
if found_source {
break;
}
}
if found_source {
break;
}
}
if !found_source {
log::info!(
"Source {} not found for query",
source_action.source_id
);
}
}
crate::model::common::ActionType::Pause => {
log::info!("Pause action for source {} (mode: {:?}) - not supported in current implementation",
source_action.source_id, source_action.execution_mode);
// Pause/Resume not implemented in Phase 4 - future enhancement
}
crate::model::common::ActionType::Resume => {
log::info!("Resume action for source {} (mode: {:?}) - not supported in current implementation",
source_action.source_id, source_action.execution_mode);
// Pause/Resume not implemented in Phase 4 - future enhancement
}
}
}
// T0326: REMOVED CreateChoiceExecutionStream handler - replaced by ExecuteScript handler
Message::Exit => should_continue = false,
Message::Terminate => should_continue = false,
Message::NextMuxBox() => {
let active_layout = app_context_unwrapped
.app
.get_active_layout_mut()
.expect("No active layout found!");
// First, collect the IDs of currently selected muxboxes before changing the selection.
let unselected_muxbox_ids: Vec<String> = active_layout
.get_selected_muxboxes()
.iter()
.map(|muxbox| muxbox.id.clone())
.collect();
// Now perform the mutation that changes the muxbox selection.
active_layout.select_next_muxbox();
// After mutation, get the newly selected muxboxes' IDs.
let selected_muxbox_ids: Vec<String> = active_layout
.get_selected_muxboxes()
.iter()
.map(|muxbox| muxbox.id.clone())
.collect();
// Update the application context and issue redraw commands based on the collected IDs.
inner.update_app_context(app_context_unwrapped.clone());
for muxbox_id in unselected_muxbox_ids {
inner.send_message(Message::RedrawMuxBox(muxbox_id));
}
for muxbox_id in selected_muxbox_ids {
inner.send_message(Message::RedrawMuxBox(muxbox_id));
}
}
Message::PreviousMuxBox() => {
let active_layout = app_context_unwrapped
.app
.get_active_layout_mut()
.expect("No active layout found!");
// First, collect the IDs of currently selected muxboxes before changing the selection.
let unselected_muxbox_ids: Vec<String> = active_layout
.get_selected_muxboxes()
.iter()
.map(|muxbox| muxbox.id.clone())
.collect();
// Now perform the mutation that changes the muxbox selection.
active_layout.select_previous_muxbox();
// After mutation, get the newly selected muxboxes' IDs.
let selected_muxbox_ids: Vec<String> = active_layout
.get_selected_muxboxes()
.iter()
.map(|muxbox| muxbox.id.clone())
.collect();
// Update the application context and issue redraw commands based on the collected IDs.
inner.update_app_context(app_context_unwrapped.clone());
for muxbox_id in unselected_muxbox_ids {
inner.send_message(Message::RedrawMuxBox(muxbox_id));
}
for muxbox_id in selected_muxbox_ids {
inner.send_message(Message::RedrawMuxBox(muxbox_id));
}
}
Message::MouseScrollUp(x, y) => {
if let Some(id) = scroll_hovered_box(
&mut app_context_unwrapped,
*x,
*y,
&crate::utils::screen_bounds(),
WheelDirection::Up,
) {
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(id));
}
}
Message::MouseScrollDown(x, y) => {
if let Some(id) = scroll_hovered_box(
&mut app_context_unwrapped,
*x,
*y,
&crate::utils::screen_bounds(),
WheelDirection::Down,
) {
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(id));
}
}
Message::MouseScrollLeft(x, y) => {
if let Some(id) = scroll_hovered_box(
&mut app_context_unwrapped,
*x,
*y,
&crate::utils::screen_bounds(),
WheelDirection::Left,
) {
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(id));
}
}
Message::MouseScrollRight(x, y) => {
if let Some(id) = scroll_hovered_box(
&mut app_context_unwrapped,
*x,
*y,
&crate::utils::screen_bounds(),
WheelDirection::Right,
) {
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(id));
}
}
Message::ScrollMuxBoxDown() => {
let selected_muxboxes = app_context_unwrapped
.app
.get_active_layout()
.unwrap()
.get_selected_muxboxes();
if !selected_muxboxes.is_empty() {
let selected_id = selected_muxboxes.first().unwrap().id.clone();
let muxbox =
app_context_unwrapped.app.get_muxbox_by_id_mut(&selected_id);
if let Some(found_muxbox) = muxbox {
// F0215: Stream-Based Choice Navigation - Use active stream choices
if let Some(choices) =
found_muxbox.get_selected_stream_choices_mut()
{
//select first or next choice
let selected_choice = choices.iter().position(|c| c.selected);
let selected_choice_unwrapped =
selected_choice.unwrap_or_default();
let new_selected_choice =
if selected_choice_unwrapped + 1 < choices.len() {
selected_choice_unwrapped + 1
} else {
0
};
for (i, choice) in choices.iter_mut().enumerate() {
choice.selected = i == new_selected_choice;
}
// Auto-scroll to keep selected choice visible
auto_scroll_to_selected_choice(
found_muxbox,
new_selected_choice,
);
} else {
found_muxbox.scroll_down(Some(1.0));
}
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(selected_id));
}
}
}
Message::ScrollMuxBoxUp() => {
let selected_muxboxes = app_context_unwrapped
.app
.get_active_layout()
.unwrap()
.get_selected_muxboxes();
if !selected_muxboxes.is_empty() {
let selected_id = selected_muxboxes.first().unwrap().id.clone();
let muxbox =
app_context_unwrapped.app.get_muxbox_by_id_mut(&selected_id);
if let Some(found_muxbox) = muxbox {
// F0215: Stream-Based Choice Navigation - Use active stream choices
if let Some(choices) =
found_muxbox.get_selected_stream_choices_mut()
{
//select first or next choice
let selected_choice = choices.iter().position(|c| c.selected);
let selected_choice_unwrapped =
selected_choice.unwrap_or_default();
let new_selected_choice = if selected_choice_unwrapped > 0 {
selected_choice_unwrapped - 1
} else {
choices.len() - 1
};
for (i, choice) in choices.iter_mut().enumerate() {
choice.selected = i == new_selected_choice;
}
// Auto-scroll to keep selected choice visible
auto_scroll_to_selected_choice(
found_muxbox,
new_selected_choice,
);
} else {
found_muxbox.scroll_up(Some(1.0));
}
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(selected_id));
}
}
}
Message::ScrollMuxBoxLeft() => {
let selected_muxboxes = app_context_unwrapped
.app
.get_active_layout()
.unwrap()
.get_selected_muxboxes();
if !selected_muxboxes.is_empty() {
let selected_id = selected_muxboxes.first().unwrap().id.clone();
let muxbox =
app_context_unwrapped.app.get_muxbox_by_id_mut(&selected_id);
if let Some(found_muxbox) = muxbox {
found_muxbox.scroll_left(Some(1.0));
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(selected_id));
}
}
}
Message::ScrollMuxBoxRight() => {
let selected_muxboxes = app_context_unwrapped
.app
.get_active_layout()
.unwrap()
.get_selected_muxboxes();
if !selected_muxboxes.is_empty() {
let selected_id = selected_muxboxes.first().unwrap().id.clone();
let muxbox =
app_context_unwrapped.app.get_muxbox_by_id_mut(&selected_id);
if let Some(found_muxbox) = muxbox {
found_muxbox.scroll_right(Some(1.0));
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(selected_id));
}
}
}
Message::ScrollMuxBoxPageUp() => {
let selected_muxboxes = app_context_unwrapped
.app
.get_active_layout()
.unwrap()
.get_selected_muxboxes();
if !selected_muxboxes.is_empty() {
let selected_id = selected_muxboxes.first().unwrap().id.clone();
let muxbox =
app_context_unwrapped.app.get_muxbox_by_id_mut(&selected_id);
if let Some(found_muxbox) = muxbox {
// Page up scrolls by larger amount (10 units for page-based scrolling)
found_muxbox.scroll_up(Some(10.0));
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(selected_id));
}
}
}
Message::ScrollMuxBoxPageDown() => {
let selected_muxboxes = app_context_unwrapped
.app
.get_active_layout()
.unwrap()
.get_selected_muxboxes();
if !selected_muxboxes.is_empty() {
let selected_id = selected_muxboxes.first().unwrap().id.clone();
let muxbox =
app_context_unwrapped.app.get_muxbox_by_id_mut(&selected_id);
if let Some(found_muxbox) = muxbox {
// Page down scrolls by larger amount (10 units for page-based scrolling)
found_muxbox.scroll_down(Some(10.0));
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(selected_id));
}
}
}
Message::ScrollMuxBoxPageLeft() => {
let selected_muxboxes = app_context_unwrapped
.app
.get_active_layout()
.unwrap()
.get_selected_muxboxes();
if !selected_muxboxes.is_empty() {
let selected_id = selected_muxboxes.first().unwrap().id.clone();
let muxbox =
app_context_unwrapped.app.get_muxbox_by_id_mut(&selected_id);
if let Some(found_muxbox) = muxbox {
// Page left scrolls by larger amount (10 units for page-based scrolling)
found_muxbox.scroll_left(Some(10.0));
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(selected_id));
}
}
}
Message::ScrollMuxBoxPageRight() => {
let selected_muxboxes = app_context_unwrapped
.app
.get_active_layout()
.unwrap()
.get_selected_muxboxes();
if !selected_muxboxes.is_empty() {
let selected_id = selected_muxboxes.first().unwrap().id.clone();
let muxbox =
app_context_unwrapped.app.get_muxbox_by_id_mut(&selected_id);
if let Some(found_muxbox) = muxbox {
// Page right scrolls by larger amount (10 units for page-based scrolling)
found_muxbox.scroll_right(Some(10.0));
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(selected_id));
}
}
}
Message::ScrollMuxBoxToBeginning() => {
// Home key: scroll to beginning horizontally (horizontal_scroll = 0)
let selected_muxboxes = app_context_unwrapped
.app
.get_active_layout()
.unwrap()
.get_selected_muxboxes();
if !selected_muxboxes.is_empty() {
let selected_id = selected_muxboxes.first().unwrap().id.clone();
let muxbox =
app_context_unwrapped.app.get_muxbox_by_id_mut(&selected_id);
if let Some(found_muxbox) = muxbox {
found_muxbox.horizontal_scroll = Some(0.0);
// F0200: Save scroll position to YAML
inner.send_message(Message::SaveMuxBoxScroll(
found_muxbox.id.clone(),
0,
(found_muxbox.vertical_scroll.unwrap_or(0.0) * 100.0) as usize,
));
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(selected_id));
}
}
}
Message::ScrollMuxBoxToEnd() => {
// End key: scroll to end horizontally (horizontal_scroll = 100)
let selected_muxboxes = app_context_unwrapped
.app
.get_active_layout()
.unwrap()
.get_selected_muxboxes();
if !selected_muxboxes.is_empty() {
let selected_id = selected_muxboxes.first().unwrap().id.clone();
let muxbox =
app_context_unwrapped.app.get_muxbox_by_id_mut(&selected_id);
if let Some(found_muxbox) = muxbox {
found_muxbox.horizontal_scroll = Some(100.0);
// F0200: Save scroll position to YAML
inner.send_message(Message::SaveMuxBoxScroll(
found_muxbox.id.clone(),
100,
(found_muxbox.vertical_scroll.unwrap_or(0.0) * 100.0) as usize,
));
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(selected_id));
}
}
}
Message::ScrollMuxBoxToTop() => {
// Ctrl+Home: scroll to top vertically (vertical_scroll = 0)
let selected_muxboxes = app_context_unwrapped
.app
.get_active_layout()
.unwrap()
.get_selected_muxboxes();
if !selected_muxboxes.is_empty() {
let selected_id = selected_muxboxes.first().unwrap().id.clone();
let muxbox =
app_context_unwrapped.app.get_muxbox_by_id_mut(&selected_id);
if let Some(found_muxbox) = muxbox {
found_muxbox.vertical_scroll = Some(0.0);
// F0200: Save scroll position to YAML
inner.send_message(Message::SaveMuxBoxScroll(
found_muxbox.id.clone(),
(found_muxbox.horizontal_scroll.unwrap_or(0.0) * 100.0)
as usize,
0,
));
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(selected_id));
}
}
}
Message::ScrollMuxBoxToBottom() => {
// Ctrl+End: scroll to bottom vertically (vertical_scroll = 100)
let selected_muxboxes = app_context_unwrapped
.app
.get_active_layout()
.unwrap()
.get_selected_muxboxes();
if !selected_muxboxes.is_empty() {
let selected_id = selected_muxboxes.first().unwrap().id.clone();
let muxbox =
app_context_unwrapped.app.get_muxbox_by_id_mut(&selected_id);
if let Some(found_muxbox) = muxbox {
found_muxbox.vertical_scroll = Some(100.0);
// F0200: Save scroll position to YAML
inner.send_message(Message::SaveMuxBoxScroll(
found_muxbox.id.clone(),
(found_muxbox.horizontal_scroll.unwrap_or(0.0) * 100.0)
as usize,
100,
));
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(selected_id));
}
}
}
Message::CopyFocusedMuxBoxContent() => {
let selected_muxboxes = app_context_unwrapped
.app
.get_active_layout()
.unwrap()
.get_selected_muxboxes();
if !selected_muxboxes.is_empty() {
let selected_id = selected_muxboxes.first().unwrap().id.clone();
let muxbox = app_context_unwrapped.app.get_muxbox_by_id(&selected_id);
if let Some(found_muxbox) = muxbox {
// Get muxbox content to copy
let content_to_copy =
get_muxbox_content_for_clipboard(found_muxbox);
// Copy to clipboard
if copy_to_clipboard(&content_to_copy).is_ok() {
// Trigger visual flash for the muxbox
trigger_muxbox_flash(&selected_id);
inner.send_message(Message::RedrawMuxBox(selected_id));
}
}
}
}
Message::RedrawMuxBox(muxbox_id) => {
if let Some(found_muxbox) = app_context_unwrapped
.app
.get_muxbox_by_id_mut(muxbox_id)
.cloned()
{
new_buffer = buffer.clone();
// Clone the parent layout to avoid mutable borrow conflicts
if let Some(parent_layout) =
found_muxbox.get_parent_layout_clone(&app_context_unwrapped)
{
draw_muxbox(
&app_context_unwrapped,
&app_graph,
&adjusted_bounds,
&parent_layout,
&found_muxbox,
&mut new_buffer,
);
apply_buffer_if_changed(buffer, &new_buffer, screen);
*buffer = new_buffer;
}
}
}
Message::RedrawApp | Message::Resize => {
screen
.execute(crossterm::terminal::Clear(
crossterm::terminal::ClearType::All,
))
.unwrap();
let mut new_buffer = ScreenBuffer::new();
draw_app(
&app_context_unwrapped,
&app_graph,
&adjusted_bounds,
&mut new_buffer,
);
apply_calibration_cursor_overlay(&app_context_unwrapped, &mut new_buffer);
apply_buffer(&mut new_buffer, screen);
*buffer = new_buffer;
}
Message::RedrawAppDiff => {
// Redraw entire app with diff-based rendering (no screen clear)
let mut new_buffer = ScreenBuffer::new();
draw_app(
&app_context_unwrapped,
&app_graph,
&adjusted_bounds,
&mut new_buffer,
);
apply_calibration_cursor_overlay(&app_context_unwrapped, &mut new_buffer);
apply_buffer_if_changed(buffer, &new_buffer, screen);
*buffer = new_buffer;
}
// T0328: REMOVED MuxBoxOutputUpdate handler - replaced by StreamUpdateMessage handler
// ExternalMessage handling is now done by RSJanusComms library
// Messages are converted to appropriate internal messages by the socket handler
Message::ExternalMessage(_) => {
// This should no longer be used - socket handler converts messages directly
log::warn!("Received deprecated ExternalMessage - should be converted by socket handler");
}
Message::ExecuteHotKeyChoice(choice_id) => {
log::info!("=== EXECUTING HOT KEY CHOICE: {} ===", choice_id);
// F0229: Unified ExecutionMode System - all execution paths use same unified stream approach
// First extract the data we need without borrowing app_context_unwrapped
let (choice_data, muxbox_id, libs) = {
let active_layout =
app_context_unwrapped.app.get_active_layout().unwrap();
let libs = app_context_unwrapped.app.libs.clone();
// Find the choice by ID in any muxbox
log::info!("Searching for choice {} in active layout", choice_id);
if let Some(choice_muxbox) =
active_layout.find_muxbox_with_choice(choice_id)
{
log::info!("Found choice in muxbox: {}", choice_muxbox.id);
if let Some(choices) = choice_muxbox.get_selected_stream_choices() {
if let Some(choice) =
choices.iter().find(|c| c.id == *choice_id)
{
log::info!("Hotkey choice config - execution_mode: {:?}, redirect: {:?}, script_lines: {}",
choice.execution_mode,
choice.redirect_output,
choice.script.as_ref().map(|s| s.len()).unwrap_or(0)
);
if let Some(script) = &choice.script {
(
Some((choice.clone(), script.clone())),
choice_muxbox.id.clone(),
libs,
)
} else {
(None, choice_muxbox.id.clone(), libs)
}
} else {
log::warn!("Choice {} found in muxbox {} but no matching choice in choices list", choice_id, choice_muxbox.id);
(None, choice_muxbox.id.clone(), libs)
}
} else {
log::warn!("MuxBox {} has no choices list", choice_muxbox.id);
(None, choice_muxbox.id.clone(), libs)
}
} else {
log::error!(
"Choice {} not found in any muxbox of active layout",
choice_id
);
(None, String::new(), libs)
}
};
// T0316: UNIFIED ARCHITECTURE - Replace legacy hotkey execution with ExecuteScript message
if let Some((choice, script)) = choice_data {
log::info!(
"T0316: Hotkey creating ExecuteScript for choice {} (mode: {:?})",
choice_id,
choice.execution_mode
);
// Create ExecuteScript message instead of direct execution
use crate::model::common::{
ExecuteScript, ExecutionSource, SourceReference, SourceType,
};
// Register execution source and get stream_id
let source_type =
crate::model::common::ExecutionSourceType::HotkeyScript {
hotkey: format!("hotkey_for_{}", choice_id), // We don't have the actual key here, use placeholder
script: script.clone(),
};
let stream_id = app_context_unwrapped
.app
.register_execution_source(source_type, muxbox_id.clone());
let execute_script = ExecuteScript {
script: script.clone(),
source: ExecutionSource {
source_type: SourceType::HotkeyScript,
source_id: format!("hotkey_choice_{}", choice_id),
source_reference: SourceReference::Choice(choice.clone()),
},
execution_mode: choice.execution_mode.clone(),
target_box_id: muxbox_id.clone(),
libs: libs.unwrap_or_default(),
redirect_output: choice.redirect_output.clone(),
append_output: choice.append_output.unwrap_or(false),
stream_id,
target_bounds: app_context_unwrapped
.app
.get_active_layout()
.and_then(|layout| {
layout
.children
.as_ref()?
.iter()
.find(|mb| mb.id == *muxbox_id)
})
.map(|mb| mb.bounds()),
};
// Send ExecuteScript message instead of calling legacy execute_choice_stream_only
inner.send_message(Message::ExecuteScriptMessage(execute_script));
log::info!(
"T0316: ExecuteScript message sent for hotkey choice {} (unified architecture)",
choice_id
);
}
}
Message::KeyPress(pressed_key) => {
let mut app_context_for_keypress = app_context_unwrapped.clone();
let active_layout = app_context_unwrapped.app.get_active_layout().unwrap();
let selected_muxboxes: Vec<&MuxBox> = active_layout.get_selected_muxboxes();
let selected_muxboxes_with_keypress_events: Vec<&MuxBox> =
selected_muxboxes
.clone()
.into_iter()
.filter(|p| p.on_keypress.is_some())
.filter(|p| p.get_selected_stream_choices().is_none())
.collect();
let libs = app_context_unwrapped.app.libs.clone();
if pressed_key == "Enter" {
let selected_muxboxes_with_choices: Vec<&MuxBox> = selected_muxboxes
.into_iter()
.filter(|p| p.get_selected_stream_choices().is_some())
.collect();
for muxbox in selected_muxboxes_with_choices {
// First, extract choice information before any mutable operations
let (selected_choice_data, choice_needs_execution) = {
let muxbox_ref = app_context_for_keypress
.app
.get_muxbox_by_id(&muxbox.id)
.unwrap();
if let Some(choices) = muxbox_ref.get_selected_stream_choices()
{
if let Some(selected_choice) =
choices.iter().find(|c| c.selected)
{
let choice_data = (
selected_choice.id.clone(),
selected_choice.script.clone(),
selected_choice.execution_mode.clone(), // Use ExecutionMode directly instead of boolean flags
selected_choice.redirect_output.clone(),
selected_choice.append_output.unwrap_or(false),
muxbox.id.clone(),
);
(Some(choice_data), selected_choice.script.is_some())
} else {
(None, false)
}
} else {
(None, false)
}
};
if let Some((
choice_id,
script_opt,
execution_mode,
redirect_output,
append_output,
muxbox_id,
)) = selected_choice_data
{
if choice_needs_execution {
log::info!(
"=== ENTER KEY CHOICE EXECUTION: {} (muxbox: {}) ===",
choice_id,
muxbox_id
);
log::info!("Enter choice config - execution_mode: {:?}, redirect: {:?}",
execution_mode, redirect_output
);
if let Some(script) = script_opt {
let libs_clone = libs.clone();
// Set choice to waiting state before execution
if let Some(muxbox_mut) = app_context_for_keypress
.app
.get_muxbox_by_id_mut(&muxbox_id)
{
if let Some(choices) =
muxbox_mut.get_selected_stream_choices_mut()
{
if let Some(choice) = choices
.iter_mut()
.find(|c| c.id == choice_id)
{
choice.waiting = true;
}
}
}
// T0314: UNIFIED ARCHITECTURE - Replace legacy execution with ExecuteScript message
log::info!("T0314: Enter key creating ExecuteScript for choice {} (mode: {:?})", choice_id, execution_mode);
// Create ExecuteScript message instead of direct execution
use crate::model::common::{
ExecuteScript, ExecutionSource, SourceReference,
SourceType,
};
// Create choice object for SourceReference
let choice_for_reference = Choice {
id: choice_id.clone(),
content: Some("".to_string()),
selected: false,
script: Some(script.clone()),
execution_mode: execution_mode.clone(),
redirect_output: redirect_output.clone(),
append_output: Some(append_output),
waiting: true,
hovered: false,
};
// Register execution source and get stream_id
let source_type = crate::model::common::ExecutionSourceType::ChoiceExecution {
choice_id: choice_id.clone(),
script: script.clone(),
redirect_output: redirect_output.clone(),
};
// Restructure to avoid borrow conflicts - get stream_id before holding references
let stream_id = {
let mut app_for_registration =
app_context_unwrapped.clone();
app_for_registration.app.register_execution_source(
source_type,
muxbox_id.clone(),
)
};
let execute_script = ExecuteScript {
script: script.clone(),
source: ExecutionSource {
source_type: SourceType::Choice(
choice_id.clone(),
),
source_id: format!("choice_{}", choice_id),
source_reference: SourceReference::Choice(
choice_for_reference,
),
},
execution_mode: execution_mode.clone(),
target_box_id: muxbox_id.clone(),
libs: libs_clone.unwrap_or_default(),
redirect_output: redirect_output.clone(),
append_output,
stream_id: stream_id.clone(),
target_bounds: Some(muxbox.bounds()),
};
// UNIFIED EXECUTION ARCHITECTURE: Route ExecuteScript based on execution mode
match execution_mode {
crate::model::common::ExecutionMode::Immediate
| crate::model::common::ExecutionMode::Thread => {
// Send to ThreadManager for Immediate/Thread execution
inner.send_message(
Message::ExecuteScriptMessage(
execute_script,
),
);
log::info!(
"T0314: ExecuteScript message sent to ThreadManager for choice {} (mode: {:?})",
choice_id, execution_mode
);
}
crate::model::common::ExecutionMode::Pty => {
// FIXED: Route PTY execution to PTYManager, never to ThreadManager
log::info!(
"T0314 FIXED: Routing PTY ExecuteScript to PTYManager for choice {} (mode: {:?})",
choice_id, execution_mode
);
// Route to PTYManager instead of ThreadManager
if let Some(pty_manager) =
&app_context_unwrapped.pty_manager
{
// Get message sender for PTY communication
if let Some(sender) =
inner.get_message_sender()
{
let uuid = uuid::Uuid::new_v4();
// Call PTYManager's ExecuteScript handler
if let Err(e) = pty_manager
.handle_execute_script(
&execute_script,
sender.clone(),
uuid,
)
{
log::error!(
"T0314: PTYManager failed to handle ExecuteScript for choice {}: {}",
choice_id, e
);
} else {
log::info!(
"T0314 FIXED: PTYManager successfully handling ExecuteScript for choice {} (architecture compliant)",
choice_id
);
}
} else {
log::error!("No message sender available for PTY execution - choice {}", choice_id);
}
} else {
log::error!("No PTYManager available - PTY execution failed for choice {}", choice_id);
}
log::info!(
"T0314 FIXED: PTY execution routed to PTYManager for choice {} (never sent to ThreadManager)",
choice_id
);
}
}
// Update the app context to persist the waiting state change
inner.update_app_context(
app_context_for_keypress.clone(),
);
}
}
}
}
}
// T0317: UNIFIED ARCHITECTURE - Replace muxbox keypress run_script with ExecuteScript messages
for muxbox in selected_muxboxes_with_keypress_events {
let actions =
handle_keypress(pressed_key, &muxbox.on_keypress.clone().unwrap());
if let Some(actions_unwrapped) = actions {
let libs = app_context_unwrapped.app.libs.clone();
log::info!("T0317: Creating ExecuteScript for muxbox keypress handler {} ({})", muxbox.id, pressed_key);
// Create ExecuteScript message for muxbox-level keypress handlers
use crate::model::common::{
ExecuteScript, ExecutionMode, ExecutionSource, SourceReference,
SourceType,
};
// Register execution source and get stream_id
let target_box_id = muxbox
.redirect_output
.as_ref()
.unwrap_or(&muxbox.id)
.clone();
let source_type =
crate::model::common::ExecutionSourceType::SocketUpdate {
command_type: format!("keypress_{}", pressed_key),
};
// Restructure to avoid borrow conflicts - get stream_id with separate context
let stream_id = {
let mut app_for_registration = app_context_unwrapped.clone();
app_for_registration.app.register_execution_source(
source_type,
target_box_id.clone(),
)
};
let execute_script = ExecuteScript {
script: actions_unwrapped,
source: ExecutionSource {
source_type: SourceType::SocketUpdate,
source_id: format!(
"muxbox_keypress_{}_{}",
muxbox.id, pressed_key
),
source_reference: SourceReference::SocketCommand(format!(
"muxbox {} keypress: {}",
muxbox.id, pressed_key
)),
},
execution_mode: ExecutionMode::Immediate, // Muxbox-level handlers use immediate execution
target_box_id,
libs: libs.unwrap_or_default(),
redirect_output: muxbox.redirect_output.clone(),
append_output: muxbox.append_output.unwrap_or(false),
stream_id,
target_bounds: Some(muxbox.bounds()),
};
inner.send_message(Message::ExecuteScriptMessage(execute_script));
log::info!("T0317: ExecuteScript message sent for muxbox {} keypress handler ({})", muxbox.id, pressed_key);
}
}
}
Message::PTYInput(muxbox_id, input) => {
log::trace!("PTY input for muxbox {}: {}", muxbox_id, input);
// Find the target muxbox to verify it exists and has PTY enabled
if let Some(muxbox) = app_context_unwrapped.app.get_muxbox_by_id(muxbox_id)
{
// F0229: Use ExecutionMode instead of legacy pty field
if muxbox.execution_mode == crate::model::common::ExecutionMode::Pty {
log::debug!(
"Routing input to PTY muxbox {}: {:?}",
muxbox_id,
input.chars().collect::<Vec<_>>()
);
// TODO: Write input to PTY process when PTY manager is thread-safe
// For now, log the successful routing detection
log::info!(
"PTY input ready for routing to muxbox {}: {} chars",
muxbox_id,
input.len()
);
} else {
log::warn!(
"MuxBox {} received PTY input but pty field is false",
muxbox_id
);
}
} else {
log::error!(
"PTY input received for non-existent muxbox: {}",
muxbox_id
);
}
}
Message::PTYMouseEvent(muxbox_id, kind, column, row, modifiers) => {
log::trace!(
"PTY mouse event for muxbox {}: {:?} at ({}, {})",
muxbox_id,
kind,
column,
row
);
// Find the target muxbox to verify it exists and has PTY enabled
if let Some(muxbox) = app_context_unwrapped.app.get_muxbox_by_id(muxbox_id)
{
if muxbox.execution_mode == crate::model::common::ExecutionMode::Pty {
// Generate terminal state-aware mouse sequence using PTY manager
if let Some(pty_manager) = &app_context_unwrapped.pty_manager {
if let Some(mouse_sequence) = pty_manager
.generate_mouse_sequence(
muxbox_id, *kind, *column, *row, *modifiers,
)
{
match pty_manager.send_input(muxbox_id, &mouse_sequence) {
Ok(_) => {
log::debug!(
"Sent PTY mouse sequence to muxbox {}: {}",
muxbox_id,
mouse_sequence
);
}
Err(e) => {
log::error!("Failed to send PTY mouse sequence to muxbox {}: {}", muxbox_id, e);
}
}
} else {
log::trace!(
"Mouse reporting disabled for muxbox {}",
muxbox_id
);
}
} else {
log::error!(
"Could not lock PTY manager for mouse event processing"
);
}
} else {
log::warn!("MuxBox {} received PTY mouse event but execution_mode is not Pty", muxbox_id);
}
} else {
log::error!(
"PTY mouse event received for non-existent muxbox: {}",
muxbox_id
);
}
}
Message::MouseClick(x, y) => {
log::trace!("Mouse click at ({}, {})", x, y);
let mut app_context_for_click = app_context_unwrapped.clone();
let active_layout = app_context_unwrapped.app.get_active_layout().unwrap();
// F0187: Check for scrollbar clicks first — but only on the
// TOP-MOST box at the cursor. Iterating every box let a box
// whose bottom-border (horizontal scrollbar) row coincides
// with another box's tab-bar row steal the click, which is why
// the central panel's tabs were unclickable at sizes where the
// edges shared a row.
let mut handled_scrollbar_click = false;
if let Some(muxbox) = active_layout.find_muxbox_at_coordinates(*x, *y) {
if muxbox.has_scrollable_content() {
let muxbox_bounds = muxbox.bounds();
// Check for vertical scrollbar click (right border)
if *x as usize == muxbox_bounds.right()
&& *y as usize > muxbox_bounds.top()
&& (*y as usize) < muxbox_bounds.bottom().saturating_sub(1)
{
let track_height =
(muxbox_bounds.height() as isize - 2).max(1) as usize;
let click_position = ((*y as usize) - muxbox_bounds.top() - 1)
as f64
/ track_height as f64;
let scroll_percentage =
(click_position * 100.0).clamp(0.0, 100.0);
log::trace!(
"Vertical scrollbar click on muxbox {} at {}%",
muxbox.id,
scroll_percentage
);
// Update muxbox vertical scroll
let (muxbox_id, horizontal_scroll) = {
let muxbox_to_update = app_context_for_click
.app
.get_muxbox_by_id_mut(&muxbox.id)
.unwrap();
muxbox_to_update.vertical_scroll = Some(scroll_percentage);
(
muxbox_to_update.id.clone(),
muxbox_to_update.horizontal_scroll.unwrap_or(0.0),
)
};
inner.update_app_context(app_context_for_click.clone());
inner.send_message(Message::RedrawAppDiff);
handled_scrollbar_click = true;
// F0200: Save scroll position to YAML
inner.send_message(Message::SaveMuxBoxScroll(
muxbox_id,
(horizontal_scroll * 100.0) as usize,
(scroll_percentage * 100.0) as usize,
));
}
// Check for horizontal scrollbar click (on bottom border)
if *y as usize == muxbox_bounds.bottom()
&& *x as usize > muxbox_bounds.left()
&& (*x as usize) < muxbox_bounds.right().saturating_sub(1)
{
let track_width =
(muxbox_bounds.width() as isize - 2).max(1) as usize;
let click_position = ((*x as usize) - muxbox_bounds.left() - 1)
as f64
/ track_width as f64;
let scroll_percentage =
(click_position * 100.0).clamp(0.0, 100.0);
log::trace!(
"Horizontal scrollbar click on muxbox {} at {}%",
muxbox.id,
scroll_percentage
);
// Update muxbox horizontal scroll
let (muxbox_id, vertical_scroll) = {
let muxbox_to_update = app_context_for_click
.app
.get_muxbox_by_id_mut(&muxbox.id)
.unwrap();
muxbox_to_update.horizontal_scroll =
Some(scroll_percentage);
(
muxbox_to_update.id.clone(),
muxbox_to_update.vertical_scroll.unwrap_or(0.0),
)
};
inner.update_app_context(app_context_for_click.clone());
inner.send_message(Message::RedrawAppDiff);
handled_scrollbar_click = true;
// F0200: Save scroll position to YAML
inner.send_message(Message::SaveMuxBoxScroll(
muxbox_id,
(scroll_percentage * 100.0) as usize,
(vertical_scroll * 100.0) as usize,
));
}
}
}
// If scrollbar click was handled, skip muxbox selection
if handled_scrollbar_click {
// Continue to next message
} else {
// F0203: Check for tab clicks first using proper z-index ordering
let mut handled_tab_click = false;
// Find the top-most muxbox at the click coordinates (respects z-index)
if let Some(clicked_muxbox) =
active_layout.find_muxbox_at_coordinates(*x, *y)
{
let muxbox_bounds = clicked_muxbox.bounds();
// Check if click is in title bar area specifically
if *y as usize == muxbox_bounds.top() {
let tab_labels = clicked_muxbox.get_tab_labels();
log::debug!("Title bar click at ({},{}) in top-most muxbox '{}' with {} tabs: {:?}",
*x, *y, clicked_muxbox.id, tab_labels.len(), tab_labels);
let has_border = clicked_muxbox
.calc_border(&app_context_unwrapped.clone(), &app_graph);
log::debug!(
"Muxbox bounds: left={}, right={}, top={}, border={}",
muxbox_bounds.left(),
muxbox_bounds.right(),
muxbox_bounds.top(),
has_border
);
let tab_close_buttons = clicked_muxbox.get_tab_close_buttons();
let tab_hit_target =
crate::draw_utils::calculate_tab_hit_target(
*x as usize,
muxbox_bounds.left(),
muxbox_bounds.right(),
&tab_labels,
&tab_close_buttons,
clicked_muxbox.tab_scroll_offset,
&clicked_muxbox.calc_border_color(
&app_context_unwrapped,
&app_graph,
),
&clicked_muxbox.bg_color,
);
// Check for navigation arrow clicks first
if let Some(crate::draw_utils::TabHitTarget::Navigation(
nav_action,
)) = tab_hit_target.as_ref()
{
log::info!(
"Tab navigation clicked: muxbox {} action {:?}",
clicked_muxbox.id,
nav_action
);
if let Some(muxbox) = app_context_for_click
.app
.get_muxbox_by_id_mut(&clicked_muxbox.id)
{
match nav_action {
crate::draw_utils::TabNavigationAction::ScrollLeft => {
muxbox.scroll_tabs_left();
log::info!("Scrolled tabs left for muxbox '{}', new offset: {}", muxbox.id, muxbox.tab_scroll_offset);
},
crate::draw_utils::TabNavigationAction::ScrollRight => {
muxbox.scroll_tabs_right();
log::info!("Scrolled tabs right for muxbox '{}', new offset: {}", muxbox.id, muxbox.tab_scroll_offset);
},
}
inner.update_app_context(app_context_for_click.clone());
}
handled_tab_click = true;
} else if let Some(
crate::draw_utils::TabHitTarget::CloseButton(
close_tab_index,
),
) = tab_hit_target.as_ref()
{
// T0323: Tab close integration with unified execution architecture
let stream_ids = clicked_muxbox.get_tab_stream_ids();
if let Some(stream_id) = stream_ids.get(*close_tab_index) {
log::info!(
"Close button clicked for tab {} (stream: {})",
close_tab_index,
stream_id
);
// Get stream info to determine source_id and execution_mode
if let Some(stream) =
clicked_muxbox.streams.get(stream_id)
{
if stream.is_closeable() {
log::info!(
"Processing close tab for closeable stream {} in muxbox {}",
stream_id,
clicked_muxbox.id
);
// Extract source_id and execution_mode from stream type
let (source_id, execution_mode) = match &stream
.stream_type
{
StreamType::ChoiceExecution(id) => {
// Choice execution streams - determine execution mode from stream context
// For now, default to Thread mode for choice executions
(id.clone(), crate::model::common::ExecutionMode::Thread)
}
StreamType::PtySession(id) => {
// PTY session streams - extract source_id from "PTY-{source_id}" format
let actual_source_id =
if let Some(stripped) =
id.strip_prefix("PTY-")
{
stripped.to_string()
} else {
id.clone()
};
(actual_source_id, crate::model::common::ExecutionMode::Pty)
}
StreamType::RedirectedOutput(_) => {
// Redirected output streams - use stream_id as source_id
(stream_id.clone(), crate::model::common::ExecutionMode::Thread)
}
StreamType::ExternalSocket => {
// External socket streams - use stream_id as source_id
(stream_id.clone(), crate::model::common::ExecutionMode::Thread)
}
_ => {
// Content/Choices streams are not closeable - this shouldn't happen
log::warn!("Unexpected closeable stream type: {:?}", stream.stream_type);
(stream_id.clone(), crate::model::common::ExecutionMode::Thread)
}
};
// Create SourceAction Kill message to terminate the source
let kill_action = crate::model::common::SourceAction {
action: crate::model::common::ActionType::Kill,
source_id,
execution_mode,
};
log::info!("Sending SourceAction Kill for source {} (mode: {:?})",
kill_action.source_id, kill_action.execution_mode);
// Send SourceAction message - this will be handled by the unified architecture
inner.send_message(
Message::SourceActionMessage(kill_action),
);
// Also directly remove the stream for immediate UI feedback
// The SourceAction will handle process termination
let mut app_context_for_close =
app_context_unwrapped.clone();
if let Some(muxbox) = app_context_for_close
.app
.get_muxbox_by_id_mut(&clicked_muxbox.id)
{
if muxbox.streams.contains_key(stream_id) {
let _removed_source =
muxbox.remove_stream(stream_id);
log::info!("Stream {} removed from UI (source termination handled by SourceAction)", stream_id);
// Update app context and trigger redraw for immediate UI response
inner.update_app_context(
app_context_for_close.clone(),
);
inner.send_message(
Message::RedrawAppDiff,
);
}
}
} else {
log::info!(
"Stream {} in muxbox {} is not closeable",
stream_id,
clicked_muxbox.id
);
}
}
}
handled_tab_click = true;
} else if let Some(crate::draw_utils::TabHitTarget::Tab(
clicked_tab_index,
)) = tab_hit_target.as_ref()
{
log::info!(
"Tab click detected: muxbox {} tab {} ({})",
clicked_muxbox.id,
clicked_tab_index,
tab_labels
.get(*clicked_tab_index)
.unwrap_or(&"unknown".to_string())
);
log::info!("Processing SwitchTab directly: muxbox={}, tab_index={}", clicked_muxbox.id, clicked_tab_index);
if let Some(muxbox) = app_context_for_click
.app
.get_muxbox_by_id_mut(&clicked_muxbox.id)
{
if muxbox.switch_to_tab(*clicked_tab_index) {
log::info!(
"Successfully switched muxbox '{}' to tab {}",
muxbox.id,
clicked_tab_index
);
inner.update_app_context(
app_context_for_click.clone(),
);
} else {
log::warn!("Failed to switch muxbox '{}' to tab {} - switch_to_tab returned false", muxbox.id, clicked_tab_index);
}
}
handled_tab_click = true;
} else {
log::debug!("Click in title bar but not on tab area - allowing move/drag operation");
}
}
}
if !handled_tab_click {
// F0091: Find which muxbox was clicked based on coordinates
if let Some(clicked_muxbox) =
active_layout.find_muxbox_at_coordinates(*x, *y)
{
log::trace!("Clicked on muxbox: {}", clicked_muxbox.id);
// FORMALIZED COORDINATE SYSTEM: Use BoxDimensions for all coordinate translation
log::info!(
"CLICK: Processing click on muxbox '{}' at screen ({}, {})",
clicked_muxbox.id,
*x,
*y
);
// UNIVERSAL BOX SELECTION: Select any muxbox that is clicked, regardless of specific actions
log::trace!("Selecting muxbox on click: {}", clicked_muxbox.id);
let layout =
app_context_for_click.app.get_active_layout_mut().unwrap();
layout.deselect_all_muxboxes();
layout.select_only_muxbox(&clicked_muxbox.id);
inner.update_app_context(app_context_for_click.clone());
inner.send_message(Message::RedrawAppDiff);
// Check if muxbox has choices (menu items) in the currently selected stream
log::info!(
"CLICK DEBUG: Checking selected stream for muxbox '{}'",
clicked_muxbox.id
);
if let Some(selected_stream) =
clicked_muxbox.get_selected_stream()
{
log::info!(
"CLICK DEBUG: Found selected stream type: {:?}, has choices: {}",
selected_stream.stream_type,
selected_stream.choices.as_ref().map(|c| c.len()).unwrap_or(0)
);
if let Some(choices) = selected_stream.choices.as_ref() {
if !choices.is_empty() {
use crate::components::box_renderer::{
BoxDimensions, BoxRenderer,
};
use crate::components::choice_menu::ChoiceMenu;
use crate::components::renderable_content::RenderableContent;
// Create BoxRenderer and ChoiceMenu
let mut box_renderer = BoxRenderer::new(
clicked_muxbox,
format!("{}_click_renderer", clicked_muxbox.id),
);
let choice_menu = ChoiceMenu::new(
format!("{}_choice_menu", clicked_muxbox.id),
choices,
)
.with_selection(
clicked_muxbox.selected_choice_index(),
)
.with_focus(clicked_muxbox.focused_choice_index());
// Create formalized BoxDimensions
let bounds = clicked_muxbox.bounds();
let (content_width, content_height) =
choice_menu.get_dimensions();
let dimensions = BoxDimensions::new(
clicked_muxbox,
&bounds,
content_width,
content_height,
);
// Generate sensitive zones (one row per choice), matching
// exactly what the renderer draws; viewable clamping happens
// during translation through the shared coordinate mapping.
let box_relative_zones =
choice_menu.get_box_relative_sensitive_zones();
let translated_zones = box_renderer
.translate_box_relative_zones_to_absolute(
&box_relative_zones,
&bounds,
content_width,
content_height,
dimensions.viewable_width,
dimensions.viewable_height,
dimensions.horizontal_scroll,
dimensions.vertical_scroll,
false,
);
box_renderer.store_translated_sensitive_zones(
translated_zones,
);
// Handle click using formalized coordinate system
if let Some(clicked_choice_idx) = box_renderer
.handle_click_with_dimensions(
*x as usize,
*y as usize,
&dimensions,
)
{
log::info!("CLICK: BoxRenderer detected click on choice {} for muxbox '{}'", clicked_choice_idx, clicked_muxbox.id);
// Extract choice execution using formalized coordinate translation
if let Some(choices) =
clicked_muxbox.get_selected_stream_choices()
{
// Find clicked choice using screen-to-inbox coordinate translation
let zones =
box_renderer.get_sensitive_zones();
let screen_x = *x as usize;
let screen_y = *y as usize;
// Convert to inbox coordinates for logging
if let Some((inbox_x, inbox_y)) = dimensions
.screen_to_inbox(screen_x, screen_y)
{
log::info!("CLICK TRANSLATION: Screen ({},{}) -> Inbox ({},{})",
screen_x, screen_y, inbox_x, inbox_y);
}
// Find clicked zone using screen coordinates (zones are stored in screen coords)
if let Some(clicked_zone) =
zones.iter().find(|z| {
z.bounds.contains_point(
screen_x, screen_y,
)
})
{
if let Some(idx_str) = clicked_zone
.content_id
.strip_prefix("choice_")
{
if let Ok(clicked_choice_idx) =
idx_str.parse::<usize>()
{
log::info!("CLICK HANDLING: Successfully detected click on choice index {}", clicked_choice_idx);
if let Some(clicked_choice) =
choices
.get(clicked_choice_idx)
{
log::trace!(
"Clicked on choice: {}",
clicked_choice.id
);
// First, select the parent muxbox if not already selected
let layout = app_context_for_click
.app
.get_active_layout_mut()
.unwrap();
layout
.deselect_all_muxboxes(
);
layout.select_only_muxbox(
&clicked_muxbox.id,
);
// Then select the clicked choice visually
let muxbox_to_update =
app_context_for_click
.app
.get_muxbox_by_id_mut(
&clicked_muxbox.id,
)
.unwrap();
if let Some(muxbox_choices) =
muxbox_to_update.get_selected_stream_choices_mut()
{
// Deselect all choices first
for choice in muxbox_choices.iter_mut() {
choice.selected = false;
}
// Select only the clicked choice and set waiting state for visual feedback
if let Some(selected_choice) =
muxbox_choices.get_mut(clicked_choice_idx)
{
selected_choice.selected = true;
selected_choice.waiting = true;
// Visual feedback consistency with Enter key
}
}
// Update the app context and immediately trigger redraw for responsiveness
inner.update_app_context(
app_context_for_click
.clone(),
);
inner.send_message(
Message::RedrawAppDiff,
);
// Then activate the clicked choice (same as pressing Enter)
// F0224: Use ExecutionMode to determine execution path for mouse clicks too
if let Some(script) =
&clicked_choice.script
{
let libs =
app_context_unwrapped
.app
.libs
.clone();
let script_clone =
script.clone();
let choice_id_clone =
clicked_choice
.id
.clone();
let muxbox_id_clone =
clicked_muxbox
.id
.clone();
let libs_clone =
libs.clone();
let execution_mode =
clicked_choice
.execution_mode
.clone();
let redirect_output =
clicked_choice
.redirect_output
.clone();
let _append_output =
clicked_choice
.append_output
.unwrap_or(
false,
);
// T0315: UNIFIED ARCHITECTURE - Replace legacy mouse click execution with ExecuteScript message
log::info!("T0315: Mouse click creating ExecuteScript for choice {} (mode: {:?})", choice_id_clone, execution_mode);
// Create ExecuteScript message instead of direct execution or legacy message routing
use crate::model::common::{
ExecuteScript,
ExecutionSource,
SourceReference,
SourceType,
};
// Create choice object for SourceReference
let choice_for_reference =
Choice {
id: choice_id_clone
.clone(),
content: Some(
"".to_string(),
),
selected: false,
script: Some(
script_clone
.clone(),
),
execution_mode:
execution_mode
.clone(),
redirect_output:
redirect_output
.clone(),
append_output: Some(
_append_output,
),
waiting: true,
hovered: false,
};
// Register execution source and get stream_id
let source_type = crate::model::common::ExecutionSourceType::ChoiceExecution {
choice_id: choice_id_clone.clone(),
script: script_clone.clone(),
redirect_output: redirect_output.clone(),
};
let stream_id = app_context_unwrapped
.app
.register_execution_source(
source_type,
muxbox_id_clone.clone(),
);
let execute_script = ExecuteScript {
script: script_clone.clone(),
source: ExecutionSource {
source_type: SourceType::Choice(
choice_id_clone.clone(),
),
source_id: format!(
"mouse_choice_{}",
choice_id_clone
),
source_reference:
SourceReference::Choice(
choice_for_reference,
),
},
execution_mode: execution_mode.clone(),
target_box_id: muxbox_id_clone.clone(),
libs: libs_clone.unwrap_or_default(),
redirect_output: redirect_output.clone(),
append_output: _append_output,
stream_id: stream_id.clone(),
target_bounds: app_context_unwrapped.app.get_active_layout()
.and_then(|layout| layout.children.as_ref()?.iter().find(|mb| mb.id == *muxbox_id_clone))
.map(|mb| mb.bounds()),
};
// Route ExecuteScript based on execution mode
match execution_mode {
crate::model::common::ExecutionMode::Immediate |
crate::model::common::ExecutionMode::Thread => {
// Send to ThreadManager for Immediate/Thread execution
inner.send_message(Message::ExecuteScriptMessage(execute_script));
log::info!(
"T0315: ExecuteScript message sent to ThreadManager for mouse-clicked choice {} (mode: {:?})",
choice_id_clone, execution_mode
);
}
crate::model::common::ExecutionMode::Pty => {
// FIXED: Route PTY execution to PTYManager, never to ThreadManager
log::info!(
"T0315 FIXED: Routing PTY ExecuteScript to PTYManager for mouse-clicked choice {} (mode: {:?})",
choice_id_clone, execution_mode
);
// Route to PTYManager instead of ThreadManager
if let Some(pty_manager) = &app_context_unwrapped.pty_manager {
// Get message sender for PTY communication
if let Some(sender) = inner.get_message_sender() {
let uuid = uuid::Uuid::new_v4();
// Call PTYManager's ExecuteScript handler
if let Err(e) = pty_manager.handle_execute_script(&execute_script, sender.clone(), uuid) {
log::error!(
"T0315: PTYManager failed to handle ExecuteScript for choice {}: {}",
choice_id_clone, e
);
} else {
log::info!(
"T0315 FIXED: PTYManager successfully handling ExecuteScript for choice {} (architecture compliant)",
choice_id_clone
);
}
} else {
log::error!("No message sender available for PTY execution - choice {}", choice_id_clone);
}
} else {
log::error!("No PTYManager available - PTY execution failed for choice {}", choice_id_clone);
}
}
}
}
} // Close if let Some(clicked_choice)
} // Close if let Ok(clicked_choice_idx)
} // Close if let Some(idx_str)
} // Close if let Some(clicked_zone)
} else {
log::info!("NEW ARCH: Click at ({}, {}) did not hit any sensitive zone - muxbox already selected", *x, *y);
}
} // Close if !choices.is_empty()
} else {
// Selected stream has empty choices - muxbox already selected
log::info!("CLICK DEBUG: MuxBox '{}' selected stream has empty choices - muxbox already selected", clicked_muxbox.id);
}
} // Close if let Some(choices)
} else {
// No selected stream - muxbox already selected
log::info!("CLICK DEBUG: MuxBox '{}' has no selected stream - muxbox already selected", clicked_muxbox.id);
} // Close if let Some(selected_stream)
} // End of clicked_muxbox
} // End of !handled_tab_click
}
}
Message::MouseMove(x, y) => {
// Hover is reconciled centrally from the latest pointer
// position (see reconcile_hover in the draw init path), so
// here we only record where the pointer is. This keeps
// highlights mutually exclusive and self-healing.
HOVER_STATE.lock().unwrap().last_position = Some((*x, *y));
}
Message::MouseDragStart(x, y) => {
// Check if muxboxes are locked before allowing resize/move
if app_context_unwrapped.config.locked {
// Skip all resize/move operations when locked
log::trace!("MuxBox resize/move blocked: muxboxes are locked");
} else {
// F0189: Check if drag started on a muxbox border first
let active_layout =
app_context_unwrapped.app.get_active_layout().unwrap();
let mut resize_state = MUXBOX_RESIZE_STATE.lock().unwrap();
*resize_state = None; // Clear any previous resize state
// Check for muxbox border resize first
let mut handled_resize = false;
for muxbox in active_layout.get_all_muxboxes() {
if let Some(resize_edge) = detect_resize_edge(muxbox, *x, *y) {
*resize_state = Some(MuxBoxResizeState {
muxbox_id: muxbox.id.clone(),
resize_edge,
start_x: *x,
start_y: *y,
original_bounds: muxbox.position.clone(),
});
log::trace!(
"Started resizing muxbox {} via {:?} edge",
muxbox.id,
resize_state.as_ref().unwrap().resize_edge
);
handled_resize = true;
break;
}
}
// F0191: If not a resize, check if drag started on muxbox title/top border for movement
let mut _handled_move = false;
if !handled_resize {
let mut move_state = MUXBOX_MOVE_STATE.lock().unwrap();
*move_state = None; // Clear any previous move state
for muxbox in active_layout.get_all_muxboxes() {
if detect_move_area(muxbox, *x, *y) {
// Check if the drag started on a tab area - if so, don't start move
let tab_labels = muxbox.get_tab_labels();
let muxbox_bounds = muxbox.bounds();
if let Some(_tab_index) =
crate::draw_utils::calculate_tab_click_index(
*x as usize,
muxbox_bounds.left(),
muxbox_bounds.right(),
&tab_labels,
muxbox.tab_scroll_offset,
&muxbox.calc_border_color(
&app_context_unwrapped,
&app_graph,
),
&muxbox.bg_color,
)
{
log::trace!("Drag started on tab area for muxbox {} - skipping move operation", muxbox.id);
// Skip move operation for tab area drags
continue;
}
*move_state = Some(MuxBoxMoveState {
muxbox_id: muxbox.id.clone(),
start_x: *x,
start_y: *y,
original_bounds: muxbox.position.clone(),
});
log::trace!(
"Started moving muxbox {} via title/top border",
muxbox.id
);
_handled_move = true;
break;
}
}
}
}
// F0188: Check for scroll knob drag (allowed even when locked)
let active_layout = app_context_unwrapped.app.get_active_layout().unwrap();
// Check if any resize/move states are active (only possible when unlocked)
let has_active_resize = if !app_context_unwrapped.config.locked {
let resize_state_guard = MUXBOX_RESIZE_STATE.lock().unwrap();
resize_state_guard.is_some()
} else {
false
};
let has_active_move = if !app_context_unwrapped.config.locked {
let move_state_guard = MUXBOX_MOVE_STATE.lock().unwrap();
move_state_guard.is_some()
} else {
false
};
// F0188: If no resize or move is active, check if drag started on a scroll knob
if !has_active_resize && !has_active_move {
let mut drag_state = DRAG_STATE.lock().unwrap();
*drag_state = None; // Clear any previous drag state
for muxbox in active_layout.get_all_muxboxes() {
if muxbox.has_scrollable_content() {
let muxbox_bounds = muxbox.bounds();
// Check if drag started on vertical scroll knob
if *x as usize == muxbox_bounds.right()
&& *y as usize > muxbox_bounds.top()
&& (*y as usize) < muxbox_bounds.bottom()
{
// Check if we clicked on the actual knob, not just the track
if is_on_vertical_knob(muxbox, *y as usize) {
let current_scroll =
muxbox.vertical_scroll.unwrap_or(0.0);
*drag_state = Some(DragState {
muxbox_id: muxbox.id.clone(),
is_vertical: true,
start_x: *x,
start_y: *y,
start_scroll_percentage: current_scroll,
});
log::trace!("Started dragging vertical scroll knob on muxbox {}", muxbox.id);
break;
}
}
// Check if drag started on horizontal scroll knob
if *y as usize == muxbox_bounds.bottom()
&& *x as usize > muxbox_bounds.left()
&& (*x as usize) < muxbox_bounds.right()
{
// Check if we clicked on the actual knob, not just the track
if is_on_horizontal_knob(muxbox, *x as usize) {
let current_scroll =
muxbox.horizontal_scroll.unwrap_or(0.0);
*drag_state = Some(DragState {
muxbox_id: muxbox.id.clone(),
is_vertical: false,
start_x: *x,
start_y: *y,
start_scroll_percentage: current_scroll,
});
log::trace!("Started dragging horizontal scroll knob on muxbox {}", muxbox.id);
break;
}
}
}
}
}
}
Message::MouseDrag(x, y) => {
// Skip resize/move operations when muxboxes are locked
if !app_context_unwrapped.config.locked {
// F0189: Handle muxbox border resize during drag
let resize_state_guard = MUXBOX_RESIZE_STATE.lock().unwrap();
if let Some(ref resize_state) = *resize_state_guard {
let terminal_width = crate::screen_width();
let terminal_height = crate::screen_height();
// FIXED: Handle 100% width panels where horizontal drag events may not work
let (effective_x, effective_y) =
if resize_state.original_bounds.x2 == "100%" {
// For 100% width panels at rightmost edge, if no horizontal movement is detected,
// use the vertical movement as a proxy for horizontal movement to enable resizing
let horizontal_delta =
(*x as i32) - (resize_state.start_x as i32);
let vertical_delta =
(*y as i32) - (resize_state.start_y as i32);
if horizontal_delta == 0 && vertical_delta != 0 {
// No horizontal movement detected but vertical movement exists
// Use diagonal movement: apply vertical delta to horizontal as well
let adjusted_x =
resize_state.start_x as i32 + vertical_delta;
(adjusted_x.max(0) as u16, *y)
} else {
(*x, *y)
}
} else {
(*x, *y)
};
let new_bounds = calculate_new_bounds(
&resize_state.original_bounds,
&resize_state.resize_edge,
resize_state.start_x,
resize_state.start_y,
effective_x,
effective_y,
terminal_width,
terminal_height,
);
// Update the muxbox bounds in real-time
if let Some(muxbox) = app_context_unwrapped
.app
.get_muxbox_by_id_mut(&resize_state.muxbox_id)
{
muxbox.position = new_bounds;
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawAppDiff);
}
}
// F0191: Handle muxbox movement during drag
let move_state_guard = MUXBOX_MOVE_STATE.lock().unwrap();
if let Some(ref move_state) = *move_state_guard {
let terminal_width = crate::screen_width();
let terminal_height = crate::screen_height();
let new_position = calculate_new_position(
&move_state.original_bounds,
move_state.start_x,
move_state.start_y,
*x,
*y,
terminal_width,
terminal_height,
);
// Update the muxbox position in real-time
if let Some(muxbox) = app_context_unwrapped
.app
.get_muxbox_by_id_mut(&move_state.muxbox_id)
{
muxbox.position = new_position;
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawAppDiff);
}
}
}
// F0188: Handle scroll knob drag (always allowed, even when locked)
let drag_state_guard = DRAG_STATE.lock().unwrap();
if let Some(ref drag_state) = *drag_state_guard {
let muxbox_to_update = app_context_unwrapped
.app
.get_muxbox_by_id_mut(&drag_state.muxbox_id);
if let Some(muxbox) = muxbox_to_update {
let muxbox_bounds = muxbox.bounds();
if drag_state.is_vertical {
// Calculate new vertical scroll percentage based on drag distance
let track_height =
(muxbox_bounds.height() as isize - 2).max(1) as usize;
let drag_delta = (*y as isize) - (drag_state.start_y as isize);
let percentage_delta =
(drag_delta as f64 / track_height as f64) * 100.0;
let new_percentage = (drag_state.start_scroll_percentage
+ percentage_delta)
.clamp(0.0, 100.0);
muxbox.vertical_scroll = Some(new_percentage);
} else {
// Calculate new horizontal scroll percentage based on drag distance
let track_width =
(muxbox_bounds.width() as isize - 2).max(1) as usize;
let drag_delta = (*x as isize) - (drag_state.start_x as isize);
let percentage_delta =
(drag_delta as f64 / track_width as f64) * 100.0;
let new_percentage = (drag_state.start_scroll_percentage
+ percentage_delta)
.clamp(0.0, 100.0);
muxbox.horizontal_scroll = Some(new_percentage);
}
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawAppDiff);
}
}
}
Message::MouseDragEnd(x, y) => {
// Only handle resize/move end when muxboxes are unlocked
if !app_context_unwrapped.config.locked {
// F0189: End muxbox resize operation
let mut resize_state = MUXBOX_RESIZE_STATE.lock().unwrap();
if let Some(ref resize_state_data) = *resize_state {
log::trace!(
"Ended muxbox resize at ({}, {}) for muxbox {}",
x,
y,
resize_state_data.muxbox_id
);
// Trigger YAML persistence
inner.send_message(Message::MuxBoxResizeComplete(
resize_state_data.muxbox_id.clone(),
));
*resize_state = None; // Clear resize state
} else {
// F0191: End muxbox move operation
let mut move_state = MUXBOX_MOVE_STATE.lock().unwrap();
if let Some(ref move_state_data) = *move_state {
log::trace!(
"Ended muxbox move at ({}, {}) for muxbox {}",
x,
y,
move_state_data.muxbox_id
);
// Trigger YAML persistence for new position
inner.send_message(Message::MuxBoxMoveComplete(
move_state_data.muxbox_id.clone(),
));
*move_state = None; // Clear move state
}
}
}
// F0188: End scroll knob drag operation (always allowed, even when locked)
let mut drag_state = DRAG_STATE.lock().unwrap();
if drag_state.is_some() {
log::trace!("Ended scroll knob drag at ({}, {})", x, y);
*drag_state = None; // Clear drag state
}
}
Message::MuxBoxResizeComplete(muxbox_id) => {
// F0190: Save muxbox bounds changes to YAML file
log::info!(
"Saving muxbox resize changes to YAML for muxbox: {}",
muxbox_id
);
// Get the updated muxbox bounds
if let Some(muxbox) = app_context_unwrapped.app.get_muxbox_by_id(muxbox_id)
{
let new_bounds = &muxbox.position;
log::debug!(
"New bounds for muxbox {}: x1={}, y1={}, x2={}, y2={}",
muxbox_id,
new_bounds.x1,
new_bounds.y1,
new_bounds.x2,
new_bounds.y2
);
// Find the original YAML file path
if let Some(yaml_path) = &app_context_unwrapped.yaml_file_path {
match save_muxbox_bounds_to_yaml(yaml_path, muxbox_id, new_bounds) {
Ok(()) => {
log::info!(
"Successfully saved muxbox {} bounds to YAML file",
muxbox_id
);
}
Err(e) => {
log::error!(
"Failed to save muxbox {} bounds to YAML: {}",
muxbox_id,
e
);
}
}
} else {
log::error!("CRITICAL: No YAML file path available for saving muxbox bounds - resize changes will not persist!");
}
} else {
log::error!("MuxBox {} not found for saving bounds", muxbox_id);
}
}
Message::MuxBoxMoveComplete(muxbox_id) => {
// F0191: Save muxbox position changes to YAML file
log::info!(
"Saving muxbox move changes to YAML for muxbox: {}",
muxbox_id
);
// Get the updated muxbox position
if let Some(muxbox) = app_context_unwrapped.app.get_muxbox_by_id(muxbox_id)
{
let new_position = &muxbox.position;
log::debug!(
"New position for muxbox {}: x1={}, y1={}, x2={}, y2={}",
muxbox_id,
new_position.x1,
new_position.y1,
new_position.x2,
new_position.y2
);
// Find the original YAML file path
if let Some(yaml_path) = &app_context_unwrapped.yaml_file_path {
match save_muxbox_bounds_to_yaml(yaml_path, muxbox_id, new_position)
{
Ok(()) => {
log::info!(
"Successfully saved muxbox {} position to YAML file",
muxbox_id
);
}
Err(e) => {
log::error!(
"Failed to save muxbox {} position to YAML: {}",
muxbox_id,
e
);
}
}
} else {
log::error!("CRITICAL: No YAML file path available for saving muxbox position - move changes will not persist!");
}
} else {
log::error!("MuxBox {} not found for saving position", muxbox_id);
}
}
Message::SaveYamlState => {
// F0200: Save complete application state to YAML
log::info!("Saving complete application state to YAML");
if let Some(yaml_path) = &app_context_unwrapped.yaml_file_path {
match save_complete_state_to_yaml(yaml_path, &app_context_unwrapped) {
Ok(()) => {
log::info!("Successfully saved complete state to YAML file");
}
Err(e) => {
log::error!("Failed to save complete state to YAML: {}", e);
}
}
} else {
log::error!(
"CRITICAL: No YAML file path available for saving complete state!"
);
}
}
Message::SaveActiveLayout(layout_id) => {
// F0200: Save active layout to YAML
log::info!("Saving active layout '{}' to YAML", layout_id);
if let Some(yaml_path) = &app_context_unwrapped.yaml_file_path {
match save_active_layout_to_yaml(yaml_path, layout_id) {
Ok(()) => {
log::info!("Successfully saved active layout to YAML file");
}
Err(e) => {
log::error!("Failed to save active layout to YAML: {}", e);
}
}
} else {
log::error!(
"CRITICAL: No YAML file path available for saving active layout!"
);
}
}
Message::SaveMuxBoxContent(muxbox_id, content) => {
// F0200: Save muxbox content changes to YAML
log::debug!("Saving content changes to YAML for muxbox: {}", muxbox_id);
if let Some(yaml_path) = &app_context_unwrapped.yaml_file_path {
match save_muxbox_content_to_yaml(yaml_path, muxbox_id, content) {
Ok(()) => {
log::debug!(
"Successfully saved muxbox {} content to YAML",
muxbox_id
);
}
Err(e) => {
log::error!(
"Failed to save muxbox {} content to YAML: {}",
muxbox_id,
e
);
}
}
} else {
log::warn!("No YAML file path available for saving muxbox content");
}
}
Message::SaveMuxBoxScroll(muxbox_id, scroll_x, scroll_y) => {
// F0200: Save muxbox scroll position to YAML
log::debug!(
"Saving scroll position to YAML for muxbox: {} ({}, {})",
muxbox_id,
scroll_x,
scroll_y
);
if let Some(yaml_path) = &app_context_unwrapped.yaml_file_path {
match save_muxbox_scroll_to_yaml(
yaml_path, muxbox_id, *scroll_x, *scroll_y,
) {
Ok(()) => {
log::debug!(
"Successfully saved muxbox {} scroll position to YAML",
muxbox_id
);
}
Err(e) => {
log::error!(
"Failed to save muxbox {} scroll position to YAML: {}",
muxbox_id,
e
);
}
}
} else {
log::warn!(
"No YAML file path available for saving muxbox scroll position"
);
}
}
Message::SwitchActiveLayout(layout_id) => {
// F0200: Switch active layout with YAML persistence
log::info!("Switching to active layout: {}", layout_id);
// Update the active layout in app context
let mut app_context_cloned = app_context_unwrapped.clone();
match app_context_cloned.app.set_active_layout_with_yaml_save(
layout_id,
app_context_cloned.yaml_file_path.as_deref(),
) {
Ok(()) => {
inner.update_app_context(app_context_cloned);
inner.send_message(Message::RedrawApp);
log::info!(
"Successfully switched to layout '{}' with YAML persistence",
layout_id
);
}
Err(e) => {
log::error!("Failed to switch layout with YAML persistence: {}", e);
// Still update app context without YAML persistence
app_context_cloned.app.set_active_layout(layout_id);
inner.update_app_context(app_context_cloned);
inner.send_message(Message::RedrawApp);
}
}
}
// F0203: Multi-Stream Input Tabs message handling
Message::SwitchTab(muxbox_id, tab_index) => {
log::debug!(
"Processing SwitchTab message: muxbox={}, tab_index={}",
muxbox_id,
tab_index
);
if let Some(muxbox) =
app_context_unwrapped.app.get_muxbox_by_id_mut(muxbox_id)
{
log::debug!(
"Found muxbox '{}', attempting to switch to tab {}",
muxbox_id,
tab_index
);
if muxbox.switch_to_tab(*tab_index) {
log::info!(
"Successfully switched muxbox '{}' to tab {}",
muxbox_id,
tab_index
);
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(muxbox_id.clone()));
} else {
log::warn!("Failed to switch muxbox '{}' to tab {} - switch_to_tab returned false", muxbox_id, tab_index);
}
} else {
log::error!("SwitchTab message for non-existent muxbox: {}", muxbox_id);
}
}
Message::ScrollTabsLeft(muxbox_id) => {
log::debug!("Processing ScrollTabsLeft message: muxbox={}", muxbox_id);
if let Some(muxbox) =
app_context_unwrapped.app.get_muxbox_by_id_mut(muxbox_id)
{
muxbox.scroll_tabs_left();
log::info!(
"Scrolled tabs left for muxbox '{}', new offset: {}",
muxbox_id,
muxbox.tab_scroll_offset
);
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(muxbox_id.clone()));
} else {
log::error!(
"ScrollTabsLeft message for non-existent muxbox: {}",
muxbox_id
);
}
}
Message::ScrollTabsRight(muxbox_id) => {
log::debug!("Processing ScrollTabsRight message: muxbox={}", muxbox_id);
if let Some(muxbox) =
app_context_unwrapped.app.get_muxbox_by_id_mut(muxbox_id)
{
muxbox.scroll_tabs_right();
log::info!(
"Scrolled tabs right for muxbox '{}', new offset: {}",
muxbox_id,
muxbox.tab_scroll_offset
);
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(muxbox_id.clone()));
} else {
log::error!(
"ScrollTabsRight message for non-existent muxbox: {}",
muxbox_id
);
}
}
Message::SwitchToStream(muxbox_id, stream_id) => {
if let Some(muxbox) =
app_context_unwrapped.app.get_muxbox_by_id_mut(muxbox_id)
{
if muxbox.switch_to_stream(stream_id) {
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(muxbox_id.clone()));
}
}
}
Message::AddStream(muxbox_id, _stream) => {
if let Some(_muxbox) =
app_context_unwrapped.app.get_muxbox_by_id_mut(muxbox_id)
{
// AddStream is deprecated - use add_input_stream() method directly on muxbox instead
log::warn!("AddStream message is deprecated - use muxbox.add_input_stream() instead");
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(muxbox_id.clone()));
}
}
Message::RemoveStream(muxbox_id, stream_id) => {
if let Some(muxbox) =
app_context_unwrapped.app.get_muxbox_by_id_mut(muxbox_id)
{
// F0213: Stream Lifecycle Management - cleanup stream sources before removal
if let Some(source) = muxbox.remove_stream(stream_id) {
log::info!(
"Cleaning up stream source for stream {}: {:?}",
stream_id,
source
);
// Perform source cleanup based on source type
match source {
crate::model::common::StreamSource::ChoiceExecution(
choice_source,
) => {
if let Err(e) = choice_source.cleanup() {
log::warn!(
"Failed to cleanup choice execution source: {}",
e
);
}
}
// F0227: ExecutionMode-specific source cleanup
crate::model::common::StreamSource::ImmediateExecution(
source,
) => {
if let Err(e) = source.cleanup() {
log::warn!(
"Failed to cleanup immediate execution source: {}",
e
);
}
}
crate::model::common::StreamSource::ThreadPoolExecution(
source,
) => {
if let Err(e) = source.cleanup() {
log::warn!("Failed to cleanup thread pool execution source: {}", e);
}
}
crate::model::common::StreamSource::PtySessionExecution(
source,
) => {
if let Err(e) = source.cleanup() {
log::warn!("Failed to cleanup PTY session execution source: {}", e);
}
}
crate::model::common::StreamSource::PTY(pty_source) => {
if let Err(e) = pty_source.cleanup() {
log::warn!("Failed to cleanup PTY source: {}", e);
}
}
crate::model::common::StreamSource::Redirect(
redirect_source,
) => {
if let Err(e) = redirect_source.cleanup() {
log::warn!("Failed to cleanup redirect source: {}", e);
}
}
crate::model::common::StreamSource::Socket(socket_source) => {
if let Err(e) = socket_source.cleanup() {
log::warn!("Failed to cleanup socket source: {}", e);
}
}
crate::model::common::StreamSource::StaticContent(_) => {
// Static content sources don't need cleanup
log::debug!(
"Static content source removed - no cleanup needed"
);
}
crate::model::common::StreamSource::PeriodicRefresh(
periodic_source,
) => {
if let Err(e) = periodic_source.cleanup() {
log::warn!(
"Failed to cleanup periodic refresh source: {}",
e
);
}
}
}
// Stream already removed by muxbox.remove_stream() call above
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(muxbox_id.clone()));
} else {
log::warn!(
"Stream {} not found in muxbox {} for cleanup",
stream_id,
muxbox_id
);
}
}
}
Message::CloseTab(muxbox_id, stream_id) => {
// F0219: Handle close tab request - handle terminated sources gracefully
log::info!(
"Close tab requested for stream {} in muxbox {}",
stream_id,
muxbox_id
);
// Check if stream is closeable before closing
if let Some(muxbox) =
app_context_unwrapped.app.get_muxbox_by_id_mut(muxbox_id)
{
if let Some(stream) = muxbox.streams.get(stream_id) {
if stream.is_closeable() {
// Handle stream removal directly - source threads may be terminated
log::info!(
"Processing close tab for closeable stream {} in muxbox {}",
stream_id,
muxbox_id
);
// Remove stream and handle source cleanup
if let Some(source) = muxbox.remove_stream(stream_id) {
log::info!(
"Stream {} removed from muxbox {}, attempting source cleanup",
stream_id,
muxbox_id
);
// Attempt source cleanup - ignore failures for terminated threads
match source {
crate::model::common::StreamSource::ChoiceExecution(
choice_source,
) => {
if let Err(e) = choice_source.cleanup() {
log::info!(
"Choice execution source cleanup failed (likely already terminated): {}",
e
);
}
}
// F0227: ExecutionMode-specific source cleanup
crate::model::common::StreamSource::ImmediateExecution(source) => {
if let Err(e) = source.cleanup() {
log::info!("Immediate execution source cleanup failed: {}", e);
}
}
crate::model::common::StreamSource::ThreadPoolExecution(source) => {
if let Err(e) = source.cleanup() {
log::info!("Thread pool execution source cleanup failed: {}", e);
}
}
crate::model::common::StreamSource::PtySessionExecution(source) => {
if let Err(e) = source.cleanup() {
log::info!("PTY session execution source cleanup failed: {}", e);
}
}
crate::model::common::StreamSource::PTY(pty_source) => {
if let Err(e) = pty_source.cleanup() {
log::info!("PTY source cleanup failed (likely already terminated): {}", e);
}
}
crate::model::common::StreamSource::Redirect(
redirect_source,
) => {
if let Err(e) = redirect_source.cleanup() {
log::info!("Redirect source cleanup failed (likely already terminated): {}", e);
}
}
crate::model::common::StreamSource::Socket(socket_source) => {
if let Err(e) = socket_source.cleanup() {
log::info!("Socket source cleanup failed (likely already terminated): {}", e);
}
}
crate::model::common::StreamSource::StaticContent(_) => {
log::debug!("Static content source removed - no cleanup needed");
}
crate::model::common::StreamSource::PeriodicRefresh(periodic_source) => {
if let Err(e) = periodic_source.cleanup() {
log::info!("Periodic refresh source cleanup failed (likely already terminated): {}", e);
}
}
}
// Update app context and trigger redraw
inner.update_app_context(app_context_unwrapped.clone());
inner
.send_message(Message::RedrawMuxBox(muxbox_id.clone()));
log::info!("Stream {} successfully closed and removed from muxbox {}", stream_id, muxbox_id);
} else {
log::warn!(
"Stream {} not found in muxbox {} during removal",
stream_id,
muxbox_id
);
}
} else {
log::warn!(
"Attempted to close non-closeable stream {} in muxbox {}",
stream_id,
muxbox_id
);
}
} else {
log::warn!(
"Stream {} not found in muxbox {} for close operation",
stream_id,
muxbox_id
);
}
} else {
log::warn!("MuxBox {} not found for close tab operation", muxbox_id);
}
}
Message::UpdateStreamContent(muxbox_id, stream_id, content) => {
if let Some(muxbox) =
app_context_unwrapped.app.get_muxbox_by_id_mut(muxbox_id)
{
// Update stream content directly using new stream system
if let Some(stream) = muxbox.streams.get_mut(stream_id) {
stream.content = content.lines().map(|s| s.to_string()).collect();
// AUTO_SCROLL_BOTTOM FIX: Apply auto-scroll after stream content update
if muxbox.auto_scroll_bottom == Some(true) {
muxbox.vertical_scroll = Some(100.0);
log::debug!("Applied auto-scroll to bottom for muxbox {} after UpdateStreamContent", muxbox_id);
}
} else {
log::warn!(
"Stream {} not found in muxbox {} for content update",
stream_id,
muxbox_id
);
}
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(muxbox_id.clone()));
}
}
// T0318: UNIFIED ARCHITECTURE - Replace legacy socket script execution with ExecuteScript message
Message::MuxBoxScriptUpdate(muxbox_id, new_script) => {
log::info!("T0318: Socket script update creating ExecuteScript for muxbox {} ({} commands)", muxbox_id, new_script.len());
// Clone libs before mutable borrow to avoid borrowing conflict
let libs = app_context_unwrapped.app.libs.clone().unwrap_or_default();
// Collect all needed data in one scope to avoid borrow conflicts
let (execution_mode, redirect_output, append_output) = {
if let Some(muxbox) =
app_context_unwrapped.app.get_muxbox_by_id_mut(muxbox_id)
{
// Update the muxbox script field and collect needed data
muxbox.script = Some(new_script.clone());
(
muxbox.execution_mode.clone(),
muxbox.redirect_output.clone(),
muxbox.append_output.unwrap_or(false),
)
} else {
log::warn!("Muxbox {} not found for script update", muxbox_id);
continue;
}
};
// Now register execution source with a fresh mutable borrow
// Create ExecuteScript message for socket-triggered script execution
use crate::model::common::{
ExecuteScript, ExecutionSource, SourceReference, SourceType,
};
// Register execution source and get stream_id
let source_type = crate::model::common::ExecutionSourceType::SocketUpdate {
command_type: "replace-box-script".to_string(),
};
let stream_id = app_context_unwrapped
.app
.register_execution_source(source_type, muxbox_id.clone());
let execute_script = ExecuteScript {
script: new_script.clone(),
source: ExecutionSource {
source_type: SourceType::SocketUpdate,
source_id: format!("socket_script_{}", muxbox_id),
source_reference: SourceReference::SocketCommand(format!(
"replace-box-script command for {}",
muxbox_id
)),
},
execution_mode,
target_box_id: muxbox_id.clone(),
libs,
redirect_output,
append_output,
stream_id,
target_bounds: app_context_unwrapped
.app
.get_active_layout()
.and_then(|layout| {
layout
.children
.as_ref()?
.iter()
.find(|mb| mb.id == *muxbox_id)
})
.map(|mb| mb.bounds()),
};
// Send ExecuteScript message instead of direct execution
inner.send_message(Message::ExecuteScriptMessage(execute_script));
log::info!(
"T0318: ExecuteScript message sent for socket-updated muxbox {} script (unified architecture)",
muxbox_id
);
inner.update_app_context(app_context_unwrapped.clone());
}
_ => {}
}
}
// T311: Choice execution now handled via ChoiceExecutionComplete messages
// Old POOL-based choice results processing removed
}
// Ensure the loop continues by sleeping briefly
std::thread::sleep(std::time::Duration::from_millis(
app_context.config.frame_delay,
));
(should_continue, app_context)
}
);
pub fn update_muxbox_content(
inner: &mut RunnableImpl,
app_context_unwrapped: &mut AppContext,
muxbox_id: &str,
success: bool,
append_output: bool,
output: &str,
) {
log::info!(
"=== UPDATE MUXBOX CONTENT: {} (success: {}, append: {}, output_len: {}) ===",
muxbox_id,
success,
append_output,
output.len()
);
let mut app_context_unwrapped_cloned = app_context_unwrapped.clone();
let muxbox = app_context_unwrapped.app.get_muxbox_by_id_mut(muxbox_id);
if let Some(found_muxbox) = muxbox {
log::info!(
"Found target muxbox: {} (redirect_output: {:?})",
muxbox_id,
found_muxbox.redirect_output
);
if found_muxbox.redirect_output.is_some()
&& found_muxbox.redirect_output.as_ref().unwrap() != muxbox_id
{
log::info!(
"MuxBox {} has its own redirect to: {}, following redirect chain",
muxbox_id,
found_muxbox.redirect_output.as_ref().unwrap()
);
update_muxbox_content(
inner,
&mut app_context_unwrapped_cloned,
found_muxbox.redirect_output.as_ref().unwrap(),
success,
append_output,
output,
);
} else {
log::info!(
"Updating muxbox {} content directly (no redirection)",
muxbox_id
);
log::info!(
"MuxBox {} current content length: {} chars",
muxbox_id,
found_muxbox
.get_selected_stream()
.map_or(0, |s| s.content.join("\n").len())
);
// Check if this is PTY streaming output by the newline indicator
let is_pty_streaming = output.ends_with('\n');
if is_pty_streaming {
// Use streaming update for PTY output (no timestamp formatting)
log::info!("Using streaming update for muxbox {}", muxbox_id);
found_muxbox.update_streaming_content(output, success);
} else {
// Use regular update for non-PTY output
log::info!(
"Using regular update for muxbox {} (append: {})",
muxbox_id,
append_output
);
found_muxbox.update_content(output, append_output, success);
}
log::info!(
"MuxBox {} updated content length: {} chars",
muxbox_id,
found_muxbox
.get_selected_stream()
.map_or(0, |s| s.content.join("\n").len())
);
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(muxbox_id.to_string()));
log::info!("Sent RedrawMuxBox message for muxbox: {}", muxbox_id);
}
} else {
log::error!("Could not find muxbox {} for content update.", muxbox_id);
// List available muxboxes for debugging
let available_muxboxes: Vec<String> = app_context_unwrapped
.app
.get_active_layout()
.unwrap()
.get_all_muxboxes()
.iter()
.map(|p| p.id.clone())
.collect();
log::error!("Available muxboxes: {:?}", available_muxboxes);
}
}
pub fn update_muxbox_content_with_stream(
inner: &mut RunnableImpl,
app_context_unwrapped: &mut AppContext,
muxbox_id: &str,
stream_id: &str,
success: bool,
append_output: bool,
output: &str,
) {
log::info!(
"=== UPDATE MUXBOX CONTENT WITH STREAM: {} stream: {} (success: {}, append: {}, output_len: {}) ===",
muxbox_id,
stream_id,
success,
append_output,
output.len()
);
let muxbox = app_context_unwrapped.app.get_muxbox_by_id_mut(muxbox_id);
if let Some(found_muxbox) = muxbox {
log::info!(
"Found target muxbox: {} with streams: {}",
muxbox_id,
found_muxbox.streams.len()
);
// F0229: Clean output formatting without unwanted timestamps
let formatted_output = if success {
output.to_string()
} else {
format!("ERROR: {}", output)
};
// Update the specific stream content - find stream by actual stream ID
let mut stream_updated = false;
// Check if stream exists and update content
if found_muxbox.streams.contains_key(stream_id) {
// Update the stream content
if let Some(stream) = found_muxbox.streams.get_mut(stream_id) {
if append_output {
stream.content.push(formatted_output.clone());
} else {
stream.content = vec![formatted_output.clone()];
}
stream_updated = true;
}
// Check if we need to select this stream (if no stream is currently selected)
let should_activate =
found_muxbox.selected_stream_id.is_none() || found_muxbox.streams.len() == 1;
if should_activate {
// Set this stream as selected
found_muxbox.selected_stream_id = Some(stream_id.to_string());
}
log::info!("Updated stream {} with new content", stream_id);
}
if !stream_updated {
log::warn!(
"Stream {} not found in muxbox {}, fallback to updating content",
stream_id,
muxbox_id
);
// Fallback to updating the muxbox content directly
found_muxbox.update_content(&formatted_output, append_output, success);
}
log::info!(
"Updated stream {} content in muxbox {}",
stream_id,
muxbox_id
);
inner.update_app_context(app_context_unwrapped.clone());
inner.send_message(Message::RedrawMuxBox(muxbox_id.to_string()));
log::info!("Sent RedrawMuxBox message for muxbox: {}", muxbox_id);
} else {
log::error!(
"Could not find muxbox {} for stream content update.",
muxbox_id
);
}
}
/// Extract muxbox content for clipboard copy
pub fn get_muxbox_content_for_clipboard(muxbox: &MuxBox) -> String {
// F0215: Stream-Based Choice Navigation - Use stream content for clipboard
// Priority order: output > stream content > static content > default message
if !muxbox.output.is_empty() {
muxbox.output.clone()
} else {
let stream_content = muxbox
.get_selected_stream()
.map_or(Vec::new(), |s| s.content.clone());
if !stream_content.is_empty() {
stream_content.join("\n")
} else if let Some(ref content) = muxbox.content {
content.clone()
} else {
format!("MuxBox '{}': No content", muxbox.id)
}
}
}
/// Copy text to system clipboard
pub fn copy_to_clipboard(content: &str) -> Result<(), Box<dyn std::error::Error>> {
use std::process::Command;
// Platform-specific clipboard commands
#[cfg(target_os = "macos")]
{
let mut child = Command::new("pbcopy")
.stdin(std::process::Stdio::piped())
.spawn()?;
if let Some(stdin) = child.stdin.take() {
use std::io::Write;
let mut stdin = stdin;
stdin.write_all(content.as_bytes())?;
}
child.wait()?;
}
#[cfg(target_os = "linux")]
{
// Try xclip first, then xsel as fallback
let result = Command::new("xclip")
.arg("-selection")
.arg("clipboard")
.stdin(std::process::Stdio::piped())
.spawn();
match result {
Ok(mut child) => {
if let Some(stdin) = child.stdin.take() {
use std::io::Write;
let mut stdin = stdin;
stdin.write_all(content.as_bytes())?;
}
child.wait()?;
}
Err(_) => {
// Fallback to xsel
let mut child = Command::new("xsel")
.arg("--clipboard")
.arg("--input")
.stdin(std::process::Stdio::piped())
.spawn()?;
if let Some(stdin) = child.stdin.take() {
use std::io::Write;
let mut stdin = stdin;
stdin.write_all(content.as_bytes())?;
}
child.wait()?;
}
}
}
#[cfg(target_os = "windows")]
{
let mut child = Command::new("clip")
.stdin(std::process::Stdio::piped())
.spawn()?;
if let Some(stdin) = child.stdin.take() {
use std::io::Write;
let mut stdin = stdin;
stdin.write_all(content.as_bytes())?;
}
child.wait()?;
}
Ok(())
}
// REMOVED: Legacy calculate_clicked_choice_index - replaced by BoxDimensions coordinate system
// REMOVED: Legacy calculate_clicked_choice_index_impl - replaced by BoxDimensions coordinate system
// REMOVED: Legacy calculate_wrapped_choice_click - replaced by BoxDimensions coordinate system
// REMOVED: Legacy wrap_text_to_width_simple - text wrapping handled by RenderableContent components
/// Auto-scroll to ensure selected choice is visible
fn auto_scroll_to_selected_choice(
muxbox: &mut crate::model::muxbox::MuxBox,
selected_choice_index: usize,
) {
use crate::draw_utils::wrap_text_to_width;
let bounds = muxbox.bounds();
let viewable_height = bounds.height().saturating_sub(2); // Account for borders
// Handle different overflow behaviors
if let Some(overflow_behavior) = &muxbox.overflow_behavior {
match overflow_behavior.as_str() {
"wrap" => {
// Calculate wrapped lines for auto-scroll in wrapped choice mode
if let Some(choices) = muxbox.get_selected_stream_choices() {
let viewable_width = bounds.width().saturating_sub(4);
let mut total_lines = 0;
let mut selected_line_start = 0;
let mut selected_line_end = 0;
for (i, choice) in choices.iter().enumerate() {
if let Some(content) = &choice.content {
let formatted_content = if choice.waiting {
format!("{}...", content)
} else {
content.clone()
};
let wrapped_lines =
wrap_text_to_width(&formatted_content, viewable_width);
let line_count = wrapped_lines.len();
if i == selected_choice_index {
selected_line_start = total_lines;
selected_line_end = total_lines + line_count - 1;
}
total_lines += line_count;
}
}
// Adjust scroll to keep selected wrapped lines visible
if total_lines > viewable_height {
let current_scroll_percent = muxbox.vertical_scroll.unwrap_or(0.0);
let current_scroll_offset = ((current_scroll_percent / 100.0)
* (total_lines - viewable_height) as f64)
.floor() as usize;
let visible_start = current_scroll_offset;
let visible_end = visible_start + viewable_height - 1;
let mut new_scroll_percent = current_scroll_percent;
// Scroll down if selected choice is below visible area
if selected_line_end > visible_end {
let new_offset = selected_line_end.saturating_sub(viewable_height - 1);
new_scroll_percent = (new_offset as f64
/ (total_lines - viewable_height) as f64)
* 100.0;
}
// Scroll up if selected choice is above visible area
else if selected_line_start < visible_start {
let new_offset = selected_line_start;
new_scroll_percent = (new_offset as f64
/ (total_lines - viewable_height) as f64)
* 100.0;
}
muxbox.vertical_scroll = Some(new_scroll_percent.clamp(0.0, 100.0));
}
}
}
"scroll" => {
// For scroll mode, use choice index directly
if let Some(choices) = muxbox.get_selected_stream_choices() {
let total_choices = choices.len();
if total_choices > viewable_height {
let current_scroll_percent = muxbox.vertical_scroll.unwrap_or(0.0);
let current_scroll_offset = ((current_scroll_percent / 100.0)
* (total_choices - viewable_height) as f64)
.floor() as usize;
let visible_start = current_scroll_offset;
let visible_end = visible_start + viewable_height - 1;
let mut new_scroll_percent = current_scroll_percent;
// Scroll down if selected choice is below visible area
if selected_choice_index > visible_end {
let new_offset =
selected_choice_index.saturating_sub(viewable_height - 1);
new_scroll_percent = (new_offset as f64
/ (total_choices - viewable_height) as f64)
* 100.0;
}
// Scroll up if selected choice is above visible area
else if selected_choice_index < visible_start {
let new_offset = selected_choice_index;
new_scroll_percent = (new_offset as f64
/ (total_choices - viewable_height) as f64)
* 100.0;
}
muxbox.vertical_scroll = Some(new_scroll_percent.clamp(0.0, 100.0));
}
}
}
_ => {
// For other overflow behaviors (fill, cross_out, etc.), use simple choice index
if let Some(choices) = muxbox.get_selected_stream_choices() {
let total_choices = choices.len();
if total_choices > viewable_height {
let current_scroll_percent = muxbox.vertical_scroll.unwrap_or(0.0);
let current_scroll_offset = ((current_scroll_percent / 100.0)
* (total_choices - viewable_height) as f64)
.floor() as usize;
let visible_start = current_scroll_offset;
let visible_end = visible_start + viewable_height - 1;
let mut new_scroll_percent = current_scroll_percent;
if selected_choice_index > visible_end {
let new_offset =
selected_choice_index.saturating_sub(viewable_height - 1);
new_scroll_percent = (new_offset as f64
/ (total_choices - viewable_height) as f64)
* 100.0;
} else if selected_choice_index < visible_start {
let new_offset = selected_choice_index;
new_scroll_percent = (new_offset as f64
/ (total_choices - viewable_height) as f64)
* 100.0;
}
muxbox.vertical_scroll = Some(new_scroll_percent.clamp(0.0, 100.0));
}
}
}
}
}
}
/// Trigger visual flash for muxbox (stub implementation)
fn trigger_muxbox_flash(_muxbox_id: &str) {
// TODO: Implement visual flash with color inversion
// This would require storing flash state and modifying muxbox rendering
// For now, the redraw provides visual feedback
}
#[cfg(test)]
mod render_gating_tests {
use super::compute_render_signature;
use crate::tests::test_utils::TestDataFactory;
/// The render loop only skips work when the signature is stable for identical
/// state; if this regresses to always-changing we lose the optimization, and
/// if it regresses to never-changing the UI would appear frozen.
#[test]
fn test_signature_is_stable_for_identical_state() {
let ctx = TestDataFactory::create_test_app_context();
assert_eq!(
compute_render_signature(&ctx),
compute_render_signature(&ctx),
"identical app state must produce an identical render signature"
);
}
#[test]
fn test_signature_changes_on_content_scroll_and_selection() {
let base = {
let ctx = TestDataFactory::create_test_app_context();
compute_render_signature(&ctx)
};
// Content change.
let mut ctx = TestDataFactory::create_test_app_context();
ctx.app.layouts[0].children.as_mut().unwrap()[0].content =
Some("brand new content".to_string());
assert_ne!(
base,
compute_render_signature(&ctx),
"a content change must change the render signature"
);
// Scroll change.
let mut ctx = TestDataFactory::create_test_app_context();
ctx.app.layouts[0].children.as_mut().unwrap()[0].vertical_scroll = Some(50.0);
assert_ne!(
base,
compute_render_signature(&ctx),
"a scroll change must change the render signature"
);
// Selection change.
let mut ctx = TestDataFactory::create_test_app_context();
ctx.app.layouts[0].children.as_mut().unwrap()[0].title =
Some("retitled".to_string());
assert_ne!(
base,
compute_render_signature(&ctx),
"a title change must change the render signature"
);
// Hover change — this is what guarantees the render gating can never
// suppress a hover affordance update.
let mut ctx = TestDataFactory::create_test_app_context();
ctx.app.layouts[0].children.as_mut().unwrap()[0].hovered_tab_target =
Some(crate::components::TabHoverTarget::CloseButton(0));
assert_ne!(
base,
compute_render_signature(&ctx),
"a hover change must change the render signature"
);
}
}
#[cfg(test)]
mod hover_reconcile_tests {
use super::{apply_hover_target, clear_all_hover};
use crate::model::choice::Choice;
use crate::model::common::{Stream, StreamType};
use crate::tests::test_utils::TestDataFactory;
fn box_with_choices() -> (crate::model::app::App, String) {
let mut app = TestDataFactory::create_test_app();
let muxbox_id = app.layouts[0].children.as_ref().unwrap()[0].id.clone();
let muxbox = app.layouts[0].children.as_mut().unwrap().get_mut(0).unwrap();
let choices = vec![
Choice {
id: "a".into(),
content: Some("A".into()),
hovered: true,
..Default::default()
},
Choice {
id: "b".into(),
content: Some("B".into()),
..Default::default()
},
Choice {
id: "c".into(),
content: Some("C".into()),
hovered: true,
..Default::default()
},
];
let stream = Stream {
id: "s".into(),
stream_type: StreamType::Choices,
label: "S".into(),
content: vec![],
choices: Some(choices),
source: None,
content_hash: 0,
last_updated: std::time::SystemTime::now(),
created_at: std::time::SystemTime::now(),
};
muxbox.streams.insert("s".into(), stream);
muxbox.selected_stream_id = Some("s".into());
muxbox.hovered_tab_target = Some(crate::draw_utils::TabHoverTarget::Tab(1));
(app, muxbox_id)
}
#[test]
fn test_clear_all_hover_removes_every_highlight() {
let (mut app, _id) = box_with_choices();
assert!(clear_all_hover(&mut app), "should report it cleared highlights");
let muxbox = &app.layouts[0].children.as_ref().unwrap()[0];
assert!(muxbox.hovered_tab_target.is_none());
for choice in muxbox.streams.get("s").unwrap().choices.as_ref().unwrap() {
assert!(!choice.hovered, "every choice highlight must be cleared");
}
// Idempotent: nothing left to clear.
assert!(!clear_all_hover(&mut app));
}
#[test]
fn test_new_highlight_is_mutually_exclusive() {
let (mut app, id) = box_with_choices();
// Setting a new highlight clears all others first (clear-all + set-one).
clear_all_hover(&mut app);
apply_hover_target(&mut app, &id, "choice_1");
let muxbox = &app.layouts[0].children.as_ref().unwrap()[0];
let choices = muxbox.streams.get("s").unwrap().choices.as_ref().unwrap();
assert!(!choices[0].hovered);
assert!(choices[1].hovered, "the newly hovered choice must be highlighted");
assert!(!choices[2].hovered);
assert!(
muxbox.hovered_tab_target.is_none(),
"a choice highlight must not coexist with a tab highlight"
);
}
#[test]
fn test_apply_tab_close_target() {
let (mut app, id) = box_with_choices();
clear_all_hover(&mut app);
apply_hover_target(&mut app, &id, "tab_close_2");
let muxbox = &app.layouts[0].children.as_ref().unwrap()[0];
assert_eq!(
muxbox.hovered_tab_target,
Some(crate::draw_utils::TabHoverTarget::CloseButton(2))
);
}
}
#[cfg(test)]
mod wheel_scroll_tests {
use super::{scroll_hovered_box, WheelDirection};
use crate::model::common::InputBounds;
use crate::tests::test_utils::TestDataFactory;
use crate::Bounds;
fn pos(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(),
}
}
/// Mouse wheel scrolls the box UNDER the cursor, never the focused box.
#[test]
fn test_wheel_scrolls_box_under_cursor_not_focused() {
let mut left = TestDataFactory::create_test_muxbox("left");
left.position = pos("0%", "0%", "49%", "99%");
left.vertical_scroll = Some(0.0);
let mut right = TestDataFactory::create_test_muxbox("right");
right.position = pos("50%", "0%", "99%", "99%");
right.vertical_scroll = Some(0.0);
let mut ctx = TestDataFactory::create_test_app_context();
ctx.app.layouts[0].active = Some(true);
ctx.app.layouts[0].children = Some(vec![left, right]);
// Deterministic coordinate space independent of the real terminal size.
let root = Bounds {
x1: 0,
y1: 0,
x2: 99,
y2: 29,
};
// Sanity: confirm the test points land in the intended boxes.
let children = ctx.app.layouts[0].children.as_ref().unwrap();
let left_b = children[0].bounds_with_parent(&root);
let right_b = children[1].bounds_with_parent(&root);
let right_point = (((right_b.x1 + right_b.x2) / 2) as u16, 10u16);
let left_point = (((left_b.x1 + left_b.x2) / 2) as u16, 10u16);
assert!(right_b.contains_point(right_point.0 as usize, right_point.1 as usize));
assert!(left_b.contains_point(left_point.0 as usize, left_point.1 as usize));
// Wheel over the RIGHT box scrolls the right box only — regardless of focus.
let scrolled = scroll_hovered_box(
&mut ctx,
right_point.0,
right_point.1,
&root,
WheelDirection::Down,
);
assert_eq!(scrolled.as_deref(), Some("right"));
let children = ctx.app.layouts[0].children.as_ref().unwrap();
assert!(
children[1].vertical_scroll.unwrap() > 0.0,
"the hovered (right) box must have scrolled"
);
assert_eq!(
children[0].vertical_scroll.unwrap(),
0.0,
"the non-hovered (left) box must not scroll"
);
// Wheel over the LEFT box targets the left box.
let scrolled = scroll_hovered_box(
&mut ctx,
left_point.0,
left_point.1,
&root,
WheelDirection::Down,
);
assert_eq!(scrolled.as_deref(), Some("left"));
// Over empty space (a column past both boxes) nothing scrolls.
let empty_x = (right_b.x2 + 1) as u16;
assert!(!right_b.contains_point(empty_x as usize, 10));
assert!(!left_b.contains_point(empty_x as usize, 10));
let none = scroll_hovered_box(&mut ctx, empty_x, 10, &root, WheelDirection::Down);
assert_eq!(none, None);
}
}