aboutsummaryrefslogtreecommitdiffstats
path: root/zellij-server/src/tab/mod.rs
blob: 7cda7506e2e334d2d81505d23ff5e636e405064b (plain) (blame)
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
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
//! `Tab`s holds multiple panes. It tracks their coordinates (x/y) and size,
//! as well as how they should be resized

mod clipboard;
mod copy_command;
mod layout_applier;
mod mouse_handler;
mod swap_layouts;

use crate::plugins::PluginId;
use copy_command::CopyCommand;
pub use mouse_handler::{MouseEffect, MouseHandler, PaneEdge, PaneResizeState};
use std::env::temp_dir;
use std::net::IpAddr;
use std::path::PathBuf;
use unicode_width::UnicodeWidthStr;
use uuid::Uuid;
use zellij_utils::data::PaneContents;
use zellij_utils::data::{
    Direction, KeyWithModifier, NewPanePlacement, PaneInfo, PermissionStatus, PermissionType,
    PluginPermission, RegexHighlight, ResizeStrategy, Style, StyledText, WebSharing,
};
use zellij_utils::errors::prelude::*;
use zellij_utils::input::theme::StackListStyle;
use zellij_utils::input::command::RunCommand;
use zellij_utils::input::mouse::MouseEvent;
use zellij_utils::position::Position;
use zellij_utils::position::{Column, Line};
use zellij_utils::shared::clean_string_from_control_and_linebreak;

use crate::background_jobs::BackgroundJob;
use crate::pane_groups::PaneGroups;
use crate::pty_writer::PtyWriteInstruction;
use crate::screen::{CopyOptions, GuestModalOutcome, ScreenInstruction};
use crate::ui::hint_text::{
    held_hint_variants, hover_hint_variants, resize_hint_variants, HintExitStatus,
};
use crate::ui::{
    loading_indication::LoadingIndication,
    pane_boundaries_frame::{stack_index_prefix, FrameParams},
    pane_contents_and_ui::PaneContentsAndUi,
};
use layout_applier::LayoutApplier;
use swap_layouts::SwapLayouts;

use self::clipboard::ClipboardProvider;
use crate::route::NotificationEnd;
use crate::{
    os_input_output::ServerOsApi,
    output::{CharacterChunk, KittyImageChunk, Output, SixelImageChunk},
    panes::floating_panes::floating_pane_grid::half_size_middle_geom,
    panes::grid::namespace_notification_id,
    panes::kitty_graphics::{KittyHostSupport, KittyImageStore},
    panes::nested_session_modal::GuestModalShortcuts,
    panes::sixel::SixelImageStore,
    panes::{FloatingPanes, TiledPanes},
    panes::{
        LinkHandler, PaneId, PluginPane, TerminalCharacter, TerminalPane,
        EMPTY_TERMINAL_CHARACTER,
    },
    plugins::PluginInstruction,
    pty::{ClientTabIndexOrPaneId, PtyInstruction, VteBytes},
    thread_bus::ThreadSenders,
    ClientId, ServerInstruction,
};
use std::cell::RefCell;
use std::rc::Rc;
use std::time::Instant;
use std::{
    collections::{BTreeMap, HashMap, HashSet},
    str,
};
use zellij_utils::{
    data::{Event, FloatingPaneCoordinates, InputMode, ModeInfo, Palette, PaletteColor, Styling},
    input::{
        command::TerminalAction,
        layout::{
            FloatingPaneLayout, Run, RunPluginOrAlias, SplitDirection, SwapFloatingLayout,
            SwapTiledLayout, TiledPaneLayout,
        },
        options::PaneFrameStyle,
        parse_keys,
    },
    nested_session::NestedSessionMessage,
    pane_size::{Dimension, Offset, PaneGeom, Size, SizeInPixels, Viewport},
};

#[macro_export]
macro_rules! resize_pty {
    ($pane:expr, $os_input:expr, $senders:expr) => {{
        match $pane.pid() {
            PaneId::Terminal(ref pid) => {
                $senders
                    .send_to_pty_writer(PtyWriteInstruction::ResizePty(
                        *pid,
                        $pane.get_content_columns() as u16,
                        $pane.get_content_rows() as u16,
                        None,
                        None,
                    ))
                    .with_context(err_context);
            },
            PaneId::Plugin(ref pid) => {
                let err_context = || format!("failed to resize plugin {pid}");
                $senders
                    .send_to_plugin(PluginInstruction::Resize(
                        *pid,
                        $pane.get_content_columns(),
                        $pane.get_content_rows(),
                    ))
                    .with_context(err_context)
            },
        }
    }};
    ($pane:expr, $os_input:expr, $senders:expr, $character_cell_size:expr) => {{
        let (width_in_pixels, height_in_pixels) = {
            let character_cell_size = $character_cell_size.borrow();
            match *character_cell_size {
                Some(size_in_pixels) => {
                    let width_in_pixels =
                        (size_in_pixels.width * $pane.get_content_columns()) as u16;
                    let height_in_pixels =
                        (size_in_pixels.height * $pane.get_content_rows()) as u16;
                    (Some(width_in_pixels), Some(height_in_pixels))
                },
                None => (None, None),
            }
        };
        match $pane.pid() {
            PaneId::Terminal(ref pid) => {
                use crate::PtyWriteInstruction;
                let err_context = || format!("Failed to send resize pty instruction");
                $senders
                    .send_to_pty_writer(PtyWriteInstruction::ResizePty(
                        *pid,
                        $pane.get_content_columns() as u16,
                        $pane.get_content_rows() as u16,
                        width_in_pixels,
                        height_in_pixels,
                    ))
                    .with_context(err_context)
            },
            PaneId::Plugin(ref pid) => {
                let err_context = || format!("failed to resize plugin {pid}");
                $senders
                    .send_to_plugin(PluginInstruction::Resize(
                        *pid,
                        $pane.get_content_columns(),
                        $pane.get_content_rows(),
                    ))
                    .with_context(err_context)
            },
        }
    }};
}

// FIXME: This should be replaced by `RESIZE_PERCENT` at some point
pub const MIN_TERMINAL_HEIGHT: usize = 5;
pub const MIN_TERMINAL_WIDTH: usize = 5;

const MAX_PENDING_VTE_EVENTS: usize = 7000;

type HoldForCommand = Option<RunCommand>;
pub type SuppressedPanes = HashMap<PaneId, (bool, Box<dyn Pane>)>; // bool => is scrollback editor

/// Internal names for the layouts the responsive collapse synthesizes. Prefixed
/// so they cannot collide with a name from a user's swap file.
const RESPONSIVE_COLLAPSE_LAYOUT_NAME: &str = "sl0p:responsive-collapse";
const RESPONSIVE_EXPAND_LAYOUT_NAME: &str = "sl0p:responsive-expand";

pub type StackListId = usize;

#[derive(Debug, Clone)]
pub struct StackList {
    pub members: Vec<PaneId>,
    pub visible: PaneId,
}

impl StackList {
    pub fn rank_of(&self, pane_id: &PaneId) -> Option<usize> {
        self.members.iter().position(|p| p == pane_id)
    }
}

/// One rendered cell of the stacked-pane picker.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StackListCell {
    /// Index into `StackList::members`.
    pub member_index: usize,
    /// Offset from the list's left edge.
    pub x_offset: usize,
    /// Offset from the list's top edge.
    pub row: usize,
    pub width: usize,
}

/// The picker's complete cell layout.
///
/// The single source of truth for "which member does this cell show, and where
/// is it". The renderer, the reserved-row budget and the mouse hit-test all read
/// it, so they cannot disagree -- a desync between just two of them already
/// caused clicks to select the wrong pane once.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StackListLayout {
    pub cells: Vec<StackListCell>,
    /// Rows the cells occupy, NOT counting the indicator row beneath them.
    pub rows: usize,
    pub hidden: usize,
}

/// Below this an entry has no room for any label at all.
const STACK_LIST_MIN_ENTRY_COLS: usize = 8;
/// Blank columns between grid cells. Without a gap the focused entry's "> "
/// marker sits flush against the previous cell and reads as belonging to it.
const STACK_LIST_CELL_GAP_COLS: usize = 2;

/// Which members are on screen, given a column count and a row budget.
///
/// Windows by ROW rather than by member so that a grid scrolls a whole row at a
/// time; with one column this reduces to "window of N members around the focused
/// one", which is what the list did before it could be a grid.
///
/// Returns (first member index, member count shown, rows occupied).
fn stack_list_window_core(
    member_count: usize,
    visible_rank: usize,
    columns: usize,
    max_rows: usize,
) -> (usize, usize, usize) {
    let columns = columns.max(1);
    if member_count == 0 {
        return (0, 0, 0);
    }
    let total_rows = member_count.div_ceil(columns);
    let rows = if max_rows == 0 {
        total_rows
    } else {
        total_rows.min(max_rows.max(1))
    };
    let focus_row = visible_rank / columns;
    let first_row = focus_row
        .saturating_sub(rows / 2)
        .min(total_rows.saturating_sub(rows));
    let start = first_row * columns;
    let shown = (member_count - start).min(rows * columns);
    (start, shown, shown.div_ceil(columns))
}

/// Spans of a picker row that no cell covers, as (start, end) column offsets.
///
/// The picker draws each entry as its own chunk, so the space between and around
/// them is never painted and keeps whatever was there before -- which matters
/// because the grid genuinely re-flows when a label's width changes.
///
/// Returns only the uncovered spans, never the cells: chunks are not composited
/// last-wins, so blanking a region a cell also draws to erases the entry instead
/// of the stale contents beneath it.
fn stack_list_row_gaps(
    layout: &StackListLayout,
    row: usize,
    available_cols: usize,
) -> Vec<(usize, usize)> {
    let mut spans: Vec<(usize, usize)> = layout
        .cells
        .iter()
        .filter(|cell| cell.row == row)
        .map(|cell| (cell.x_offset, cell.x_offset + cell.width))
        .collect();
    spans.sort_unstable();
    let mut gaps = vec![];
    let mut cursor = 0;
    for (start, end) in spans {
        if start > cursor {
            gaps.push((cursor, start));
        }
        cursor = cursor.max(end);
    }
    if cursor < available_cols {
        gaps.push((cursor, available_cols));
    }
    gaps
}

enum StackListRemoval {
    NotRemoved,
    DissolvedInPlace,
    Removed(Option<Box<dyn Pane>>),
}

enum BufferedTabInstruction {
    SetPaneSelectable(PaneId, bool),
    HandlePtyBytes(u32, VteBytes),
    HoldPane(PaneId, Option<i32>, bool, RunCommand), // Option<i32> is the exit status, bool is is_first_run
}

pub(crate) struct Tab {
    pub id: usize,
    pub position: usize,
    pub name: String,
    pub prev_name: String,
    default_name: String,
    pub size: Size,
    pub visible_to: Option<HashSet<ClientId>>,
    tiled_panes: TiledPanes,
    floating_panes: FloatingPanes,
    suppressed_panes: SuppressedPanes,
    stacked_pane_list: Rc<RefCell<bool>>,
    reserved_top_rows: Rc<RefCell<HashMap<PaneId, usize>>>,
    stack_lists: HashMap<StackListId, StackList>,
    stack_list_of_member: HashMap<PaneId, StackListId>,
    stack_list_parked_pairs: HashMap<PaneId, PaneId>,
    next_stack_list_id: StackListId,
    stack_list_session_is_mirrored: bool,
    max_panes: Option<usize>,
    viewport: Rc<RefCell<Viewport>>, // includes all non-UI panes
    display_area: Rc<RefCell<Size>>, // includes all panes (including eg. the status bar and tab bar in the default layout)
    character_cell_size: Rc<RefCell<Option<SizeInPixels>>>,
    sixel_image_store: Rc<RefCell<SixelImageStore>>,
    kitty_image_store: Rc<RefCell<KittyImageStore>>,
    os_api: Box<dyn ServerOsApi>,
    pub senders: ThreadSenders,
    synchronize_is_active: bool,
    should_clear_display_before_rendering: bool,
    mode_info: Rc<RefCell<HashMap<ClientId, ModeInfo>>>,
    default_mode_info: ModeInfo,
    pub style: Style,
    connected_clients: Rc<RefCell<HashSet<ClientId>>>,
    pane_frame_style: PaneFrameStyle,
    auto_layout: bool,
    pending_vte_events: HashMap<u32, Vec<VteBytes>>,
    pub selecting_with_mouse_in_pane: Option<PaneId>, // this is only pub for the tests
    pane_being_resized_with_mouse: Option<PaneResizeState>,
    link_handler: Rc<RefCell<LinkHandler>>,
    clipboard_provider: ClipboardProvider,
    // TODO: used only to focus the pane when the layout is loaded
    // it seems that optimization is possible using `active_panes`
    focus_pane_id: Option<PaneId>,
    copy_on_select: bool,
    terminal_emulator_colors: Rc<RefCell<Palette>>,
    terminal_emulator_color_codes: Rc<RefCell<HashMap<usize, String>>>,
    pids_waiting_resize: HashSet<u32>, // u32 is the terminal_id
    cursor_positions_and_shape: HashMap<ClientId, (usize, usize, String)>, // (x_position,
    // y_position,
    // cursor_shape_csi)
    is_pending: bool, // a pending tab is one that is still being loaded or otherwise waiting
    pending_instructions: Vec<BufferedTabInstruction>, // instructions that came while the tab was
    // pending and need to be re-applied
    swap_layouts: SwapLayouts,
    default_shell: PathBuf,
    default_editor: Option<PathBuf>,
    debug: bool,
    arrow_fonts: bool,
    kitty_host_support: Option<KittyHostSupport>,
    styled_underlines: bool,
    osc8_hyperlinks: bool,
    explicitly_disable_kitty_keyboard_protocol: bool,
    web_clients_allowed: bool,
    web_sharing: WebSharing,
    mouse_hover_pane_id: HashMap<ClientId, PaneId>,
    dimmed_clients: HashSet<ClientId>,
    plugin_hover_pane_id: HashMap<ClientId, PaneId>,
    mouse_last_pane_id: HashMap<ClientId, PaneId>,
    mouse_help_text_visible: HashMap<ClientId, bool>,
    last_mouse_activity_time: HashMap<ClientId, Instant>,
    last_hint_text: HashMap<ClientId, BTreeMap<usize, StyledText>>,
    last_active_pane_scroll: HashMap<ClientId, Option<(usize, usize)>>,
    current_pane_group: Rc<RefCell<PaneGroups>>,
    advanced_mouse_actions: bool,
    mouse_scroll_resize: bool,
    mouse_hover_effects: bool,
    focus_follows_mouse: bool,
    mouse_click_through: bool,
    /// Repeated clicks on pane FRAMES, per client. Separate from the grid's own
    /// click tracking (which is for selecting text inside a pane) because a
    /// click that lands on the frame never reaches the grid.
    frame_clicks: HashMap<ClientId, crate::panes::grid::Click>,
    /// Tiled pane currently being dragged by its title bar, per client.
    tiled_pane_being_dragged: HashMap<ClientId, PaneId>,
    /// While dragging, the pane the dragged one is currently swapped WITH, so
    /// the live layout acts as the preview. Undone when the drag moves to a
    /// different target.
    drag_preview_swapped_with: HashMap<ClientId, PaneId>,
    /// Whether the tab is currently collapsed by the responsive layout. The
    /// only state the feature keeps: everything else is resolved from the panes
    /// as they are, and this is flipped only after a layout was applied.
    responsive_collapsed: bool,
    responsive_min_cols: usize,
    responsive_layout_name: String,
    /// Cap on picker rows; see stack_list_window. 0 = uncapped.
    stack_list_max_rows: usize,
    /// Stacks the user has expanded past the cap by clicking "+N more".
    expanded_stack_lists: HashSet<StackListId>,
    /// Pack picker entries into a grid rather than one per row.
    stack_list_grid: bool,
    /// Visual treatment of picker entries.
    stack_list_style: StackListStyle,
    /// So the "no such swap layout" warning is logged once, not per resize.
    responsive_missing_layout_warned: bool,
    currently_marking_pane_group: Rc<RefCell<HashMap<ClientId, bool>>>,
    connected_clients_in_app: Rc<RefCell<HashMap<ClientId, bool>>>, // bool -> is_web_client
    // the below are the configured values - the ones that will be set if and when the web server
    // is brought online
    web_server_ip: IpAddr,
    web_server_port: u16,
    pub panes_with_pending_bell: HashSet<PaneId>,
    pub tab_has_pending_bell: bool,
    pub tab_bell_flash: bool, // currently in mid-notification-flash
    pub tab_bell_ring: bool,  // need to send ANSI BEL to the controlling terminal
}

// FIXME: Use a struct that has a pane_type enum, to reduce all of the duplication
pub trait Pane {
    fn x(&self) -> usize;
    fn y(&self) -> usize;
    fn rows(&self) -> usize;
    fn cols(&self) -> usize;
    fn get_content_x(&self) -> usize;
    fn get_content_y(&self) -> usize;
    fn get_content_columns(&self) -> usize;
    fn get_content_rows(&self) -> usize;
    fn reset_size_and_position_override(&mut self);
    fn set_geom(&mut self, position_and_size: PaneGeom);
    fn set_geom_override(&mut self, pane_geom: PaneGeom);
    fn handle_pty_bytes(&mut self, _bytes: VteBytes) {}
    fn handle_plugin_bytes(&mut self, _client_id: ClientId, _bytes: VteBytes) {}
    fn show_cursor(&mut self, _client_id: ClientId, _cursor_position: Option<(usize, usize)>) {}
    /// Returns the cursor position and whether it is visible.
    /// The position is returned unconditionally (as long as the cursor is within
    /// bounds) so that the host terminal can position the cursor for IME even
    /// when the app has hidden it. The bool is true when the cursor is visible.
    fn cursor_coordinates(&self, _client_id: Option<ClientId>) -> Option<(usize, usize, bool)>;
    fn is_mid_frame(&self) -> bool {
        false
    }
    fn adjust_input_to_terminal(
        &mut self,
        _key_with_modifier: &Option<KeyWithModifier>,
        _raw_input_bytes: Vec<u8>,
        _raw_input_bytes_are_kitty: bool,
        _client_id: Option<ClientId>,
    ) -> Option<AdjustedInput> {
        None
    }
    fn position_and_size(&self) -> PaneGeom;
    fn current_geom(&self) -> PaneGeom;
    fn geom_override(&self) -> Option<PaneGeom>;
    fn should_render(&self) -> bool;
    fn set_should_render(&mut self, should_render: bool);
    fn set_should_render_boundaries(&mut self, _should_render: bool) {}
    fn selectable(&self) -> bool;
    fn set_selectable(&mut self, selectable: bool);
    fn request_permissions_from_user(&mut self, _permissions: Option<PluginPermission>) {}
    fn render(
        &mut self,
        client_id: Option<ClientId>,
    ) -> Result<
        Option<(
            Vec<CharacterChunk>,
            Option<String>,
            Vec<SixelImageChunk>,
            Vec<KittyImageChunk>,
        )>,
    >; // TODO: better
    fn render_frame(
        &mut self,
        client_id: ClientId,
        frame_params: FrameParams,
        input_mode: InputMode,
    ) -> Result<Option<(Vec<CharacterChunk>, Option<String>)>>; // TODO: better
    fn render_fake_cursor(
        &mut self,
        cursor_color: PaletteColor,
        text_color: PaletteColor,
    ) -> Option<String>;
    fn render_terminal_title(&mut self, _input_mode: InputMode) -> String;
    fn update_name(&mut self, name: &str);
    fn pid(&self) -> PaneId;
    fn reduce_height(&mut self, percent: f64);
    fn increase_height(&mut self, percent: f64);
    fn reduce_width(&mut self, percent: f64);
    fn increase_width(&mut self, percent: f64);
    fn push_down(&mut self, count: usize);
    fn push_right(&mut self, count: usize);
    fn pull_left(&mut self, count: usize);
    fn pull_up(&mut self, count: usize);
    fn clear_screen(&mut self);
    fn dump_screen(&self, _full: bool, _client_id: Option<ClientId>) -> String {
        "".to_owned()
    }
    fn dump_screen_with_ansi(&self, _full: bool, _client_id: Option<ClientId>) -> String {
        "".to_owned()
    }
    fn scroll_up(&mut self, count: usize, client_id: ClientId);
    fn scroll_down(&mut self, count: usize, client_id: ClientId);
    fn scroll_left(&mut self, _count: usize, _client_id: ClientId) {}
    fn scroll_right(&mut self, _count: usize, _client_id: ClientId) {}
    fn clear_scroll(&mut self);
    fn is_scrolled(&self) -> bool;
    fn active_at(&self) -> Instant;
    fn set_active_at(&mut self, instant: Instant);
    fn set_frame(&mut self, frame: bool);
    fn set_content_offset(&mut self, offset: Offset);
    fn get_content_offset(&self) -> Offset {
        Offset::default()
    }
    fn cursor_shape_csi(&self) -> String {
        "\u{1b}[0 q".to_string() // default to non blinking block
    }
    fn contains(&self, position: &Position) -> bool {
        match self.geom_override() {
            Some(position_and_size) => position_and_size.contains(position),
            None => self.position_and_size().contains(position),
        }
    }
    fn start_selection(&mut self, _start: &Position, _client_id: ClientId) {}
    fn update_selection(&mut self, _position: &Position, _client_id: ClientId) {}
    fn end_selection(&mut self, _end: &Position, _client_id: ClientId) {}
    fn reset_selection(&mut self, _client_id: Option<ClientId>) {}
    fn supports_mouse_selection(&self) -> bool {
        true
    }
    fn get_selected_text(&self, _client_id: ClientId) -> Option<String> {
        None
    }
    fn set_pane_default_colors(&mut self, _fg: Option<String>, _bg: Option<String>) {}
    fn get_pane_default_colors(&self) -> (Option<String>, Option<String>) {
        (None, None)
    }

    fn right_boundary_x_coords(&self) -> usize {
        self.x() + self.cols()
    }
    fn right_boundary_x_content_coords(&self) -> usize {
        self.get_content_x() + self.get_content_columns()
    }
    fn bottom_boundary_y_coords(&self) -> usize {
        self.y() + self.rows()
    }
    fn bottom_boundary_y_content_coords(&self) -> usize {
        self.get_content_y() + self.get_content_rows()
    }
    fn is_right_of(&self, other: &dyn Pane) -> bool {
        self.x() > other.x()
    }
    fn is_directly_right_of(&self, other: &dyn Pane) -> bool {
        self.x() == other.x() + other.cols()
    }
    fn is_left_of(&self, other: &dyn Pane) -> bool {
        self.x() < other.x()
    }
    fn is_directly_left_of(&self, other: &dyn Pane) -> bool {
        self.x() + self.cols() == other.x()
    }
    fn is_below(&self, other: &dyn Pane) -> bool {
        self.y() > other.y()
    }
    fn is_directly_below(&self, other: &dyn Pane) -> bool {
        self.y() == other.y() + other.rows()
    }
    fn is_above(&self, other: &dyn Pane) -> bool {
        self.y() < other.y()
    }
    fn is_directly_above(&self, other: &dyn Pane) -> bool {
        self.y() + self.rows() == other.y()
    }
    fn horizontally_overlaps_with(&self, other: &dyn Pane) -> bool {
        (self.y() >= other.y() && self.y() < (other.y() + other.rows()))
            || ((self.y() + self.rows()) <= (other.y() + other.rows())
                && (self.y() + self.rows()) > other.y())
            || (self.y() <= other.y() && (self.y() + self.rows() >= (other.y() + other.rows())))
            || (other.y() <= self.y() && (other.y() + other.rows() >= (self.y() + self.rows())))
    }
    fn get_horizontal_overlap_with(&self, other: &dyn Pane) -> usize {
        std::cmp::min(self.y() + self.rows(), other.y() + other.rows())
            - std::cmp::max(self.y(), other.y())
    }
    fn vertically_overlaps_with(&self, other: &dyn Pane) -> bool {
        (self.x() >= other.x() && self.x() < (other.x() + other.cols()))
            || ((self.x() + self.cols()) <= (other.x() + other.cols())
                && (self.x() + self.cols()) > other.x())
            || (self.x() <= other.x() && (self.x() + self.cols() >= (other.x() + other.cols())))
            || (other.x() <= self.x() && (other.x() + other.cols() >= (self.x() + self.cols())))
    }
    fn get_vertical_overlap_with(&self, other: &dyn Pane) -> usize {
        std::cmp::min(self.x() + self.cols(), other.x() + other.cols())
            - std::cmp::max(self.x(), other.x())
    }
    fn can_reduce_height_by(&self, reduce_by: usize) -> bool {
        self.rows() > reduce_by && self.rows() - reduce_by >= self.min_height()
    }
    fn can_reduce_width_by(&self, reduce_by: usize) -> bool {
        self.cols() > reduce_by && self.cols() - reduce_by >= self.min_width()
    }
    fn min_width(&self) -> usize {
        MIN_TERMINAL_WIDTH
    }
    fn min_height(&self) -> usize {
        MIN_TERMINAL_HEIGHT
    }
    fn drain_messages_to_pty(&mut self) -> Vec<Vec<u8>> {
        // TODO: this is only relevant to terminal panes
        // we should probably refactor away from this trait at some point
        vec![]
    }
    fn drain_forwarded_queries(&mut self) -> Vec<crate::host_query::HostQuery> {
        // Only terminal panes forward whitelisted queries to the host;
        // plugin panes have no such concept.
        vec![]
    }
    fn drain_nested_session_messages(&mut self) -> Vec<NestedSessionMessage> {
        vec![]
    }
    fn is_nested_guest(&self) -> bool {
        false
    }
    fn set_is_nested_guest(&mut self, _is_nested_guest: bool) {}
    fn set_guest_modal(&mut self, _client_ids: &[ClientId]) {}
    fn clear_guest_modal(&mut self, _client_id: ClientId) {}
    fn clear_all_guest_modals(&mut self) {}
    fn guest_modal_selection(&self, _client_id: ClientId) -> Option<usize> {
        None
    }
    fn has_guest_modal_for_any_client(&self) -> bool {
        false
    }
    fn set_guest_choice_indicator(
        &mut self,
        _client_id: ClientId,
        _indicator: Option<GuestChoiceIndicator>,
    ) {
    }
    fn guest_choice_indicator(&self, _client_id: ClientId) -> Option<GuestChoiceIndicator> {
        None
    }
    fn clear_all_guest_choice_indicators(&mut self) {}
    fn set_guest_session_name(&mut self, _session_name: Option<String>) {}
    fn guest_session_name(&self) -> Option<String> {
        None
    }
    fn set_guest_modal_shortcuts(&mut self, _shortcuts: GuestModalShortcuts) {}
    fn guest_modal_shortcuts(&self) -> GuestModalShortcuts {
        GuestModalShortcuts::default()
    }
    /// Mark this pane as awaiting a host-terminal reply for a forward
    /// it just dispatched. While paused, vte byte feeding is buffered
    /// so that the eventual host reply lands on the pane's stdin in
    /// the same stream position the original query occupied. Default
    /// no-op for non-terminal panes (plugins do not forward queries).
    fn arm_forward_pause(&mut self) {}
    /// Clear the forward-pause flag set by `arm_forward_pause`, returning
    /// `true` if the pane was previously paused. Default no-op.
    fn clear_forward_pause(&mut self) -> bool {
        false
    }
    /// Drain and return any PTY bytes that arrived while the pane was
    /// forward-paused. Tab calls this on resume and re-feeds the bytes
    /// through `handle_pty_bytes`. Default empty for non-terminal panes.
    fn drain_pending_pty_input(&mut self) -> Vec<u8> {
        vec![]
    }
    /// Whether this pane is currently waiting for a host-forward reply.
    fn is_forward_paused(&self) -> bool {
        false
    }
    /// Push a CSI ?997 DSR notification (host color-palette theme mode)
    /// onto this pane's pending pty-write queue, but only if the pane's
    /// underlying app opted in via `CSI ? 2031 h`.
    /// Only relevant to terminal panes, plugin panes receive this through
    /// `Event::HostTerminalThemeChanged`
    fn push_color_palette_dsr(&mut self, _mode: zellij_utils::data::HostTerminalThemeMode) {}
    fn drain_clipboard_update(&mut self) -> Option<String> {
        None
    }
    fn drain_desktop_notifications(&mut self) -> Vec<(String, String)> {
        vec![]
    }
    fn drain_osc7_cwd(&mut self) -> Option<std::path::PathBuf> {
        None
    }
    fn render_full_viewport(&mut self) {}
    /// Called when this pane gains or loses focus.
    ///
    /// The output buffer only emits CHANGED cells, so focus-dependent styling
    /// (desaturating unfocused panes) would otherwise not appear until the pane
    /// happened to print something - an idle pane would keep its old colours
    /// indefinitely. Panes that have no focus-dependent styling do nothing
    /// here, so this costs nothing when the feature is off.
    fn refresh_for_focus_change(&mut self) {}
    fn relative_position(&self, position_on_screen: &Position) -> Position {
        position_on_screen.relative_to(self.get_content_y(), self.get_content_x())
    }
    fn position_is_on_frame(&self, position: &Position) -> bool {
        if !self.contains(position) {
            return false;
        }
        if (self.x()..self.get_content_x()).contains(&position.column()) {
            // position is on left border
            return true;
        }
        if (self.get_content_x() + self.get_content_columns()..(self.x() + self.cols()))
            .contains(&position.column())
        {
            // position is on right border
            return true;
        }
        if (self.y() as isize..self.get_content_y() as isize).contains(&position.line()) {
            // position is on top border
            return true;
        }
        if ((self.get_content_y() + self.get_content_rows()) as isize
            ..(self.y() + self.rows()) as isize)
            .contains(&position.line())
        {
            // position is on bottom border
            return true;
        }
        false
    }
    /// Is this position on the pane's TOP border, i.e. the row the title is
    /// drawn on?
    ///
    /// Deliberately geometric rather than derived from get_edge_at_position():
    /// that function quadrant-splits the pane and only ever returns the four
    /// CORNER variants, never PaneEdge::Top, so a title-row click reports as
    /// TopLeft/TopRight.
    fn position_is_on_title_row(&self, position: &Position) -> bool {
        if !self.contains(position) {
            return false;
        }
        (self.y() as isize..self.get_content_y() as isize).contains(&position.line())
    }
    /// Is this position on the part of the title row that acts as a MOVE
    /// handle, i.e. the title row excluding the corners?
    ///
    /// The corners stay resize handles, so two-axis resize from the top is
    /// preserved. Losing plain top-edge resize costs nothing: every boundary is
    /// shared, so the boundary above this pane is the bottom edge of the pane
    /// above and can be dragged from there. A pane at the top of the viewport
    /// has the screen edge above it, which was never resizable.
    fn position_is_on_title_move_handle(&self, position: &Position) -> bool {
        const CORNER_WIDTH: usize = 2;
        if !self.position_is_on_title_row(position) {
            return false;
        }
        let left_edge = self.x();
        let right_edge = self.x() + self.cols();
        let col = position.column();
        col >= left_edge.saturating_add(CORNER_WIDTH)
            && col < right_edge.saturating_sub(CORNER_WIDTH)
    }
    fn get_edge_at_position(&self, position: &Position) -> Option<PaneEdge> {
        if !self.contains(position) {
            return None;
        }

        let pos_col = position.column();
        let pos_line = position.line();
        let pane_x = self.x();
        let pane_y = self.y();
        let pane_cols = self.cols();
        let pane_rows = self.rows();

        let mid_col = pane_x + pane_cols / 2;
        let mid_line = pane_y + pane_rows / 2;

        let is_left = pos_col < mid_col;
        let is_top = (pos_line as usize) < mid_line;

        return Some(match (is_top, is_left) {
            (true, true) => PaneEdge::TopLeft,
            (true, false) => PaneEdge::TopRight,
            (false, true) => PaneEdge::BottomLeft,
            (false, false) => PaneEdge::BottomRight,
        });
    }
    // TODO: get rid of this in favor of intercept_mouse_event_on_frame
    fn intercept_left_mouse_click(&mut self, _position: &Position, _client_id: ClientId) -> bool {
        let intercepted = false;
        intercepted
    }
    fn intercept_mouse_event_on_frame(
        &mut self,
        _event: &MouseEvent,
        _client_id: ClientId,
    ) -> bool {
        let intercepted = false;
        intercepted
    }
    fn store_pane_name(&mut self);
    fn load_pane_name(&mut self);
    fn set_borderless(&mut self, borderless: bool);
    fn borderless(&self) -> bool;
    fn set_exclude_from_sync(&mut self, exclude_from_sync: bool);
    fn exclude_from_sync(&self) -> bool;

    // TODO: this should probably be merged with the mouse_right_click
    fn handle_right_click(&mut self, _to: &Position, _client_id: ClientId) {}
    fn mouse_event(&self, _event: &MouseEvent, _client_id: ClientId) -> Option<String> {
        None
    }
    fn mouse_left_click(&self, _position: &Position, _is_held: bool) -> Option<String> {
        None
    }
    fn mouse_left_click_release(&self, _position: &Position) -> Option<String> {
        None
    }
    fn mouse_right_click(&self, _position: &Position, _is_held: bool) -> Option<String> {
        None
    }
    fn mouse_right_click_release(&self, _position: &Position) -> Option<String> {
        None
    }
    fn mouse_middle_click(&self, _position: &Position, _is_held: bool) -> Option<String> {
        None
    }
    fn mouse_middle_click_release(&self, _position: &Position) -> Option<String> {
        None
    }
    fn mouse_scroll_up(&self, _position: &Position) -> Option<String> {
        None
    }
    fn mouse_scroll_down(&self, _position: &Position) -> Option<String> {
        None
    }
    fn focus_event(&self) -> Option<String> {
        None
    }
    fn unfocus_event(&self) -> Option<String> {
        None
    }
    fn get_line_number(&self) -> Option<usize> {
        None
    }
    fn update_search_term(&mut self, _needle: &str) {
        // No-op by default (only terminal-panes currently have search capability)
    }
    fn search_down(&mut self) {
        // No-op by default (only terminal-panes currently have search capability)
    }
    fn search_up(&mut self) {
        // No-op by default (only terminal-panes currently have search capability)
    }
    fn toggle_search_case_sensitivity(&mut self) {
        // No-op by default (only terminal-panes currently have search capability)
    }
    fn toggle_search_whole_words(&mut self) {
        // No-op by default (only terminal-panes currently have search capability)
    }
    fn toggle_search_wrap(&mut self) {
        // No-op by default (only terminal-panes currently have search capability)
    }
    fn clear_search(&mut self) {
        // No-op by default (only terminal-panes currently have search capability)
    }
    fn is_alternate_mode_active(&self) -> bool {
        // False by default (only terminal-panes support alternate mode)
        false
    }
    fn hold(&mut self, _exit_status: Option<i32>, _is_first_run: bool, _run_command: RunCommand) {
        // No-op by default, only terminal panes support holding
    }
    fn has_bell(&self) -> bool {
        false
    }
    fn consume_bell(&mut self) {}
    fn set_bell_notification(&mut self, _val: bool) {}
    fn get_bell_notification(&self) -> bool {
        false
    }
    fn add_red_pane_frame_color_override(&mut self, _error_text: Option<String>);
    fn add_highlight_pane_frame_color_override(
        &mut self,
        _text: Option<String>,
        _client_id: Option<ClientId>,
    ) {
    }
    fn clear_pane_frame_color_override(&mut self, _client_id: Option<ClientId>);
    fn frame_color_override(&self) -> Option<PaletteColor>;
    fn invoked_with(&self) -> &Option<Run>;
    fn set_title(&mut self, title: String);
    fn update_loading_indication(&mut self, _loading_indication: LoadingIndication) {} // only relevant for plugins
    fn start_loading_indication(&mut self, _loading_indication: LoadingIndication) {} // only relevant for plugins
    fn progress_animation_offset(&mut self) {} // only relevant for plugins
    fn current_title(&self) -> String;
    fn stack_list_entry_label(&self) -> String {
        self.current_title()
    }
    fn custom_title(&self) -> Option<String>;
    fn has_explicit_title(&self) -> bool {
        false
    }
    fn scroll_position(&self) -> (usize, usize) {
        (0, 0)
    }
    fn is_held(&self) -> bool {
        false
    }
    fn exited(&self) -> bool {
        false
    }
    fn exit_status(&self) -> Option<i32> {
        None
    }
    fn rename(&mut self, _buf: Vec<u8>) {}
    fn serialize(&self, _scrollback_lines_to_serialize: Option<usize>) -> Option<String> {
        None
    }
    fn rerun(&mut self) -> Option<RunCommand> {
        None
    } // only relevant to terminal panes
    fn update_theme(&mut self, _theme: Styling) {}
    fn update_arrow_fonts(&mut self, _should_support_arrow_fonts: bool) {}
    fn update_kitty_host_support(&mut self, _supported: KittyHostSupport) {}
    fn update_rounded_corners(&mut self, _rounded_corners: bool) {}
    /// Per-side outer gap, decided by the container (which knows the viewport).
    /// MUST be followed by set_content_offset: the gap is baked into
    /// content_offset, so it only takes effect on the next offset sweep.
    fn set_gap_offset(&mut self, _gap_offset: zellij_utils::pane_size::Offset) {}
    /// Live-update the sl0p frame layout options (title alignment, outer gap,
    /// inner padding). Callers MUST follow this with the usual
    /// `set_pane_frames` sweep: gap/padding are baked into `content_offset`
    /// when it is set, so changing them here only takes effect once
    /// `set_content_offset` is re-run.
    fn update_frame_layout(
        &mut self,
        _title_alignment: zellij_utils::data::PaneTitleAlignment,
        _gap_x: usize,
        _gap_y: usize,
        _padding: zellij_utils::data::PanePadding,
        _inactive_grayscale: u8,
        _hide_default_pane_names: bool,
    ) {
    }
    fn set_should_be_suppressed(&mut self, _should_be_suppressed: bool) {}
    fn query_should_be_suppressed(&self) -> bool {
        false
    }
    fn drain_fake_cursors(&mut self) -> Option<HashSet<(usize, usize)>> {
        None
    }
    fn toggle_pinned(&mut self) {}
    fn set_pinned(&mut self, _should_be_pinned: bool) {}
    fn reset_logical_position(&mut self) {}
    fn set_mouse_selection_support(&mut self, _selection_support: bool) {}
    fn pane_contents(
        &self,
        client_id: Option<ClientId>,
        _get_full_scrollback: bool,
        _max_scrollback_lines: Option<usize>,
    ) -> PaneContents;
    fn pane_contents_with_ansi(
        &self,
        _client_id: Option<ClientId>,
        _get_full_scrollback: bool,
        _max_scrollback_lines: Option<usize>,
    ) -> PaneContents {
        Default::default()
    }
    fn update_exit_status(&mut self, _exit_status: i32) {}
    fn set_plugin_regex_highlights(
        &mut self,
        _plugin_id: u32,
        _highlights: Vec<RegexHighlight>,
        _style: &Style,
    ) {
    }
    fn clear_plugin_highlights(&mut self, _plugin_id: u32) {}
    fn set_hover_position(&mut self, _position: Option<Position>) -> bool {
        false
    }
    fn cached_hover_tooltip(&self) -> Option<String> {
        None
    }
    fn plugin_highlight_at(
        &self,
        _position: &Position,
    ) -> Option<(u32, String, String, BTreeMap<String, String>)> {
        None
    }
    fn terminal_emulator_wants_mouse(&self) -> bool {
        false
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GuestChoiceIndicator {
    Descended,
    Dismissed,
}

#[derive(Clone, Debug)]
pub enum AdjustedInput {
    WriteBytesToTerminal(Vec<u8>),
    ReRunCommandInThisPane(RunCommand),
    PermissionRequestResult(Vec<PermissionType>, PermissionStatus),
    CloseThisPane,
    DropToShellInThisPane { working_dir: Option<PathBuf> },
    WriteKeyToPlugin(KeyWithModifier),
    GuestModalSelectionChanged,
    GuestModalZoom,
    GuestModalDescend,
}
pub fn get_next_terminal_position(
    tiled_panes: &TiledPanes,
    floating_panes: &FloatingPanes,
) -> usize {
    let tiled_panes_count = tiled_panes
        .get_panes()
        .filter(|(k, _)| match k {
            PaneId::Plugin(_) => false,
            PaneId::Terminal(_) => true,
        })
        .count();
    let floating_panes_count = floating_panes
        .get_panes()
        .filter(|(k, _)| match k {
            PaneId::Plugin(_) => false,
            PaneId::Terminal(_) => true,
        })
        .count();
    tiled_panes_count + floating_panes_count + 1
}

impl Tab {
    // FIXME: Still too many arguments for clippy to be happy...
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: usize,
        position: usize,
        name: String,
        display_area: Size,
        character_cell_size: Rc<RefCell<Option<SizeInPixels>>>,
        stacked_resize: Rc<RefCell<bool>>,
        stacked_pane_list: Rc<RefCell<bool>>,
        sixel_image_store: Rc<RefCell<SixelImageStore>>,
        kitty_image_store: Rc<RefCell<KittyImageStore>>,
        os_api: Box<dyn ServerOsApi>,
        senders: ThreadSenders,
        max_panes: Option<usize>,
        style: Style,
        default_mode_info: ModeInfo,
        pane_frame_style: PaneFrameStyle,
        auto_layout: bool,
        connected_clients_in_app: Rc<RefCell<HashMap<ClientId, bool>>>, // bool -> is_web_client
        session_is_mirrored: bool,
        client_id: Option<ClientId>,
        copy_options: CopyOptions,
        terminal_emulator_colors: Rc<RefCell<Palette>>,
        terminal_emulator_color_codes: Rc<RefCell<HashMap<usize, String>>>,
        swap_layouts: (Vec<SwapTiledLayout>, Vec<SwapFloatingLayout>),
        default_shell: PathBuf,
        debug: bool,
        arrow_fonts: bool,
        styled_underlines: bool,
        osc8_hyperlinks: bool,
        explicitly_disable_kitty_keyboard_protocol: bool,
        default_editor: Option<PathBuf>,
        web_clients_allowed: bool,
        web_sharing: WebSharing,
        current_pane_group: Rc<RefCell<PaneGroups>>,
        currently_marking_pane_group: Rc<RefCell<HashMap<ClientId, bool>>>,
        advanced_mouse_actions: bool,
        mouse_scroll_resize: bool,
        mouse_hover_effects: bool,
        focus_follows_mouse: bool,
        mouse_click_through: bool,
        web_server_ip: IpAddr,
        web_server_port: u16,
        mobile_tab_count: usize,
    ) -> Self {
        let default_name = if name.is_empty() {
            format!("Tab #{}", (id + 1).saturating_sub(mobile_tab_count))
        } else {
            String::new()
        };
        let name = if name.is_empty() {
            default_name.clone()
        } else {
            name
        };

        let mut connected_clients = HashSet::new();
        if let Some(client_id) = client_id {
            connected_clients.insert(client_id);
        }
        let initial_size = display_area;
        let viewport: Viewport = display_area.into();
        let viewport = Rc::new(RefCell::new(viewport));
        let display_area = Rc::new(RefCell::new(display_area));
        let connected_clients = Rc::new(RefCell::new(connected_clients));
        let mode_info = Rc::new(RefCell::new(HashMap::new()));
        let reserved_top_rows: Rc<RefCell<HashMap<PaneId, usize>>> =
            Rc::new(RefCell::new(HashMap::new()));
        let fullscreen_covers_ui = Rc::new(RefCell::new(false));

        let tiled_panes = TiledPanes::new(
            display_area.clone(),
            viewport.clone(),
            connected_clients.clone(),
            connected_clients_in_app.clone(),
            mode_info.clone(),
            character_cell_size.clone(),
            stacked_resize.clone(),
            stacked_pane_list.clone(),
            reserved_top_rows.clone(),
            fullscreen_covers_ui.clone(),
            session_is_mirrored,
            pane_frame_style,
            default_mode_info.clone(),
            style,
            os_api.clone(),
            senders.clone(),
        );
        let floating_panes = FloatingPanes::new(
            display_area.clone(),
            viewport.clone(),
            connected_clients.clone(),
            connected_clients_in_app.clone(),
            mode_info.clone(),
            character_cell_size.clone(),
            fullscreen_covers_ui.clone(),
            pane_frame_style,
            session_is_mirrored,
            default_mode_info.clone(),
            style,
            os_api.clone(),
            senders.clone(),
        );

        let clipboard_provider = match copy_options.command {
            Some(command) => ClipboardProvider::Command(CopyCommand::new(command)),
            None => ClipboardProvider::Osc52(copy_options.clipboard),
        };
        let swap_layouts = SwapLayouts::new(swap_layouts, display_area.clone());

        Tab {
            id,
            position,
            tiled_panes,
            floating_panes,
            suppressed_panes: HashMap::new(),
            stacked_pane_list,
            reserved_top_rows,
            stack_lists: HashMap::new(),
            stack_list_of_member: HashMap::new(),
            stack_list_parked_pairs: HashMap::new(),
            next_stack_list_id: 0,
            stack_list_session_is_mirrored: session_is_mirrored,
            name: name.clone(),
            prev_name: name,
            default_name,
            size: initial_size,
            visible_to: None,
            max_panes,
            viewport,
            display_area,
            character_cell_size,
            sixel_image_store,
            kitty_image_store,
            synchronize_is_active: false,
            os_api,
            senders,
            should_clear_display_before_rendering: false,
            style,
            mode_info,
            default_mode_info,
            pane_frame_style,
            auto_layout,
            pending_vte_events: HashMap::new(),
            connected_clients,
            selecting_with_mouse_in_pane: None,
            pane_being_resized_with_mouse: None,
            link_handler: Rc::new(RefCell::new(LinkHandler::new())),
            clipboard_provider,
            focus_pane_id: None,
            copy_on_select: copy_options.copy_on_select,
            terminal_emulator_colors,
            terminal_emulator_color_codes,
            pids_waiting_resize: HashSet::new(),
            cursor_positions_and_shape: HashMap::new(),
            is_pending: true, // will be switched to false once the layout is applied
            pending_instructions: vec![],
            swap_layouts,
            default_shell,
            debug,
            arrow_fonts,
            kitty_host_support: None,
            styled_underlines,
            osc8_hyperlinks,
            explicitly_disable_kitty_keyboard_protocol,
            default_editor,
            web_clients_allowed,
            web_sharing,
            mouse_hover_pane_id: HashMap::new(),
            plugin_hover_pane_id: HashMap::new(),
            mouse_last_pane_id: HashMap::new(),
            mouse_help_text_visible: HashMap::new(),
            last_mouse_activity_time: HashMap::new(),
            last_hint_text: HashMap::new(),
            last_active_pane_scroll: HashMap::new(),
            current_pane_group,
            currently_marking_pane_group,
            advanced_mouse_actions,
            mouse_scroll_resize,
            mouse_hover_effects,
            focus_follows_mouse,
            mouse_click_through,
            frame_clicks: HashMap::new(),
            tiled_pane_being_dragged: HashMap::new(),
            drag_preview_swapped_with: HashMap::new(),
            responsive_collapsed: false,
            responsive_min_cols: 0,
            responsive_layout_name: String::from("stacked"),
            stack_list_max_rows: 0,
            expanded_stack_lists: HashSet::new(),
            stack_list_grid: false,
            stack_list_style: StackListStyle::default(),
            responsive_missing_layout_warned: false,
            connected_clients_in_app,
            web_server_ip,
            web_server_port,
            panes_with_pending_bell: HashSet::new(),
            tab_has_pending_bell: false,
            tab_bell_flash: false,
            tab_bell_ring: false,
            dimmed_clients: HashSet::new(),
        }
    }

    pub fn set_client_dimmed(&mut self, client_id: ClientId, dimmed: bool) {
        if dimmed {
            self.dimmed_clients.insert(client_id);
        } else {
            self.dimmed_clients.remove(&client_id);
        }
        self.tiled_panes.set_client_dimmed(client_id, dimmed);
        self.floating_panes.set_client_dimmed(client_id, dimmed);
    }

    pub fn stacked_pane_list_is_active(&self) -> bool {
        *self.stacked_pane_list.borrow()
    }
    pub fn pane_is_stack_list_member(&self, pane_id: &PaneId) -> bool {
        self.stack_list_of_member.contains_key(pane_id)
    }
    pub fn has_stack_lists(&self) -> bool {
        !self.stack_lists.is_empty()
    }
    fn stack_list_id_of_member(&self, pane_id: &PaneId) -> Option<StackListId> {
        self.stack_list_of_member.get(pane_id).copied()
    }
    pub fn pane_is_hidden_stack_list_member(&self, pane_id: &PaneId) -> bool {
        self.stack_list_id_of_member(pane_id)
            .and_then(|stack_list_id| self.stack_lists.get(&stack_list_id))
            .map(|list| list.visible != *pane_id)
            .unwrap_or(false)
    }
    pub fn focus_hidden_stack_list_member(&mut self, pane_id: PaneId, client_id: ClientId) -> bool {
        self.swap_in_hidden_stack_list_member(pane_id, Some(client_id))
    }
    fn swap_in_hidden_stack_list_member(
        &mut self,
        pane_id: PaneId,
        client_id: Option<ClientId>,
    ) -> bool {
        if !self.pane_is_hidden_stack_list_member(&pane_id) {
            return false;
        }
        match self.stack_list_id_of_member(&pane_id) {
            Some(stack_list_id) => {
                self.select_stack_list_member(stack_list_id, pane_id, client_id);
                true
            },
            None => false,
        }
    }
    fn stack_list_member_at_point(&self, pane_id: PaneId, point: &Position) -> PaneId {
        let Some(stack_list_id) = self.stack_list_id_of_member(&pane_id) else {
            return pane_id;
        };
        let Some(pane) = self.tiled_panes.get_pane(pane_id) else {
            return pane_id;
        };
        // the same geometry the renderer laid the list out against
        let geom = pane.position_and_size();
        if point.line() < geom.y as isize {
            return pane_id;
        }
        // A screen CELL, not the member's rank: the picker draws a window of the
        // members and may pack several per row, so neither the row nor the
        // column maps directly onto an index. Resolved through the same layout
        // the renderer used, which is the only way these cannot drift apart.
        let row = (point.line() - geom.y as isize) as usize;
        let Some((list, entry_x, layout)) = self.stack_list_layout_of(stack_list_id) else {
            return pane_id;
        };
        let column = (point.column()).saturating_sub(entry_x);
        layout
            .cells
            .iter()
            .find(|cell| {
                cell.row == row && column >= cell.x_offset && column < cell.x_offset + cell.width
            })
            .and_then(|cell| list.members.get(cell.member_index).copied())
            .unwrap_or(pane_id)
    }
    pub fn suppressed_stack_list_members(&self) -> impl Iterator<Item = (&PaneId, &Box<dyn Pane>)> {
        self.suppressed_panes
            .iter()
            .filter(|(pane_id, _)| self.stack_list_of_member.contains_key(pane_id))
            .map(|(pane_id, (_, pane))| (pane_id, pane))
    }
    pub fn stack_list_serialization_geoms(&self) -> HashMap<PaneId, PaneGeom> {
        let mut synthetic_geoms = HashMap::new();
        if self.stack_lists.is_empty() {
            return synthetic_geoms;
        }
        let mut next_synthetic_stack_id = self
            .tiled_panes
            .get_panes()
            .filter_map(|(_, pane)| pane.position_and_size().stacked)
            .max()
            .map(|highest_stack_id| highest_stack_id + 1)
            .unwrap_or(0);
        for list in self.stack_lists.values() {
            let Some(visible_pane) = self.tiled_panes.get_pane(list.visible) else {
                continue;
            };
            let full_rect = visible_pane.position_and_size();
            let collapsed_member_count = list.members.len().saturating_sub(1);
            let mut running_y = full_rect.y;
            for member in &list.members {
                let mut member_geom = full_rect;
                member_geom.stacked = Some(next_synthetic_stack_id);
                member_geom.y = running_y;
                if *member == list.visible {
                    member_geom.rows.set_inner(
                        full_rect
                            .rows
                            .as_usize()
                            .saturating_sub(collapsed_member_count),
                    );
                } else {
                    member_geom.rows = Dimension::fixed(1);
                    member_geom.logical_position = self
                        .suppressed_panes
                        .get(member)
                        .and_then(|(_, pane)| pane.position_and_size().logical_position);
                }
                running_y += member_geom.rows.as_usize();
                synthetic_geoms.insert(*member, member_geom);
            }
            next_synthetic_stack_id += 1;
        }
        synthetic_geoms
    }
    pub fn hidden_stack_list_members_for_serialization(
        &self,
    ) -> Vec<(PaneId, &Box<dyn Pane>, PaneGeom)> {
        let synthetic_geoms = self.stack_list_serialization_geoms();
        let mut hidden_members = vec![];
        for list in self.stack_lists.values() {
            for member in &list.members {
                if *member == list.visible {
                    continue;
                }
                let Some(member_geom) = synthetic_geoms.get(member) else {
                    continue;
                };
                let resolved_pane = self
                    .stack_list_parked_pairs
                    .get(member)
                    .and_then(|parked_pid| self.suppressed_panes.get(parked_pid))
                    .filter(|(is_scrollback_editor, _)| *is_scrollback_editor)
                    .or_else(|| self.suppressed_panes.get(member));
                if let Some((_, pane)) = resolved_pane {
                    hidden_members.push((pane.pid(), pane, *member_geom));
                }
            }
        }
        hidden_members
    }
    fn pane_parked_by(&self, id: &PaneId) -> Option<PaneId> {
        self.suppressed_panes
            .get(id)
            .map(|(_, parked)| parked.pid())
            .filter(|parked_pid| parked_pid != id)
    }
    fn adopt_parked_pair(&mut self, member: PaneId) {
        if let Some(parked_pid) = self.stack_list_parked_pairs.remove(&member) {
            if let Some(parked_entry) = self.suppressed_panes.remove(&parked_pid) {
                self.suppressed_panes.insert(member, parked_entry);
            }
        }
    }
    /// Where the picker's visible window starts, and how many entries it shows.
    ///
    /// `stack_list_max_rows` caps the height; the window slides to keep the
    /// currently visible member on screen, so ordinary focus movement scrolls
    /// the list instead of needing its own binding.
    ///
    /// Both the reserved-row arithmetic and the renderer go through this. If
    /// they ever disagree the list draws into rows the geometry did not reserve,
    /// i.e. over the pane below it.
    /// Build the picker's cell layout for a stack.
    ///
    /// `available_cols` is the width the list may use, `widest_label` the widest
    /// entry label including its index prefix. In rows mode every cell spans the
    /// full width, exactly as before the grid existed.
    fn stack_list_layout(
        &self,
        stack_list_id: StackListId,
        member_count: usize,
        visible_rank: usize,
        available_cols: usize,
        widest_label: usize,
    ) -> StackListLayout {
        let expanded = self.expanded_stack_lists.contains(&stack_list_id);
        // from the style, so the column arithmetic and the renderer cannot
        // disagree about how wide an entry's decoration is
        let natural_cell = (widest_label + self.stack_list_style.decoration_cols())
            .max(STACK_LIST_MIN_ENTRY_COLS);
        let columns = if self.stack_list_grid {
            // standard packing: n cells and n-1 gaps must fit
            ((available_cols + STACK_LIST_CELL_GAP_COLS)
                / (natural_cell + STACK_LIST_CELL_GAP_COLS).max(1))
            .max(1)
        } else {
            1
        };
        // one column keeps the historical full-width entry, which centres its own
        // label; only a real grid needs fixed-width cells and a centred block
        let (cell_width, cell_stride, left_margin) = if columns <= 1 {
            (available_cols, available_cols, 0)
        } else {
            let stride = natural_cell + STACK_LIST_CELL_GAP_COLS;
            // the block spans n cells and n-1 gaps; centre that, not n strides
            let block = columns * natural_cell + (columns - 1) * STACK_LIST_CELL_GAP_COLS;
            (
                natural_cell,
                stride,
                available_cols.saturating_sub(block) / 2,
            )
        };
        let max_rows = if expanded { 0 } else { self.stack_list_max_rows };
        let (start, shown, rows) =
            stack_list_window_core(member_count, visible_rank, columns, max_rows);
        let cells = (0..shown)
            .map(|i| StackListCell {
                member_index: start + i,
                x_offset: left_margin + (i % columns) * cell_stride,
                row: i / columns,
                width: cell_width,
            })
            .collect();
        StackListLayout {
            cells,
            rows,
            hidden: member_count - shown,
        }
    }

    /// Text for the picker's indicator row, if it has one.
    ///
    /// Rendered in the padding row the list already reserves, so it never costs
    /// a row or displaces a member. Also the click target that toggles the
    /// expansion, which is why collapse gets a label too: an invisible way back
    /// out is not an affordance.
    fn stack_list_indicator(&self, stack_list_id: StackListId, hidden: usize) -> Option<String> {
        if hidden > 0 {
            Some(format!("+{} more", hidden))
        } else if self.expanded_stack_lists.contains(&stack_list_id) {
            Some(String::from("- fewer"))
        } else {
            None
        }
    }
    /// Toggle a stack's expansion if `point` is on its indicator row.
    ///
    /// Returns true if the click was consumed. Expanding changes the reserved
    /// row count, hence the refresh: that is a one-off pane resize, which is
    /// why this hangs off a deliberate click and not off hover.
    fn toggle_stack_list_expansion_at_point(&mut self, pane_id: PaneId, point: &Position) -> bool {
        let Some(stack_list_id) = self.stack_list_id_of_member(&pane_id) else {
            return false;
        };
        let Some(visible) = self.stack_lists.get(&stack_list_id).map(|list| list.visible) else {
            return false;
        };
        let Some(pane) = self.tiled_panes.get_pane(visible) else {
            return false;
        };
        let geom = pane.position_and_size();
        if point.line() < geom.y as isize {
            return false;
        }
        let row = (point.line() - geom.y as isize) as usize;
        let Some((_list, _entry_x, layout)) = self.stack_list_layout_of(stack_list_id) else {
            return false;
        };
        if row != layout.rows
            || self
                .stack_list_indicator(stack_list_id, layout.hidden)
                .is_none()
        {
            return false;
        }
        if !self.expanded_stack_lists.remove(&stack_list_id) {
            self.expanded_stack_lists.insert(stack_list_id);
        }
        self.refresh_or_dissolve_stack_list(stack_list_id);
        self.set_force_render();
        self.set_should_clear_display_before_rendering();
        true
    }
    /// Geometry and label metrics the picker needs, read from the stack's visible
    /// pane. Shared so the renderer, the row budget and the hit-test all derive
    /// the column count from identical inputs.
    ///
    /// Returns (list left edge, width available to the list, widest label).
    fn stack_list_metrics(&self, list: &StackList) -> Option<(usize, usize, usize)> {
        let pane = self.tiled_panes.get_pane(list.visible)?;
        let rect = pane.position_and_size();
        let content_offset = pane.get_content_offset();
        let entry_x = rect.x + content_offset.left;
        let available_cols = rect
            .cols
            .as_usize()
            .saturating_sub(content_offset.left + content_offset.right);
        // measured over ALL members, not just the shown ones, so the cell width
        // does not jitter as the window scrolls
        let widest_label = list
            .members
            .iter()
            .enumerate()
            .filter_map(|(rank, member)| {
                let pane = if *member == list.visible {
                    self.tiled_panes.get_pane(*member).map(|p| &**p)
                } else {
                    self.suppressed_panes.get(member).map(|(_, p)| &**p)
                };
                pane.map(|pane| {
                    stack_index_prefix(rank + 1).width() + pane.stack_list_entry_label().width()
                })
            })
            .max()
            .unwrap_or(0);
        Some((entry_x, available_cols, widest_label))
    }
    /// The picker layout for a stack, or None if its pane has gone.
    fn stack_list_layout_of(&self, stack_list_id: StackListId) -> Option<(StackList, usize, StackListLayout)> {
        let list = self.stack_lists.get(&stack_list_id)?.clone();
        let (entry_x, available_cols, widest_label) = self.stack_list_metrics(&list)?;
        let visible_rank = list.rank_of(&list.visible).unwrap_or(0);
        let layout = self.stack_list_layout(
            stack_list_id,
            list.members.len(),
            visible_rank,
            available_cols,
            widest_label,
        );
        Some((list, entry_x, layout))
    }
    fn refresh_or_dissolve_stack_list(&mut self, stack_list_id: StackListId) {
        let (member_count, visible) = match self.stack_lists.get(&stack_list_id) {
            Some(list) => (list.members.len(), list.visible),
            None => return,
        };
        if member_count <= 1 {
            self.dissolve_stack_list(stack_list_id);
        } else {
            let rows = self
                .stack_list_layout_of(stack_list_id)
                .map(|(_list, _x, layout)| layout.rows)
                .unwrap_or(member_count);
            let previous = self
                .reserved_top_rows
                .borrow_mut()
                .insert(visible, rows + 1);
            self.tiled_panes.reapply_pane_frames();
            self.resize_stack_list_hidden_members(stack_list_id);
            if previous != Some(rows + 1) {
                // the list changed height, so the visible pane moved: rows the
                // list used to own are now nobody's and keep their old contents
                // until something repaints them
                self.set_force_render();
                self.set_should_clear_display_before_rendering();
            }
        }
    }
    fn select_stack_list_member(
        &mut self,
        stack_list_id: StackListId,
        target_member: PaneId,
        client_id: Option<ClientId>,
    ) {
        let current_visible = match self.stack_lists.get(&stack_list_id) {
            Some(list) => list.visible,
            None => return,
        };
        if current_visible == target_member {
            return;
        }
        let pane_parked_by_current_visible = self.pane_parked_by(&current_visible);
        let target_box = match self.suppressed_panes.remove(&target_member) {
            Some((_is_scrollback_editor, pane)) => pane,
            None => {
                log::error!(
                    "stack-list member {:?} not found in suppressed panes",
                    target_member
                );
                return;
            },
        };
        let removed_visible = self.tiled_panes.replace_pane(current_visible, target_box);
        if let Some(removed_visible) = removed_visible {
            self.insert_suppressed_pane(current_visible, (false, removed_visible));
            if let Some(parked_pid) = pane_parked_by_current_visible {
                self.stack_list_parked_pairs
                    .insert(current_visible, parked_pid);
            }
        }
        self.adopt_parked_pair(target_member);
        if let Some(list) = self.stack_lists.get_mut(&stack_list_id) {
            list.visible = target_member;
        }
        self.reserved_top_rows.borrow_mut().remove(&current_visible);
        if let Some(client_id) = client_id {
            self.tiled_panes.focus_pane(target_member, client_id);
        }
        self.refresh_or_dissolve_stack_list(stack_list_id);
        self.set_force_render();
        self.set_should_clear_display_before_rendering();
    }
    fn move_focus_within_stack_list(&mut self, client_id: ClientId, down: bool) -> bool {
        let active_pane_id = match self.tiled_panes.get_active_pane_id(client_id) {
            Some(id) => id,
            None => return false,
        };
        let stack_list_id = match self.stack_list_id_of_member(&active_pane_id) {
            Some(id) => id,
            None => return false,
        };
        let target_member = {
            let list = match self.stack_lists.get(&stack_list_id) {
                Some(l) => l,
                None => return false,
            };
            if list.visible != active_pane_id {
                return false;
            }
            let rank = match list.rank_of(&active_pane_id) {
                Some(r) => r,
                None => return false,
            };
            let target_rank = if down {
                rank + 1
            } else if rank == 0 {
                return false;
            } else {
                rank - 1
            };
            match list.members.get(target_rank) {
                Some(member) => *member,
                None => return false,
            }
        };
        self.select_stack_list_member(stack_list_id, target_member, Some(client_id));
        true
    }
    fn close_stack_list_member(&mut self, id: PaneId, exit_status: Option<i32>) -> bool {
        match self.remove_stack_list_member(id) {
            StackListRemoval::Removed(removed) => {
                if let (Some(exit_status), Some(mut removed)) = (exit_status, removed) {
                    removed.update_exit_status(exit_status);
                }
                true
            },
            StackListRemoval::DissolvedInPlace | StackListRemoval::NotRemoved => false,
        }
    }
    fn remove_stack_list_member(&mut self, id: PaneId) -> StackListRemoval {
        let stack_list_id = match self.stack_list_id_of_member(&id) {
            Some(sid) => sid,
            None => return StackListRemoval::NotRemoved,
        };
        let is_visible = self
            .stack_lists
            .get(&stack_list_id)
            .map(|l| l.visible == id)
            .unwrap_or(false);
        let removed = if is_visible {
            let (members, rank) = {
                let list = match self.stack_lists.get(&stack_list_id) {
                    Some(l) => l,
                    None => return StackListRemoval::NotRemoved,
                };
                (list.members.clone(), list.rank_of(&id).unwrap_or(0))
            };
            let promote_target = members
                .iter()
                .skip(rank + 1)
                .next()
                .copied()
                .or_else(|| members[..rank].iter().last().copied());
            let promote_target = match promote_target {
                Some(target) => target,
                None => {
                    self.dissolve_stack_list(stack_list_id);
                    self.reserved_top_rows.borrow_mut().remove(&id);
                    return StackListRemoval::DissolvedInPlace;
                },
            };
            let target_box = match self.suppressed_panes.remove(&promote_target) {
                Some((_is_scrollback_editor, pane)) => pane,
                None => {
                    log::error!("stack-list promote target not found in suppressed panes");
                    return StackListRemoval::NotRemoved;
                },
            };
            let removed_visible = self.tiled_panes.replace_pane(id, target_box);
            self.adopt_parked_pair(promote_target);
            self.stack_list_of_member.remove(&id);
            self.reserved_top_rows.borrow_mut().remove(&id);
            if let Some(list) = self.stack_lists.get_mut(&stack_list_id) {
                list.members.retain(|m| *m != id);
                list.visible = promote_target;
            }
            self.refresh_or_dissolve_stack_list(stack_list_id);
            removed_visible
        } else {
            let removed = self.suppressed_panes.remove(&id).map(|(_, p)| p);
            let substitute_member = self
                .stack_list_parked_pairs
                .remove(&id)
                .filter(|parked_pid| self.suppressed_panes.contains_key(parked_pid));
            self.stack_list_of_member.remove(&id);
            self.reserved_top_rows.borrow_mut().remove(&id);
            if let Some(substitute_member) = substitute_member {
                self.stack_list_of_member
                    .insert(substitute_member, stack_list_id);
                if let Some(list) = self.stack_lists.get_mut(&stack_list_id) {
                    for member in list.members.iter_mut() {
                        if *member == id {
                            *member = substitute_member;
                        }
                    }
                }
            } else if let Some(list) = self.stack_lists.get_mut(&stack_list_id) {
                list.members.retain(|m| *m != id);
            }
            self.refresh_or_dissolve_stack_list(stack_list_id);
            removed
        };
        self.set_force_render();
        self.set_should_clear_display_before_rendering();
        StackListRemoval::Removed(removed)
    }
    fn track_stack_list_member_id_swap(&mut self, old_id: PaneId, new_id: PaneId) {
        let stack_list_id = match self.stack_list_id_of_member(&old_id) {
            Some(sid) => sid,
            None => return,
        };
        self.stack_list_of_member.remove(&old_id);
        self.stack_list_of_member.insert(new_id, stack_list_id);
        let mut swapped_visible_member = false;
        if let Some(list) = self.stack_lists.get_mut(&stack_list_id) {
            for member in list.members.iter_mut() {
                if *member == old_id {
                    *member = new_id;
                }
            }
            if list.visible == old_id {
                list.visible = new_id;
                swapped_visible_member = true;
            }
        }
        {
            let mut reserved = self.reserved_top_rows.borrow_mut();
            if let Some(reserved_rows) = reserved.remove(&old_id) {
                reserved.insert(new_id, reserved_rows);
            }
        }
        if swapped_visible_member {
            self.refresh_or_dissolve_stack_list(stack_list_id);
            self.set_force_render();
            self.set_should_clear_display_before_rendering();
        }
    }
    fn dissolve_stack_list(&mut self, stack_list_id: StackListId) {
        if let Some(list) = self.stack_lists.get(&stack_list_id) {
            let members = list.members.clone();
            self.drop_stack_list_ledger(stack_list_id, &members);
            self.tiled_panes.reapply_pane_frames();
        }
    }
    fn drop_stack_list_ledger(&mut self, stack_list_id: StackListId, members: &[PaneId]) {
        self.stack_lists.remove(&stack_list_id);
        self.expanded_stack_lists.remove(&stack_list_id);
        let mut reserved = self.reserved_top_rows.borrow_mut();
        for member in members {
            self.stack_list_of_member.remove(member);
            self.stack_list_parked_pairs.remove(member);
            reserved.remove(member);
        }
    }
    fn degroupify(&mut self, stack_list_id: StackListId) {
        let (members, visible) = match self.stack_lists.get(&stack_list_id) {
            Some(list) => (list.members.clone(), list.visible),
            None => return,
        };
        let n = members.len();
        if n == 0 || !self.tiled_panes.panes_contain(&visible) {
            self.drop_stack_list_ledger(stack_list_id, &members);
            return;
        }
        let geoms = self.tiled_panes.stack_panes(visible, n);
        if geoms.len() != n {
            log::error!("degroupify: could not compute classic stack geoms");
            return;
        }
        for (i, member) in members.iter().enumerate() {
            let mut geom = geoms[i];
            if *member == visible {
                geom.logical_position = self
                    .tiled_panes
                    .get_pane(*member)
                    .and_then(|p| p.position_and_size().logical_position);
                self.tiled_panes.set_geom_for_pane_with_id(member, geom);
            } else if let Some((_is_scrollback_editor, mut pane)) =
                self.suppressed_panes.remove(member)
            {
                geom.logical_position = pane.position_and_size().logical_position;
                pane.set_geom(geom);
                self.tiled_panes.add_pane_with_existing_geom(*member, pane);
                self.adopt_parked_pair(*member);
            }
        }
        self.drop_stack_list_ledger(stack_list_id, &members);
        self.tiled_panes.expand_pane_in_stack(visible);
        self.tiled_panes.reapply_pane_frames();
        self.set_force_render();
        self.set_should_clear_display_before_rendering();
    }
    // the classic layout solver cannot see suppressed stack-list members; dissolve
    // lists into in-grid stacks first, groupify_all re-forms them on mode entry
    fn degroupify_all(&mut self) {
        let ids: Vec<StackListId> = self.stack_lists.keys().copied().collect();
        for id in ids {
            self.degroupify(id);
        }
    }
    fn dissolve_stack_lists_for_classic_mutation(&mut self) {
        if self.stacked_pane_list_is_active() {
            self.degroupify_all();
        }
    }
    pub fn sync_stacked_pane_list_mode(&mut self) {
        if self.stacked_pane_list_is_active() {
            self.groupify_all();
        } else if self.has_stack_lists() {
            self.degroupify_all();
        }
    }
    // the inverse of degroupify_all: adopts classic in-grid stacks into stack
    // lists, suppressing all but the visible member of each
    fn groupify_all(&mut self) {
        if self.tiled_panes.fullscreen_is_active() {
            return;
        }
        let mut stacks: HashMap<usize, Vec<(usize, PaneId, bool)>> = HashMap::new();
        for (id, pane) in self.tiled_panes.get_panes() {
            let geom = pane.position_and_size();
            if let Some(stack_id) = geom.stacked {
                let is_expanded = !geom.rows.is_fixed();
                stacks
                    .entry(stack_id)
                    .or_default()
                    .push((geom.y, *id, is_expanded));
            }
        }
        let mut converted_any = false;
        for (_stack_id, mut members) in stacks {
            if members.len() < 2 {
                continue;
            }
            members.sort_by_key(|(y, _, _)| *y);
            let representative = members[0].1;
            let rect = match self.tiled_panes.position_and_size_of_stack(&representative) {
                Some(r) => r,
                None => continue,
            };
            let visible = members
                .iter()
                .find(|(_, _, expanded)| *expanded)
                .map(|(_, id, _)| *id)
                .unwrap_or_else(|| members.last().map(|(_, id, _)| *id).unwrap());
            let ordered_ids: Vec<PaneId> = members.iter().map(|(_, id, _)| *id).collect();
            let logical_position = self
                .tiled_panes
                .get_pane(visible)
                .and_then(|p| p.position_and_size().logical_position);
            for (_, id, _) in &members {
                if *id == visible {
                    continue;
                }
                if let Some(pane) = self.tiled_panes.extract_pane(*id) {
                    let pane_parked_by_member = self.pane_parked_by(id);
                    self.insert_suppressed_pane(*id, (false, pane));
                    if let Some(parked_pid) = pane_parked_by_member {
                        self.stack_list_parked_pairs.insert(*id, parked_pid);
                    }
                }
            }
            if let Some(vpane) = self.tiled_panes.get_pane_mut(visible) {
                let mut g = rect;
                g.stacked = None;
                g.logical_position = logical_position;
                vpane.set_geom(g);
            }
            let stack_list_id = self.next_stack_list_id;
            self.next_stack_list_id += 1;
            for id in &ordered_ids {
                self.stack_list_of_member.insert(*id, stack_list_id);
            }
            self.stack_lists.insert(
                stack_list_id,
                StackList {
                    members: ordered_ids,
                    visible,
                },
            );
            self.refresh_or_dissolve_stack_list(stack_list_id);
            converted_any = true;
        }
        if converted_any {
            self.set_force_render();
            self.set_should_clear_display_before_rendering();
        }
    }
    fn resize_all_stack_list_hidden_members(&mut self) {
        let ids: Vec<StackListId> = self.stack_lists.keys().copied().collect();
        for id in ids {
            self.resize_stack_list_hidden_members(id);
        }
    }
    fn resize_stack_list_hidden_members(&mut self, stack_list_id: StackListId) {
        let (visible_geom, visible_offset, hidden_members) = {
            let list = match self.stack_lists.get(&stack_list_id) {
                Some(l) => l,
                None => return,
            };
            let (geom, offset) = match self.tiled_panes.get_pane(list.visible) {
                Some(p) => (p.position_and_size(), p.get_content_offset()),
                None => return,
            };
            let hidden: Vec<PaneId> = list
                .members
                .iter()
                .copied()
                .filter(|m| *m != list.visible)
                .collect();
            (geom, offset, hidden)
        };
        for member in hidden_members {
            if let Some((_is_scrollback_editor, pane)) = self.suppressed_panes.get_mut(&member) {
                pane.set_geom(visible_geom);
                pane.set_content_offset(visible_offset);
                let _ = resize_pty!(pane, self.os_api, self.senders, self.character_cell_size);
            }
        }
    }
    fn render_stack_list_headers(
        &mut self,
        output: &mut Output,
        client_id_override: Option<ClientId>,
    ) -> Result<()> {
        if self.stack_lists.is_empty() || self.tiled_panes.fullscreen_is_active() {
            return Ok(());
        }
        let mut connected_clients: HashSet<ClientId> =
            { self.connected_clients.borrow().iter().copied().collect() };
        if let Some(override_id) = client_id_override {
            connected_clients.insert(override_id);
        }
        if connected_clients.is_empty() {
            return Ok(());
        }
        let multiple_users_exist_in_session = { self.connected_clients_in_app.borrow().len() > 1 };
        let should_draw_pane_frames = self.pane_frame_style.draws_full_frames();
        let session_is_mirrored = self.stack_list_session_is_mirrored;
        let current_pane_group: HashMap<ClientId, Vec<PaneId>> =
            { self.current_pane_group.borrow().clone_inner() };
        let active_panes: HashMap<ClientId, PaneId> = connected_clients
            .iter()
            .filter_map(|c| self.tiled_panes.get_active_pane_id(*c).map(|p| (*c, p)))
            .collect();
        let client_modes: Vec<(ClientId, InputMode)> = {
            let mode_info = self.mode_info.borrow();
            connected_clients
                .iter()
                .map(|c| {
                    let mode = mode_info.get(c).unwrap_or(&self.default_mode_info).mode;
                    (*c, mode)
                })
                .collect()
        };
        let lists: Vec<(StackListId, StackList)> = self
            .stack_lists
            .iter()
            .map(|(id, list)| (*id, list.clone()))
            .collect();
        for (stack_list_id, list) in lists {
            let (rect, visible_content_offset) = match self.tiled_panes.get_pane(list.visible) {
                Some(p) => (p.position_and_size(), p.get_content_offset()),
                None => continue,
            };
            let entry_x = rect.x + visible_content_offset.left;
            let entry_cols = rect
                .cols
                .as_usize()
                .saturating_sub(visible_content_offset.left + visible_content_offset.right);
            // NB: measured INCLUDING the index prefix each entry will be
            // rendered with, otherwise every entry is one prefix too narrow and
            // the list misaligns.
            let widest_member_title = list
                .members
                .iter()
                .enumerate()
                .filter_map(|(rank, member)| {
                    let pane = if *member == list.visible {
                        self.tiled_panes.get_pane(*member).map(|p| &**p)
                    } else {
                        self.suppressed_panes.get(member).map(|(_, p)| &**p)
                    };
                    pane.map(|pane| {
                        stack_index_prefix(rank + 1).width() + pane.stack_list_entry_label().width()
                    })
                })
                .max()
                .unwrap_or(0);
            let stack_is_focused = active_panes.values().any(|p_id| *p_id == list.visible);
            let visible_rank = list.rank_of(&list.visible).unwrap_or(0);
            let layout = self.stack_list_layout(
                stack_list_id,
                list.members.len(),
                visible_rank,
                entry_cols,
                widest_member_title,
            );
            let indicator = self.stack_list_indicator(stack_list_id, layout.hidden);
            // Blank the parts of the list region no cell covers.
            //
            // Entries are drawn as individual cells, so the gaps between them
            // keep whatever was drawn there before -- and the layout genuinely
            // changes shape when a pane is added, because an unnamed pane's
            // "Pane #N" label is far wider than a named one and re-flows the
            // whole grid.
            //
            // Only the gaps, never the cells: chunks are not composited
            // last-wins, so blanking a region a cell also draws to can erase the
            // cell instead of the stale pixels underneath it.
            for row in 0..layout.rows {
                for (start, end) in stack_list_row_gaps(&layout, row, entry_cols) {
                    let blanks = vec![EMPTY_TERMINAL_CHARACTER; end - start];
                    output.add_character_chunks_to_multiple_clients(
                        vec![CharacterChunk::new(blanks, entry_x + start, rect.y + row)],
                        connected_clients.iter().copied(),
                        None,
                    )?;
                }
            }
            let cells = layout.cells.clone();
            for cell in cells {
                let rank = cell.member_index;
                let Some(member) = list.members.get(rank).copied() else {
                    continue;
                };
                let member = &member;
                let mut header_geom = rect;
                header_geom.x = entry_x + cell.x_offset;
                header_geom.cols.set_inner(cell.width);
                // cell.row is the position on screen, `rank` stays the member's
                // real position in the stack, so the numbering keeps meaning
                // something once the window has scrolled away from the top
                header_geom.y = rect.y + cell.row;
                header_geom.rows = Dimension::fixed(1);
                header_geom.stacked = None;
                let pane_box = if *member == list.visible {
                    self.tiled_panes.get_pane_mut(*member)
                } else {
                    self.suppressed_panes.get_mut(member).map(|(_, p)| p)
                };
                let pane_box = match pane_box {
                    Some(p) => p,
                    None => continue,
                };
                let mut pane_contents_and_ui = PaneContentsAndUi::new(
                    pane_box,
                    output,
                    self.style,
                    &active_panes,
                    multiple_users_exist_in_session,
                    None,
                    false,
                    false,
                    should_draw_pane_frames,
                    &self.mouse_hover_pane_id,
                    current_pane_group.clone(),
                    false,
                    false,
                    self.mouse_scroll_resize,
                    self.dimmed_clients.clone(),
                );
                pane_contents_and_ui.set_frame_geom_override(Some(header_geom));
                pane_contents_and_ui.set_stack_list_entry(
                    Some(widest_member_title),
                    *member == list.visible,
                    stack_is_focused,
                    Some(rank + 1),
                    self.stack_list_style,
                );
                for (client_id, client_mode) in &client_modes {
                    pane_contents_and_ui.render_pane_frame(
                        *client_id,
                        *client_mode,
                        session_is_mirrored,
                        false,
                        true,
                    )?;
                }
            }
            // The row after the entries is already part of the reserved budget,
            // so the "+N hidden" indicator costs nothing extra and never steals a
            // row from a real entry.
            let mut padding_row = Vec::with_capacity(entry_cols);
            if let Some(indicator) = indicator {
                let indicator_start = entry_cols.saturating_sub(indicator.width()) / 2;
                for _ in 0..indicator_start {
                    padding_row.push(EMPTY_TERMINAL_CHARACTER);
                }
                for character in indicator.chars() {
                    padding_row.push(TerminalCharacter::new_styled(
                        character,
                        EMPTY_TERMINAL_CHARACTER.styles,
                    ));
                }
            }
            for _ in padding_row.len()..entry_cols {
                padding_row.push(EMPTY_TERMINAL_CHARACTER);
            }
            let padding_chunk = CharacterChunk::new(padding_row, entry_x, rect.y + layout.rows);
            output.add_character_chunks_to_multiple_clients(
                vec![padding_chunk],
                connected_clients.iter().copied(),
                None,
            )?;
        }
        Ok(())
    }

    pub fn apply_layout(
        &mut self,
        layout: TiledPaneLayout,
        floating_panes_layout: Vec<FloatingPaneLayout>,
        new_terminal_ids: Vec<(u32, HoldForCommand)>,
        new_floating_terminal_ids: Vec<(u32, HoldForCommand)>,
        new_plugin_ids: HashMap<RunPluginOrAlias, Vec<u32>>,
        client_id: ClientId,
        blocking_terminal: Option<(u32, NotificationEnd)>,
    ) -> Result<()> {
        self.swap_layouts
            .set_base_layout((layout.clone(), floating_panes_layout.clone()));
        match LayoutApplier::new(
            &self.viewport,
            &self.senders,
            &self.sixel_image_store,
            &self.kitty_image_store,
            &self.link_handler,
            &self.terminal_emulator_colors,
            &self.terminal_emulator_color_codes,
            &self.character_cell_size,
            &self.connected_clients_in_app,
            &self.style,
            &self.display_area,
            &mut self.tiled_panes,
            &mut self.floating_panes,
            self.pane_frame_style,
            &mut self.focus_pane_id,
            &self.os_api,
            self.debug,
            self.arrow_fonts,
            self.styled_underlines,
            self.osc8_hyperlinks,
            self.explicitly_disable_kitty_keyboard_protocol,
            blocking_terminal,
        )
        .apply_layout(
            layout,
            floating_panes_layout,
            new_terminal_ids,
            new_floating_terminal_ids,
            new_plugin_ids,
            client_id,
        ) {
            Ok(should_show_floating_panes) => {
                if should_show_floating_panes && !self.floating_panes.panes_are_visible() {
                    self.toggle_floating_panes(Some(client_id), None, None)
                        .non_fatal();
                } else if !should_show_floating_panes && self.floating_panes.panes_are_visible() {
                    self.toggle_floating_panes(Some(client_id), None, None)
                        .non_fatal();
                }
                self.tiled_panes.reapply_pane_frames();
                self.is_pending = false;
                self.apply_buffered_instructions().non_fatal();
            },
            Err(e) => {
                // TODO: this should only happen due to an erroneous layout created by user
                // configuration that was somehow not caught in our KDL layout parser
                // we should still be able to properly recover from this with a useful error
                // message though
                log::error!("Failed to apply layout: {}", e);
                self.tiled_panes.reapply_pane_frames();
                self.is_pending = false;
                self.apply_buffered_instructions().non_fatal();
            },
        }
        if let Some(supported) = self.kitty_host_support {
            self.tiled_panes.update_pane_kitty_host_support(supported);
            self.floating_panes
                .update_pane_kitty_host_support(supported);
        }
        Ok(())
    }
    pub fn override_layout(
        &mut self,
        layout: TiledPaneLayout,
        floating_panes_layout: Vec<FloatingPaneLayout>,
        mut new_swap_tiled_layouts: Option<Vec<SwapTiledLayout>>,
        mut new_swap_floating_layouts: Option<Vec<SwapFloatingLayout>>,
        new_terminal_ids: Vec<(u32, HoldForCommand)>,
        new_floating_terminal_ids: Vec<(u32, HoldForCommand)>,
        new_plugin_ids: HashMap<RunPluginOrAlias, Vec<u32>>,
        retain_existing_terminal_panes: bool,
        retain_existing_plugin_panes: bool,
        client_id: ClientId,
        blocking_terminal: Option<(u32, NotificationEnd)>,
    ) -> Result<()> {
        let new_swap_tiled_layouts = new_swap_tiled_layouts.take().unwrap_or_else(|| vec![]);
        let new_swap_floating_layouts = new_swap_floating_layouts.take().unwrap_or_else(|| vec![]);
        self.swap_layouts
            .set_swap_tiled_layouts(new_swap_tiled_layouts);
        self.swap_layouts
            .set_swap_floating_layouts(new_swap_floating_layouts);
        self.swap_layouts
            .set_base_layout((layout.clone(), floating_panes_layout.clone()));
        match LayoutApplier::new(
            &self.viewport,
            &self.senders,
            &self.sixel_image_store,
            &self.kitty_image_store,
            &self.link_handler,
            &self.terminal_emulator_colors,
            &self.terminal_emulator_color_codes,
            &self.character_cell_size,
            &self.connected_clients_in_app,
            &self.style,
            &self.display_area,
            &mut self.tiled_panes,
            &mut self.floating_panes,
            self.pane_frame_style,
            &mut self.focus_pane_id,
            &self.os_api,
            self.debug,
            self.arrow_fonts,
            self.styled_underlines,
            self.osc8_hyperlinks,
            self.explicitly_disable_kitty_keyboard_protocol,
            blocking_terminal,
        )
        .override_layout(
            layout,
            floating_panes_layout,
            new_terminal_ids,
            new_floating_terminal_ids,
            new_plugin_ids,
            retain_existing_terminal_panes,
            retain_existing_plugin_panes,
            client_id,
        ) {
            Ok(should_show_floating_panes) => {
                if should_show_floating_panes && !self.floating_panes.panes_are_visible() {
                    self.toggle_floating_panes(Some(client_id), None, None)
                        .non_fatal();
                } else if !should_show_floating_panes && self.floating_panes.panes_are_visible() {
                    self.toggle_floating_panes(Some(client_id), None, None)
                        .non_fatal();
                }

                // this is essentially another pass of the layout applier
                // we do this because the layout applier does not know about swap layouts, and in
                // this case we might have had to re-add existing panes that were not in the
                // overridden layout (eg. if we had more panes than were in the layout). In such a
                // case, we would like to make sure these extra panes fit the current swap layout
                self.swap_layouts.set_is_tiled_damaged();
                self.swap_layouts.set_is_floating_damaged();
                let _ = self.relayout_tiled_panes(false);
                let _ = self.relayout_floating_panes(false);

                self.tiled_panes.reapply_pane_frames();
                self.is_pending = false;

                LayoutApplier::offset_viewport(
                    self.viewport.clone(),
                    self.display_area.clone(),
                    &mut self.tiled_panes,
                    self.pane_frame_style,
                );

                self.apply_buffered_instructions().non_fatal();
            },
            Err(e) => {
                // TODO: this should only happen due to an erroneous layout created by user
                // configuration that was somehow not caught in our KDL layout parser
                // we should still be able to properly recover from this with a useful error
                // message though
                log::error!("Failed to apply layout: {}", e);
            },
        }
        Ok(())
    }
    pub fn swap_layout_info(&self) -> (Option<String>, bool) {
        if self.floating_panes.panes_are_visible() {
            self.swap_layouts.floating_layout_info()
        } else {
            let selectable_tiled_panes =
                self.tiled_panes.get_panes().filter(|(_, p)| p.selectable());
            if selectable_tiled_panes.count() + self.suppressed_stack_list_members().count() > 1 {
                self.swap_layouts.tiled_layout_info()
            } else {
                // no layout for single pane
                (None, false)
            }
        }
    }
    fn relayout_floating_panes(&mut self, search_backwards: bool) -> Result<()> {
        if let Some(layout_candidate) = self
            .swap_layouts
            .swap_floating_panes(&self.floating_panes, search_backwards)
        {
            LayoutApplier::new(
                &self.viewport,
                &self.senders,
                &self.sixel_image_store,
                &self.kitty_image_store,
                &self.link_handler,
                &self.terminal_emulator_colors,
                &self.terminal_emulator_color_codes,
                &self.character_cell_size,
                &self.connected_clients_in_app,
                &self.style,
                &self.display_area,
                &mut self.tiled_panes,
                &mut self.floating_panes,
                self.pane_frame_style,
                &mut self.focus_pane_id,
                &self.os_api,
                self.debug,
                self.arrow_fonts,
                self.styled_underlines,
                self.osc8_hyperlinks,
                self.explicitly_disable_kitty_keyboard_protocol,
                None,
            )
            .apply_floating_panes_layout_to_existing_panes(&layout_candidate)
            .non_fatal();
        }
        self.set_force_render();
        self.senders
            .send_to_pty_writer(PtyWriteInstruction::ApplyCachedResizes)
            .with_context(|| format!("failed to apply cached resizes"))?;
        Ok(())
    }
    /// Apply a resolved swap layout to the existing panes.
    ///
    /// Extracted from relayout_tiled_panes so the responsive-layout switch
    /// applies layouts through exactly the same path rather than a lookalike.
    fn apply_tiled_layout_candidate(&mut self, layout_candidate: &TiledPaneLayout) {
        let application_res = LayoutApplier::new(
            &self.viewport,
            &self.senders,
            &self.sixel_image_store,
            &self.kitty_image_store,
            &self.link_handler,
            &self.terminal_emulator_colors,
            &self.terminal_emulator_color_codes,
            &self.character_cell_size,
            &self.connected_clients_in_app,
            &self.style,
            &self.display_area,
            &mut self.tiled_panes,
            &mut self.floating_panes,
            self.pane_frame_style,
            &mut self.focus_pane_id,
            &self.os_api,
            self.debug,
            self.arrow_fonts,
            self.styled_underlines,
            self.osc8_hyperlinks,
            self.explicitly_disable_kitty_keyboard_protocol,
            None,
        )
        .apply_tiled_panes_layout_to_existing_panes(layout_candidate);
        if application_res.is_err() {
            self.swap_layouts.set_is_tiled_damaged();
            application_res.non_fatal();
        }
    }
    fn relayout_tiled_panes(&mut self, search_backwards: bool) -> Result<()> {
        if self.tiled_panes.fullscreen_is_active() {
            self.tiled_panes.unset_fullscreen();
        }
        self.dissolve_stack_lists_for_classic_mutation();
        if let Some(layout_candidate) = self
            .swap_layouts
            .swap_tiled_panes(&self.tiled_panes, search_backwards)
        {
            self.apply_tiled_layout_candidate(&layout_candidate);
        } else {
            self.swap_layouts.set_is_tiled_damaged();
        }
        self.tiled_panes.reapply_pane_frames();
        let display_area = *self.display_area.borrow();
        // we do this so that the new swap layout has a chance to pass through the constraint system
        self.tiled_panes.resize(display_area);
        self.set_should_clear_display_before_rendering();
        self.senders
            .send_to_pty_writer(PtyWriteInstruction::ApplyCachedResizes)
            .with_context(|| format!("failed to apply cached resizes"))?;
        Ok(())
    }
    pub fn previous_swap_layout(&mut self) -> Result<()> {
        let search_backwards = true;
        if self.floating_panes.panes_are_visible() {
            self.relayout_floating_panes(search_backwards)?;
        } else {
            self.relayout_tiled_panes(search_backwards)?;
        }
        Ok(())
    }
    pub fn next_swap_layout(&mut self) -> Result<()> {
        let search_backwards = false;
        if self.floating_panes.panes_are_visible() {
            self.relayout_floating_panes(search_backwards)?;
        } else {
            self.relayout_tiled_panes(search_backwards)?;
        }
        Ok(())
    }
    pub fn apply_buffered_instructions(&mut self) -> Result<()> {
        let buffered_instructions: Vec<BufferedTabInstruction> =
            self.pending_instructions.drain(..).collect();
        for buffered_instruction in buffered_instructions {
            match buffered_instruction {
                BufferedTabInstruction::SetPaneSelectable(pane_id, selectable) => {
                    self.set_pane_selectable(pane_id, selectable);
                },
                BufferedTabInstruction::HandlePtyBytes(terminal_id, bytes) => {
                    self.handle_pty_bytes(terminal_id, bytes)?;
                },
                BufferedTabInstruction::HoldPane(
                    terminal_id,
                    exit_status,
                    is_first_run,
                    run_command,
                ) => {
                    self.hold_pane(terminal_id, exit_status, is_first_run, run_command);
                },
            }
        }
        Ok(())
    }
    pub fn rename_session(&mut self, new_session_name: String) -> Result<()> {
        {
            let mode_infos = &mut self.mode_info.borrow_mut();
            for (_client_id, mode_info) in mode_infos.iter_mut() {
                mode_info.session_name = Some(new_session_name.clone());
            }
            self.default_mode_info.session_name = Some(new_session_name);
        }
        self.update_input_modes()
    }
    pub fn update_input_modes(&mut self) -> Result<()> {
        // this updates only this tab's plugins with the client's input mode
        let mode_infos = self.mode_info.borrow();
        let mut plugin_updates = vec![];
        let currently_marking_pane_group = self.currently_marking_pane_group.borrow();
        let tab_plugin_ids = self.get_plugin_ids();
        for client_id in self.connected_clients.borrow().iter() {
            let mut mode_info = mode_infos
                .get(client_id)
                .unwrap_or(&self.default_mode_info)
                .clone();
            mode_info.shell = Some(self.default_shell.clone());
            mode_info.editor = self.default_editor.clone();
            mode_info.web_clients_allowed = Some(self.web_clients_allowed);
            mode_info.web_sharing = Some(self.web_sharing);
            mode_info.currently_marking_pane_group =
                currently_marking_pane_group.get(client_id).copied();
            mode_info.web_server_ip = Some(self.web_server_ip);
            mode_info.web_server_port = Some(self.web_server_port);
            mode_info.is_web_client = self
                .connected_clients_in_app
                .borrow()
                .get(&client_id)
                .copied();
            if cfg!(feature = "web_server_capability") {
                mode_info.web_server_capability = Some(true);
            } else {
                mode_info.web_server_capability = Some(false);
            }
            mode_info.pane_frame_style = Some(self.pane_frame_style);
            for plugin_id in &tab_plugin_ids {
                plugin_updates.push((
                    Some(*plugin_id),
                    Some(*client_id),
                    Event::ModeUpdate(mode_info.clone()),
                ));
            }
        }
        if !plugin_updates.is_empty() {
            self.senders
                .send_to_plugin(PluginInstruction::Update(plugin_updates))
                .with_context(|| format!("failed to update plugins with mode info"))?;
        }
        Ok(())
    }
    fn resolve_hint_text(&self, client_id: ClientId) -> BTreeMap<usize, StyledText> {
        let focused_pane_id = self.get_active_pane_id(client_id);
        let hovered_pane_id = self.mouse_hover_pane_id.get(&client_id).copied();
        if let Some(hovered_pane_id) = hovered_pane_id {
            if Some(hovered_pane_id) != focused_pane_id {
                return hover_hint_variants();
            }
        }
        if let Some(focused_pane) = self.get_active_pane(client_id) {
            if focused_pane.is_held() {
                let exited = focused_pane.exited();
                let is_first_run = !exited;
                let exit_status = if exited {
                    Some(match focused_pane.exit_status() {
                        Some(exit_code) => HintExitStatus::Code(exit_code),
                        None => HintExitStatus::Exited,
                    })
                } else {
                    None
                };
                return held_hint_variants(is_first_run, exit_status);
            }
        }
        let resize_help_visible = self
            .mouse_help_text_visible
            .get(&client_id)
            .copied()
            .unwrap_or(false);
        if resize_help_visible {
            let selectable_pane_count = self.get_selectable_tiled_panes().count()
                + self.get_selectable_floating_panes().count();
            if selectable_pane_count > 1 && !self.is_fullscreen_active() {
                let focused_pane_is_floating = self.floating_panes.panes_are_visible();
                return resize_hint_variants(focused_pane_is_floating, self.mouse_scroll_resize);
            }
        }
        BTreeMap::new()
    }
    pub fn emit_hint_text_if_changed(&mut self) -> Result<()> {
        let connected_clients: Vec<ClientId> =
            self.connected_clients.borrow().iter().copied().collect();
        let mut plugin_updates = vec![];
        for client_id in connected_clients {
            let hint_text = self.resolve_hint_text(client_id);
            if self.last_hint_text.get(&client_id) != Some(&hint_text) {
                self.last_hint_text.insert(client_id, hint_text.clone());
                plugin_updates.push((None, Some(client_id), Event::HintText(hint_text)));
            }
        }
        if !plugin_updates.is_empty() {
            self.senders
                .send_to_plugin(PluginInstruction::Update(plugin_updates))
                .with_context(|| format!("failed to update plugins with hint text"))?;
        }
        Ok(())
    }
    pub fn clear_hint_text_cache(&mut self) {
        self.last_hint_text.clear();
    }
    fn get_selectable_tiled_content_panes(
        &self,
    ) -> impl Iterator<Item = (&PaneId, &Box<dyn Pane>)> {
        self.get_selectable_tiled_panes()
            .filter(|(_, p)| !p.borderless())
    }
    pub fn single_pane_titles(&self) -> bool {
        self.pane_frame_style.draws_titles()
            && self.get_selectable_tiled_content_panes().count() == 1
    }
    fn tab_name_is_default(&self) -> bool {
        !self.name.is_empty() && self.name == self.default_name
    }
    pub fn single_pane_tab_name(&self) -> Option<String> {
        if !self.single_pane_titles() {
            return None;
        }
        let (_, pane) = self.get_selectable_tiled_content_panes().next()?;
        let mut base = if self.tab_name_is_default() && pane.has_explicit_title() {
            pane.current_title()
        } else {
            self.name.clone()
        };
        if pane.is_held() && pane.exited() {
            match pane.exit_status() {
                Some(exit_code) => base.push_str(&format!(" [ EXIT CODE: {} ] ", exit_code)),
                None => base.push_str(" [ EXITED ] "),
            }
        }
        Some(base)
    }
    fn resolve_active_pane_scroll(&self, _client_id: ClientId) -> Option<(usize, usize)> {
        if !self.single_pane_titles() {
            return None;
        }
        let (_, pane) = self.get_selectable_tiled_content_panes().next()?;
        let (position, length) = pane.scroll_position();
        if position > 0 || length > 0 {
            Some((position, length))
        } else {
            None
        }
    }
    pub fn emit_active_pane_scroll_if_changed(&mut self) -> Result<()> {
        let connected_clients: Vec<ClientId> =
            self.connected_clients.borrow().iter().copied().collect();
        let mut plugin_updates = vec![];
        for client_id in connected_clients {
            let active_pane_scroll = self.resolve_active_pane_scroll(client_id);
            if self.last_active_pane_scroll.get(&client_id) != Some(&active_pane_scroll) {
                self.last_active_pane_scroll
                    .insert(client_id, active_pane_scroll);
                plugin_updates.push((
                    None,
                    Some(client_id),
                    Event::ActivePaneScroll(active_pane_scroll),
                ));
            }
        }
        if !plugin_updates.is_empty() {
            self.senders
                .send_to_plugin(PluginInstruction::Update(plugin_updates))
                .with_context(|| format!("failed to update plugins with active pane scroll"))?;
        }
        Ok(())
    }
    pub fn add_client(&mut self, client_id: ClientId, mode_info: Option<ModeInfo>) -> Result<()> {
        let other_clients_exist_in_tab = { !self.connected_clients.borrow().is_empty() };
        if other_clients_exist_in_tab {
            if let Some(first_active_floating_pane_id) =
                self.floating_panes.first_active_floating_pane_id()
            {
                self.floating_panes
                    .focus_pane_if_client_not_focused(first_active_floating_pane_id, client_id);
            }
            if let Some(first_active_tiled_pane_id) = self.tiled_panes.first_active_pane_id() {
                self.tiled_panes
                    .focus_pane_if_client_not_focused(first_active_tiled_pane_id, client_id);
            }
            self.connected_clients.borrow_mut().insert(client_id);
            self.mode_info.borrow_mut().insert(
                client_id,
                mode_info.unwrap_or_else(|| self.default_mode_info.clone()),
            );
        } else {
            let mut pane_ids: Vec<PaneId> = self.tiled_panes.pane_ids().copied().collect();
            if pane_ids.is_empty() {
                // no panes here, bye bye
                return Ok(());
            }
            let focus_pane_id = if let Some(id) = self.focus_pane_id {
                id
            } else {
                pane_ids.sort(); // TODO: make this predictable
                pane_ids.retain(|p| !self.tiled_panes.panes_to_hide_contains(*p));
                *(pane_ids.get(0).with_context(|| {
                    format!("failed to acquire id of focused pane while adding client {client_id}",)
                })?)
            };
            self.tiled_panes
                .focus_pane_if_client_not_focused(focus_pane_id, client_id);
            self.floating_panes
                .focus_first_pane_if_client_not_focused(client_id);
            self.connected_clients.borrow_mut().insert(client_id);
            self.mode_info.borrow_mut().insert(
                client_id,
                mode_info.unwrap_or_else(|| self.default_mode_info.clone()),
            );
        }
        self.set_force_render();
        Ok(())
    }

    pub fn change_mode_info(&mut self, mode_info: ModeInfo, client_id: ClientId) {
        self.mode_info.borrow_mut().insert(client_id, mode_info);
    }

    pub fn add_multiple_clients(
        &mut self,
        client_ids_to_mode_infos: Vec<(ClientId, ModeInfo)>,
    ) -> Result<()> {
        for (client_id, client_mode_info) in client_ids_to_mode_infos {
            self.add_client(client_id, None)
                .context("failed to add clients")?;
            self.mode_info
                .borrow_mut()
                .insert(client_id, client_mode_info);
        }
        Ok(())
    }
    pub fn remove_client(&mut self, client_id: ClientId) {
        self.focus_pane_id = None;
        self.mode_info
            .borrow_mut()
            .get_mut(&client_id)
            .map(|c| c.change_to_default_mode()); // TODO: no races?
        self.connected_clients.borrow_mut().remove(&client_id);
        self.mouse_help_text_visible.remove(&client_id);
        self.mouse_last_pane_id.remove(&client_id);
        self.last_mouse_activity_time.remove(&client_id);
        self.set_client_dimmed(client_id, false);
        self.set_force_render();
    }
    pub fn drain_connected_clients(
        &mut self,
        clients_to_drain: Option<Vec<ClientId>>,
    ) -> Vec<(ClientId, ModeInfo)> {
        // None => all clients
        let mut client_ids_to_mode_infos = vec![];
        let clients_to_drain = clients_to_drain
            .unwrap_or_else(|| self.connected_clients.borrow_mut().drain().collect());
        for client_id in clients_to_drain {
            client_ids_to_mode_infos.push(self.drain_single_client(client_id));
        }
        client_ids_to_mode_infos
    }
    pub fn drain_single_client(&mut self, client_id: ClientId) -> (ClientId, ModeInfo) {
        let client_mode_info = self
            .mode_info
            .borrow_mut()
            .remove(&client_id)
            .unwrap_or_else(|| self.default_mode_info.clone());
        self.connected_clients.borrow_mut().remove(&client_id);
        (client_id, client_mode_info)
    }
    pub fn has_no_connected_clients(&self) -> bool {
        self.connected_clients.borrow().is_empty()
    }
    pub fn pane_id_is_floating(&self, pane_id: &PaneId) -> bool {
        self.floating_panes.panes_contain(pane_id)
    }
    pub fn toggle_pane_embed_or_floating(&mut self, client_id: ClientId) -> Result<()> {
        let err_context =
            || format!("failed to toggle embedded/floating pane for client {client_id}");
        if self.tiled_panes.fullscreen_is_active() {
            self.tiled_panes.unset_fullscreen();
        }
        if self.floating_panes.panes_are_visible() {
            if let Some(focused_floating_pane_id) = self.floating_panes.active_pane_id(client_id) {
                if self.tiled_panes.has_room_for_new_pane() {
                    let floating_pane_to_embed = self
                        .extract_pane(focused_floating_pane_id, true)
                        .with_context(|| format!(
                        "failed to find floating pane (ID: {focused_floating_pane_id:?}) to embed for client {client_id}",
                    ))
                        .with_context(err_context)?;
                    self.hide_floating_panes();
                    self.add_tiled_pane(
                        floating_pane_to_embed,
                        focused_floating_pane_id,
                        false,
                        Some(client_id),
                    )?;
                }
            }
        } else if let Some(focused_pane_id) = self.tiled_panes.focused_pane_id(client_id) {
            if self.get_selectable_tiled_panes().count() <= 1
                && !self.pane_is_stack_list_member(&focused_pane_id)
            {
                // don't close the only pane on screen...
                return Ok(());
            }
            if let Some(embedded_pane_to_float) = self.extract_pane(focused_pane_id, true) {
                self.show_floating_panes();
                self.add_floating_pane(
                    embedded_pane_to_float,
                    focused_pane_id,
                    None,
                    true,
                    Some(client_id),
                )?;
            }
        }
        Ok(())
    }
    pub fn toggle_pane_embed_or_floating_for_pane_id(
        &mut self,
        pane_id: PaneId,
        client_id: Option<ClientId>,
    ) -> Result<()> {
        let err_context = || {
            format!(
                "failed to toggle embedded/floating pane for pane_id {:?}",
                pane_id
            )
        };
        if self.tiled_panes.fullscreen_is_active() {
            self.tiled_panes.unset_fullscreen();
        }
        if self.floating_panes.panes_contain(&pane_id) {
            if self.tiled_panes.has_room_for_new_pane() {
                let floating_pane_to_embed = self
                    .extract_pane(pane_id, true)
                    .with_context(|| {
                        format!("failed to find floating pane (ID: {pane_id:?}) to embed",)
                    })
                    .with_context(err_context)?;
                self.add_tiled_pane(floating_pane_to_embed, pane_id, false, client_id)?;
            }
        } else if self.tiled_panes.panes_contain(&pane_id) {
            if self.get_selectable_tiled_panes().count() <= 1
                && !self.pane_is_stack_list_member(&pane_id)
            {
                log::error!("Cannot float the last tiled pane...");
                // don't close the only pane on screen...
                return Ok(());
            }
            if let Some(embedded_pane_to_float) = self.extract_pane(pane_id, true) {
                self.add_floating_pane(embedded_pane_to_float, pane_id, None, true, client_id)?;
            }
        } else if self.pane_is_hidden_stack_list_member(&pane_id) {
            if let Some(hidden_member_to_float) = self.extract_pane(pane_id, true) {
                self.add_floating_pane(hidden_member_to_float, pane_id, None, true, client_id)?;
            }
        }
        Ok(())
    }
    pub fn toggle_floating_panes(
        &mut self,
        client_id: Option<ClientId>,
        default_shell: Option<TerminalAction>,
        completion_tx: Option<NotificationEnd>,
    ) -> Result<()> {
        if self.floating_panes.panes_are_visible() {
            self.hide_floating_panes();
            self.set_force_render();
        } else {
            self.show_floating_panes();
            match self.floating_panes.last_selectable_floating_pane_id() {
                Some(last_selectable_floating_pane_id) => match client_id {
                    Some(client_id) => {
                        if !self.floating_panes.active_panes_contain(&client_id) {
                            self.floating_panes
                                .focus_pane(last_selectable_floating_pane_id, client_id);
                        }
                    },
                    None => {
                        self.floating_panes
                            .focus_pane_for_all_clients(last_selectable_floating_pane_id);
                    },
                },
                None => {
                    let name = None;
                    let client_id_or_tab_index = match client_id {
                        Some(client_id) => ClientTabIndexOrPaneId::ClientId(client_id),
                        None => ClientTabIndexOrPaneId::TabIndex(self.id),
                    };
                    let should_start_suppressed = false;
                    let instruction = PtyInstruction::SpawnTerminal(
                        default_shell,
                        name,
                        NewPanePlacement::Floating(None),
                        should_start_suppressed,
                        client_id_or_tab_index,
                        completion_tx,
                        false, // set_blocking
                    );
                    self.senders
                        .send_to_pty(instruction)
                        .with_context(|| format!("failed to open a floating pane for client"))?;
                },
            }
            self.floating_panes.set_force_render();
        }
        self.set_force_render();
        Ok(())
    }
    fn normalize_invoked_with_for_default_shell(&self, invoked_with: Option<Run>) -> Option<Run> {
        let default_shell_run_command = Run::Command(RunCommand {
            command: self.default_shell.clone(),
            use_terminal_title: true,
            ..Default::default()
        });
        if invoked_with == Some(default_shell_run_command) {
            None
        } else {
            invoked_with
        }
    }
    pub fn new_pane(
        &mut self,
        pid: PaneId,
        initial_pane_title: Option<String>,
        invoked_with: Option<Run>,
        start_suppressed: bool,
        should_focus_pane: bool,
        new_pane_placement: NewPanePlacement,
        client_id: Option<ClientId>,
        blocking_notification: Option<NotificationEnd>,
    ) -> Result<()> {
        let invoked_with = self.normalize_invoked_with_for_default_shell(invoked_with);
        match new_pane_placement {
            NewPanePlacement::NoPreference { borderless } => self.new_no_preference_pane(
                pid,
                initial_pane_title,
                invoked_with,
                start_suppressed,
                should_focus_pane,
                client_id,
                blocking_notification,
                borderless,
            ),
            NewPanePlacement::Tiled {
                direction: None,
                borderless,
            } => self.new_tiled_pane(
                pid,
                initial_pane_title,
                invoked_with,
                start_suppressed,
                should_focus_pane,
                client_id,
                blocking_notification,
                borderless,
            ),
            NewPanePlacement::Tiled {
                direction: Some(direction),
                borderless,
            } => {
                let is_vertical = direction == Direction::Left || direction == Direction::Right;
                if should_focus_pane {
                    if let Some(client_id) = client_id {
                        if is_vertical {
                            self.vertical_split(
                                pid,
                                initial_pane_title,
                                client_id,
                                blocking_notification,
                                borderless,
                            )?;
                        } else {
                            self.horizontal_split(
                                pid,
                                initial_pane_title,
                                client_id,
                                blocking_notification,
                                borderless,
                            )?;
                        }
                    }
                } else if let Some(target_pane_id) =
                    client_id.and_then(|client_id| self.tiled_panes.get_active_pane_id(client_id))
                {
                    if is_vertical {
                        self.vertical_split_of_pane_id(
                            pid,
                            initial_pane_title,
                            invoked_with,
                            target_pane_id,
                            blocking_notification,
                            borderless,
                        )?;
                    } else {
                        self.horizontal_split_of_pane_id(
                            pid,
                            initial_pane_title,
                            invoked_with,
                            target_pane_id,
                            blocking_notification,
                            borderless,
                        )?;
                    }
                }
                Ok(())
            },
            NewPanePlacement::Floating(floating_pane_coordinates) => self.new_floating_pane(
                pid,
                initial_pane_title,
                invoked_with,
                start_suppressed,
                should_focus_pane,
                floating_pane_coordinates,
                blocking_notification,
            ),
            NewPanePlacement::InPlace {
                pane_id_to_replace,
                close_replaced_pane,
                borderless,
            } => self.new_in_place_pane(
                pid,
                initial_pane_title,
                invoked_with,
                pane_id_to_replace.map(|id| id.into()),
                close_replaced_pane,
                client_id,
                blocking_notification,
                borderless,
            ),
            NewPanePlacement::Stacked {
                pane_id_to_stack_under,
                borderless,
            } => self.new_stacked_pane(
                pid,
                initial_pane_title,
                invoked_with,
                start_suppressed,
                should_focus_pane,
                pane_id_to_stack_under.map(|id| id.into()),
                client_id,
                blocking_notification,
                borderless,
            ),
        }
    }
    pub fn new_no_preference_pane(
        &mut self,
        pid: PaneId,
        initial_pane_title: Option<String>,
        invoked_with: Option<Run>,
        start_suppressed: bool,
        should_focus_pane: bool,
        client_id: Option<ClientId>,
        blocking_notification: Option<NotificationEnd>,
        borderless: Option<bool>,
    ) -> Result<()> {
        let err_context = || format!("failed to create new pane with id {pid:?}");
        self.close_down_to_max_terminals()
            .with_context(err_context)?;
        let mut new_pane = match pid {
            PaneId::Terminal(term_pid) => {
                let next_terminal_position = self.get_next_terminal_position();
                Box::new(TerminalPane::new(
                    term_pid,
                    PaneGeom::default(), // this will be filled out later
                    self.style,
                    next_terminal_position,
                    initial_pane_title.clone().unwrap_or_default(),
                    self.link_handler.clone(),
                    self.character_cell_size.clone(),
                    self.sixel_image_store.clone(),
                    self.kitty_image_store.clone(),
                    self.terminal_emulator_colors.clone(),
                    self.terminal_emulator_color_codes.clone(),
                    initial_pane_title,
                    invoked_with,
                    self.debug,
                    self.arrow_fonts,
                    self.styled_underlines,
                    self.osc8_hyperlinks,
                    self.explicitly_disable_kitty_keyboard_protocol,
                    blocking_notification,
                )) as Box<dyn Pane>
            },
            PaneId::Plugin(plugin_pid) => {
                Box::new(PluginPane::new(
                    plugin_pid,
                    PaneGeom::default(), // this will be filled out later
                    self.senders
                        .to_plugin
                        .as_ref()
                        .with_context(err_context)?
                        .clone(),
                    initial_pane_title.unwrap_or("".to_owned()),
                    String::new(),
                    self.sixel_image_store.clone(),
                    self.kitty_image_store.clone(),
                    self.terminal_emulator_colors.clone(),
                    self.terminal_emulator_color_codes.clone(),
                    self.link_handler.clone(),
                    self.character_cell_size.clone(),
                    self.connected_clients_in_app
                        .borrow()
                        .keys()
                        .copied()
                        .collect(),
                    self.style,
                    invoked_with,
                    self.debug,
                    self.arrow_fonts,
                    self.styled_underlines,
                )) as Box<dyn Pane>
            },
        };

        if let Some(borderless) = borderless {
            new_pane.set_borderless(borderless);
        }

        if start_suppressed {
            // this pane needs to start in the background (suppressed), only accessible if a plugin takes it out
            // of there in one way or another
            // we need to do some bookkeeping for this pane, namely setting its geom and
            // content_offset so that things will appear properly in the terminal - we set it to
            // the default geom of the first floating pane - this is just in order to give it some
            // reasonable size, when it is shown - if needed - it will be given the proper geom as if it were
            // resized
            let viewport = { self.viewport.borrow().clone() };
            let new_pane_geom = half_size_middle_geom(&viewport, 0);
            new_pane.set_active_at(Instant::now());
            new_pane.set_geom(new_pane_geom);
            new_pane.set_content_offset(Offset::frame(1));
            resize_pty!(
                new_pane,
                self.os_api,
                self.senders,
                self.character_cell_size
            )
            .with_context(err_context)?;
            let is_scrollback_editor = false;
            self.suppressed_panes
                .insert(pid, (is_scrollback_editor, new_pane));
            Ok(())
        } else if should_focus_pane {
            if self.floating_panes.panes_are_visible() {
                self.add_floating_pane(new_pane, pid, None, true, client_id)
            } else {
                self.add_tiled_pane(new_pane, pid, false, client_id)
            }
        } else {
            if self.floating_panes.panes_are_visible() {
                self.add_floating_pane(new_pane, pid, None, false, client_id)
            } else {
                self.add_tiled_pane(new_pane, pid, false, None)
            }
        }
    }
    pub fn new_tiled_pane(
        &mut self,
        pid: PaneId,
        initial_pane_title: Option<String>,
        invoked_with: Option<Run>,
        start_suppressed: bool,
        should_focus_pane: bool,
        client_id: Option<ClientId>,
        blocking_notification: Option<NotificationEnd>,
        borderless: Option<bool>,
    ) -> Result<()> {
        let err_context = || format!("failed to create new pane with id {pid:?}");
        if should_focus_pane {
            self.hide_floating_panes();
        }
        self.close_down_to_max_terminals()
            .with_context(err_context)?;
        let mut new_pane = match pid {
            PaneId::Terminal(term_pid) => {
                let next_terminal_position = self.get_next_terminal_position();
                Box::new(TerminalPane::new(
                    term_pid,
                    PaneGeom::default(), // this will be filled out later
                    self.style,
                    next_terminal_position,
                    initial_pane_title.clone().unwrap_or_default(),
                    self.link_handler.clone(),
                    self.character_cell_size.clone(),
                    self.sixel_image_store.clone(),
                    self.kitty_image_store.clone(),
                    self.terminal_emulator_colors.clone(),
                    self.terminal_emulator_color_codes.clone(),
                    initial_pane_title,
                    invoked_with,
                    self.debug,
                    self.arrow_fonts,
                    self.styled_underlines,
                    self.osc8_hyperlinks,
                    self.explicitly_disable_kitty_keyboard_protocol,
                    blocking_notification,
                )) as Box<dyn Pane>
            },
            PaneId::Plugin(plugin_pid) => {
                Box::new(PluginPane::new(
                    plugin_pid,
                    PaneGeom::default(), // this will be filled out later
                    self.senders
                        .to_plugin
                        .as_ref()
                        .with_context(err_context)?
                        .clone(),
                    initial_pane_title.unwrap_or("".to_owned()),
                    String::new(),
                    self.sixel_image_store.clone(),
                    self.kitty_image_store.clone(),
                    self.terminal_emulator_colors.clone(),
                    self.terminal_emulator_color_codes.clone(),
                    self.link_handler.clone(),
                    self.character_cell_size.clone(),
                    self.connected_clients_in_app
                        .borrow()
                        .keys()
                        .copied()
                        .collect(),
                    self.style,
                    invoked_with,
                    self.debug,
                    self.arrow_fonts,
                    self.styled_underlines,
                )) as Box<dyn Pane>
            },
        };

        if let Some(borderless) = borderless {
            new_pane.set_borderless(borderless);
        }

        if start_suppressed {
            // this pane needs to start in the background (suppressed), only accessible if a plugin takes it out
            // of there in one way or another
            // we need to do some bookkeeping for this pane, namely setting its geom and
            // content_offset so that things will appear properly in the terminal - we set it to
            // the default geom of the first floating pane - this is just in order to give it some
            // reasonable size, when it is shown - if needed - it will be given the proper geom as if it were
            // resized
            let viewport = { self.viewport.borrow().clone() };
            let new_pane_geom = half_size_middle_geom(&viewport, 0);
            new_pane.set_active_at(Instant::now());
            new_pane.set_geom(new_pane_geom);
            new_pane.set_content_offset(Offset::frame(1));
            resize_pty!(
                new_pane,
                self.os_api,
                self.senders,
                self.character_cell_size
            )
            .with_context(err_context)?;
            let is_scrollback_editor = false;
            self.suppressed_panes
                .insert(pid, (is_scrollback_editor, new_pane));
            Ok(())
        } else {
            let focus_client_id = if should_focus_pane { client_id } else { None };
            self.add_tiled_pane(new_pane, pid, false, focus_client_id)
        }
    }
    pub fn new_floating_pane(
        &mut self,
        pid: PaneId,
        initial_pane_title: Option<String>,
        invoked_with: Option<Run>,
        start_suppressed: bool,
        should_focus_pane: bool,
        floating_pane_coordinates: Option<FloatingPaneCoordinates>,
        blocking_notification: Option<NotificationEnd>,
    ) -> Result<()> {
        let err_context = || format!("failed to create new pane with id {pid:?}");
        if should_focus_pane {
            self.show_floating_panes();
        }
        self.close_down_to_max_terminals()
            .with_context(err_context)?;
        let mut new_pane = match pid {
            PaneId::Terminal(term_pid) => {
                let next_terminal_position = self.get_next_terminal_position();
                Box::new(TerminalPane::new(
                    term_pid,
                    PaneGeom::default(), // this will be filled out later
                    self.style,
                    next_terminal_position,
                    initial_pane_title.clone().unwrap_or_default(),
                    self.link_handler.clone(),
                    self.character_cell_size.clone(),
                    self.sixel_image_store.clone(),
                    self.kitty_image_store.clone(),
                    self.terminal_emulator_colors.clone(),
                    self.terminal_emulator_color_codes.clone(),
                    initial_pane_title,
                    invoked_with,
                    self.debug,
                    self.arrow_fonts,
                    self.styled_underlines,
                    self.osc8_hyperlinks,
                    self.explicitly_disable_kitty_keyboard_protocol,
                    blocking_notification,
                )) as Box<dyn Pane>
            },
            PaneId::Plugin(plugin_pid) => {
                Box::new(PluginPane::new(
                    plugin_pid,
                    PaneGeom::default(), // this will be filled out later
                    self.senders
                        .to_plugin
                        .as_ref()
                        .with_context(err_context)?
                        .clone(),
                    initial_pane_title.unwrap_or("".to_owned()),
                    String::new(),
                    self.sixel_image_store.clone(),
                    self.kitty_image_store.clone(),
                    self.terminal_emulator_colors.clone(),
                    self.terminal_emulator_color_codes.clone(),
                    self.link_handler.clone(),
                    self.character_cell_size.clone(),
                    self.connected_clients_in_app
                        .borrow()
                        .keys()
                        .copied()
                        .collect(),
                    self.style,
                    invoked_with,
                    self.debug,
                    self.arrow_fonts,
                    self.styled_underlines,
                )) as Box<dyn Pane>
            },
        };

        if start_suppressed {
            // this pane needs to start in the background (suppressed), only accessible if a plugin takes it out
            // of there in one way or another
            // we need to do some bookkeeping for this pane, namely setting its geom and
            // content_offset so that things will appear properly in the terminal - we set it to
            // the default geom of the first floating pane - this is just in order to give it some
            // reasonable size, when it is shown - if needed - it will be given the proper geom as if it were
            // resized
            let viewport = { self.viewport.borrow().clone() };
            let new_pane_geom = half_size_middle_geom(&viewport, 0);
            new_pane.set_active_at(Instant::now());
            new_pane.set_geom(new_pane_geom);
            new_pane.set_content_offset(Offset::frame(1));
            resize_pty!(
                new_pane,
                self.os_api,
                self.senders,
                self.character_cell_size
            )
            .with_context(err_context)?;
            let is_scrollback_editor = false;
            self.suppressed_panes
                .insert(pid, (is_scrollback_editor, new_pane));
            Ok(())
        } else {
            self.add_floating_pane(
                new_pane,
                pid,
                floating_pane_coordinates,
                should_focus_pane,
                None,
            )
        }
    }
    pub fn new_in_place_pane(
        &mut self,
        pid: PaneId,
        initial_pane_title: Option<String>,
        invoked_with: Option<Run>,
        pane_id_to_replace: Option<PaneId>,
        close_replaced_pane: bool,
        client_id: Option<ClientId>,
        blocking_notification: Option<NotificationEnd>,
        borderless: Option<bool>,
    ) -> Result<()> {
        match (pane_id_to_replace, client_id) {
            (Some(pane_id_to_replace), _) => {
                self.suppress_pane_and_replace_with_pid(
                    pane_id_to_replace,
                    pid,
                    close_replaced_pane,
                    invoked_with,
                    blocking_notification,
                    borderless,
                )?;
            },
            (None, Some(client_id)) => match self.get_active_pane_id(client_id) {
                Some(active_pane_id) => {
                    self.suppress_pane_and_replace_with_pid(
                        active_pane_id,
                        pid,
                        close_replaced_pane,
                        invoked_with,
                        blocking_notification,
                        borderless,
                    )?;
                },
                None => {
                    log::error!("Cannot find active pane");
                },
            },
            _ => {
                log::error!("Must have pane id to replace or client id to start pane in place>");
            },
        }
        if let Some(initial_pane_title) = initial_pane_title {
            let _ = self.rename_pane(initial_pane_title.as_bytes().to_vec(), pid);
        }
        Ok(())
    }
    pub fn new_stacked_pane(
        &mut self,
        pid: PaneId,
        initial_pane_title: Option<String>,
        invoked_with: Option<Run>,
        start_suppressed: bool,
        should_focus_pane: bool,
        pane_id_to_stack_under: Option<PaneId>,
        client_id: Option<ClientId>,
        blocking_notification: Option<NotificationEnd>,
        borderless: Option<bool>,
    ) -> Result<()> {
        let err_context = || format!("failed to create new pane with id {pid:?}");
        if should_focus_pane {
            self.hide_floating_panes();
        }
        self.close_down_to_max_terminals()
            .with_context(err_context)?;
        let mut new_pane = match pid {
            PaneId::Terminal(term_pid) => {
                let next_terminal_position = self.get_next_terminal_position();
                Box::new(TerminalPane::new(
                    term_pid,
                    PaneGeom::default(), // this will be filled out later
                    self.style,
                    next_terminal_position,
                    initial_pane_title.clone().unwrap_or_default(),
                    self.link_handler.clone(),
                    self.character_cell_size.clone(),
                    self.sixel_image_store.clone(),
                    self.kitty_image_store.clone(),
                    self.terminal_emulator_colors.clone(),
                    self.terminal_emulator_color_codes.clone(),
                    initial_pane_title,
                    invoked_with,
                    self.debug,
                    self.arrow_fonts,
                    self.styled_underlines,
                    self.osc8_hyperlinks,
                    self.explicitly_disable_kitty_keyboard_protocol,
                    blocking_notification,
                )) as Box<dyn Pane>
            },
            PaneId::Plugin(plugin_pid) => {
                Box::new(PluginPane::new(
                    plugin_pid,
                    PaneGeom::default(), // this will be filled out later
                    self.senders
                        .to_plugin
                        .as_ref()
                        .with_context(err_context)?
                        .clone(),
                    initial_pane_title.unwrap_or("".to_owned()),
                    String::new(),
                    self.sixel_image_store.clone(),
                    self.kitty_image_store.clone(),
                    self.terminal_emulator_colors.clone(),
                    self.terminal_emulator_color_codes.clone(),
                    self.link_handler.clone(),
                    self.character_cell_size.clone(),
                    self.connected_clients_in_app
                        .borrow()
                        .keys()
                        .copied()
                        .collect(),
                    self.style,
                    invoked_with,
                    self.debug,
                    self.arrow_fonts,
                    self.styled_underlines,
                )) as Box<dyn Pane>
            },
        };

        if let Some(borderless) = borderless {
            new_pane.set_borderless(borderless);
        }

        if start_suppressed {
            // this pane needs to start in the background (suppressed), only accessible if a plugin takes it out
            // of there in one way or another
            // we need to do some bookkeeping for this pane, namely setting its geom and
            // content_offset so that things will appear properly in the terminal - we set it to
            // the default geom of the first floating pane - this is just in order to give it some
            // reasonable size, when it is shown - if needed - it will be given the proper geom as if it were
            // resized
            let viewport = { self.viewport.borrow().clone() };
            let new_pane_geom = half_size_middle_geom(&viewport, 0);
            new_pane.set_active_at(Instant::now());
            new_pane.set_geom(new_pane_geom);
            new_pane.set_content_offset(Offset::frame(1));
            resize_pty!(
                new_pane,
                self.os_api,
                self.senders,
                self.character_cell_size
            )
            .with_context(err_context)?;
            let is_scrollback_editor = false;
            self.suppressed_panes
                .insert(pid, (is_scrollback_editor, new_pane));
            Ok(())
        } else {
            if let Some(pane_id_to_stack_under) = pane_id_to_stack_under {
                self.add_stacked_pane_to_pane_id(
                    new_pane,
                    pid,
                    pane_id_to_stack_under,
                    should_focus_pane,
                )
            } else if let Some(client_id) = client_id {
                self.add_stacked_pane_to_active_pane(new_pane, pid, client_id, should_focus_pane)
            } else {
                log::error!("Must have client id or pane id to stack pane");
                return Ok(());
            }
        }
    }
    pub fn replace_active_pane_with_editor_pane(
        &mut self,
        pid: PaneId,
        client_id: ClientId,
    ) -> Result<()> {
        // this method creates a new pane from pid and replaces it with the active pane
        // the active pane is then suppressed (hidden and not rendered) until the current
        // created pane is closed, in which case it will be replaced back by it
        let err_context = || format!("failed to suppress active pane for client {client_id}");

        match pid {
            PaneId::Terminal(pid) => {
                let new_pane = self.new_scrollback_editor_pane(pid);
                let replaced_pane = if self.floating_panes.panes_are_visible() {
                    self.floating_panes
                        .replace_active_pane(Box::new(new_pane), client_id)
                        .ok()
                } else {
                    self.tiled_panes
                        .replace_active_pane(Box::new(new_pane), client_id)
                };
                match replaced_pane {
                    Some(replaced_pane) => {
                        self.track_stack_list_member_id_swap(
                            replaced_pane.pid(),
                            PaneId::Terminal(pid),
                        );
                        self.insert_scrollback_editor_replaced_pane(replaced_pane, pid);
                        self.get_active_pane(client_id)
                            .with_context(|| format!("no active pane found for client {client_id}"))
                            .and_then(|current_active_pane| {
                                resize_pty!(
                                    current_active_pane,
                                    self.os_api,
                                    self.senders,
                                    self.character_cell_size
                                )
                            })
                            .with_context(err_context)?;
                    },
                    None => {
                        Err::<(), _>(anyhow!(
                            "Could not find editor pane to replace - is no pane focused?"
                        ))
                        .with_context(err_context)
                        .non_fatal();
                    },
                }
            },
            PaneId::Plugin(_pid) => {
                // TBD, currently unsupported
            },
        }
        Ok(())
    }
    pub fn replace_pane_with_editor_pane(
        &mut self,
        pid: PaneId,
        pane_id_to_replace: PaneId,
    ) -> Result<()> {
        // this method creates a new pane from pid and replaces it with the pane iwth the given pane_id_to_replace
        // the pane with the given pane_id_to_replace is then suppressed (hidden and not rendered) until the current
        // created pane is closed, in which case it will be replaced back by it
        let err_context = || format!("failed to suppress pane");

        match pid {
            PaneId::Terminal(pid) => {
                let new_pane = self.new_scrollback_editor_pane(pid);
                let replaced_pane = if self.floating_panes.panes_contain(&pane_id_to_replace) {
                    self.floating_panes
                        .replace_pane(pane_id_to_replace, Box::new(new_pane))
                        .ok()
                } else if self.tiled_panes.panes_contain(&pane_id_to_replace) {
                    self.tiled_panes
                        .replace_pane(pane_id_to_replace, Box::new(new_pane))
                } else if self
                    .suppressed_panes
                    .values()
                    .any(|s_p| s_p.1.pid() == pane_id_to_replace)
                {
                    log::error!("Cannot replace suppressed pane");
                    None
                } else {
                    // not a thing
                    None
                };
                match replaced_pane {
                    Some(replaced_pane) => {
                        resize_pty!(
                            replaced_pane,
                            self.os_api,
                            self.senders,
                            self.character_cell_size
                        )
                        .non_fatal();
                        self.track_stack_list_member_id_swap(
                            pane_id_to_replace,
                            PaneId::Terminal(pid),
                        );
                        self.insert_scrollback_editor_replaced_pane(replaced_pane, pid);
                    },
                    None => {
                        Err::<(), _>(anyhow!("Could not find editor pane to replace"))
                            .with_context(err_context)
                            .non_fatal();
                    },
                }
            },
            PaneId::Plugin(_pid) => {
                // TBD, currently unsupported
            },
        }
        Ok(())
    }
    pub fn suppress_pane_and_replace_with_pid(
        &mut self,
        old_pane_id: PaneId,
        new_pane_id: PaneId,
        close_replaced_pane: bool,
        run: Option<Run>,
        completion_tx: Option<NotificationEnd>,
        borderless: Option<bool>,
    ) -> Result<()> {
        // this method creates a new pane from pid and replaces it with the active pane
        // the active pane is then suppressed (hidden and not rendered) until the current
        // created pane is closed, in which case it will be replaced back by it
        let err_context = || format!("failed to suppress active pane");

        match new_pane_id {
            PaneId::Terminal(new_pane_id) => {
                let next_terminal_position = self.get_next_terminal_position(); // TODO: this is not accurate in this case
                let mut new_pane = TerminalPane::new(
                    new_pane_id,
                    PaneGeom::default(), // the initial size will be set later
                    self.style,
                    next_terminal_position,
                    String::new(),
                    self.link_handler.clone(),
                    self.character_cell_size.clone(),
                    self.sixel_image_store.clone(),
                    self.kitty_image_store.clone(),
                    self.terminal_emulator_colors.clone(),
                    self.terminal_emulator_color_codes.clone(),
                    None,
                    run,
                    self.debug,
                    self.arrow_fonts,
                    self.styled_underlines,
                    self.osc8_hyperlinks,
                    self.explicitly_disable_kitty_keyboard_protocol,
                    completion_tx,
                );
                if let Some(supported) = self.kitty_host_support {
                    new_pane.update_kitty_host_support(supported);
                }
                if let Some(borderless) = borderless {
                    new_pane.set_borderless(borderless);
                }
                let replaced_pane = if self.floating_panes.panes_contain(&old_pane_id) {
                    self.floating_panes
                        .replace_pane(old_pane_id, Box::new(new_pane))
                        .ok()
                } else {
                    self.tiled_panes
                        .replace_pane(old_pane_id, Box::new(new_pane))
                };
                if replaced_pane.is_some() {
                    self.track_stack_list_member_id_swap(
                        old_pane_id,
                        PaneId::Terminal(new_pane_id),
                    );
                }
                if close_replaced_pane {
                    if let Some(pid) = replaced_pane.as_ref().map(|p| p.pid()) {
                        self.senders
                            .send_to_pty(PtyInstruction::ClosePane(pid, None))
                            .with_context(err_context)?;
                    }
                    drop(replaced_pane);
                } else {
                    match replaced_pane {
                        Some(replaced_pane) => {
                            let _ = resize_pty!(
                                replaced_pane,
                                self.os_api,
                                self.senders,
                                self.character_cell_size
                            );
                            let is_scrollback_editor = false;
                            self.suppressed_panes.insert(
                                PaneId::Terminal(new_pane_id),
                                (is_scrollback_editor, replaced_pane),
                            );
                        },
                        None => {
                            Err::<(), _>(anyhow!(
                                "Could not find editor pane to replace - is no pane focused?"
                            ))
                            .with_context(err_context)
                            .non_fatal();
                        },
                    }
                }
            },
            PaneId::Plugin(plugin_pid) => {
                let mut new_pane = PluginPane::new(
                    plugin_pid,
                    PaneGeom::default(), // this will be filled out later
                    self.senders
                        .to_plugin
                        .as_ref()
                        .with_context(err_context)?
                        .clone(),
                    String::new(),
                    String::new(),
                    self.sixel_image_store.clone(),
                    self.kitty_image_store.clone(),
                    self.terminal_emulator_colors.clone(),
                    self.terminal_emulator_color_codes.clone(),
                    self.link_handler.clone(),
                    self.character_cell_size.clone(),
                    self.connected_clients_in_app
                        .borrow()
                        .keys()
                        .copied()
                        .collect(),
                    self.style,
                    run,
                    self.debug,
                    self.arrow_fonts,
                    self.styled_underlines,
                );
                if let Some(borderless) = borderless {
                    new_pane.set_borderless(borderless);
                }
                let replaced_pane = if self.floating_panes.panes_contain(&old_pane_id) {
                    self.floating_panes
                        .replace_pane(old_pane_id, Box::new(new_pane))
                        .ok()
                } else {
                    self.tiled_panes
                        .replace_pane(old_pane_id, Box::new(new_pane))
                };
                if replaced_pane.is_some() {
                    self.track_stack_list_member_id_swap(old_pane_id, PaneId::Plugin(plugin_pid));
                }
                if close_replaced_pane {
                    drop(replaced_pane);
                } else {
                    match replaced_pane {
                        Some(replaced_pane) => {
                            let _ = resize_pty!(
                                replaced_pane,
                                self.os_api,
                                self.senders,
                                self.character_cell_size
                            );
                            let is_scrollback_editor = false;
                            self.suppressed_panes.insert(
                                PaneId::Plugin(plugin_pid),
                                (is_scrollback_editor, replaced_pane),
                            );
                        },
                        None => {
                            Err::<(), _>(anyhow!(
                                "Could not find editor pane to replace - is no pane focused?"
                            ))
                            .with_context(err_context)
                            .non_fatal();
                        },
                    }
                }
            },
        }
        Ok(())
    }
    pub fn close_pane_and_replace_with_other_pane(
        &mut self,
        pane_id_to_replace: PaneId,
        pane_to_replace_with: Box<dyn Pane>,
        completion_tx: Option<NotificationEnd>,
    ) {
        let replacement_pane_id = pane_to_replace_with.pid();
        let mut replaced_pane = if self.floating_panes.panes_contain(&pane_id_to_replace) {
            self.floating_panes
                .replace_pane(pane_id_to_replace, pane_to_replace_with)
                .ok()
        } else {
            self.tiled_panes
                .replace_pane(pane_id_to_replace, pane_to_replace_with)
        };
        if replaced_pane.is_some() {
            self.track_stack_list_member_id_swap(pane_id_to_replace, replacement_pane_id);
        }
        if let Some(replaced_pane) = replaced_pane.take() {
            let pane_id = replaced_pane.pid();
            let _ = self
                .senders
                .send_to_pty(PtyInstruction::ClosePane(pane_id, completion_tx));
            let _ = self.senders.send_to_plugin(PluginInstruction::Update(vec![(
                None,
                None,
                Event::PaneClosed(pane_id.into()),
            )]));
            let _ = self
                .senders
                .send_to_screen(ScreenInstruction::NotifyPaneClosedToSubscribers {
                    pane_id: pane_id.into(),
                });
            drop(replaced_pane);
        }
    }
    pub fn suppress_pane_and_replace_with_other_pane(
        &mut self,
        pane_id_to_replace: PaneId,
        pane_to_replace_with: Box<dyn Pane>,
        _completion_tx: Option<NotificationEnd>,
    ) {
        let mut replaced_pane = if self.floating_panes.panes_contain(&pane_id_to_replace) {
            self.floating_panes
                .replace_pane(pane_id_to_replace, pane_to_replace_with)
                .ok()
        } else {
            self.tiled_panes
                .replace_pane(pane_id_to_replace, pane_to_replace_with)
        };

        if let Some(replaced_pane) = replaced_pane.take() {
            let is_scrollback_editor = false;
            self.insert_suppressed_pane(replaced_pane.pid(), (is_scrollback_editor, replaced_pane));
        }
    }
    pub fn horizontal_split(
        &mut self,
        pid: PaneId,
        initial_pane_title: Option<String>,
        client_id: ClientId,
        completion_tx: Option<NotificationEnd>,
        borderless: Option<bool>,
    ) -> Result<()> {
        let err_context =
            || format!("failed to split pane {pid:?} horizontally for client {client_id}");
        if self.floating_panes.panes_are_visible() {
            return Ok(());
        }
        self.close_down_to_max_terminals()
            .with_context(err_context)?;
        if self.tiled_panes.fullscreen_is_active() {
            self.toggle_active_pane_fullscreen(client_id);
        }
        self.dissolve_stack_lists_for_classic_mutation();
        if self.tiled_panes.can_split_pane_horizontally(client_id) {
            if let PaneId::Terminal(term_pid) = pid {
                let next_terminal_position = self.get_next_terminal_position();
                let mut new_terminal = TerminalPane::new(
                    term_pid,
                    PaneGeom::default(), // the initial size will be set later
                    self.style,
                    next_terminal_position,
                    String::new(),
                    self.link_handler.clone(),
                    self.character_cell_size.clone(),
                    self.sixel_image_store.clone(),
                    self.kitty_image_store.clone(),
                    self.terminal_emulator_colors.clone(),
                    self.terminal_emulator_color_codes.clone(),
                    initial_pane_title,
                    None,
                    self.debug,
                    self.arrow_fonts,
                    self.styled_underlines,
                    self.osc8_hyperlinks,
                    self.explicitly_disable_kitty_keyboard_protocol,
                    completion_tx,
                );
                if let Some(supported) = self.kitty_host_support {
                    new_terminal.update_kitty_host_support(supported);
                }
                if let Some(borderless) = borderless {
                    new_terminal.set_borderless(borderless);
                }
                self.tiled_panes
                    .split_pane_horizontally(pid, Box::new(new_terminal), client_id);
                self.set_should_clear_display_before_rendering();
                self.tiled_panes.focus_pane(pid, client_id);
                self.swap_layouts.set_is_tiled_damaged();
            }
        } else {
            log::error!("No room to split pane horizontally");
            if let Some(active_pane_id) = self.tiled_panes.get_active_pane_id(client_id) {
                self.senders
                    .send_to_background_jobs(BackgroundJob::DisplayPaneError(
                        vec![active_pane_id],
                        "CAN'T SPLIT!".into(),
                    ))
                    .with_context(err_context)?;
            }
            self.senders
                .send_to_pty(PtyInstruction::ClosePane(pid, completion_tx))
                .with_context(err_context)?;
            return Ok(());
        }
        Ok(())
    }
    pub fn vertical_split(
        &mut self,
        pid: PaneId,
        initial_pane_title: Option<String>,
        client_id: ClientId,
        completion_tx: Option<NotificationEnd>,
        borderless: Option<bool>,
    ) -> Result<()> {
        let err_context =
            || format!("failed to split pane {pid:?} vertically for client {client_id}");
        if self.floating_panes.panes_are_visible() {
            return Ok(());
        }
        self.close_down_to_max_terminals()
            .with_context(err_context)?;
        if self.tiled_panes.fullscreen_is_active() {
            self.toggle_active_pane_fullscreen(client_id);
        }
        self.dissolve_stack_lists_for_classic_mutation();
        if self.tiled_panes.can_split_pane_vertically(client_id) {
            if let PaneId::Terminal(term_pid) = pid {
                let next_terminal_position = self.get_next_terminal_position();
                let mut new_terminal = TerminalPane::new(
                    term_pid,
                    PaneGeom::default(), // the initial size will be set later
                    self.style,
                    next_terminal_position,
                    String::new(),
                    self.link_handler.clone(),
                    self.character_cell_size.clone(),
                    self.sixel_image_store.clone(),
                    self.kitty_image_store.clone(),
                    self.terminal_emulator_colors.clone(),
                    self.terminal_emulator_color_codes.clone(),
                    initial_pane_title,
                    None,
                    self.debug,
                    self.arrow_fonts,
                    self.styled_underlines,
                    self.osc8_hyperlinks,
                    self.explicitly_disable_kitty_keyboard_protocol,
                    completion_tx,
                );
                if let Some(supported) = self.kitty_host_support {
                    new_terminal.update_kitty_host_support(supported);
                }
                if let Some(borderless) = borderless {
                    new_terminal.set_borderless(borderless);
                }
                self.tiled_panes
                    .split_pane_vertically(pid, Box::new(new_terminal), client_id);
                self.set_should_clear_display_before_rendering();
                self.tiled_panes.focus_pane(pid, client_id);
                self.swap_layouts.set_is_tiled_damaged();
            }
        } else {
            log::error!("No room to split pane vertically");
            if let Some(active_pane_id) = self.tiled_panes.get_active_pane_id(client_id) {
                self.senders
                    .send_to_background_jobs(BackgroundJob::DisplayPaneError(
                        vec![active_pane_id],
                        "CAN'T SPLIT!".into(),
                    ))
                    .with_context(err_context)?;
            }
            self.senders
                .send_to_pty(PtyInstruction::ClosePane(pid, completion_tx))
                .with_context(err_context)?;
            return Ok(());
        }
        Ok(())
    }

    pub fn horizontal_split_of_pane_id(
        &mut self,
        pid: PaneId,
        initial_pane_title: Option<String>,
        invoked_with: Option<Run>,
        target_pane_id: PaneId,
        completion_tx: Option<NotificationEnd>,
        borderless: Option<bool>,
    ) -> Result<()> {
        self.split_of_pane_id(
            pid,
            initial_pane_title,
            invoked_with,
            target_pane_id,
            SplitDirection::Horizontal,
            completion_tx,
            borderless,
        )
    }
    pub fn vertical_split_of_pane_id(
        &mut self,
        pid: PaneId,
        initial_pane_title: Option<String>,
        invoked_with: Option<Run>,
        target_pane_id: PaneId,
        completion_tx: Option<NotificationEnd>,
        borderless: Option<bool>,
    ) -> Result<()> {
        self.split_of_pane_id(
            pid,
            initial_pane_title,
            invoked_with,
            target_pane_id,
            SplitDirection::Vertical,
            completion_tx,
            borderless,
        )
    }
    fn split_of_pane_id(
        &mut self,
        pid: PaneId,
        initial_pane_title: Option<String>,
        invoked_with: Option<Run>,
        target_pane_id: PaneId,
        split_direction: SplitDirection,
        completion_tx: Option<NotificationEnd>,
        borderless: Option<bool>,
    ) -> Result<()> {
        let err_context =
            || format!("failed to split pane {target_pane_id:?} without changing focus");
        if self.floating_panes.panes_are_visible() {
            return Ok(());
        }
        if !self.tiled_panes.panes_contain(&target_pane_id) {
            return Ok(());
        }
        self.close_down_to_max_terminals()
            .with_context(err_context)?;
        if self.tiled_panes.fullscreen_is_active() {
            self.tiled_panes.unset_fullscreen();
        }
        self.dissolve_stack_lists_for_classic_mutation();
        let can_split = match split_direction {
            SplitDirection::Horizontal => self
                .tiled_panes
                .can_split_pane_id_horizontally(target_pane_id),
            SplitDirection::Vertical => self
                .tiled_panes
                .can_split_pane_id_vertically(target_pane_id),
        };
        if !can_split {
            self.senders
                .send_to_pty(PtyInstruction::ClosePane(pid, completion_tx))
                .with_context(err_context)?;
            return Ok(());
        }
        if let PaneId::Terminal(term_pid) = pid {
            let next_terminal_position = self.get_next_terminal_position();
            let mut new_terminal = TerminalPane::new(
                term_pid,
                PaneGeom::default(),
                self.style,
                next_terminal_position,
                String::new(),
                self.link_handler.clone(),
                self.character_cell_size.clone(),
                self.sixel_image_store.clone(),
                self.kitty_image_store.clone(),
                self.terminal_emulator_colors.clone(),
                self.terminal_emulator_color_codes.clone(),
                initial_pane_title,
                invoked_with,
                self.debug,
                self.arrow_fonts,
                self.styled_underlines,
                self.osc8_hyperlinks,
                self.explicitly_disable_kitty_keyboard_protocol,
                completion_tx,
            );
            if let Some(supported) = self.kitty_host_support {
                new_terminal.update_kitty_host_support(supported);
            }
            if let Some(borderless) = borderless {
                new_terminal.set_borderless(borderless);
            }
            match split_direction {
                SplitDirection::Horizontal => self.tiled_panes.split_pane_id_horizontally(
                    pid,
                    Box::new(new_terminal),
                    target_pane_id,
                ),
                SplitDirection::Vertical => self.tiled_panes.split_pane_id_vertically(
                    pid,
                    Box::new(new_terminal),
                    target_pane_id,
                ),
            }
            self.set_should_clear_display_before_rendering();
            self.swap_layouts.set_is_tiled_damaged();
        }
        Ok(())
    }

    pub fn get_active_pane(&self, client_id: ClientId) -> Option<&dyn Pane> {
        self.get_active_pane_id(client_id).and_then(|ap| {
            if self.floating_panes.panes_are_visible() {
                self.floating_panes.get_pane(ap).map(Box::as_ref)
            } else {
                self.tiled_panes.get_pane(ap).map(Box::as_ref)
            }
        })
    }
    pub fn get_pane_with_id(&self, pane_id: PaneId) -> Option<&dyn Pane> {
        self.floating_panes
            .get_pane(pane_id)
            .map(Box::as_ref)
            .or_else(|| self.tiled_panes.get_pane(pane_id).map(Box::as_ref))
            .or_else(|| self.suppressed_panes.get(&pane_id).map(|p| p.1.as_ref()))
    }
    pub fn get_pane_with_id_mut(&mut self, pane_id: PaneId) -> Option<&mut Box<dyn Pane>> {
        self.floating_panes
            .get_pane_mut(pane_id)
            .or_else(|| self.tiled_panes.get_pane_mut(pane_id))
            .or_else(|| {
                self.suppressed_panes
                    .get_mut(&pane_id)
                    .map(|(_, pane)| pane)
            })
    }
    pub fn get_active_pane_mut(&mut self, client_id: ClientId) -> Option<&mut Box<dyn Pane>> {
        self.get_active_pane_id(client_id).and_then(|ap| {
            if self.floating_panes.panes_are_visible() {
                self.floating_panes.get_pane_mut(ap)
            } else {
                self.tiled_panes.get_pane_mut(ap)
            }
        })
    }
    pub fn get_active_pane_or_floating_pane_mut(
        &mut self,
        client_id: ClientId,
    ) -> Option<&mut Box<dyn Pane>> {
        if self.floating_panes.panes_are_visible() && self.floating_panes.has_active_panes() {
            self.floating_panes.get_active_pane_mut(client_id)
        } else {
            self.get_active_pane_mut(client_id)
        }
    }
    pub fn get_active_pane_id(&self, client_id: ClientId) -> Option<PaneId> {
        if self.floating_panes.panes_are_visible() {
            self.floating_panes.get_active_pane_id(client_id)
        } else {
            self.tiled_panes.get_active_pane_id(client_id)
        }
    }
    fn get_active_terminal_id(&self, client_id: ClientId) -> Option<u32> {
        if let Some(PaneId::Terminal(pid)) = self.get_active_pane_id(client_id) {
            Some(pid)
        } else {
            None
        }
    }
    pub fn check_and_handle_bell_notifications(
        &mut self,
        is_active_tab: bool,
    ) -> (Vec<PaneId>, bool) {
        let mut newly_notified_panes = vec![];
        let mut tab_bell_newly_set = false;

        let focused_pane_ids: HashSet<PaneId> = self
            .connected_clients
            .borrow()
            .iter()
            .filter_map(|c_id| self.get_active_pane_id(*c_id))
            .collect();

        // Collect ringing pane IDs first (immutable borrow)
        let ringing_panes: Vec<PaneId> = self
            .tiled_panes
            .get_panes()
            .chain(self.floating_panes.get_panes())
            .chain(self.suppressed_stack_list_members())
            .filter(|(_, pane)| pane.has_bell())
            .map(|(pane_id, _)| *pane_id)
            .collect();

        for pane_id in ringing_panes {
            // Consume the bell from the pane
            if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
                pane.consume_bell();
            }
            let is_focused = focused_pane_ids.contains(&pane_id);
            if !is_focused && !self.panes_with_pending_bell.contains(&pane_id) {
                if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
                    pane.set_bell_notification(true);
                }
                self.panes_with_pending_bell.insert(pane_id);
                newly_notified_panes.push(pane_id);
            }
            if !self.tab_bell_ring {
                self.tab_bell_ring = true;
                tab_bell_newly_set = true;
            }
            if !is_active_tab {
                self.tab_has_pending_bell = true;
            }
        }
        (newly_notified_panes, tab_bell_newly_set)
    }
    pub fn clear_bell_notification_for_pane(&mut self, pane_id: PaneId) {
        self.panes_with_pending_bell.remove(&pane_id);
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            pane.set_bell_notification(false);
            pane.clear_pane_frame_color_override(None);
        }
        self.tab_has_pending_bell = false;
    }
    pub fn clear_tab_bell_notification(&mut self) {
        self.tab_has_pending_bell = false;
    }
    pub fn clear_tab_bell_ring(&mut self) {
        self.tab_bell_ring = false;
    }
    /// Checks if any pane in the tab has a pending bell, consumes all such bells, and returns
    /// whether any were found. Does not update notification state (used when visual_bell is
    /// disabled but ANSI BEL forwarding is still desired).
    pub fn check_and_consume_bells_without_visual_notification(&mut self) -> bool {
        let ringing_panes: Vec<PaneId> = self
            .tiled_panes
            .get_panes()
            .chain(self.floating_panes.get_panes())
            .chain(self.suppressed_stack_list_members())
            .filter(|(_, pane)| pane.has_bell())
            .map(|(pane_id, _)| *pane_id)
            .collect();
        let had_bell = !ringing_panes.is_empty();
        for pane_id in ringing_panes {
            if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
                pane.consume_bell();
            }
        }
        had_bell
    }
    pub fn has_terminal_pid(&self, pid: u32) -> bool {
        self.tiled_panes.panes_contain(&PaneId::Terminal(pid))
            || self.floating_panes.panes_contain(&PaneId::Terminal(pid))
            || self
                .suppressed_panes
                .values()
                .any(|s_p| s_p.1.pid() == PaneId::Terminal(pid))
    }
    pub fn has_plugin(&self, plugin_id: u32) -> bool {
        self.tiled_panes.panes_contain(&PaneId::Plugin(plugin_id))
            || self
                .floating_panes
                .panes_contain(&PaneId::Plugin(plugin_id))
            || self
                .suppressed_panes
                .values()
                .any(|s_p| s_p.1.pid() == PaneId::Plugin(plugin_id))
    }
    pub fn set_pane_color(
        &mut self,
        pane_id: PaneId,
        fg: Option<String>,
        bg: Option<String>,
    ) -> Result<()> {
        let pane = self
            .floating_panes
            .get_mut(&pane_id)
            .or_else(|| self.tiled_panes.get_pane_mut(pane_id))
            .or_else(|| self.suppressed_panes.get_mut(&pane_id).map(|p| &mut p.1));
        if let Some(pane) = pane {
            pane.set_pane_default_colors(fg, bg);
        }
        Ok(())
    }
    pub fn has_pane_with_pid(&self, pid: &PaneId) -> bool {
        self.tiled_panes.panes_contain(pid)
            || self.floating_panes.panes_contain(pid)
            || self
                .suppressed_panes
                .values()
                .any(|s_p| s_p.1.pid() == *pid)
    }
    pub fn has_non_suppressed_pane_with_pid(&self, pid: &PaneId) -> bool {
        self.tiled_panes.panes_contain(pid) || self.floating_panes.panes_contain(pid)
    }
    pub fn set_pane_is_nested_guest(&mut self, pane_id: PaneId, is_nested_guest: bool) {
        if let Some(pane) = self
            .tiled_panes
            .get_pane_mut(pane_id)
            .or_else(|| self.floating_panes.get_pane_mut(pane_id))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == pane_id)
                    .map(|s_p| &mut s_p.1)
            })
        {
            pane.set_is_nested_guest(is_nested_guest);
        }
    }
    pub fn is_pane_nested_guest(&self, pane_id: PaneId) -> bool {
        if let Some(pane) = self
            .tiled_panes
            .get_pane(pane_id)
            .or_else(|| self.floating_panes.get_pane(pane_id))
            .or_else(|| {
                self.suppressed_panes
                    .values()
                    .find(|s_p| s_p.1.pid() == pane_id)
                    .map(|s_p| &s_p.1)
            })
        {
            pane.is_nested_guest()
        } else {
            false
        }
    }
    pub fn nested_guest_pane_ids(&self) -> Vec<PaneId> {
        self.get_all_pane_ids()
            .into_iter()
            .filter(|pane_id| self.is_pane_nested_guest(*pane_id))
            .collect()
    }
    pub fn set_guest_modal_on_pane(&mut self, pane_id: PaneId, client_ids: &[ClientId]) {
        if let Some(pane) = self
            .tiled_panes
            .get_pane_mut(pane_id)
            .or_else(|| self.floating_panes.get_pane_mut(pane_id))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == pane_id)
                    .map(|s_p| &mut s_p.1)
            })
        {
            pane.set_guest_modal(client_ids);
        }
    }
    pub fn clear_guest_modal_on_pane(&mut self, pane_id: PaneId, client_id: ClientId) {
        if let Some(pane) = self
            .tiled_panes
            .get_pane_mut(pane_id)
            .or_else(|| self.floating_panes.get_pane_mut(pane_id))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == pane_id)
                    .map(|s_p| &mut s_p.1)
            })
        {
            pane.clear_guest_modal(client_id);
        }
    }
    pub fn clear_all_guest_modals_on_pane(&mut self, pane_id: PaneId) {
        if let Some(pane) = self
            .tiled_panes
            .get_pane_mut(pane_id)
            .or_else(|| self.floating_panes.get_pane_mut(pane_id))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == pane_id)
                    .map(|s_p| &mut s_p.1)
            })
        {
            pane.clear_all_guest_modals();
        }
    }
    pub fn set_guest_choice_indicator_on_pane(
        &mut self,
        pane_id: PaneId,
        client_id: ClientId,
        indicator: Option<GuestChoiceIndicator>,
    ) {
        if let Some(pane) = self
            .tiled_panes
            .get_pane_mut(pane_id)
            .or_else(|| self.floating_panes.get_pane_mut(pane_id))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == pane_id)
                    .map(|s_p| &mut s_p.1)
            })
        {
            pane.set_guest_choice_indicator(client_id, indicator);
        }
    }
    pub fn clear_all_guest_choice_indicators_on_pane(&mut self, pane_id: PaneId) {
        if let Some(pane) = self
            .tiled_panes
            .get_pane_mut(pane_id)
            .or_else(|| self.floating_panes.get_pane_mut(pane_id))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == pane_id)
                    .map(|s_p| &mut s_p.1)
            })
        {
            pane.clear_all_guest_choice_indicators();
        }
    }
    pub fn pane_has_guest_modal_for_client(&self, pane_id: PaneId, client_id: ClientId) -> bool {
        if let Some(pane) = self
            .tiled_panes
            .get_pane(pane_id)
            .or_else(|| self.floating_panes.get_pane(pane_id))
            .or_else(|| {
                self.suppressed_panes
                    .values()
                    .find(|s_p| s_p.1.pid() == pane_id)
                    .map(|s_p| &s_p.1)
            })
        {
            pane.guest_modal_selection(client_id).is_some()
        } else {
            false
        }
    }
    pub fn clear_guest_modal_for_client_on_all_panes(&mut self, client_id: ClientId) {
        for pane_id in self.get_all_pane_ids() {
            self.clear_guest_modal_on_pane(pane_id, client_id);
        }
    }
    pub fn clear_guest_choice_indicator_for_client_on_all_panes(&mut self, client_id: ClientId) {
        for pane_id in self.get_all_pane_ids() {
            self.set_guest_choice_indicator_on_pane(pane_id, client_id, None);
        }
    }
    pub fn set_guest_session_name_on_pane(
        &mut self,
        pane_id: PaneId,
        session_name: Option<String>,
    ) {
        if let Some(pane) = self
            .tiled_panes
            .get_pane_mut(pane_id)
            .or_else(|| self.floating_panes.get_pane_mut(pane_id))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == pane_id)
                    .map(|s_p| &mut s_p.1)
            })
        {
            pane.set_guest_session_name(session_name);
        }
    }
    pub fn set_guest_modal_shortcuts_on_pane(
        &mut self,
        pane_id: PaneId,
        shortcuts: GuestModalShortcuts,
    ) {
        if let Some(pane) = self
            .tiled_panes
            .get_pane_mut(pane_id)
            .or_else(|| self.floating_panes.get_pane_mut(pane_id))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == pane_id)
                    .map(|s_p| &mut s_p.1)
            })
        {
            pane.set_guest_modal_shortcuts(shortcuts);
        }
    }
    pub fn set_shadow_focus(&mut self, client_id: ClientId, pane_id: PaneId) -> bool {
        if self.tiled_panes.panes_contain(&pane_id) {
            self.tiled_panes.set_shadow_focus(client_id, pane_id);
            true
        } else if self.floating_panes.panes_contain(&pane_id) {
            self.floating_panes.set_shadow_focus(client_id, pane_id);
            true
        } else {
            false
        }
    }
    pub fn clear_shadow_focus(&mut self, client_id: ClientId) {
        if self.tiled_panes.is_shadow_focus_client(&client_id) {
            self.tiled_panes.clear_shadow_focus(client_id);
        }
        if self.floating_panes.is_shadow_focus_client(&client_id) {
            self.floating_panes.clear_shadow_focus(client_id);
        }
    }
    pub fn shadow_focus_clients(&self) -> Vec<ClientId> {
        let mut out = self.tiled_panes.shadow_focus_clients();
        out.extend(self.floating_panes.shadow_focus_clients());
        out.sort_unstable();
        out.dedup();
        out
    }
    pub fn has_shadow_focus_on(&self, client_id: ClientId, pane_id: PaneId) -> bool {
        self.tiled_panes.has_shadow_focus_on(client_id, pane_id)
            || self.floating_panes.has_shadow_focus_on(client_id, pane_id)
    }
    pub fn handle_pty_bytes(&mut self, pid: u32, bytes: VteBytes) -> Result<()> {
        if self.is_pending {
            self.pending_instructions
                .push(BufferedTabInstruction::HandlePtyBytes(pid, bytes));
            return Ok(());
        }
        let err_context = || format!("failed to handle pty bytes from fd {pid}");
        if let Some(terminal_output) = self
            .tiled_panes
            .get_pane_mut(PaneId::Terminal(pid))
            .or_else(|| self.floating_panes.get_pane_mut(PaneId::Terminal(pid)))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == PaneId::Terminal(pid))
                    .map(|s_p| &mut s_p.1)
            })
        {
            // If the pane is scrolled buffer the vte events
            if terminal_output.is_scrolled() {
                self.pending_vte_events.entry(pid).or_default().push(bytes);
                if let Some(evs) = self.pending_vte_events.get(&pid) {
                    // Reset scroll - and process all pending events for this pane
                    if evs.len() >= MAX_PENDING_VTE_EVENTS {
                        terminal_output.clear_scroll();
                        self.process_pending_vte_events(pid)
                            .with_context(err_context)?;
                    }
                }
                return Ok(());
            }
        }
        self.process_pty_bytes(pid, bytes).with_context(err_context)
    }
    pub fn handle_plugin_bytes(
        &mut self,
        pid: u32,
        client_id: ClientId,
        bytes: VteBytes,
    ) -> Result<()> {
        if let Some(plugin_pane) = self
            .tiled_panes
            .get_pane_mut(PaneId::Plugin(pid))
            .or_else(|| self.floating_panes.get_pane_mut(PaneId::Plugin(pid)))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == PaneId::Plugin(pid))
                    .map(|s_p| &mut s_p.1)
            })
        {
            plugin_pane.handle_plugin_bytes(client_id, bytes);
        }
        Ok(())
    }
    pub fn process_pending_vte_events(&mut self, pid: u32) -> Result<()> {
        if let Some(pending_vte_events) = self.pending_vte_events.get_mut(&pid) {
            let vte_events: Vec<VteBytes> = pending_vte_events.drain(..).collect();
            for vte_event in vte_events {
                self.process_pty_bytes(pid, vte_event)
                    .context("failed to process pending vte events")?;
            }
        }
        Ok(())
    }
    /// Deliver a forwarded host reply (or cache-fallback synthesis,
    /// or a locally-answered query payload) to a pane that is currently
    /// forward-paused. The reply bytes are written to the pane's PTY
    /// first (so the app reads them on its stdin in the same stream
    /// position the original query occupied), then the pause flag is
    /// cleared and any PTY bytes that arrived while the pane was
    /// paused are re-fed through vte. The re-feed itself may produce
    /// another forward and re-arm the pause; the cycle bounds at the
    /// buffered byte count.
    pub fn resume_pane_after_forward(&mut self, pid: u32, reply_bytes: Vec<u8>) -> Result<()> {
        let err_context = || format!("failed to resume pane {pid} after forward");
        // Write the reply first so the app sees it on stdin before
        // any subsequent (sync or async) reply that follows in the
        // buffered byte stream.
        if !reply_bytes.is_empty() {
            self.write_to_pane_id_without_preprocessing(reply_bytes, PaneId::Terminal(pid))
                .with_context(err_context)?;
        }
        // Clear the pause and pull out any bytes that were buffered
        // while it waited for the host reply.
        let buffered = if let Some(terminal_output) = self
            .tiled_panes
            .get_pane_mut(PaneId::Terminal(pid))
            .or_else(|| self.floating_panes.get_pane_mut(PaneId::Terminal(pid)))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == PaneId::Terminal(pid))
                    .map(|s_p| &mut s_p.1)
            }) {
            terminal_output.clear_forward_pause();
            terminal_output.drain_pending_pty_input()
        } else {
            // Pane closed between forward dispatch and reply arrival.
            return Ok(());
        };
        if !buffered.is_empty() {
            self.process_pty_bytes(pid, buffered)
                .with_context(err_context)?;
        }
        Ok(())
    }
    fn process_pty_bytes(&mut self, pid: u32, bytes: VteBytes) -> Result<()> {
        let err_context = || format!("failed to process pty bytes from pid {pid}");

        if let Some(terminal_output) = self
            .tiled_panes
            .get_pane_mut(PaneId::Terminal(pid))
            .or_else(|| self.floating_panes.get_pane_mut(PaneId::Terminal(pid)))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == PaneId::Terminal(pid))
                    .map(|s_p| &mut s_p.1)
            })
        {
            if self.pids_waiting_resize.remove(&pid) {
                resize_pty!(
                    terminal_output,
                    self.os_api,
                    self.senders,
                    self.character_cell_size
                )
                .with_context(err_context)?;
            }
            terminal_output.handle_pty_bytes(bytes);
            let messages_to_pty = terminal_output.drain_messages_to_pty();
            let forwarded_queries = terminal_output.drain_forwarded_queries();
            // If at least one forward was produced, the pane stopped
            // processing its `pending_pty_input` queue at the byte
            // that produced the forward. Arm the pause so subsequent
            // PTY bytes accumulate in the same queue rather than
            // being processed; they will be drained in stream order
            // when the host reply (or cache-fallback synthesis, or
            // 500 ms timeout) lands via `resume_pane_after_forward`.
            // Pause arming is independent of which forward bears the
            // reply: resume is keyed by pane_id, not by token, so a
            // single flag suffices for any number of queued forwards.
            if !forwarded_queries.is_empty() {
                terminal_output.arm_forward_pause();
            }
            let nested_session_messages = terminal_output.drain_nested_session_messages();
            let clipboard_update = terminal_output.drain_clipboard_update();
            let desktop_notifications = terminal_output.drain_desktop_notifications();
            let osc7_cwd = terminal_output.drain_osc7_cwd();
            for message in messages_to_pty {
                self.write_to_pane_id_without_preprocessing(message, PaneId::Terminal(pid))
                    .with_context(err_context)?;
            }
            for query in forwarded_queries {
                let _ = self
                    .senders
                    .send_to_screen(ScreenInstruction::ForwardHostQuery {
                        pane_id: PaneId::Terminal(pid),
                        query,
                    });
            }
            for message in nested_session_messages {
                let _ =
                    self.senders
                        .send_to_screen(ScreenInstruction::NestedSessionMessageFromPane {
                            pane_id: PaneId::Terminal(pid),
                            message,
                        });
            }
            if let Some(string) = clipboard_update {
                self.write_selection_to_clipboard(&string)
                    .with_context(err_context)?;
            }
            if !desktop_notifications.is_empty() {
                self.forward_desktop_notifications(desktop_notifications, pid)
                    .with_context(err_context)?;
            }
            if let Some(path) = osc7_cwd {
                let _ = self
                    .senders
                    .send_to_pty(PtyInstruction::NotifyCwdFromOsc7(pid, path));
            }
        }
        Ok(())
    }

    pub fn write_to_terminals_on_current_tab(
        &mut self,
        key_with_modifier: &Option<KeyWithModifier>,
        raw_input_bytes: Vec<u8>,
        raw_input_bytes_are_kitty: bool,
        client_id: ClientId,
    ) -> Result<bool> {
        // returns true if a UI update should be triggered (eg. when closing a command pane with
        // ctrl-c)
        let mut should_trigger_ui_change = false;
        let mut pane_ids = self.get_static_and_floating_pane_ids();
        pane_ids.extend(
            self.stack_list_of_member
                .keys()
                .filter(|member| self.pane_is_hidden_stack_list_member(member))
                .copied(),
        );
        for pane_id in pane_ids {
            let ui_change_triggered = self
                .write_to_pane_id(
                    key_with_modifier,
                    raw_input_bytes.clone(),
                    raw_input_bytes_are_kitty,
                    pane_id,
                    Some(client_id),
                    None,
                )
                .context("failed to write to terminals on current tab")?;
            if ui_change_triggered {
                should_trigger_ui_change = true;
            }
        }
        Ok(should_trigger_ui_change)
    }

    pub fn write_to_active_terminal(
        &mut self,
        key_with_modifier: &Option<KeyWithModifier>,
        raw_input_bytes: Vec<u8>,
        raw_input_bytes_are_kitty: bool,
        client_id: ClientId,
    ) -> Result<bool> {
        // returns true if a UI update should be triggered (eg. if a command pane
        // was closed with ctrl-c)
        let err_context = || {
            format!(
                "failed to write to active terminal for client {client_id} - msg: {raw_input_bytes:?}"
            )
        };

        self.clear_search(client_id);
        self.mouse_help_text_visible.clear();
        let pane_id = if self.floating_panes.panes_are_visible() {
            self.floating_panes
                .get_active_pane_id(client_id)
                .or_else(|| self.tiled_panes.get_active_pane_id(client_id))
                .ok_or_else(|| {
                    anyhow!(format!(
                        "failed to find active pane id for client {client_id}"
                    ))
                })
                .with_context(err_context)?
        } else {
            self.tiled_panes
                .get_active_pane_id(client_id)
                .with_context(err_context)?
        };
        // Can't use 'err_context' here since it borrows 'raw_input_bytes'
        self.write_to_pane_id(
            key_with_modifier,
            raw_input_bytes,
            raw_input_bytes_are_kitty,
            pane_id,
            Some(client_id),
            None,
        )
        .with_context(|| format!("failed to write to active terminal for client {client_id}"))
    }

    pub fn write_to_terminal_at(
        &mut self,
        input_bytes: Vec<u8>,
        position: &Position,
        client_id: ClientId,
    ) -> Result<()> {
        let err_context = || format!("failed to write to terminal at position {position:?}");

        if self.floating_panes.panes_are_visible() {
            let pane_id = self
                .floating_panes
                .get_pane_id_at(position, false)
                .with_context(err_context)?;
            if let Some(pane_id) = pane_id {
                self.write_to_pane_id(&None, input_bytes, false, pane_id, Some(client_id), None)
                    .with_context(err_context)?;
                return Ok(());
            }
        }

        let pane_id = self
            .get_pane_id_at(position, false)
            .with_context(err_context)?;
        if let Some(pane_id) = pane_id {
            self.write_to_pane_id(&None, input_bytes, false, pane_id, Some(client_id), None)
                .with_context(err_context)?;
            return Ok(());
        }
        Ok(())
    }

    pub fn paste_to_pane_id(
        &mut self,
        bytes: Vec<u8>,
        pane_id: PaneId,
        completion: Option<NotificationEnd>,
    ) -> Result<()> {
        let bracketed_paste_begin = vec![27, 91, 50, 48, 48, 126];
        let bracketed_paste_end = vec![27, 91, 50, 48, 49, 126];

        self.write_to_pane_id(&None, bracketed_paste_begin, false, pane_id, None, None)?;
        self.write_to_pane_id(&None, bytes, false, pane_id, None, None)?;
        self.write_to_pane_id(&None, bracketed_paste_end, false, pane_id, None, completion)?;
        Ok(())
    }

    pub fn paste_to_active_terminal(
        &mut self,
        bytes: Vec<u8>,
        client_id: ClientId,
        completion: Option<NotificationEnd>,
    ) -> Result<()> {
        let err_context = || format!("failed to paste to active terminal for client {client_id}");
        let active_pane_id = self
            .get_active_pane_id(client_id)
            .ok_or_else(|| anyhow!("no active pane for client {client_id}"))
            .with_context(err_context)?;
        self.paste_to_pane_id(bytes, active_pane_id, completion)
    }

    pub fn write_to_pane_id(
        &mut self,
        key_with_modifier: &Option<KeyWithModifier>,
        raw_input_bytes: Vec<u8>,
        raw_input_bytes_are_kitty: bool,
        pane_id: PaneId,
        client_id: Option<ClientId>,
        completion_tx: Option<NotificationEnd>,
    ) -> Result<bool> {
        // returns true if we need to update the UI (eg. when a command pane is closed with ctrl-c)
        let err_context = || format!("failed to write to pane with id {pane_id:?}");

        let mut should_update_ui = false;
        let is_sync_panes_active = self.is_sync_panes_active();

        let active_pane = self
            .floating_panes
            .get_mut(&pane_id)
            .or_else(|| self.tiled_panes.get_pane_mut(pane_id))
            .or_else(|| self.suppressed_panes.get_mut(&pane_id).map(|p| &mut p.1))
            .ok_or_else(|| anyhow!(format!("failed to find pane with id {pane_id:?}")))
            .with_context(err_context)?;

        // We always write for non-synced terminals.
        // However if the terminal is part of a tab-sync, we need to
        // check if the terminal should receive input or not (depending on its
        // 'exclude_from_sync' configuration).
        let should_not_write_to_terminal = is_sync_panes_active && active_pane.exclude_from_sync();

        if should_not_write_to_terminal {
            return Ok(should_update_ui);
        }

        match pane_id {
            PaneId::Terminal(active_terminal_id) => {
                match active_pane.adjust_input_to_terminal(
                    key_with_modifier,
                    raw_input_bytes,
                    raw_input_bytes_are_kitty,
                    client_id,
                ) {
                    Some(AdjustedInput::WriteBytesToTerminal(adjusted_input)) => {
                        self.senders
                            .send_to_pty_writer(PtyWriteInstruction::Write(
                                adjusted_input,
                                active_terminal_id,
                                completion_tx,
                            ))
                            .with_context(err_context)?;
                    },
                    Some(AdjustedInput::ReRunCommandInThisPane(command)) => {
                        self.pids_waiting_resize.insert(active_terminal_id);
                        self.senders
                            .send_to_pty(PtyInstruction::ReRunCommandInPane(
                                PaneId::Terminal(active_terminal_id),
                                command,
                                completion_tx,
                            ))
                            .with_context(err_context)?;
                        should_update_ui = true;
                    },
                    Some(AdjustedInput::CloseThisPane) => {
                        self.close_pane(PaneId::Terminal(active_terminal_id), false, None);
                        should_update_ui = true;
                    },
                    Some(AdjustedInput::DropToShellInThisPane { working_dir }) => {
                        self.pids_waiting_resize.insert(active_terminal_id);
                        self.senders
                            .send_to_pty(PtyInstruction::DropToShellInPane {
                                pane_id: PaneId::Terminal(active_terminal_id),
                                shell: Some(self.default_shell.clone()),
                                working_dir,
                                completion_tx,
                            })
                            .with_context(err_context)?;
                        should_update_ui = true;
                    },
                    Some(AdjustedInput::GuestModalSelectionChanged) => {
                        should_update_ui = true;
                    },
                    Some(AdjustedInput::GuestModalZoom) => {
                        if let Some(client_id) = client_id {
                            let _ =
                                self.senders
                                    .send_to_screen(ScreenInstruction::GuestModalChoice {
                                        client_id,
                                        pane_id: PaneId::Terminal(active_terminal_id),
                                        outcome: GuestModalOutcome::Zoom,
                                    });
                        }
                    },
                    Some(AdjustedInput::GuestModalDescend) => {
                        if let Some(client_id) = client_id {
                            let _ =
                                self.senders
                                    .send_to_screen(ScreenInstruction::GuestModalChoice {
                                        client_id,
                                        pane_id: PaneId::Terminal(active_terminal_id),
                                        outcome: GuestModalOutcome::Descend,
                                    });
                        }
                    },
                    Some(_) => {},
                    None => {},
                }
            },
            PaneId::Plugin(pid) => match active_pane.adjust_input_to_terminal(
                key_with_modifier,
                raw_input_bytes,
                raw_input_bytes_are_kitty,
                client_id,
            ) {
                Some(AdjustedInput::WriteKeyToPlugin(key_with_modifier)) => {
                    self.senders
                        .send_to_plugin(PluginInstruction::Update(vec![(
                            Some(pid),
                            client_id,
                            Event::Key(key_with_modifier),
                        )]))
                        .with_context(err_context)?;
                },
                Some(AdjustedInput::WriteBytesToTerminal(adjusted_input)) => {
                    let mut plugin_updates = vec![];
                    for key in parse_keys(&adjusted_input) {
                        plugin_updates.push((Some(pid), client_id, Event::Key(key)));
                    }
                    self.senders
                        .send_to_plugin(PluginInstruction::Update(plugin_updates))
                        .with_context(err_context)?;
                },
                Some(AdjustedInput::PermissionRequestResult(permissions, status)) => {
                    if active_pane.query_should_be_suppressed() {
                        active_pane.set_should_be_suppressed(false);
                        self.suppress_pane(PaneId::Plugin(pid), client_id);
                    }
                    self.request_plugin_permissions(pid, None);
                    self.senders
                        .send_to_plugin(PluginInstruction::PermissionRequestResult(
                            pid,
                            client_id,
                            permissions,
                            status,
                            None,
                        ))
                        .with_context(err_context)?;
                    should_update_ui = true;
                },
                Some(_) => {},
                None => {},
            },
        }
        Ok(should_update_ui)
    }
    pub fn write_to_pane_id_without_preprocessing(
        &mut self,
        raw_input_bytes: Vec<u8>,
        pane_id: PaneId,
    ) -> Result<bool> {
        // returns true if we need to update the UI (eg. when a command pane is closed with ctrl-c)
        let err_context = || format!("failed to write to pane with id {pane_id:?}");

        let mut should_update_ui = false;

        match pane_id {
            PaneId::Terminal(active_terminal_id) => {
                self.senders
                    .send_to_pty_writer(PtyWriteInstruction::Write(
                        raw_input_bytes,
                        active_terminal_id,
                        None,
                    ))
                    .with_context(err_context)?;
                should_update_ui = true;
            },
            PaneId::Plugin(_pid) => {
                log::error!("Unsupported plugin action");
            },
        }
        Ok(should_update_ui)
    }
    pub fn active_terminal_is_mid_frame(&self, client_id: ClientId) -> Option<bool> {
        let active_pane_id = if self.floating_panes.panes_are_visible() {
            self.floating_panes
                .get_active_pane_id(client_id)
                .or_else(|| self.tiled_panes.get_active_pane_id(client_id))?
        } else {
            self.tiled_panes.get_active_pane_id(client_id)?
        };
        let active_terminal = &self
            .floating_panes
            .get(&active_pane_id)
            .or_else(|| self.tiled_panes.get_pane(active_pane_id))?;
        Some(active_terminal.is_mid_frame())
    }
    pub fn get_active_terminal_cursor_position(
        &self,
        client_id: ClientId,
    ) -> Option<(usize, usize, bool)> {
        // (x, y, is_cursor_visible)
        let active_pane_id = if self.floating_panes.panes_are_visible() {
            self.floating_panes
                .get_active_pane_id(client_id)
                .or_else(|| self.tiled_panes.get_active_pane_id(client_id))?
        } else {
            self.tiled_panes.get_active_pane_id(client_id)?
        };
        let active_terminal = &self
            .floating_panes
            .get(&active_pane_id)
            .or_else(|| self.tiled_panes.get_pane(active_pane_id))?;
        active_terminal.cursor_coordinates(Some(client_id)).map(
            |(x_in_terminal, y_in_terminal, is_visible)| {
                let x = active_terminal.x() + x_in_terminal;
                let y = active_terminal.y() + y_in_terminal;
                (x, y, is_visible)
            },
        )
    }
    pub fn toggle_active_pane_fullscreen(&mut self, client_id: ClientId) {
        if self.floating_panes.fullscreen_is_active()
            || (self.floating_panes.panes_are_visible() && self.floating_panes.has_active_panes())
        {
            self.floating_panes.toggle_active_pane_fullscreen(client_id);
            self.set_force_render();
            self.set_should_clear_display_before_rendering();
            return;
        }
        if self.floating_panes.panes_are_visible() {
            return;
        }
        self.dissolve_stack_lists_for_classic_mutation();
        self.tiled_panes.toggle_active_pane_fullscreen(client_id);
    }
    pub fn toggle_pane_fullscreen(&mut self, pane_id: PaneId) {
        if self.floating_panes.panes_contain(&pane_id) {
            self.floating_panes.toggle_pane_fullscreen(pane_id);
            self.set_force_render();
            self.set_should_clear_display_before_rendering();
            return;
        }
        if self.pane_is_hidden_stack_list_member(&pane_id) {
            self.make_hidden_stack_list_member_visible(pane_id);
        }
        self.dissolve_stack_lists_for_classic_mutation();
        if self.tiled_panes.panes_contain(&pane_id) {
            self.tiled_panes.toggle_pane_fullscreen(pane_id);
        } else {
            log::error!("No tiled pane with id: {:?} found", pane_id);
        }
    }
    pub fn toggle_active_pane_no_ui_fullscreen(&mut self, client_id: ClientId) {
        if self.floating_panes.fullscreen_is_active()
            || (self.floating_panes.panes_are_visible() && self.floating_panes.has_active_panes())
        {
            self.floating_panes
                .toggle_active_pane_no_ui_fullscreen(client_id);
            self.set_force_render();
            self.set_should_clear_display_before_rendering();
            return;
        }
        if self.floating_panes.panes_are_visible() {
            return;
        }
        self.dissolve_stack_lists_for_classic_mutation();
        self.tiled_panes
            .toggle_active_pane_no_ui_fullscreen(client_id);
    }
    pub fn toggle_pane_no_ui_fullscreen(&mut self, pane_id: PaneId) {
        if self.floating_panes.panes_contain(&pane_id) {
            self.floating_panes.toggle_pane_no_ui_fullscreen(pane_id);
            self.set_force_render();
            self.set_should_clear_display_before_rendering();
            return;
        }
        if self.pane_is_hidden_stack_list_member(&pane_id) {
            self.make_hidden_stack_list_member_visible(pane_id);
        }
        self.dissolve_stack_lists_for_classic_mutation();
        if self.tiled_panes.panes_contain(&pane_id) {
            self.tiled_panes.toggle_pane_no_ui_fullscreen(pane_id);
        } else {
            log::error!("No tiled pane with id: {:?} found", pane_id);
        }
    }
    pub fn is_fullscreen_active(&self) -> bool {
        self.tiled_panes.fullscreen_is_active() || self.floating_panes.fullscreen_is_active()
    }
    pub fn fullscreen_covers_ui(&self) -> bool {
        self.tiled_panes.fullscreen_covers_ui() || self.floating_panes.fullscreen_covers_ui()
    }
    pub fn fullscreen_pane_id(&self) -> Option<PaneId> {
        self.tiled_panes
            .fullscreen_pane_id()
            .or_else(|| self.floating_panes.fullscreen_pane_id())
    }
    pub fn are_floating_panes_visible(&self) -> bool {
        self.floating_panes.panes_are_visible()
    }
    pub fn focus_pane_left_fullscreen(&mut self, client_id: ClientId) -> bool {
        if !self.is_fullscreen_active() {
            return false;
        }

        return self.tiled_panes.focus_pane_left_fullscreen(client_id);
    }
    pub fn focus_pane_right_fullscreen(&mut self, client_id: ClientId) -> bool {
        if !self.is_fullscreen_active() {
            return false;
        }

        return self.tiled_panes.focus_pane_right_fullscreen(client_id);
    }
    pub fn focus_pane_up_fullscreen(&mut self, client_id: ClientId) -> bool {
        if !self.is_fullscreen_active() {
            return false;
        }

        return self.tiled_panes.focus_pane_up_fullscreen(client_id);
    }
    pub fn focus_pane_down_fullscreen(&mut self, client_id: ClientId) -> bool {
        if !self.is_fullscreen_active() {
            return false;
        }

        return self.tiled_panes.focus_pane_down_fullscreen(client_id);
    }
    pub fn switch_next_pane_fullscreen(&mut self, client_id: ClientId) {
        if !self.is_fullscreen_active() {
            return;
        }
        self.tiled_panes.switch_next_pane_fullscreen(client_id);
    }
    pub fn switch_prev_pane_fullscreen(&mut self, client_id: ClientId) {
        if !self.is_fullscreen_active() {
            return;
        }
        self.tiled_panes.switch_prev_pane_fullscreen(client_id);
    }
    pub fn switch_last_pane_fullscreen(&mut self, client_id: ClientId) {
        if !self.is_fullscreen_active() {
            return;
        }
        self.tiled_panes.switch_last_pane_fullscreen(client_id);
    }
    pub fn set_force_render(&mut self) {
        self.tiled_panes.set_force_render();
        self.floating_panes.set_force_render();
        for member in self.stack_list_of_member.keys() {
            if let Some((_is_scrollback_editor, pane)) = self.suppressed_panes.get_mut(member) {
                pane.set_should_render(true);
                pane.render_full_viewport();
            }
        }
    }
    pub fn set_should_clear_display_before_rendering(&mut self) {
        self.should_clear_display_before_rendering = true;
        self.floating_panes.set_force_render(); // we do this to make sure pinned panes are
                                                // rendered even if their surface is not visible
    }
    #[cfg(test)]
    pub fn should_clear_display_before_rendering(&self) -> bool {
        self.should_clear_display_before_rendering
    }
    pub fn is_sync_panes_active(&self) -> bool {
        self.synchronize_is_active
    }
    pub fn toggle_sync_panes_is_active(&mut self) {
        self.synchronize_is_active = !self.synchronize_is_active;
    }
    pub fn mark_active_pane_for_rerender(&mut self, client_id: ClientId) {
        if let Some(active_pane) = self.get_active_pane_mut(client_id) {
            active_pane.set_should_render(true);
        }
    }
    fn update_active_panes_in_pty_thread(&self) -> Result<()> {
        // this is a bit hacky and we should ideally not keep this state in two different places at
        // some point
        let connected_clients: Vec<ClientId> =
            { self.connected_clients.borrow().iter().copied().collect() };
        for client_id in connected_clients {
            self.senders
                .send_to_pty(PtyInstruction::UpdateActivePane(
                    self.get_active_pane_id(client_id),
                    client_id,
                ))
                .with_context(|| format!("failed to update active pane for client {client_id}"))?;
        }
        Ok(())
    }

    pub fn render(
        &mut self,
        output: &mut Output,
        client_id_override: Option<ClientId>,
    ) -> Result<()> {
        let err_context = || "failed to render tab".to_string();

        let mut connected_clients: HashSet<ClientId> =
            { self.connected_clients.borrow().iter().copied().collect() };

        // If we have a client_id_override (for watcher rendering), add it temporarily
        if let Some(override_id) = client_id_override {
            connected_clients.insert(override_id);
        }

        if connected_clients.is_empty() || !self.tiled_panes.has_active_panes() {
            return Ok(());
        }
        if self.stacked_pane_list_is_active() {
            self.groupify_all();
        }
        self.update_active_panes_in_pty_thread()
            .with_context(err_context)?;

        let floating_panes_stack = self.floating_panes.stack();
        output.add_clients(
            &connected_clients,
            self.link_handler.clone(),
            floating_panes_stack,
        );

        let current_pane_group: HashMap<ClientId, Vec<PaneId>> =
            { self.current_pane_group.borrow().clone_inner() };
        self.tiled_panes
            .render(
                output,
                self.floating_panes.panes_are_visible(),
                &self.mouse_hover_pane_id,
                current_pane_group.clone(),
                client_id_override,
                &self.mouse_help_text_visible,
                self.mouse_scroll_resize,
            )
            .with_context(err_context)?;
        self.render_stack_list_headers(output, client_id_override)
            .with_context(err_context)?;
        let no_ui_fullscreen_active = self.tiled_panes.fullscreen_covers_ui();
        if !no_ui_fullscreen_active
            && ((self.floating_panes.panes_are_visible() && self.floating_panes.has_active_panes())
                || self.floating_panes.has_pinned_panes())
        {
            self.floating_panes
                .render(
                    output,
                    &self.mouse_hover_pane_id,
                    current_pane_group,
                    client_id_override,
                    &self.mouse_help_text_visible,
                    self.mouse_scroll_resize,
                )
                .with_context(err_context)?;
        }

        self.render_cursor(output);
        if output.has_rendered_assets() {
            self.hide_cursor_and_clear_display_as_needed(output);
        }

        self.emit_hint_text_if_changed().with_context(err_context)?;
        self.emit_active_pane_scroll_if_changed()
            .with_context(err_context)?;

        Ok(())
    }

    fn hide_cursor_and_clear_display_as_needed(&mut self, output: &mut Output) {
        let hide_cursor = "\u{1b}[?25l";
        let connected_clients: Vec<ClientId> =
            { self.connected_clients.borrow().iter().copied().collect() };
        output.add_pre_vte_instruction_to_multiple_clients(
            connected_clients.iter().copied(),
            hide_cursor,
        );
        if self.should_clear_display_before_rendering {
            let clear_display = "\u{1b}[m\u{1b}[2J";
            output.add_pre_vte_instruction_to_multiple_clients(
                connected_clients.iter().copied(),
                clear_display,
            );
            output.mark_host_display_cleared_for_clients(connected_clients.iter().copied());
            self.should_clear_display_before_rendering = false;
        }
    }
    fn render_cursor(&mut self, output: &mut Output) {
        let connected_clients: Vec<ClientId> =
            { self.connected_clients.borrow().iter().copied().collect() };
        for client_id in connected_clients {
            match self.get_active_terminal_cursor_position(client_id) {
                Some((cursor_position_x, cursor_position_y, is_cursor_visible)) => {
                    let active_pane_z_index = self
                        .get_active_pane_id(client_id)
                        .and_then(|pane_id| self.floating_panes.get_pane_z_index(pane_id));
                    let not_occluded = output.cursor_is_visible(
                        cursor_position_x,
                        cursor_position_y,
                        active_pane_z_index,
                    );
                    let active_terminal_is_mid_frame = self
                        .active_terminal_is_mid_frame(client_id)
                        .unwrap_or(false);

                    if active_terminal_is_mid_frame {
                        // no-op, this means the active terminal is currently rendering a frame,
                        // which means the cursor can be jumping around and we definitely do not
                        // want to render it
                    } else if not_occluded && is_cursor_visible {
                        let desired_cursor_shape = self
                            .get_active_pane(client_id)
                            .map(|ap| ap.cursor_shape_csi())
                            .unwrap_or_default();
                        let cursor_changed_position_or_shape = self
                            .cursor_positions_and_shape
                            .get(&client_id)
                            .map(|(previous_x, previous_y, previous_shape)| {
                                previous_x != &cursor_position_x
                                    || previous_y != &cursor_position_y
                                    || previous_shape != &desired_cursor_shape
                            })
                            .unwrap_or(true);
                        if output.is_dirty() || cursor_changed_position_or_shape {
                            let show_cursor = "\u{1b}[?25h";
                            let goto_cursor_position = &format!(
                                "\u{1b}[{};{}H\u{1b}[m{}",
                                cursor_position_y + 1,
                                cursor_position_x + 1,
                                desired_cursor_shape
                            ); // goto row/col
                            output.add_post_vte_instruction_to_client(client_id, show_cursor);
                            output.add_post_vte_instruction_to_client(
                                client_id,
                                goto_cursor_position,
                            );
                            self.cursor_positions_and_shape.insert(
                                client_id,
                                (cursor_position_x, cursor_position_y, desired_cursor_shape),
                            );
                        }
                    } else if not_occluded {
                        // Cursor is hidden by the app but not occluded by a floating
                        // pane. Position the host terminal cursor at the correct
                        // location (for IME) then hide it. The IME subsystem reads
                        // the cursor position regardless of visibility.
                        let hide_cursor = "\u{1b}[?25l";
                        let goto_cursor_position = &format!(
                            "\u{1b}[{};{}H",
                            cursor_position_y + 1,
                            cursor_position_x + 1,
                        );
                        output.add_post_vte_instruction_to_client(client_id, hide_cursor);
                        output.add_post_vte_instruction_to_client(client_id, goto_cursor_position);
                    } else {
                        let hide_cursor = "\u{1b}[?25l";
                        output.add_post_vte_instruction_to_client(client_id, hide_cursor);
                    }
                },
                None => {
                    let hide_cursor = "\u{1b}[?25l";
                    output.add_post_vte_instruction_to_client(client_id, hide_cursor);
                },
            }
        }
    }
    pub(crate) fn get_tiled_panes(&self) -> impl Iterator<Item = (&PaneId, &Box<dyn Pane>)> {
        self.tiled_panes.get_panes()
    }
    pub(crate) fn get_floating_panes(&self) -> impl Iterator<Item = (&PaneId, &Box<dyn Pane>)> {
        self.floating_panes.get_panes()
    }
    pub(crate) fn get_suppressed_panes(
        &self,
    ) -> impl Iterator<Item = (&PaneId, &(bool, Box<dyn Pane>))> {
        // bool => is_scrollback_editor
        self.suppressed_panes.iter()
    }
    fn get_selectable_tiled_panes(&self) -> impl Iterator<Item = (&PaneId, &Box<dyn Pane>)> {
        self.get_tiled_panes().filter(|(_, p)| p.selectable())
    }
    fn get_selectable_floating_panes(&self) -> impl Iterator<Item = (&PaneId, &Box<dyn Pane>)> {
        self.get_floating_panes().filter(|(_, p)| p.selectable())
    }
    pub fn get_selectable_tiled_panes_count(&self) -> usize {
        self.get_selectable_tiled_panes().count()
    }
    pub fn get_selectable_floating_panes_count(&self) -> usize {
        self.get_selectable_floating_panes().count()
    }
    pub fn get_visible_selectable_floating_panes_count(&self) -> usize {
        if self.are_floating_panes_visible() {
            self.get_selectable_floating_panes().count()
        } else {
            0
        }
    }
    fn get_next_terminal_position(&self) -> usize {
        let tiled_panes_count = self
            .tiled_panes
            .get_panes()
            .filter(|(k, _)| match k {
                PaneId::Plugin(_) => false,
                PaneId::Terminal(_) => true,
            })
            .count();
        let floating_panes_count = self
            .floating_panes
            .get_panes()
            .filter(|(k, _)| match k {
                PaneId::Plugin(_) => false,
                PaneId::Terminal(_) => true,
            })
            .count();
        let hidden_stack_list_members_count = self
            .suppressed_stack_list_members()
            .filter(|(pane_id, _)| matches!(pane_id, PaneId::Terminal(_)))
            .count();
        tiled_panes_count + floating_panes_count + hidden_stack_list_members_count + 1
    }
    pub fn has_selectable_panes(&self) -> bool {
        let selectable_tiled_panes = self.tiled_panes.get_panes().filter(|(_, p)| p.selectable());
        let selectable_floating_panes = self
            .floating_panes
            .get_panes()
            .filter(|(_, p)| p.selectable());
        selectable_tiled_panes.count() > 0 || selectable_floating_panes.count() > 0
    }
    pub fn has_selectable_tiled_panes(&self) -> bool {
        let selectable_tiled_panes = self.tiled_panes.get_panes().filter(|(_, p)| p.selectable());
        selectable_tiled_panes.count() > 0
    }
    /// Collapse into a narrow layout when the terminal is too narrow, and spread
    /// back out when it grows again.
    ///
    /// Hysteresis: collapsing happens below `responsive_min_cols`, expanding only
    /// above `responsive_min_cols + RESPONSIVE_HYSTERESIS_COLS`. Without a dead
    /// band, dragging a terminal edge that lands exactly on the threshold flips
    /// the layout on every motion event, and each flip resizes every PTY.
    ///
    /// BOTH directions resolve their target from the panes as they are now,
    /// rather than replaying a remembered one. Remembering a position was the
    /// source of every bug this feature has had: the remembered layout stops
    /// applying when the pane count changes, positions are only stable if
    /// nothing is ever inserted, and a failed apply left the state claiming a
    /// transition that never happened. The only state kept now is one bit --
    /// which side of the threshold we are on -- and even that is flipped only
    /// after a layout has actually been applied.
    fn apply_responsive_layout(&mut self, new_size: Size) -> Result<()> {
        const RESPONSIVE_HYSTERESIS_COLS: usize = 10;
        if self.responsive_min_cols == 0 {
            return Ok(());
        }
        let collapse = match (
            self.responsive_collapsed,
            new_size.cols < self.responsive_min_cols,
            new_size.cols >= self.responsive_min_cols + RESPONSIVE_HYSTERESIS_COLS,
        ) {
            (false, true, _) => true,
            (true, _, true) => false,
            // inside the dead band, or already on the right side of it
            _ => return Ok(()),
        };

        let resolved = if collapse {
            self.responsive_collapse_target()
        } else {
            self.responsive_expand_target()
        };
        let Some((position, layout)) = resolved else {
            // Nothing applied, so change nothing -- not even the flag. Claiming
            // a transition that did not happen is what previously left a tab
            // stacked while believing it had expanded, with no path back.
            return Ok(());
        };
        self.swap_layouts.set_tiled_layout_position(position);
        self.dissolve_stack_lists_for_classic_mutation();
        self.apply_tiled_layout_candidate(&layout);
        self.tiled_panes.reapply_pane_frames();
        self.set_should_clear_display_before_rendering();
        self.responsive_collapsed = collapse;
        Ok(())
    }
    /// Where to collapse to: the configured swap layout, else a synthesized
    /// single stack.
    ///
    /// The synthesized one is kept under its own name rather than the
    /// configured one, so a layout that exists but does not currently apply --
    /// a `stacked` layout with `min_panes=4` and three panes open, say -- falls
    /// back instead of failing.
    fn responsive_collapse_target(&mut self) -> Option<(usize, TiledPaneLayout)> {
        if let Some(position) = self
            .swap_layouts
            .position_of_tiled_layout_named(&self.responsive_layout_name)
        {
            if let Some(layout) = self.swap_layouts.tiled_layout_at(position, &self.tiled_panes) {
                return Some((position, layout));
            }
        }
        // Logged once per tab: a synthesized layout is not what someone who DID
        // write a swap file expects, and staying silent would hide both a name
        // that does not match and a constraint that never fits.
        if !self.responsive_missing_layout_warned {
            self.responsive_missing_layout_warned = true;
            log::info!(
                "no usable swap layout named {:?} in this tab, so the responsive collapse \
                 synthesized one that flattens every pane into a single stack. Define \
                 `swap_tiled_layout name={:?}` in a `<layout>.swap.kdl` beside your layout \
                 file (and check its min_panes/max_panes) to control this yourself.",
                self.responsive_layout_name,
                self.responsive_layout_name
            );
        }
        let position = self
            .swap_layouts
            .append_synthesized_stack_layout(RESPONSIVE_COLLAPSE_LAYOUT_NAME);
        self.swap_layouts
            .tiled_layout_at(position, &self.tiled_panes)
            .map(|layout| (position, layout))
    }
    /// Where to expand to, resolved from the current panes.
    ///
    /// BASE first, because when the pane count has not changed it reproduces the
    /// user's actual layout, which no synthesized grid can. It is pinned to
    /// ExactPanes though, so a single added or closed pane rules it out -- hence
    /// the grid, which carries no constraint and so always applies.
    fn responsive_expand_target(&mut self) -> Option<(usize, TiledPaneLayout)> {
        if let Some(position) = self
            .swap_layouts
            .position_of_tiled_layout_named(swap_layouts::BASE_LAYOUT_NAME)
        {
            if let Some(layout) = self.swap_layouts.tiled_layout_at(position, &self.tiled_panes) {
                return Some((position, layout));
            }
        }
        let position = self
            .swap_layouts
            .append_synthesized_grid_layout(RESPONSIVE_EXPAND_LAYOUT_NAME);
        self.swap_layouts
            .tiled_layout_at(position, &self.tiled_panes)
            .map(|layout| (position, layout))
    }
    pub fn resize_whole_tab(&mut self, new_screen_size: Size) -> Result<()> {
        let err_context = || format!("failed to resize whole tab (id {})", self.id);
        self.size = new_screen_size;
        // If a tiled pane is fullscreen, exit fullscreen first so that *all*
        // tiled panes (including the currently hidden ones) participate in the
        // resize/relayout. We re-enter fullscreen on the same pane after the
        // resize so the user-visible state is preserved. Without this, hidden
        // panes retain stale geometry from before the resize and the layout
        // solver fails when fullscreen is later toggled off.
        let fullscreen_pane_to_restore = self.tiled_panes.fullscreen_pane_id();
        let fullscreen_covered_ui = self.tiled_panes.fullscreen_covers_ui();
        if fullscreen_pane_to_restore.is_some() {
            self.tiled_panes.unset_fullscreen();
        }
        let floating_fullscreen_pane_to_restore = self.floating_panes.fullscreen_pane_id();
        let floating_fullscreen_covered_ui = self.floating_panes.fullscreen_covers_ui();
        if floating_fullscreen_pane_to_restore.is_some() {
            self.floating_panes.unset_fullscreen();
        }
        self.floating_panes.resize(new_screen_size);
        // we need to do this explicitly because floating_panes.resize does not do this
        self.floating_panes
            .resize_pty_all_panes(&mut self.os_api)
            .with_context(err_context)?;
        self.tiled_panes.resize(new_screen_size);
        if self.auto_layout && !self.swap_layouts.is_floating_damaged() {
            // we do this only for floating panes, because the constraint system takes care of the
            // tiled panes
            self.swap_layouts.set_is_floating_damaged();
            let _ = self.relayout_floating_panes(false);
        }
        if self.auto_layout
            && !self.swap_layouts.is_tiled_damaged()
            && fullscreen_pane_to_restore.is_none()
        {
            self.swap_layouts.set_is_tiled_damaged();
            let _ = self.relayout_tiled_panes(false);
        }
        self.set_should_clear_display_before_rendering();
        self.senders
            .send_to_pty_writer(PtyWriteInstruction::ApplyCachedResizes)
            .with_context(|| format!("failed to update plugins with mode info"))?;
        LayoutApplier::offset_viewport(
            self.viewport.clone(),
            self.display_area.clone(),
            &mut self.tiled_panes,
            self.pane_frame_style,
        );
        if let Some(pane_id) = fullscreen_pane_to_restore {
            if self.tiled_panes.panes_contain(&pane_id) {
                if fullscreen_covered_ui {
                    self.tiled_panes.toggle_pane_no_ui_fullscreen(pane_id);
                } else {
                    self.tiled_panes.toggle_pane_fullscreen(pane_id);
                }
            }
        }
        if let Some(pane_id) = floating_fullscreen_pane_to_restore {
            if self.floating_panes.panes_contain(&pane_id) {
                if floating_fullscreen_covered_ui {
                    self.floating_panes.toggle_pane_no_ui_fullscreen(pane_id);
                } else {
                    self.floating_panes.toggle_pane_fullscreen(pane_id);
                }
            }
        }
        self.resize_all_stack_list_hidden_members();
        // after the geometry settles, decide whether this size warrants
        // collapsing or expanding
        self.apply_responsive_layout(new_screen_size)?;
        Ok(())
    }
    pub fn resize(&mut self, client_id: ClientId, strategy: ResizeStrategy) -> Result<()> {
        let err_context = || format!("unable to resize pane");
        if self.floating_panes.fullscreen_is_active() {
            return Ok(());
        }
        if self.floating_panes.panes_are_visible() {
            let successfully_resized = self
                .floating_panes
                .resize_active_pane(client_id, &mut self.os_api, &strategy)
                .with_context(err_context)?;
            if successfully_resized {
                self.swap_layouts.set_is_floating_damaged();
                self.set_force_render(); // we force render here to make sure the panes under the floating pane render and don't leave "garbage" in case of a decrease
            }
        } else {
            self.dissolve_stack_lists_for_classic_mutation();
            match self.tiled_panes.resize_active_pane(client_id, &strategy) {
                Ok(_) => {
                    self.swap_layouts.set_is_tiled_damaged();
                },
                Err(err) => match err.downcast_ref::<ZellijError>() {
                    Some(ZellijError::CantResizeFixedPanes { pane_ids }) => {
                        let mut pane_ids_to_error = vec![];
                        for (id, is_terminal) in pane_ids {
                            if *is_terminal {
                                pane_ids_to_error.push(PaneId::Terminal(*id));
                            } else {
                                pane_ids_to_error.push(PaneId::Plugin(*id));
                            };
                        }
                        self.senders
                            .send_to_background_jobs(BackgroundJob::DisplayPaneError(
                                pane_ids_to_error,
                                "FIXED!".into(),
                            ))
                            .with_context(err_context)?;
                    },
                    _ => Err::<(), _>(err).non_fatal(),
                },
            }
        }
        Ok(())
    }
    fn set_pane_active_at(&mut self, pane_id: PaneId) {
        if let Some(pane) = self.tiled_panes.get_pane_mut(pane_id) {
            pane.set_active_at(Instant::now());
        } else if let Some(pane) = self.floating_panes.get_pane_mut(pane_id) {
            pane.set_active_at(Instant::now());
        }
    }
    pub fn focus_next_pane(&mut self, client_id: ClientId) {
        if !self.has_selectable_panes() {
            return;
        }
        if self.tiled_panes.fullscreen_is_active() {
            self.switch_next_pane_fullscreen(client_id);
            return;
        }
        self.tiled_panes.focus_next_pane(client_id);
    }
    pub fn focus_previous_pane(&mut self, client_id: ClientId) {
        if !self.has_selectable_panes() {
            return;
        }
        if self.tiled_panes.fullscreen_is_active() {
            self.switch_prev_pane_fullscreen(client_id);
            return;
        }
        self.tiled_panes.focus_previous_pane(client_id);
    }
    pub fn focus_last_pane(&mut self, client_id: ClientId) {
        if !self.has_selectable_panes() {
            return;
        }
        if self.floating_panes.panes_are_visible() {
            self.floating_panes.focus_last_pane(client_id);
            return;
        } else if self.tiled_panes.fullscreen_is_active() {
            self.switch_last_pane_fullscreen(client_id);
            return;
        }
        self.tiled_panes.focus_last_pane(client_id);
    }
    pub fn focus_pane_on_edge(&mut self, direction: Direction, client_id: ClientId) {
        if self.floating_panes.panes_are_visible() {
            self.floating_panes.focus_pane_on_edge(direction, client_id);
        } else if self.has_selectable_panes() && !self.tiled_panes.fullscreen_is_active() {
            self.tiled_panes.focus_pane_on_edge(direction, client_id);
        }
    }
    pub fn focus_pane_adjacent_to(
        &mut self,
        pane_id: PaneId,
        direction: Direction,
        client_id: ClientId,
    ) -> Option<PaneId> {
        if self.floating_panes.panes_are_visible() {
            return self
                .floating_panes
                .focus_pane_adjacent_to(pane_id, direction, client_id);
        }
        if self.tiled_panes.fullscreen_is_active() {
            return None;
        }
        self.tiled_panes
            .focus_pane_adjacent_to(pane_id, direction, client_id)
    }
    // returns a boolean that indicates whether the focus moved
    pub fn move_focus_left(&mut self, client_id: ClientId) -> Result<bool> {
        let err_context = || format!("failed to move focus left for client {}", client_id);

        if self.floating_panes.panes_are_visible() {
            self.floating_panes
                .move_focus(
                    client_id,
                    &self.connected_clients.borrow().iter().copied().collect(),
                    &Direction::Left,
                )
                .with_context(err_context)
        } else {
            if !self.has_selectable_panes() {
                return Ok(false);
            }
            if self.tiled_panes.fullscreen_is_active() {
                return Ok(self.focus_pane_left_fullscreen(client_id));
            }
            Ok(self.tiled_panes.move_focus_left(client_id))
        }
    }
    pub fn move_focus_down(&mut self, client_id: ClientId) -> Result<bool> {
        let err_context = || format!("failed to move focus down for client {}", client_id);

        if self.floating_panes.panes_are_visible() {
            self.floating_panes
                .move_focus(
                    client_id,
                    &self.connected_clients.borrow().iter().copied().collect(),
                    &Direction::Down,
                )
                .with_context(err_context)
        } else {
            if !self.has_selectable_panes() {
                return Ok(false);
            }
            if self.tiled_panes.fullscreen_is_active() {
                return Ok(self.focus_pane_down_fullscreen(client_id));
            }
            if self.stacked_pane_list_is_active()
                && self.move_focus_within_stack_list(client_id, true)
            {
                return Ok(true);
            }
            Ok(self.tiled_panes.move_focus_down(client_id))
        }
    }
    pub fn move_focus_up(&mut self, client_id: ClientId) -> Result<bool> {
        let err_context = || format!("failed to move focus up for client {}", client_id);

        if self.floating_panes.panes_are_visible() {
            self.floating_panes
                .move_focus(
                    client_id,
                    &self.connected_clients.borrow().iter().copied().collect(),
                    &Direction::Up,
                )
                .with_context(err_context)
        } else {
            if !self.has_selectable_panes() {
                return Ok(false);
            }
            if self.tiled_panes.fullscreen_is_active() {
                return Ok(self.focus_pane_up_fullscreen(client_id));
            }
            if self.stacked_pane_list_is_active()
                && self.move_focus_within_stack_list(client_id, false)
            {
                return Ok(true);
            }
            Ok(self.tiled_panes.move_focus_up(client_id))
        }
    }
    // returns a boolean that indicates whether the focus moved
    pub fn move_focus_right(&mut self, client_id: ClientId) -> Result<bool> {
        let err_context = || format!("failed to move focus right for client {}", client_id);

        if self.floating_panes.panes_are_visible() {
            self.floating_panes
                .move_focus(
                    client_id,
                    &self.connected_clients.borrow().iter().copied().collect(),
                    &Direction::Right,
                )
                .with_context(err_context)
        } else {
            if !self.has_selectable_panes() {
                return Ok(false);
            }
            if self.tiled_panes.fullscreen_is_active() {
                return Ok(self.focus_pane_right_fullscreen(client_id));
            }
            Ok(self.tiled_panes.move_focus_right(client_id))
        }
    }
    pub fn move_active_pane(&mut self, client_id: ClientId) {
        if !self.has_selectable_panes() {
            return;
        }
        if self.tiled_panes.fullscreen_is_active() {
            return;
        }
        let search_backwards = false;
        if self.floating_panes.panes_are_visible() {
            self.floating_panes
                .move_active_pane(search_backwards, &mut self.os_api, client_id);
        } else {
            self.dissolve_stack_lists_for_classic_mutation();
            self.tiled_panes
                .move_active_pane(search_backwards, client_id);
        }
    }
    pub fn move_pane(&mut self, pane_id: PaneId) {
        if !self.has_selectable_panes() {
            return;
        }
        if self.tiled_panes.fullscreen_is_active() {
            return;
        }
        let search_backwards = false;
        if self.floating_panes.panes_are_visible() {
            self.floating_panes.move_pane(search_backwards, pane_id);
        } else {
            self.dissolve_stack_lists_for_classic_mutation();
            self.tiled_panes.move_pane(search_backwards, pane_id);
        }
    }
    pub fn move_active_pane_backwards(&mut self, client_id: ClientId) {
        if !self.has_selectable_panes() {
            return;
        }
        if self.tiled_panes.fullscreen_is_active() {
            return;
        }
        let search_backwards = true;
        if self.floating_panes.panes_are_visible() {
            self.floating_panes
                .move_active_pane(search_backwards, &mut self.os_api, client_id);
        } else {
            self.dissolve_stack_lists_for_classic_mutation();
            self.tiled_panes
                .move_active_pane(search_backwards, client_id);
        }
    }
    pub fn move_active_pane_down(&mut self, client_id: ClientId) {
        if self.floating_panes.panes_are_visible() {
            self.floating_panes.move_active_pane_down(client_id);
            self.swap_layouts.set_is_floating_damaged();
            self.set_force_render(); // we force render here to make sure the panes under the floating pane render and don't leave "garbage" behind
        } else {
            if !self.has_selectable_panes() {
                return;
            }
            if self.tiled_panes.fullscreen_is_active() {
                return;
            }
            self.dissolve_stack_lists_for_classic_mutation();
            self.tiled_panes.move_active_pane_down(client_id);
        }
    }
    pub fn move_pane_down(&mut self, pane_id: PaneId) {
        if self.floating_panes.panes_are_visible() {
            self.floating_panes.move_pane_down(pane_id);
            self.swap_layouts.set_is_floating_damaged();
            self.set_force_render(); // we force render here to make sure the panes under the floating pane render and don't leave "garbage" behind
        } else {
            if !self.has_selectable_panes() {
                return;
            }
            if self.tiled_panes.fullscreen_is_active() {
                return;
            }
            self.dissolve_stack_lists_for_classic_mutation();
            self.tiled_panes.move_pane_down(pane_id);
        }
    }
    pub fn move_active_pane_up(&mut self, client_id: ClientId) {
        if self.floating_panes.panes_are_visible() {
            self.floating_panes.move_active_pane_up(client_id);
            self.swap_layouts.set_is_floating_damaged();
            self.set_force_render(); // we force render here to make sure the panes under the floating pane render and don't leave "garbage" behind
        } else {
            if !self.has_selectable_panes() {
                return;
            }
            if self.tiled_panes.fullscreen_is_active() {
                return;
            }
            self.dissolve_stack_lists_for_classic_mutation();
            self.tiled_panes.move_active_pane_up(client_id);
        }
    }
    pub fn move_pane_up(&mut self, pane_id: PaneId) {
        if self.floating_panes.panes_are_visible() {
            self.floating_panes.move_pane_up(pane_id);
            self.swap_layouts.set_is_floating_damaged();
            self.set_force_render(); // we force render here to make sure the panes under the floating pane render and don't leave "garbage" behind
        } else {
            if !self.has_selectable_panes() {
                return;
            }
            if self.tiled_panes.fullscreen_is_active() {
                return;
            }
            self.dissolve_stack_lists_for_classic_mutation();
            self.tiled_panes.move_pane_up(pane_id);
        }
    }
    pub fn move_active_pane_right(&mut self, client_id: ClientId) {
        if self.floating_panes.panes_are_visible() {
            self.floating_panes.move_active_pane_right(client_id);
            self.swap_layouts.set_is_floating_damaged();
            self.set_force_render(); // we force render here to make sure the panes under the floating pane render and don't leave "garbage" behind
        } else {
            if !self.has_selectable_panes() {
                return;
            }
            if self.tiled_panes.fullscreen_is_active() {
                return;
            }
            self.dissolve_stack_lists_for_classic_mutation();
            self.tiled_panes.move_active_pane_right(client_id);
        }
    }
    pub fn move_pane_right(&mut self, pane_id: PaneId) {
        if self.floating_panes.panes_are_visible() {
            self.floating_panes.move_pane_right(pane_id);
            self.swap_layouts.set_is_floating_damaged();
            self.set_force_render(); // we force render here to make sure the panes under the floating pane render and don't leave "garbage" behind
        } else {
            if !self.has_selectable_panes() {
                return;
            }
            if self.tiled_panes.fullscreen_is_active() {
                return;
            }
            self.dissolve_stack_lists_for_classic_mutation();
            self.tiled_panes.move_pane_right(pane_id);
        }
    }
    pub fn move_active_pane_left(&mut self, client_id: ClientId) {
        if self.floating_panes.panes_are_visible() {
            self.floating_panes.move_active_pane_left(client_id);
            self.swap_layouts.set_is_floating_damaged();
            self.set_force_render(); // we force render here to make sure the panes under the floating pane render and don't leave "garbage" behind
        } else {
            if !self.has_selectable_panes() {
                return;
            }
            if self.tiled_panes.fullscreen_is_active() {
                return;
            }
            self.dissolve_stack_lists_for_classic_mutation();
            self.tiled_panes.move_active_pane_left(client_id);
        }
    }
    pub fn move_pane_left(&mut self, pane_id: PaneId) {
        if self.floating_panes.panes_are_visible() {
            self.floating_panes.move_pane_left(pane_id);
            self.swap_layouts.set_is_floating_damaged();
            self.set_force_render(); // we force render here to make sure the panes under the floating pane render and don't leave "garbage" behind
        } else {
            if !self.has_selectable_panes() {
                return;
            }
            if self.tiled_panes.fullscreen_is_active() {
                return;
            }
            self.dissolve_stack_lists_for_classic_mutation();
            self.tiled_panes.move_pane_left(pane_id);
        }
    }
    fn close_down_to_max_terminals(&mut self) -> Result<()> {
        if let Some(max_panes) = self.max_panes {
            self.dissolve_stack_lists_for_classic_mutation();
            let terminals = self.get_tiled_pane_ids();
            for &pid in terminals.iter().skip(max_panes - 1) {
                self.senders
                    .send_to_pty(PtyInstruction::ClosePane(pid, None))
                    .context("failed to close down to max terminals")?;
                self.close_pane(pid, false, None);
            }
        }
        Ok(())
    }
    pub fn get_tiled_pane_ids(&self) -> Vec<PaneId> {
        self.get_tiled_panes().map(|(&pid, _)| pid).collect()
    }
    pub fn kitty_visible_pane_ids(&self) -> HashSet<PaneId> {
        let mut pane_ids: HashSet<PaneId> =
            self.tiled_panes.rendered_pane_ids().into_iter().collect();
        pane_ids.extend(self.floating_panes.rendered_pane_ids());
        pane_ids
    }
    pub fn get_all_pane_ids(&self) -> Vec<PaneId> {
        let mut static_and_floating_pane_ids = self.get_static_and_floating_pane_ids();
        let mut suppressed_pane_ids = self
            .suppressed_panes
            .values()
            .map(|(_key, pane)| pane.pid())
            .collect();
        static_and_floating_pane_ids.append(&mut suppressed_pane_ids);
        static_and_floating_pane_ids
    }
    pub fn get_static_and_floating_pane_ids(&self) -> Vec<PaneId> {
        self.tiled_panes
            .pane_ids()
            .chain(self.floating_panes.pane_ids())
            .copied()
            .collect()
    }
    pub fn get_plugin_ids(&self) -> Vec<PluginId> {
        self.get_static_and_floating_pane_ids()
            .into_iter()
            .filter_map(|pane_id| match pane_id {
                PaneId::Plugin(pid) => Some(pid),
                _ => None,
            })
            .collect()
    }
    pub fn get_pane_info(&self, pane_id: PaneId) -> Option<PaneInfo> {
        let current_pane_group: HashMap<ClientId, Vec<PaneId>> =
            { self.current_pane_group.borrow().clone_inner() };

        // Check tiled panes
        if let Some(pane) = self.tiled_panes.get_pane(pane_id) {
            let mut info = pane_info_for_pane(&pane_id, pane, &current_pane_group);
            // Note: is_focused will be false since we don't have a specific client_id context
            // Plugins calling this API would need to compare the pane_id with their own focused pane
            info.is_focused = false;
            info.is_fullscreen = self.tiled_panes.fullscreen_is_active();
            info.is_floating = false;
            info.is_suppressed = false;
            return Some(info);
        }

        // Check floating panes
        if let Some(pane) = self.floating_panes.get_pane(pane_id) {
            let mut info = pane_info_for_pane(&pane_id, pane, &current_pane_group);
            info.is_focused = false;
            info.is_fullscreen = self.floating_panes.fullscreen_pane_id() == Some(pane_id);
            info.is_floating = true;
            info.is_suppressed = false;
            return Some(info);
        }

        // Check suppressed panes
        if let Some((_previous_id, pane)) = self.suppressed_panes.get(&pane_id) {
            let mut info = pane_info_for_pane(&pane_id, pane, &current_pane_group);
            info.is_focused = false;
            info.is_fullscreen = false;
            info.is_floating = false;
            info.is_suppressed = true;
            return Some(info);
        }

        None
    }
    pub fn set_pane_selectable(&mut self, id: PaneId, selectable: bool) {
        if self.is_pending {
            self.pending_instructions
                .push(BufferedTabInstruction::SetPaneSelectable(id, selectable));
            return;
        }
        if let Some(pane) = self.tiled_panes.get_pane_mut(id) {
            pane.set_selectable(selectable);
            if !selectable {
                self.tiled_panes.move_clients_out_of_pane(id);
            }
        } else if let Some(pane) = self.floating_panes.get_pane_mut(id) {
            pane.set_selectable(selectable);
            if !selectable {
                self.floating_panes.move_clients_out_of_pane(id);
                if !self.floating_panes.has_selectable_panes() {
                    self.hide_floating_panes();
                }
            }
        }
        // we do this here because if there is a non-selectable pane on the edge, we consider it
        // outside the viewport (a ui-pane, eg. the status-bar and tab-bar) and need to adjust for it
        LayoutApplier::offset_viewport(
            self.viewport.clone(),
            self.display_area.clone(),
            &mut self.tiled_panes,
            self.pane_frame_style,
        );
    }
    pub fn set_mouse_selection_support(&mut self, pane_id: PaneId, selection_support: bool) {
        MouseHandler::set_mouse_selection_support(self, pane_id, selection_support);
    }
    pub fn close_pane(
        &mut self,
        id: PaneId,
        ignore_suppressed_panes: bool,
        exit_status: Option<i32>,
    ) {
        let id_parks_a_different_pane = self.pane_parked_by(&id).is_some();
        if !ignore_suppressed_panes
            && !id_parks_a_different_pane
            && self.pane_is_stack_list_member(&id)
        {
            if self.close_stack_list_member(id, exit_status) {
                let _ = self.senders.send_to_plugin(PluginInstruction::Update(vec![(
                    None,
                    None,
                    Event::PaneClosed(id.into()),
                )]));
                let _ =
                    self.senders
                        .send_to_screen(ScreenInstruction::NotifyPaneClosedToSubscribers {
                            pane_id: id.into(),
                        });
                return;
            }
        }
        // we need to ignore suppressed panes when we toggle a pane to be floating/embedded(tiled)
        // this is because in that case, while we do use this logic, we're not actually closing the
        // pane, we're moving it
        if !ignore_suppressed_panes && self.suppressed_panes.contains_key(&id) {
            return match self.replace_pane_with_suppressed_pane(id) {
                Ok(_pane) => {},
                Err(e) => {
                    Err::<(), _>(e)
                        .with_context(|| format!("failed to close pane {:?}", id))
                        .non_fatal();
                },
            };
        }
        let closed_pane = if self.floating_panes.panes_contain(&id) {
            if self.floating_panes.fullscreen_pane_id() == Some(id) {
                self.floating_panes.unset_fullscreen();
            }
            let closed_pane = self.floating_panes.remove_pane(id);
            self.floating_panes.move_clients_out_of_pane(id);
            if !self.floating_panes.has_selectable_panes() {
                self.swap_layouts.reset_floating_damage();
                self.hide_floating_panes();
            }
            self.set_force_render();
            self.floating_panes.set_force_render();
            if self.auto_layout
                && !self.swap_layouts.is_floating_damaged()
                && self.floating_panes.visible_panes_count() > 0
            {
                self.swap_layouts.set_is_floating_damaged();
                // only relayout if the user is already "in" a layout, otherwise this might be
                // confusing
                let _ = self.relayout_floating_panes(false);
            }
            closed_pane
        } else {
            if self.tiled_panes.fullscreen_is_active() {
                self.tiled_panes.unset_fullscreen();
            }
            let closed_pane = self.tiled_panes.remove_pane(id);
            self.set_force_render();
            self.tiled_panes.set_force_render();
            if self.auto_layout && !self.swap_layouts.is_tiled_damaged() {
                self.swap_layouts.set_is_tiled_damaged();
                // only relayout if the user is already "in" a layout, otherwise this might be
                // confusing
                let _ = self.relayout_tiled_panes(false);
            }
            self.resize_all_stack_list_hidden_members();
            closed_pane
        };
        if let Some(exit_status) = exit_status {
            if let Some(mut closed_pane) = closed_pane {
                // in case we need to update on Drop
                closed_pane.update_exit_status(exit_status);
            }
        }
        let _ = self.senders.send_to_plugin(PluginInstruction::Update(vec![(
            None,
            None,
            Event::PaneClosed(id.into()),
        )]));
        let _ = self
            .senders
            .send_to_screen(ScreenInstruction::NotifyPaneClosedToSubscribers {
                pane_id: id.into(),
            });
    }
    pub fn extract_pane(
        &mut self,
        id: PaneId,
        dont_swap_if_suppressed: bool,
    ) -> Option<Box<dyn Pane>> {
        let id_parks_a_different_pane = self.pane_parked_by(&id).is_some();
        if self.pane_is_stack_list_member(&id)
            && (dont_swap_if_suppressed || !id_parks_a_different_pane)
        {
            if let StackListRemoval::Removed(removed) = self.remove_stack_list_member(id) {
                return removed.map(|mut pane| {
                    pane.reset_logical_position();
                    pane
                });
            }
        }
        if !dont_swap_if_suppressed && self.suppressed_panes.contains_key(&id) {
            // this is done for the scrollback editor
            return match self.replace_pane_with_suppressed_pane(id) {
                Ok(mut pane) => {
                    // we do this so that the logical index will not affect ordering in the target tab
                    if let Some(pane) = pane.as_mut() {
                        pane.reset_logical_position();
                    }
                    pane
                },
                Err(e) => {
                    Err::<(), _>(e)
                        .with_context(|| format!("failed to close pane {:?}", id))
                        .non_fatal();
                    None
                },
            };
        }
        if self.floating_panes.panes_contain(&id) {
            if self.floating_panes.fullscreen_pane_id() == Some(id) {
                self.floating_panes.unset_fullscreen();
            }
            let mut closed_pane = self.floating_panes.remove_pane(id);
            self.floating_panes.move_clients_out_of_pane(id);
            if !self.floating_panes.has_panes() {
                self.swap_layouts.reset_floating_damage();
                self.hide_floating_panes();
            }
            self.set_force_render();
            self.floating_panes.set_force_render();
            if self.auto_layout
                && !self.swap_layouts.is_floating_damaged()
                && self.floating_panes.visible_panes_count() > 0
            {
                self.swap_layouts.set_is_floating_damaged();
                // only relayout if the user is already "in" a layout, otherwise this might be
                // confusing
                let _ = self.relayout_floating_panes(false);
            }
            // we do this so that the logical index will not affect ordering in the target tab
            if let Some(closed_pane) = closed_pane.as_mut() {
                closed_pane.reset_logical_position();
            }
            closed_pane
        } else if self.tiled_panes.panes_contain(&id) {
            if self.tiled_panes.fullscreen_is_active() {
                self.tiled_panes.unset_fullscreen();
            }
            let mut closed_pane = self.tiled_panes.remove_pane(id);
            self.set_force_render();
            self.tiled_panes.set_force_render();
            if self.auto_layout && !self.swap_layouts.is_tiled_damaged() {
                self.swap_layouts.set_is_tiled_damaged();
                // only relayout if the user is already "in" a layout, otherwise this might be
                // confusing
                let _ = self.relayout_tiled_panes(false);
            }
            self.resize_all_stack_list_hidden_members();
            // we do this so that the logical index will not affect ordering in the target tab
            if let Some(closed_pane) = closed_pane.as_mut() {
                closed_pane.reset_logical_position();
            }
            closed_pane
        } else if let Some(suppressed_key_of_pane) = self
            .suppressed_panes
            .iter()
            .find_map(|(key, (_, pane))| if &pane.pid() == &id { Some(*key) } else { None })
        {
            // TODO: test this (from the path in screen.rs focus_plugin_pane ~line 2519
            self.suppressed_panes
                .remove(&suppressed_key_of_pane)
                .map(|s_p| s_p.1)
        } else {
            None
        }
    }
    pub fn hold_pane(
        &mut self,
        id: PaneId,
        exit_status: Option<i32>,
        is_first_run: bool,
        run_command: RunCommand,
    ) {
        if self.is_pending {
            self.pending_instructions
                .push(BufferedTabInstruction::HoldPane(
                    id,
                    exit_status,
                    is_first_run,
                    run_command,
                ));
            return;
        }
        if self.floating_panes.panes_contain(&id) {
            self.floating_panes
                .hold_pane(id, exit_status, is_first_run, run_command);
        } else if self.tiled_panes.panes_contain(&id) {
            self.tiled_panes
                .hold_pane(id, exit_status, is_first_run, run_command);
        } else if let Some(pane) = self.suppressed_panes.values_mut().find(|p| p.1.pid() == id) {
            pane.1.hold(exit_status, is_first_run, run_command);
        }
    }
    pub fn replace_pane_with_suppressed_pane(
        &mut self,
        pane_id: PaneId,
    ) -> Result<Option<Box<dyn Pane>>> {
        self.suppressed_panes
            .remove(&pane_id)
            .with_context(|| {
                format!(
                    "couldn't find pane with id {:?} in suppressed panes",
                    pane_id
                )
            })
            .and_then(|(_is_scrollback_editor, suppressed_pane)| {
                let suppressed_pane_id = suppressed_pane.pid();
                let replaced_pane = if self.are_floating_panes_visible() {
                    Some(self.floating_panes.replace_pane(pane_id, suppressed_pane)).transpose()?
                } else {
                    self.tiled_panes.replace_pane(pane_id, suppressed_pane)
                };
                if replaced_pane.is_some() {
                    self.track_stack_list_member_id_swap(pane_id, suppressed_pane_id);
                }
                if let Some(suppressed_pane) = self
                    .floating_panes
                    .get_pane(suppressed_pane_id)
                    .or_else(|| self.tiled_panes.get_pane(suppressed_pane_id))
                {
                    // You may be thinking: why aren't we using the original "suppressed_pane" here,
                    // isn't it the same one?
                    //
                    // Yes, you are right! However, we moved it into its correct environment above
                    // (either floating_panes or tiled_panes) where it received a new geometry based on
                    // the pane there we replaced. Now, we need to update its pty about its new size.
                    // We couldn't do that before, and we can't use the original moved item now - so we
                    // need to refetch it
                    resize_pty!(
                        suppressed_pane,
                        self.os_api,
                        self.senders,
                        self.character_cell_size
                    )?;
                }
                Ok(replaced_pane)
            })
            .with_context(|| {
                format!(
                    "failed to replace active pane with suppressed pane {:?}",
                    pane_id
                )
            })
    }
    pub fn close_focused_pane(
        &mut self,
        client_id: ClientId,
        completion_tx: Option<NotificationEnd>,
    ) -> Result<()> {
        let err_context = |pane_id| {
            format!("failed to close focused pane (ID {pane_id:?}) for client {client_id}")
        };

        if self.floating_panes.panes_are_visible() {
            if let Some(active_floating_pane_id) = self.floating_panes.active_pane_id(client_id) {
                self.close_pane(active_floating_pane_id, false, None);
                self.senders
                    .send_to_pty(PtyInstruction::ClosePane(
                        active_floating_pane_id,
                        completion_tx,
                    ))
                    .with_context(|| err_context(active_floating_pane_id))?;
                return Ok(());
            }
        }
        if let Some(active_pane_id) = self.tiled_panes.get_active_pane_id(client_id) {
            self.close_pane(active_pane_id, false, None);
            self.senders
                .send_to_pty(PtyInstruction::ClosePane(active_pane_id, completion_tx))
                .with_context(|| err_context(active_pane_id))?;
        }
        Ok(())
    }
    pub fn clear_active_terminal_screen(&mut self, client_id: ClientId) -> Result<()> {
        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            active_pane.clear_screen();
        }
        Ok(())
    }
    pub fn clear_screen_for_pane_id(&mut self, pane_id: PaneId) {
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            pane.clear_screen();
        }
    }
    pub fn dump_active_terminal_screen(
        &mut self,
        file: Option<String>,
        client_id: ClientId,
        full: bool,
    ) -> Result<()> {
        let err_context =
            || format!("failed to dump active terminal screen for client {client_id}");

        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            let dump = active_pane.dump_screen(full, Some(client_id));
            self.os_api
                .write_to_file(dump, file)
                .with_context(err_context)?;
        }
        Ok(())
    }
    pub fn dump_with_ansi_active_terminal_screen(
        &mut self,
        file: Option<String>,
        client_id: ClientId,
        full: bool,
    ) -> Result<()> {
        let err_context =
            || format!("failed to dump active terminal screen for client {client_id}");

        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            let dump = active_pane.dump_screen_with_ansi(full, Some(client_id));
            self.os_api
                .write_to_file(dump, file)
                .with_context(err_context)?;
        }
        Ok(())
    }
    pub fn dump_terminal_screen(
        &mut self,
        file: Option<String>,
        pane_id: PaneId,
        full: bool,
    ) -> Result<()> {
        if let Some(pane) = self.get_pane_with_id(pane_id) {
            let dump = pane.dump_screen(full, None);
            self.os_api.write_to_file(dump, file).non_fatal()
        }
        Ok(())
    }
    pub fn dump_with_ansi_terminal_screen(
        &mut self,
        file: Option<String>,
        pane_id: PaneId,
        full: bool,
    ) -> Result<()> {
        if let Some(pane) = self.get_pane_with_id(pane_id) {
            let dump = pane.dump_screen_with_ansi(full, None);
            self.os_api.write_to_file(dump, file).non_fatal()
        }
        Ok(())
    }
    pub fn get_dump_active_terminal_screen(&mut self, client_id: ClientId, full: bool) -> String {
        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            active_pane.dump_screen(full, Some(client_id))
        } else {
            String::new()
        }
    }
    pub fn get_dump_with_ansi_active_terminal_screen(
        &mut self,
        client_id: ClientId,
        full: bool,
    ) -> String {
        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            active_pane.dump_screen_with_ansi(full, Some(client_id))
        } else {
            String::new()
        }
    }
    pub fn get_dump_terminal_screen(&mut self, pane_id: PaneId, full: bool) -> Option<String> {
        if let Some(pane) = self.get_pane_with_id(pane_id) {
            Some(pane.dump_screen(full, None))
        } else {
            None
        }
    }
    pub fn get_dump_with_ansi_terminal_screen(
        &mut self,
        pane_id: PaneId,
        full: bool,
    ) -> Option<String> {
        if let Some(pane) = self.get_pane_with_id(pane_id) {
            Some(pane.dump_screen_with_ansi(full, None))
        } else {
            None
        }
    }
    pub fn edit_scrollback(
        &mut self,
        client_id: ClientId,
        completion_tx: Option<NotificationEnd>,
    ) -> Result<()> {
        let err_context = || format!("failed to edit scrollback for client {client_id}");

        let mut file = temp_dir();
        file.push(format!("{}.dump", Uuid::new_v4()));
        self.dump_active_terminal_screen(
            Some(String::from(file.to_string_lossy())),
            client_id,
            true,
        )
        .with_context(err_context)?;
        let line_number = self
            .get_active_pane(client_id)
            .and_then(|a_t| a_t.get_line_number());
        self.senders
            .send_to_pty(PtyInstruction::OpenInPlaceEditor(
                file,
                line_number,
                ClientTabIndexOrPaneId::ClientId(client_id),
                completion_tx,
            ))
            .with_context(err_context)
    }
    pub fn edit_scrollback_raw(
        &mut self,
        client_id: ClientId,
        completion_tx: Option<NotificationEnd>,
    ) -> Result<()> {
        let err_context = || format!("failed to edit scrollback for client {client_id}");

        let mut file = temp_dir();
        file.push(format!("{}.dump", Uuid::new_v4()));
        self.dump_with_ansi_active_terminal_screen(
            Some(String::from(file.to_string_lossy())),
            client_id,
            true,
        )
        .with_context(err_context)?;
        let line_number = self
            .get_active_pane(client_id)
            .and_then(|a_t| a_t.get_line_number());
        self.senders
            .send_to_pty(PtyInstruction::OpenInPlaceEditor(
                file,
                line_number,
                ClientTabIndexOrPaneId::ClientId(client_id),
                completion_tx,
            ))
            .with_context(err_context)
    }
    pub fn edit_scrollback_for_pane_with_id(
        &mut self,
        pane_id: PaneId,
        completion_tx: Option<NotificationEnd>,
    ) -> Result<()> {
        if let PaneId::Terminal(_terminal_pane_id) = pane_id {
            self.make_hidden_stack_list_member_visible(pane_id);
            let mut file = temp_dir();
            file.push(format!("{}.dump", Uuid::new_v4()));
            self.dump_terminal_screen(Some(String::from(file.to_string_lossy())), pane_id, true)
                .non_fatal();
            let line_number = self
                .get_pane_with_id(pane_id)
                .and_then(|a_t| a_t.get_line_number());
            self.senders.send_to_pty(PtyInstruction::OpenInPlaceEditor(
                file,
                line_number,
                ClientTabIndexOrPaneId::PaneId(pane_id),
                completion_tx,
            ))
        } else {
            log::error!("Editing plugin pane scrollback is currently unsupported.");
            Ok(())
        }
    }
    pub fn edit_scrollback_raw_for_pane_with_id(
        &mut self,
        pane_id: PaneId,
        completion_tx: Option<NotificationEnd>,
    ) -> Result<()> {
        if let PaneId::Terminal(_terminal_pane_id) = pane_id {
            self.make_hidden_stack_list_member_visible(pane_id);
            let mut file = temp_dir();
            file.push(format!("{}.dump", Uuid::new_v4()));
            self.dump_with_ansi_terminal_screen(
                Some(String::from(file.to_string_lossy())),
                pane_id,
                true,
            )
            .non_fatal();
            let line_number = self
                .get_pane_with_id(pane_id)
                .and_then(|a_t| a_t.get_line_number());
            self.senders.send_to_pty(PtyInstruction::OpenInPlaceEditor(
                file,
                line_number,
                ClientTabIndexOrPaneId::PaneId(pane_id),
                completion_tx,
            ))
        } else {
            log::error!("Editing plugin pane scrollback is currently unsupported.");
            Ok(())
        }
    }
    pub fn scroll_active_terminal_up(&mut self, client_id: ClientId) {
        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            active_pane.scroll_up(1, client_id);
        }
    }

    pub fn scroll_terminal_up(&mut self, terminal_pane_id: u32) -> Result<()> {
        let pane_id = PaneId::Terminal(terminal_pane_id);
        let err_context = || format!("failed to scroll up pane {pane_id:?}");
        let fictitious_client_id = 1;
        let synthetic_position = Position::new(0, 0);
        let (mouse_sgr, is_alt) = match self.get_pane_with_id(pane_id) {
            Some(pane) => (
                pane.mouse_scroll_up(&synthetic_position),
                pane.is_alternate_mode_active(),
            ),
            None => return Ok(()),
        };
        if let Some(sgr) = mouse_sgr {
            self.write_to_pane_id(&None, sgr.into_bytes(), false, pane_id, None, None)
                .with_context(err_context)?;
        } else if is_alt {
            self.write_to_pane_id(&None, b"\x1b[A".to_vec(), false, pane_id, None, None)
                .with_context(err_context)?;
        } else if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            pane.scroll_up(1, fictitious_client_id);
        }
        Ok(())
    }

    pub fn scroll_active_terminal_down(&mut self, client_id: ClientId) -> Result<()> {
        let err_context = || format!("failed to scroll down active pane for client {client_id}");

        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            active_pane.scroll_down(1, client_id);
            if !active_pane.is_scrolled() {
                if let PaneId::Terminal(raw_fd) = active_pane.pid() {
                    self.process_pending_vte_events(raw_fd)
                        .with_context(err_context)?;
                }
            }
        }
        Ok(())
    }

    pub fn scroll_terminal_down(&mut self, terminal_pane_id: u32) -> Result<()> {
        let pane_id = PaneId::Terminal(terminal_pane_id);
        let err_context = || format!("failed to scroll down pane {pane_id:?}");
        let fictitious_client_id = 1;
        let synthetic_position = Position::new(0, 0);
        let (mouse_sgr, is_alt) = match self.get_pane_with_id(pane_id) {
            Some(pane) => (
                pane.mouse_scroll_down(&synthetic_position),
                pane.is_alternate_mode_active(),
            ),
            None => return Ok(()),
        };
        if let Some(sgr) = mouse_sgr {
            self.write_to_pane_id(&None, sgr.into_bytes(), false, pane_id, None, None)
                .with_context(err_context)?;
        } else if is_alt {
            self.write_to_pane_id(&None, b"\x1b[B".to_vec(), false, pane_id, None, None)
                .with_context(err_context)?;
        } else {
            let needs_flush = if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
                pane.scroll_down(1, fictitious_client_id);
                !pane.is_scrolled()
            } else {
                false
            };
            if needs_flush {
                self.process_pending_vte_events(terminal_pane_id)
                    .with_context(err_context)?;
            }
        }
        Ok(())
    }

    pub fn scroll_active_terminal_up_page(&mut self, client_id: ClientId) {
        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            // prevent overflow when row == 0
            let scroll_rows = active_pane.rows().max(1).saturating_sub(1);
            active_pane.scroll_up(scroll_rows, client_id);
        }
    }

    pub fn scroll_terminal_page_up(&mut self, terminal_pane_id: u32) {
        if let Some(terminal_pane) = self.get_pane_with_id_mut(PaneId::Terminal(terminal_pane_id)) {
            let fictitious_client_id = 1; // this is not checked for terminal panes and we
                                          // don't have an actual client id here
                                          // TODO: traits were a mistake
                                          // prevent overflow when row == 0
            let scroll_rows = terminal_pane.rows().max(1).saturating_sub(1);
            terminal_pane.scroll_up(scroll_rows, fictitious_client_id);
        }
    }

    pub fn scroll_active_terminal_down_page(&mut self, client_id: ClientId) -> Result<()> {
        let err_context =
            || format!("failed to scroll down one page in active pane for client {client_id}");

        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            let scroll_rows = active_pane.get_content_rows();
            active_pane.scroll_down(scroll_rows, client_id);
            if !active_pane.is_scrolled() {
                if let PaneId::Terminal(raw_fd) = active_pane.pid() {
                    self.process_pending_vte_events(raw_fd)
                        .with_context(err_context)?;
                }
            }
        }
        Ok(())
    }

    pub fn scroll_terminal_page_down(&mut self, terminal_pane_id: u32) {
        if let Some(terminal_pane) = self.get_pane_with_id_mut(PaneId::Terminal(terminal_pane_id)) {
            let fictitious_client_id = 1; // this is not checked for terminal panes and we
                                          // don't have an actual client id here
                                          // TODO: traits were a mistake
            let scroll_rows = terminal_pane.get_content_rows();
            terminal_pane.scroll_down(scroll_rows, fictitious_client_id);
            if !terminal_pane.is_scrolled() {
                if let PaneId::Terminal(raw_fd) = terminal_pane.pid() {
                    self.process_pending_vte_events(raw_fd).non_fatal()
                }
            }
        }
    }

    pub fn scroll_active_terminal_up_half_page(&mut self, client_id: ClientId) {
        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            // prevent overflow when row == 0
            let scroll_rows = (active_pane.rows().max(1).saturating_sub(1)) / 2;
            active_pane.scroll_up(scroll_rows, client_id);
        }
    }

    pub fn scroll_active_terminal_down_half_page(&mut self, client_id: ClientId) -> Result<()> {
        let err_context =
            || format!("failed to scroll down half a page in active pane for client {client_id}");

        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            let scroll_rows = (active_pane.rows().max(1) - 1) / 2;
            active_pane.scroll_down(scroll_rows, client_id);
            if !active_pane.is_scrolled() {
                if let PaneId::Terminal(raw_fd) = active_pane.pid() {
                    self.process_pending_vte_events(raw_fd)
                        .with_context(err_context)?;
                }
            }
        }
        Ok(())
    }

    pub fn scroll_active_terminal_to_bottom(&mut self, client_id: ClientId) -> Result<()> {
        let err_context =
            || format!("failed to scroll to bottom in active pane for client {client_id}");

        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            active_pane.clear_scroll();
            if !active_pane.is_scrolled() {
                if let PaneId::Terminal(raw_fd) = active_pane.pid() {
                    self.process_pending_vte_events(raw_fd)
                        .with_context(err_context)?;
                }
            }
        }
        Ok(())
    }

    pub fn scroll_terminal_to_bottom(&mut self, terminal_pane_id: u32) {
        if let Some(terminal_pane) = self.get_pane_with_id_mut(PaneId::Terminal(terminal_pane_id)) {
            terminal_pane.clear_scroll();
            if !terminal_pane.is_scrolled() {
                if let PaneId::Terminal(raw_fd) = terminal_pane.pid() {
                    self.process_pending_vte_events(raw_fd).non_fatal();
                }
            }
        }
    }

    pub fn scroll_active_terminal_to_top(&mut self, client_id: ClientId) -> Result<()> {
        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            active_pane.clear_scroll();
            if let Some(size) = active_pane.get_line_number() {
                active_pane.scroll_up(size, client_id);
            }
        }
        Ok(())
    }

    pub fn scroll_terminal_to_top(&mut self, terminal_pane_id: u32) {
        if let Some(terminal_pane) = self.get_pane_with_id_mut(PaneId::Terminal(terminal_pane_id)) {
            terminal_pane.clear_scroll();
            if let Some(size) = terminal_pane.get_line_number() {
                let fictitious_client_id = 1; // this is not checked for terminal panes and we
                                              // don't have an actual client id here
                                              // TODO: traits were a mistake
                terminal_pane.scroll_up(size, fictitious_client_id);
            }
        }
    }

    pub fn clear_active_terminal_scroll(&mut self, client_id: ClientId) -> Result<()> {
        // TODO: is this a thing?
        let err_context =
            || format!("failed to clear scroll in active pane for client {client_id}");

        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            active_pane.clear_scroll();
            if !active_pane.is_scrolled() {
                if let PaneId::Terminal(raw_fd) = active_pane.pid() {
                    self.process_pending_vte_events(raw_fd)
                        .with_context(err_context)?;
                }
            }
        }
        Ok(())
    }

    pub fn handle_scrollwheel_up(
        &mut self,
        point: &Position,
        lines: usize,
        client_id: ClientId,
    ) -> Result<MouseEffect> {
        MouseHandler::handle_scrollwheel_up(self, point, lines, client_id)
    }

    pub fn handle_scrollwheel_down(
        &mut self,
        point: &Position,
        lines: usize,
        client_id: ClientId,
    ) -> Result<MouseEffect> {
        MouseHandler::handle_scrollwheel_down(self, point, lines, client_id)
    }

    fn get_pane_id_at(
        &mut self,
        point: &Position,
        search_selectable: bool,
    ) -> Result<Option<PaneId>> {
        let err_context = || format!("failed to get id of pane at position {point:?}");

        if self.tiled_panes.fullscreen_is_active()
            && (self.tiled_panes.fullscreen_covers_ui()
                || self
                    .is_position_inside_viewport(point)
                    .with_context(err_context)?)
        {
            return Ok(self.tiled_panes.fullscreen_pane_id());
        }

        let (stacked_pane_ids_under_flexible_pane, _stacked_pane_ids_over_flexible_pane) = {
            self.tiled_panes
                .stacked_pane_ids_under_and_over_flexible_panes()
                .with_context(err_context)?
        };
        let pane_contains_point = |p: &Box<dyn Pane>,
                                   point: &Position,
                                   stacked_pane_ids_under_flexible_pane: &HashSet<PaneId>|
         -> bool {
            let is_flexible_in_stack =
                p.current_geom().is_stacked() && !p.current_geom().rows.is_fixed();
            let is_stacked_under = stacked_pane_ids_under_flexible_pane.contains(&p.pid());
            let geom_to_compare_against =
                if is_stacked_under && !self.pane_frame_style.draws_full_frames() {
                    // these sort of panes are one-liner panes under a flexible pane in a stack when we
                    // don't draw pane frames - because the whole stack's content is offset to allow
                    // room for the boundary between panes, they are actually drawn 1 line above where
                    // they are
                    let mut geom = p.current_geom();
                    geom.y = geom.y.saturating_sub(p.get_content_offset().bottom);
                    geom
                } else if is_flexible_in_stack && !self.pane_frame_style.draws_full_frames() {
                    // these sorts of panes are flexible panes inside a stack when we don't draw pane
                    // frames - because the whole stack's content is offset to give room for the
                    // boundary between panes, we need to take this offset into account when figuring
                    // out whether the position is inside them
                    let mut geom = p.current_geom();
                    geom.rows.decrease_inner(p.get_content_offset().bottom);
                    geom
                } else {
                    p.current_geom()
                };
            geom_to_compare_against.contains(point)
        };

        let found_pane_id = if search_selectable {
            self.get_selectable_tiled_panes()
                .find(|(_, p)| pane_contains_point(p, point, &stacked_pane_ids_under_flexible_pane))
                .map(|(&id, _)| id)
        } else {
            self.get_tiled_panes()
                .find(|(_, p)| pane_contains_point(p, point, &stacked_pane_ids_under_flexible_pane))
                .map(|(&id, _)| id)
        };
        let resolved_pane_id = found_pane_id.map(|id| self.stack_list_member_at_point(id, point));
        if search_selectable {
            Ok(resolved_pane_id.filter(|id| {
                self.get_pane_with_id(*id)
                    .map(|p| p.selectable())
                    .unwrap_or(false)
            }))
        } else {
            Ok(resolved_pane_id)
        }
    }

    pub fn handle_mouse_event(
        &mut self,
        event: &MouseEvent,
        client_id: ClientId,
    ) -> Result<MouseEffect> {
        MouseHandler::handle_mouse_event(self, event, client_id)
    }

    pub fn copy_selection(&self, client_id: ClientId) -> Result<()> {
        let selected_text = self
            .get_active_pane(client_id)
            .and_then(|p| p.get_selected_text(client_id));
        if let Some(selected_text) = selected_text {
            self.write_selection_to_clipboard(&selected_text)
                .with_context(|| {
                    format!("failed to write selection to clipboard for client {client_id}")
                })?;
            self.senders
                .send_to_plugin(PluginInstruction::Update(vec![(
                    None,
                    None,
                    Event::CopyToClipboard(self.clipboard_provider.as_copy_destination()),
                )]))
                .with_context(|| {
                    format!("failed to inform plugins about copy selection for client {client_id}")
                })
                .non_fatal();
        }
        Ok(())
    }
    pub fn copy_text_to_clipboard(&self, text: &str) -> Result<()> {
        self.write_selection_to_clipboard(text)
            .with_context(|| format!("failed to write text to clipboard"))?;
        self.senders
            .send_to_plugin(PluginInstruction::Update(vec![(
                None,
                None,
                Event::CopyToClipboard(self.clipboard_provider.as_copy_destination()),
            )]))
            .with_context(|| "failed to inform plugins about clipboard copy")
            .non_fatal();
        Ok(())
    }

    fn write_selection_to_clipboard(&self, selection: &str) -> Result<()> {
        let err_context = || format!("failed to write selection to clipboard: '{}'", selection);

        let mut output = Output::default();
        let connected_clients: HashSet<ClientId> =
            { self.connected_clients.borrow().iter().copied().collect() };
        output.add_clients(&connected_clients, self.link_handler.clone(), None);
        let client_ids = connected_clients.iter().copied();
        let clipboard_event =
            match self
                .clipboard_provider
                .set_content(selection, &mut output, client_ids)
            {
                Ok(_) => output
                    .serialize()
                    .and_then(|serialized_output| {
                        self.senders
                            .send_to_server(ServerInstruction::Render(Some(serialized_output)))
                    })
                    .and_then(|_| {
                        Ok(Event::CopyToClipboard(
                            self.clipboard_provider.as_copy_destination(),
                        ))
                    })
                    .with_context(err_context)?,
                Err(err) => {
                    Err::<(), _>(err).with_context(err_context).non_fatal();
                    Event::SystemClipboardFailure
                },
            };
        self.senders
            .send_to_plugin(PluginInstruction::Update(vec![(
                None,
                None,
                clipboard_event,
            )]))
            .context("failed to notify plugins about new clipboard event")
            .non_fatal();

        Ok(())
    }
    fn forward_desktop_notifications(
        &self,
        notifications: Vec<(String, String)>,
        pane_id: u32,
    ) -> Result<()> {
        let err_context = || "failed to forward desktop notifications to host terminal".to_string();
        let mut output = Output::default();
        // Use all clients in the app, not just those viewing this tab —
        // desktop notifications should reach the host terminal regardless
        // of which tab is currently focused.
        let all_clients: HashSet<ClientId> = {
            self.connected_clients_in_app
                .borrow()
                .keys()
                .copied()
                .collect()
        };
        output.add_clients(&all_clients, self.link_handler.clone(), None);
        for (payload, terminator) in notifications {
            // Apply identifier namespacing (Phase 3)
            // The first semicolon-delimited part of payload is the metadata
            let (metadata, rest) = match payload.find(';') {
                Some(idx) => (
                    payload.get(..idx).unwrap_or_default(),
                    payload.get(idx..).unwrap_or_default(),
                ),
                None => (payload.as_str(), ""),
            };
            let namespaced_metadata = namespace_notification_id(metadata, pane_id);
            let raw = if rest.is_empty() {
                format!("\x1b]99;{}{}", namespaced_metadata, terminator)
            } else {
                format!("\x1b]99;{}{}{}", namespaced_metadata, rest, terminator)
            };
            output.add_post_vte_instruction_to_multiple_clients(all_clients.iter().copied(), &raw);
        }
        let serialized_output = output.serialize().with_context(err_context)?;
        self.senders
            .send_to_server(ServerInstruction::Render(Some(serialized_output)))
            .with_context(err_context)?;
        Ok(())
    }
    pub fn visible(&mut self, visible: bool) -> Result<()> {
        let pids_in_this_tab = self.tiled_panes.pane_ids().filter_map(|p| match p {
            PaneId::Plugin(pid) => Some(pid),
            _ => None,
        });
        let mut plugin_updates = vec![];
        for pid in pids_in_this_tab {
            plugin_updates.push((Some(*pid), None, Event::Visible(visible)));
        }
        self.senders
            .send_to_plugin(PluginInstruction::Update(plugin_updates))
            .with_context(|| format!("failed to set visibility of tab to {visible}"))?;
        if !visible {
            self.mouse_hover_pane_id.clear();
            self.plugin_hover_pane_id.clear();
        }
        Ok(())
    }

    pub fn clear_mouse_help_text(&mut self, client_id: ClientId) {
        self.mouse_help_text_visible.insert(client_id, false);
    }

    pub fn update_active_pane_name(&mut self, buf: Vec<u8>, client_id: ClientId) -> Result<()> {
        let err_context =
            || format!("failed to update name of active pane to '{buf:?}' for client {client_id}");
        let s = str::from_utf8(&buf).with_context(err_context)?;
        self.get_active_pane_mut(client_id)
            .with_context(|| format!("no active pane found for client {client_id}"))
            .map(|active_pane| {
                let to_update = match s {
                    "\0" => s, // pane name terminator
                    "\u{007F}" | "\u{0008}" => {
                        // delete and backspace keys
                        s
                    },
                    _ => &clean_string_from_control_and_linebreak(s),
                };
                active_pane.update_name(&to_update);
            })?;
        Ok(())
    }

    pub fn rename_pane(&mut self, buf: Vec<u8>, pane_id: PaneId) -> Result<()> {
        let err_context = || {
            format!(
                "failed to update name of active pane to '{buf:?}' for pane_id {:?}",
                pane_id
            )
        };
        let pane = self
            .floating_panes
            .get_pane_mut(pane_id)
            .or_else(|| self.tiled_panes.get_pane_mut(pane_id))
            .or_else(|| {
                self.suppressed_panes
                    .get_mut(&pane_id)
                    .map(|s_p| &mut s_p.1)
            })
            .with_context(err_context)?;
        pane.rename(buf);
        Ok(())
    }

    pub fn rename_active_pane(&mut self, buf: Vec<u8>, client_id: ClientId) -> Result<()> {
        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            active_pane.rename(buf);
        }
        Ok(())
    }

    pub fn undo_active_rename_pane(&mut self, client_id: ClientId) -> Result<()> {
        if let Some(active_terminal_id) = self.get_active_terminal_id(client_id) {
            let active_terminal = if self.are_floating_panes_visible() {
                self.floating_panes
                    .get_pane_mut(PaneId::Terminal(active_terminal_id))
            } else {
                self.tiled_panes
                    .get_pane_mut(PaneId::Terminal(active_terminal_id))
            }
            .with_context(|| {
                format!("failed to undo rename of active pane for client {client_id}")
            })?;

            active_terminal.load_pane_name();
        }
        Ok(())
    }

    pub fn is_position_inside_viewport(&self, point: &Position) -> Result<bool> {
        let Position {
            line: Line(line),
            column: Column(column),
        } = *point;
        let line: usize = line.try_into().with_context(|| {
            format!("failed to determine if position {point:?} is inside viewport")
        })?;

        let viewport = self.viewport.borrow();
        Ok(line >= viewport.y
            && column >= viewport.x
            && line < viewport.y + viewport.rows
            && column < viewport.x + viewport.cols)
    }

    pub fn set_pane_frames(&mut self, pane_frame_style: PaneFrameStyle) {
        self.tiled_panes.set_pane_frames(pane_frame_style);
        self.floating_panes.set_pane_frame_style(pane_frame_style);
        self.pane_frame_style = pane_frame_style;
        self.set_should_clear_display_before_rendering();
        self.set_force_render();
    }
    pub fn panes_to_hide_count(&self) -> usize {
        self.tiled_panes.panes_to_hide_count()
    }

    pub fn update_search_term(&mut self, buf: Vec<u8>, client_id: ClientId) -> Result<()> {
        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            // It only allows terminating char(\0), printable unicode, delete and backspace keys.
            // TODO: we should really remove this limitation to allow searching for emojis and
            // other wide chars - currently the search mechanism itself ignores wide chars, so we
            // should first fix that before removing this condition
            let is_updatable = buf
                .iter()
                .all(|u| matches!(u, 0x00 | 0x20..=0x7E | 0x08 | 0x7F));
            if is_updatable {
                let s = str::from_utf8(&buf).with_context(|| {
                    format!("failed to update search term to '{buf:?}' for client {client_id}")
                })?;
                active_pane.update_search_term(s);
            }
        }
        Ok(())
    }

    pub fn search_down(&mut self, client_id: ClientId) {
        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            active_pane.search_down();
        }
    }

    pub fn search_up(&mut self, client_id: ClientId) {
        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            active_pane.search_up();
        }
    }

    pub fn toggle_search_case_sensitivity(&mut self, client_id: ClientId) {
        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            active_pane.toggle_search_case_sensitivity();
        }
    }

    pub fn toggle_search_wrap(&mut self, client_id: ClientId) {
        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            active_pane.toggle_search_wrap();
        }
    }

    pub fn toggle_search_whole_words(&mut self, client_id: ClientId) {
        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            active_pane.toggle_search_whole_words();
        }
    }

    pub fn clear_search(&mut self, client_id: ClientId) {
        if let Some(active_pane) = self.get_active_pane_or_floating_pane_mut(client_id) {
            active_pane.clear_search();
        }
    }

    pub fn is_pending(&self) -> bool {
        self.is_pending
    }

    pub fn add_red_pane_frame_color_override(
        &mut self,
        pane_id: PaneId,
        error_text: Option<String>,
    ) {
        if let Some(pane) = self
            .tiled_panes
            .get_pane_mut(pane_id)
            .or_else(|| self.floating_panes.get_pane_mut(pane_id))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == pane_id)
                    .map(|s_p| &mut s_p.1)
            })
        {
            pane.add_red_pane_frame_color_override(error_text);
        }
    }
    pub fn add_highlight_pane_frame_color_override(
        &mut self,
        pane_id: PaneId,
        error_text: Option<String>,
        client_id: Option<ClientId>,
    ) {
        if let Some(pane) = self
            .tiled_panes
            .get_pane_mut(pane_id)
            .or_else(|| self.floating_panes.get_pane_mut(pane_id))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == pane_id)
                    .map(|s_p| &mut s_p.1)
            })
        {
            pane.add_highlight_pane_frame_color_override(error_text, client_id);
        }
    }
    pub fn clear_pane_frame_color_override(
        &mut self,
        pane_id: PaneId,
        client_id: Option<ClientId>,
    ) {
        if let Some(pane) = self
            .tiled_panes
            .get_pane_mut(pane_id)
            .or_else(|| self.floating_panes.get_pane_mut(pane_id))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == pane_id)
                    .map(|s_p| &mut s_p.1)
            })
        {
            pane.clear_pane_frame_color_override(client_id);
        }
    }
    pub fn set_plugin_regex_highlights_for_pane(
        &mut self,
        pane_id: PaneId,
        plugin_id: u32,
        highlights: Vec<RegexHighlight>,
        style: &Style,
    ) {
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            pane.set_plugin_regex_highlights(plugin_id, highlights, style);
        }
    }

    pub fn clear_all_plugin_highlights(&mut self, plugin_id: u32) {
        for pane_id in self.get_all_pane_ids() {
            if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
                pane.clear_plugin_highlights(plugin_id);
            }
        }
    }

    pub fn clear_plugin_highlights_for_pane(&mut self, pane_id: PaneId, plugin_id: u32) {
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            pane.clear_plugin_highlights(plugin_id);
        }
    }

    pub fn update_plugin_loading_stage(&mut self, pid: u32, loading_indication: LoadingIndication) {
        if let Some(plugin_pane) = self
            .tiled_panes
            .get_pane_mut(PaneId::Plugin(pid))
            .or_else(|| self.floating_panes.get_pane_mut(PaneId::Plugin(pid)))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == PaneId::Plugin(pid))
                    .map(|s_p| &mut s_p.1)
            })
        {
            plugin_pane.update_loading_indication(loading_indication);
        }
    }
    pub fn show_plugin_cursor(
        &mut self,
        pid: u32,
        client_id: ClientId,
        cursor_position: Option<(usize, usize)>,
    ) {
        if let Some(plugin_pane) = self
            .tiled_panes
            .get_pane_mut(PaneId::Plugin(pid))
            .or_else(|| self.floating_panes.get_pane_mut(PaneId::Plugin(pid)))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == PaneId::Plugin(pid))
                    .map(|s_p| &mut s_p.1)
            })
        {
            plugin_pane.show_cursor(client_id, cursor_position);
        }
    }
    pub fn start_plugin_loading_indication(
        &mut self,
        pid: u32,
        loading_indication: LoadingIndication,
    ) {
        if let Some(plugin_pane) = self
            .tiled_panes
            .get_pane_mut(PaneId::Plugin(pid))
            .or_else(|| self.floating_panes.get_pane_mut(PaneId::Plugin(pid)))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == PaneId::Plugin(pid))
                    .map(|s_p| &mut s_p.1)
            })
        {
            plugin_pane.start_loading_indication(loading_indication);
        }
    }
    pub fn progress_plugin_loading_offset(&mut self, pid: u32) {
        if let Some(plugin_pane) = self
            .tiled_panes
            .get_pane_mut(PaneId::Plugin(pid))
            .or_else(|| self.floating_panes.get_pane_mut(PaneId::Plugin(pid)))
            .or_else(|| {
                self.suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == PaneId::Plugin(pid))
                    .map(|s_p| &mut s_p.1)
            })
        {
            plugin_pane.progress_animation_offset();
        }
    }
    pub fn show_floating_panes(&mut self) {
        // this function is to be preferred to directly invoking floating_panes.toggle_show_panes(true)
        self.floating_panes.toggle_show_panes(true);
        self.tiled_panes.unfocus_all_panes();
        self.set_force_render();
    }

    pub fn hide_floating_panes(&mut self) {
        // this function is to be preferred to directly invoking
        // floating_panes.toggle_show_panes(false)
        if self.floating_panes.fullscreen_is_active() {
            self.floating_panes.unset_fullscreen();
        }
        self.floating_panes.toggle_show_panes(false);
        self.tiled_panes.focus_all_panes();
        self.set_force_render();
    }

    pub fn show_floating_panes_atomic(&mut self, mut completion: Option<NotificationEnd>) {
        if self.floating_panes.panes_are_visible() {
            if let Some(c) = completion.as_mut() {
                c.set_exit_status(2);
            }
        } else {
            match self.floating_panes.last_selectable_floating_pane_id() {
                Some(last_selectable_floating_pane_id) => {
                    self.show_floating_panes();
                    self.floating_panes
                        .focus_pane_for_all_clients(last_selectable_floating_pane_id);
                    if let Some(c) = completion.as_mut() {
                        c.set_exit_status(0);
                    }
                },
                None => {
                    // No selectable floating panes exist — surface must not be shown
                    if let Some(c) = completion.as_mut() {
                        c.set_exit_status(1);
                    }
                },
            }
        }
        drop(completion);
    }

    pub fn hide_floating_panes_atomic(&mut self, mut completion: Option<NotificationEnd>) {
        if !self.floating_panes.panes_are_visible() {
            if let Some(c) = completion.as_mut() {
                c.set_exit_status(2);
            }
        } else {
            self.hide_floating_panes();
            if let Some(c) = completion.as_mut() {
                c.set_exit_status(0);
            }
        }
        drop(completion);
    }

    pub fn find_plugin(&self, run_plugin_or_alias: &RunPluginOrAlias) -> Option<PaneId> {
        self.tiled_panes
            .get_plugin_pane_id(run_plugin_or_alias)
            .or_else(|| self.floating_panes.get_plugin_pane_id(run_plugin_or_alias))
            .or_else(|| {
                self.suppressed_panes
                    .iter()
                    .find(|(_id, (_, pane))| {
                        run_plugin_or_alias.is_equivalent_to_run(pane.invoked_with())
                    })
                    .map(|(_, (_, pane))| pane.pid()) // TODO: does this break things????
            })
    }

    pub fn focus_pane_with_id(
        &mut self,
        pane_id: PaneId,
        should_float: bool,
        should_be_in_place: bool,
        client_id: ClientId,
    ) -> Result<()> {
        // TODO: should error if pane is not selectable
        if self.focus_hidden_stack_list_member(pane_id, client_id) {
            return Ok(());
        }
        self.tiled_panes
            .focus_pane_if_exists(pane_id, client_id)
            .map(|_| self.hide_floating_panes())
            .or_else(|_| {
                let focused_floating_pane =
                    self.floating_panes.focus_pane_if_exists(pane_id, client_id);
                if focused_floating_pane.is_ok() {
                    self.show_floating_panes()
                };
                focused_floating_pane
            })
            // TODO: change suppressed_panes to be a proper struct with methods that make sense rather
            // than doing this dance every time
            .or_else(|_| {
                match self
                    .suppressed_panes
                    .extract_if(|_key, (_, pane)| pane.pid() == pane_id)
                    .next()
                    .map(|(_key, (_, pane))| pane)
                {
                    Some(mut pane) => {
                        pane.set_selectable(true);
                        if should_float {
                            self.show_floating_panes();
                            self.add_floating_pane(pane, pane_id, None, true, Some(client_id))
                        } else if should_be_in_place {
                            let replaced_pane = if self.are_floating_panes_visible() {
                                self.floating_panes
                                    .replace_active_pane(pane, client_id)
                                    .ok()
                            } else {
                                self.tiled_panes.replace_active_pane(pane, client_id)
                            };
                            if let Some(replaced_pane) = replaced_pane {
                                let is_scrollback_editor = false;
                                self.track_stack_list_member_id_swap(replaced_pane.pid(), pane_id);
                                self.insert_suppressed_pane(
                                    pane_id,
                                    (is_scrollback_editor, replaced_pane),
                                );
                            } else {
                                log::error!("Could not find pane to replace, aborting.");
                            }
                            Ok(())
                        } else {
                            self.hide_floating_panes();
                            self.add_tiled_pane(pane, pane_id, false, Some(client_id))
                        }
                    },
                    None => Ok(()),
                }
            })
    }
    pub fn focus_suppressed_pane_for_all_clients(&mut self, pane_id: PaneId) {
        if self.make_hidden_stack_list_member_visible(pane_id) {
            self.tiled_panes.focus_pane_for_all_clients(pane_id);
            return;
        }
        match self.suppressed_panes.remove(&pane_id) {
            Some(pane) => {
                self.show_floating_panes();
                self.add_floating_pane(pane.1, pane_id, None, true, None)
                    .non_fatal();
                self.floating_panes.focus_pane_for_all_clients(pane_id);
            },
            None => {
                log::error!("Could not find suppressed pane wiht id: {:?}", pane_id);
            },
        }
    }
    pub fn suppress_pane(&mut self, pane_id: PaneId, _client_id: Option<ClientId>) {
        // this method places a pane in the suppressed pane with its own ID - this means we'll
        // not take it out of there when another pane is closed (eg. like happens with the
        // scrollback editor), but it has to take itself out on its own (eg. a plugin using the
        // show_self() method)
        if let Some(pane) = self.extract_pane(pane_id, true) {
            self.insert_suppressed_pane(pane_id, (false, pane));
        }
    }
    fn make_hidden_stack_list_member_visible(&mut self, pane_id: PaneId) -> bool {
        self.swap_in_hidden_stack_list_member(pane_id, None)
    }
    pub fn unsuppress_pane(&mut self, pane_id: PaneId, should_float_if_hidden: bool) {
        // removes a pane from being suppressed (hidden) but does not focus it
        if self.make_hidden_stack_list_member_visible(pane_id) {
            return;
        }
        match self
            .suppressed_panes
            .extract_if(|_key, (_, pane)| pane.pid() == pane_id)
            .next()
            .map(|(_key, (_, pane))| pane)
        {
            Some(pane) => {
                if should_float_if_hidden {
                    self.add_floating_pane(pane, pane_id, None, true, None)
                        .non_fatal();
                } else {
                    self.add_tiled_pane(pane, pane_id, false, None).non_fatal();
                }
            },
            None => {
                log::error!("Could not find suppressed pane with id: {:?}", pane_id);
            },
        }
    }
    pub fn unsuppress_or_expand_pane(&mut self, pane_id: PaneId, should_float_if_hidden: bool) {
        // removes a pane from being suppressed (hidden) but does not focus it
        if self.make_hidden_stack_list_member_visible(pane_id) {
            return;
        }
        match self
            .suppressed_panes
            .extract_if(|_key, (_, pane)| pane.pid() == pane_id)
            .next()
            .map(|(_key, (_, pane))| pane)
        {
            Some(pane) => {
                if should_float_if_hidden {
                    self.add_floating_pane(pane, pane_id, None, true, None)
                        .non_fatal();
                } else {
                    self.add_tiled_pane(pane, pane_id, false, None).non_fatal();
                }
            },
            None => {
                let expand_panes_success = self.tiled_panes.expand_pane_in_stack(pane_id).len() > 0;
                if !expand_panes_success {
                    log::error!(
                        "Could not find suppressed or stacked pane with id: {:?}",
                        pane_id
                    );
                }
            },
        }
    }
    fn insert_suppressed_pane(
        &mut self,
        suppressing_pane_id: PaneId,
        pane_to_suppress: (bool, Box<dyn Pane>),
    ) {
        // bool -> is_scrollback_editor
        // this method is intended to insert an existing provided pane into suppressed_panes, while
        // making sure any existing panes already in suppressed_panes still remain there
        // if there's a key collision (eg. the suppressing_pane_id already suppresses another
        // pane), we fix the colliding pane so that it now becomes suppressed by its own id (i.e.
        // needs to explicitly be removed from suppressed_panes by eg. a plugin action rather than
        // being conditionally removed when its suppressing pane is closed or itself suppressed)
        //
        // - suppressing_pane_id: the id of the pane suppressing this pane - the pane that if
        // closed, should trigger this pane being unsuppressed
        // - pane_to_suppress: the pane itself that we want to suppress

        // this closure removes and returns an existing pane from the map if it exists under this key
        // and inserts the given pane into the map under this key
        let mut insert_and_return_existing_value =
            |key: PaneId, value: (bool, Box<dyn Pane>)| -> Option<(bool, Box<dyn Pane>)> {
                let existing = self.suppressed_panes.remove(&key);
                self.suppressed_panes.insert(key, value);
                existing
            };

        // here we try to insert a pane into the suppressed panes map while making sure not to drop
        // (close) any existing panes in the map. We repeat the action of remapping existing panes
        // under their own keys until all keys either reference the suppressing_pane_id (only one
        // can do this) or themselves
        let mut key_to_insert = suppressing_pane_id;
        let mut pane_to_insert = Some(pane_to_suppress);
        loop {
            pane_to_insert = pane_to_insert
                .take()
                .and_then(|p| insert_and_return_existing_value(key_to_insert, p));
            if let Some(pane_to_insert) = pane_to_insert.as_ref() {
                key_to_insert = pane_to_insert.1.pid();
            } else {
                break;
            }
        }
    }

    pub fn pane_infos(&self) -> Vec<PaneInfo> {
        let mut pane_info = vec![];
        let current_pane_group = { self.current_pane_group.borrow().clone_inner() };
        let mut tiled_pane_info = self.tiled_panes.pane_info(&current_pane_group);
        let mut floating_pane_info = self.floating_panes.pane_info(&current_pane_group);
        pane_info.append(&mut tiled_pane_info);
        pane_info.append(&mut floating_pane_info);
        for (_pane_id_of_suppressing_pane, (_is_scrollback_editor, pane)) in
            self.suppressed_panes.iter()
        {
            let mut pane_info_for_suppressed_pane =
                pane_info_for_pane(&pane.pid(), pane, &current_pane_group);
            pane_info_for_suppressed_pane.is_floating = false;
            pane_info_for_suppressed_pane.is_suppressed = true;
            pane_info_for_suppressed_pane.is_focused = false;
            pane_info_for_suppressed_pane.is_fullscreen = false;
            pane_info.push(pane_info_for_suppressed_pane);
        }
        pane_info
    }
    pub fn add_floating_pane(
        &mut self,
        mut pane: Box<dyn Pane>,
        pane_id: PaneId,
        floating_pane_coordinates: Option<FloatingPaneCoordinates>,
        should_focus_new_pane: bool,
        client_id: Option<ClientId>,
    ) -> Result<()> {
        let err_context = || format!("failed to add floating pane");
        if self.floating_panes.fullscreen_is_active() {
            self.floating_panes.unset_fullscreen();
        }
        if let Some(mut new_pane_geom) = self.floating_panes.find_room_for_new_pane() {
            if let Some(floating_pane_coordinates) = &floating_pane_coordinates {
                let viewport = self.viewport.borrow();
                if let Some(pinned) = floating_pane_coordinates.pinned.as_ref() {
                    pane.set_pinned(*pinned);
                }
                new_pane_geom.adjust_coordinates(floating_pane_coordinates.clone(), *viewport);
                self.swap_layouts.set_is_floating_damaged();
            }
            pane.set_active_at(Instant::now());
            pane.set_geom(new_pane_geom);
            let is_borderless = floating_pane_coordinates
                .and_then(|c| c.borderless)
                .unwrap_or(false);
            if is_borderless {
                pane.set_content_offset(Offset::frame(0));
                pane.set_borderless(true);
            } else {
                pane.set_content_offset(Offset::frame(1)); // floating panes always have a frame
                pane.render_full_viewport(); // to make sure the frame is re-rendered
            }
            resize_pty!(pane, self.os_api, self.senders, self.character_cell_size)
                .with_context(err_context)?;
            self.floating_panes.add_pane(pane_id, pane);
            if should_focus_new_pane {
                if let Some(client_id) = client_id {
                    self.floating_panes.focus_pane(pane_id, client_id);
                } else {
                    self.floating_panes.focus_pane_for_all_clients(pane_id);
                }
            }
        }
        if self.auto_layout && !self.swap_layouts.is_floating_damaged() {
            // only do this if we're already in this layout, otherwise it might be
            // confusing and not what the user intends
            self.swap_layouts.set_is_floating_damaged(); // we do this so that we won't skip to the
                                                         // next layout
            self.relayout_floating_panes(false)?;
        }
        Ok(())
    }
    pub fn add_tiled_pane(
        &mut self,
        mut pane: Box<dyn Pane>,
        pane_id: PaneId,
        without_relayout: bool,
        client_id: Option<ClientId>,
    ) -> Result<()> {
        if self.tiled_panes.fullscreen_is_active() {
            self.tiled_panes.unset_fullscreen();
        }
        self.dissolve_stack_lists_for_classic_mutation();
        let should_auto_layout =
            self.auto_layout && !self.swap_layouts.is_tiled_damaged() && !without_relayout;
        if self.tiled_panes.has_room_for_new_pane() {
            pane.set_active_at(Instant::now());
            if should_auto_layout {
                // no need to relayout here, we'll do it when reapplying the swap layout
                // below
                self.tiled_panes
                    .insert_pane_without_relayout(pane_id, pane, client_id);
            } else {
                self.tiled_panes.insert_pane(pane_id, pane, client_id);
            }
            self.tiled_panes.reapply_pane_frames();
            self.set_should_clear_display_before_rendering();
            if let Some(client_id) = client_id {
                self.tiled_panes.focus_pane(pane_id, client_id);
            }
        }
        if should_auto_layout {
            // only do this if we're already in this layout, otherwise it might be
            // confusing and not what the user intends
            self.swap_layouts.set_is_tiled_damaged(); // we do this so that we won't skip to the
                                                      // next layout
            self.relayout_tiled_panes(false)?;
        }
        Ok(())
    }
    pub fn add_stacked_pane_to_pane_id(
        &mut self,
        pane: Box<dyn Pane>,
        pane_id: PaneId,
        root_pane_id: PaneId,
        should_focus: bool,
    ) -> Result<()> {
        if self.tiled_panes.fullscreen_is_active() {
            self.tiled_panes.unset_fullscreen();
        }
        self.dissolve_stack_lists_for_classic_mutation();
        self.tiled_panes
            .add_pane_to_stack_of_pane_id(pane_id, pane, root_pane_id);
        self.set_should_clear_display_before_rendering();
        if should_focus {
            self.tiled_panes.expand_pane_in_stack(pane_id);
        }
        self.swap_layouts.set_is_tiled_damaged();
        Ok(())
    }
    pub fn add_stacked_pane_to_active_pane(
        &mut self,
        pane: Box<dyn Pane>,
        pane_id: PaneId,
        client_id: ClientId,
        should_focus: bool,
    ) -> Result<()> {
        if self.tiled_panes.fullscreen_is_active() {
            self.tiled_panes.unset_fullscreen();
        }
        self.dissolve_stack_lists_for_classic_mutation();
        self.tiled_panes
            .add_pane_to_stack_of_active_pane(pane_id, pane, client_id);
        if should_focus {
            self.tiled_panes.focus_pane(pane_id, client_id);
        }
        self.swap_layouts.set_is_tiled_damaged();
        Ok(())
    }
    pub fn request_plugin_permissions(&mut self, pid: u32, permissions: Option<PluginPermission>) {
        let mut should_focus_pane = false;
        if let Some(plugin_pane) = self
            .tiled_panes
            .get_pane_mut(PaneId::Plugin(pid))
            .or_else(|| self.floating_panes.get_pane_mut(PaneId::Plugin(pid)))
            .or_else(|| {
                let mut suppressed_pane = self
                    .suppressed_panes
                    .values_mut()
                    .find(|s_p| s_p.1.pid() == PaneId::Plugin(pid))
                    .map(|s_p| &mut s_p.1);
                if let Some(suppressed_pane) = suppressed_pane.as_mut() {
                    if permissions.is_some() {
                        // here what happens is that we're requesting permissions for a pane that
                        // is suppressed, meaning the user cannot see the permission request
                        // so we temporarily focus this pane as a floating pane, marking it so that
                        // once the permissions are accepted/rejected by the user, it will be
                        // suppressed again
                        suppressed_pane.set_should_be_suppressed(true);
                        should_focus_pane = true;
                    }
                }
                suppressed_pane
            })
        {
            plugin_pane.request_permissions_from_user(permissions);
        }
        if should_focus_pane {
            self.focus_suppressed_pane_for_all_clients(PaneId::Plugin(pid));
        }
    }
    pub fn rerun_terminal_pane_with_id(
        &mut self,
        terminal_pane_id: u32,
        completion_tx: Option<NotificationEnd>,
    ) {
        let pane_id = PaneId::Terminal(terminal_pane_id);
        match self
            .floating_panes
            .get_mut(&pane_id)
            .or_else(|| self.tiled_panes.get_pane_mut(pane_id))
            .or_else(|| self.suppressed_panes.get_mut(&pane_id).map(|p| &mut p.1))
        {
            Some(pane_to_rerun) => {
                if let Some(command_to_rerun) = pane_to_rerun.rerun() {
                    self.pids_waiting_resize.insert(terminal_pane_id);
                    let _ = self.senders.send_to_pty(PtyInstruction::ReRunCommandInPane(
                        pane_id,
                        command_to_rerun,
                        completion_tx,
                    ));
                } else {
                    log::error!("Pane is still running!")
                }
            },
            None => {
                log::error!(
                    "Failed to find terminal pane with id {} to rerun in tab",
                    terminal_pane_id
                );
            },
        }
    }
    pub fn resize_pane_with_id(&mut self, strategy: ResizeStrategy, pane_id: PaneId) -> Result<()> {
        let err_context = || format!("unable to resize pane");
        if self.pane_is_stack_list_member(&pane_id) {
            self.dissolve_stack_lists_for_classic_mutation();
        }
        if self.floating_panes.panes_contain(&pane_id) {
            let successfully_resized = self
                .floating_panes
                .resize_pane_with_id(strategy, pane_id)
                .with_context(err_context)?;
            if successfully_resized {
                self.swap_layouts.set_is_floating_damaged();
                self.swap_layouts.set_is_tiled_damaged();
                self.set_force_render(); // we force render here to make sure the panes under the floating pane render and don't leave "garbage" in case of a decrease
            }
        } else if self.tiled_panes.panes_contain(&pane_id) {
            match self
                .tiled_panes
                .resize_pane_with_id(strategy, pane_id, None)
            {
                Ok(_) => {},
                Err(err) => match err.downcast_ref::<ZellijError>() {
                    Some(ZellijError::CantResizeFixedPanes { pane_ids }) => {
                        let mut pane_ids_to_error = vec![];
                        for (id, is_terminal) in pane_ids {
                            if *is_terminal {
                                pane_ids_to_error.push(PaneId::Terminal(*id));
                            } else {
                                pane_ids_to_error.push(PaneId::Plugin(*id));
                            };
                        }
                        self.senders
                            .send_to_background_jobs(BackgroundJob::DisplayPaneError(
                                pane_ids_to_error,
                                "FIXED!".into(),
                            ))
                            .with_context(err_context)?;
                    },
                    _ => Err::<(), _>(err).non_fatal(),
                },
            }
        } else if self
            .suppressed_panes
            .values()
            .any(|s_p| s_p.1.pid() == pane_id)
        {
            log::error!("Cannot resize suppressed panes");
        }
        Ok(())
    }
    pub fn update_theme(&mut self, theme: Styling) {
        self.style.colors = theme;
        // The tab's `default_mode_info` is what `update_input_modes`
        // falls back to when no per-client entry exists in
        // `self.mode_info`. Without this update, plugins on a
        // freshly-connected client (one that has never manually
        // changed mode) receive `Event::ModeUpdate` carrying the old
        // style and skip their re-render.
        self.default_mode_info.update_theme(theme);
        self.floating_panes.update_pane_themes(theme);
        self.tiled_panes.update_pane_themes(theme);
        for (_, pane) in self.suppressed_panes.values_mut() {
            pane.update_theme(theme);
        }
    }
    pub fn update_rounded_corners(&mut self, rounded_corners: bool) {
        self.style.rounded_corners = rounded_corners;
        self.floating_panes
            .update_pane_rounded_corners(rounded_corners);
        self.tiled_panes
            .update_pane_rounded_corners(rounded_corners);
        for (_, pane) in self.suppressed_panes.values_mut() {
            pane.update_rounded_corners(rounded_corners);
        }
    }
    pub fn update_frame_layout(
        &mut self,
        title_alignment: zellij_utils::data::PaneTitleAlignment,
        gap_x: usize,
        gap_y: usize,
        padding: zellij_utils::data::PanePadding,
        inactive_grayscale: u8,
        hide_default_pane_names: bool,
    ) {
        self.style.pane_title_alignment = title_alignment;
        self.style.pane_gap_x = gap_x;
        self.style.pane_gap_y = gap_y;
        self.style.pane_padding = padding;
        self.style.inactive_pane_grayscale = inactive_grayscale;
        self.style.hide_default_pane_names = hide_default_pane_names;
        self.floating_panes
            .update_pane_frame_layout(title_alignment, gap_x, gap_y, padding, inactive_grayscale, hide_default_pane_names);
        self.tiled_panes
            .update_pane_frame_layout(title_alignment, gap_x, gap_y, padding, inactive_grayscale, hide_default_pane_names);
        for (_, pane) in self.suppressed_panes.values_mut() {
            pane.update_frame_layout(title_alignment, gap_x, gap_y, padding, inactive_grayscale, hide_default_pane_names);
        }
    }
    pub fn update_arrow_fonts(&mut self, should_support_arrow_fonts: bool) {
        self.arrow_fonts = should_support_arrow_fonts;
        self.floating_panes
            .update_pane_arrow_fonts(should_support_arrow_fonts);
        self.tiled_panes
            .update_pane_arrow_fonts(should_support_arrow_fonts);
        for (_, pane) in self.suppressed_panes.values_mut() {
            pane.update_arrow_fonts(should_support_arrow_fonts);
        }
    }
    pub fn update_kitty_host_support(&mut self, supported: KittyHostSupport) {
        self.kitty_host_support = Some(supported);
        self.floating_panes
            .update_pane_kitty_host_support(supported);
        self.tiled_panes.update_pane_kitty_host_support(supported);
        for (_, pane) in self.suppressed_panes.values_mut() {
            pane.update_kitty_host_support(supported);
        }
    }
    pub fn update_default_shell(&mut self, mut default_shell: Option<PathBuf>) {
        if let Some(default_shell) = default_shell.take() {
            self.default_shell = default_shell;
        }
    }
    pub fn update_default_editor(&mut self, mut default_editor: Option<PathBuf>) {
        if let Some(default_editor) = default_editor.take() {
            self.default_editor = Some(default_editor);
        }
    }
    pub fn update_copy_options(&mut self, copy_options: &CopyOptions) {
        self.clipboard_provider = match &copy_options.command {
            Some(command) => ClipboardProvider::Command(CopyCommand::new(command.clone())),
            None => ClipboardProvider::Osc52(copy_options.clipboard),
        };
        self.copy_on_select = copy_options.copy_on_select;
    }
    pub fn update_auto_layout(&mut self, auto_layout: bool) {
        self.auto_layout = auto_layout;
    }
    pub fn update_advanced_mouse_actions(&mut self, advanced_mouse_actions: bool) {
        self.advanced_mouse_actions = advanced_mouse_actions;
    }
    pub fn update_mouse_scroll_resize(&mut self, mouse_scroll_resize: bool) {
        self.mouse_scroll_resize = mouse_scroll_resize;
    }
    pub fn update_mouse_hover_effects(&mut self, mouse_hover_effects: bool) {
        self.mouse_hover_effects = mouse_hover_effects;
    }
    /// Is this client currently typing into a modal prompt (renaming a pane or
    /// tab, entering a search term)?
    ///
    /// These modes act on whatever is ACTIVE, so letting hover move the focus
    /// underneath them drags the prompt from pane to pane: rename one pane,
    /// then sweep the mouse across the tab and every pane you touch appears to
    /// enter rename mode.
    pub fn client_is_in_text_entry_mode(&self, client_id: ClientId) -> bool {
        self.mode_info
            .borrow()
            .get(&client_id)
            .map(|mode_info| {
                matches!(
                    mode_info.mode,
                    InputMode::RenamePane
                        | InputMode::RenameTab
                        | InputMode::EnterSearch
                        | InputMode::Prompt
                )
            })
            .unwrap_or(false)
    }
    /// Threshold + target layout for the responsive collapse. Set from config
    /// at tab creation and on reconfigure.
    pub fn update_responsive_layout(&mut self, min_cols: usize, layout_name: String) {
        self.responsive_min_cols = min_cols;
        self.responsive_layout_name = layout_name;
    }
    /// Cap on stacked-pane picker rows. Takes effect on the next list refresh,
    /// which is what recomputes the reserved rows.
    pub fn update_stack_list_max_rows(&mut self, max_rows: usize) {
        self.stack_list_max_rows = max_rows;
    }
    pub fn update_stack_list_grid(&mut self, grid: bool) {
        self.stack_list_grid = grid;
    }
    pub fn update_stack_list_style(&mut self, style: StackListStyle) {
        self.stack_list_style = style;
    }
    pub fn update_focus_follows_mouse(&mut self, focus_follows_mouse: bool) {
        self.focus_follows_mouse = focus_follows_mouse;
    }
    pub fn update_mouse_click_through(&mut self, mouse_click_through: bool) {
        self.mouse_click_through = mouse_click_through;
    }
    pub fn clear_mouse_hover_state(&mut self) {
        self.mouse_hover_pane_id.clear();
        self.plugin_hover_pane_id.clear();
        self.mouse_last_pane_id.clear();
        self.mouse_help_text_visible.clear();
    }
    pub fn update_web_sharing(&mut self, web_sharing: WebSharing) {
        let old_value = self.web_sharing;
        self.web_sharing = web_sharing;
        if old_value != self.web_sharing {
            let _ = self.update_input_modes();
        }
    }
    pub fn extract_suppressed_panes(&mut self) -> SuppressedPanes {
        let stack_list_members = &self.stack_list_of_member;
        self.suppressed_panes
            .extract_if(|key, _| !stack_list_members.contains_key(key))
            .collect()
    }
    pub fn add_suppressed_panes(&mut self, mut suppressed_panes: SuppressedPanes) {
        for (pane_id, suppressed_pane_entry) in suppressed_panes.drain() {
            self.insert_suppressed_pane(pane_id, suppressed_pane_entry);
        }
    }
    pub fn toggle_pane_pinned(&mut self, client_id: ClientId) {
        if let Some(pane) = self.get_active_pane_mut(client_id) {
            pane.toggle_pinned();
            self.set_force_render();
        }
    }
    pub fn set_floating_pane_pinned(&mut self, pane_id: PaneId, should_be_pinned: bool) {
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            pane.set_pinned(should_be_pinned);
            self.set_force_render();
        }
    }
    pub fn has_room_for_stack(&mut self, root_pane_id: PaneId, stack_size: usize) -> bool {
        self.dissolve_stack_lists_for_classic_mutation();
        if self.floating_panes.panes_contain(&root_pane_id)
            || self.suppressed_panes.contains_key(&root_pane_id)
        {
            log::error!("Root pane of stack cannot be floating or suppressed");
            return false;
        }
        if self.pane_is_stacked(root_pane_id) {
            let room_left_in_stack = self
                .tiled_panes
                .room_left_in_stack_of_pane_id(&root_pane_id)
                .unwrap_or(0);
            stack_size <= room_left_in_stack
        } else {
            self.get_pane_with_id(root_pane_id)
                .map(|p| p.position_and_size().rows.as_usize() >= stack_size + MIN_TERMINAL_HEIGHT)
                .unwrap_or(false)
        }
    }
    pub fn set_tiled_panes_damaged(&mut self) {
        self.swap_layouts.set_is_tiled_damaged();
    }
    pub fn stack_panes(&mut self, root_pane_id: PaneId, mut panes_to_stack: Vec<Box<dyn Pane>>) {
        if panes_to_stack.is_empty() {
            // nothing to do
            return;
        }
        self.dissolve_stack_lists_for_classic_mutation();
        self.swap_layouts.set_is_tiled_damaged(); // TODO: verify we can do all the below first
        if self.pane_is_stacked(root_pane_id) {
            for pane in panes_to_stack.drain(..) {
                self.tiled_panes.add_pane_to_stack(&root_pane_id, pane);
            }
        } else {
            // + 1 for the root pane
            let mut stack_geoms = self
                .tiled_panes
                .stack_panes(root_pane_id, panes_to_stack.len() + 1);
            if stack_geoms.is_empty() {
                log::error!("Failed to find room for stacked panes");
                return;
            }
            self.tiled_panes
                .set_geom_for_pane_with_id(&root_pane_id, stack_geoms.remove(0));
            let mut focused_pane_id_in_stack = None;
            for mut pane in panes_to_stack.drain(..) {
                let pane_id = pane.pid();
                let stack_geom = stack_geoms.remove(0);
                pane.set_geom(stack_geom);
                self.tiled_panes.add_pane_with_existing_geom(pane_id, pane);
                if self.tiled_panes.pane_id_is_focused(&pane_id) {
                    focused_pane_id_in_stack = Some(pane_id);
                }
            }
            // if we had a focused pane in the stack, we expand it
            if let Some(focused_pane_id_in_stack) = focused_pane_id_in_stack {
                self.tiled_panes
                    .expand_pane_in_stack(focused_pane_id_in_stack);
            } else if self.tiled_panes.pane_id_is_focused(&root_pane_id) {
                self.tiled_panes.expand_pane_in_stack(root_pane_id);
            }
        }
    }
    pub fn change_floating_pane_coordinates(
        &mut self,
        pane_id: &PaneId,
        floating_pane_coordinates: FloatingPaneCoordinates,
    ) -> Result<()> {
        if !self.floating_panes.panes_contain(pane_id) {
            // if these panes are not floating, we make them floating (assuming doing so wouldn't
            // be removing the last selectable tiled pane in the tab, which would close it)
            if (self.tiled_panes.panes_contain(&pane_id)
                && self.get_selectable_tiled_panes().count() <= 1)
                || self.suppressed_panes.contains_key(pane_id)
            {
                if let Some(pane) = self.extract_pane(*pane_id, true) {
                    self.add_floating_pane(pane, *pane_id, None, false, None)?;
                }
            }
        }
        self.floating_panes
            .change_pane_coordinates(*pane_id, floating_pane_coordinates)?;
        self.set_force_render();
        self.swap_layouts.set_is_floating_damaged();
        Ok(())
    }
    pub fn toggle_pane_borderless(&mut self, pane_id: &PaneId) -> Result<()> {
        if let Some(pane) = self.floating_panes.get_pane_mut(*pane_id) {
            let is_borderless = pane.borderless();
            if is_borderless {
                pane.set_content_offset(Offset::frame(1));
            } else {
                pane.set_content_offset(Offset::default());
            }
            pane.set_borderless(!is_borderless);
            self.set_force_render();
            return Ok(());
        }

        if let Some(pane) = self.tiled_panes.get_pane_mut(*pane_id) {
            let is_borderless = pane.borderless();
            if is_borderless {
                pane.set_content_offset(Offset::frame(1));
            } else {
                pane.set_content_offset(Offset::default());
            }
            pane.set_borderless(!is_borderless);
            self.set_force_render();
            return Ok(());
        }

        if let Some(pane) = self.suppressed_panes.get_mut(pane_id) {
            let is_borderless = pane.1.borderless();
            if is_borderless {
                pane.1.set_content_offset(Offset::frame(1));
            } else {
                pane.1.set_content_offset(Offset::default());
            }
            pane.1.set_borderless(!is_borderless);
            return Ok(());
        }

        log::error!("Pane with id {:?} not found", pane_id);
        Ok(())
    }
    pub fn set_pane_borderless(&mut self, pane_id: &PaneId, borderless: bool) -> Result<()> {
        // Try floating panes first
        if let Some(pane) = self.floating_panes.get_pane_mut(*pane_id) {
            if borderless {
                pane.set_content_offset(Offset::default()); // Borderless: no offset
            } else {
                pane.set_content_offset(Offset::frame(1)); // Bordered: 1-char offset
            }
            pane.set_borderless(borderless);
            self.set_force_render();
            return Ok(());
        }

        // Try tiled panes
        if let Some(pane) = self.tiled_panes.get_pane_mut(*pane_id) {
            if borderless {
                pane.set_content_offset(Offset::default());
            } else {
                pane.set_content_offset(Offset::frame(1));
            }
            pane.set_borderless(borderless);
            self.set_force_render();
            return Ok(());
        }

        // Try suppressed panes
        if let Some(pane) = self.suppressed_panes.get_mut(pane_id) {
            if borderless {
                pane.1.set_content_offset(Offset::default());
            } else {
                pane.1.set_content_offset(Offset::frame(1));
            }
            pane.1.set_borderless(borderless);
            return Ok(());
        }

        log::error!("Pane with id {:?} not found", pane_id);
        Ok(())
    }
    pub fn get_viewport(&self) -> Viewport {
        self.viewport.borrow().clone()
    }
    pub fn get_display_area(&self) -> Size {
        self.display_area.borrow().clone()
    }
    pub fn get_client_input_mode(&self, client_id: ClientId) -> Option<InputMode> {
        self.mode_info.borrow().get(&client_id).map(|m| m.mode)
    }
    #[allow(unused)] // this is used for tests
    pub fn query_mouse_hover_pane_id(&self) -> HashMap<ClientId, PaneId> {
        self.mouse_hover_pane_id.clone()
    }
    fn new_scrollback_editor_pane(&self, pid: u32) -> TerminalPane {
        let next_terminal_position = self.get_next_terminal_position();
        let mut new_pane = TerminalPane::new(
            pid,
            PaneGeom::default(), // the initial size will be set later
            self.style,
            next_terminal_position,
            String::new(),
            self.link_handler.clone(),
            self.character_cell_size.clone(),
            self.sixel_image_store.clone(),
            self.kitty_image_store.clone(),
            self.terminal_emulator_colors.clone(),
            self.terminal_emulator_color_codes.clone(),
            None,
            None,
            self.debug,
            self.arrow_fonts,
            self.styled_underlines,
            self.osc8_hyperlinks,
            self.explicitly_disable_kitty_keyboard_protocol,
            None,
        );
        if let Some(supported) = self.kitty_host_support {
            new_pane.update_kitty_host_support(supported);
        }
        new_pane.update_name("EDITING SCROLLBACK"); // we do this here and not in the
                                                    // constructor so it won't be overrided
                                                    // by the editor
        new_pane
    }
    fn insert_scrollback_editor_replaced_pane(
        &mut self,
        replaced_pane: Box<dyn Pane>,
        terminal_pane_id: u32,
    ) {
        let is_scrollback_editor = true;
        self.suppressed_panes.insert(
            PaneId::Terminal(terminal_pane_id),
            (is_scrollback_editor, replaced_pane),
        );
    }
    fn pane_is_stacked(&self, pane_id: PaneId) -> bool {
        self.get_pane_with_id(pane_id)
            .map(|p| p.position_and_size().stacked.is_some())
            .unwrap_or(false)
    }
    // --- Pane-targeting CLI methods ---
    pub fn scroll_up_by_pane_id(&mut self, pane_id: PaneId) {
        let fictitious_client_id = 1;
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            pane.scroll_up(1, fictitious_client_id);
        }
    }
    pub fn scroll_down_by_pane_id(&mut self, pane_id: PaneId) -> Result<()> {
        let fictitious_client_id = 1;
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            pane.scroll_down(1, fictitious_client_id);
            if !pane.is_scrolled() {
                if let PaneId::Terminal(raw_fd) = pane.pid() {
                    self.process_pending_vte_events(raw_fd)?;
                }
            }
        }
        Ok(())
    }
    pub fn scroll_to_top_by_pane_id(&mut self, pane_id: PaneId) -> Result<()> {
        let fictitious_client_id = 1;
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            pane.clear_scroll();
            if let Some(size) = pane.get_line_number() {
                pane.scroll_up(size, fictitious_client_id);
            }
        }
        Ok(())
    }
    pub fn scroll_to_bottom_by_pane_id(&mut self, pane_id: PaneId) -> Result<()> {
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            pane.clear_scroll();
            if !pane.is_scrolled() {
                if let PaneId::Terminal(raw_fd) = pane.pid() {
                    self.process_pending_vte_events(raw_fd)?;
                }
            }
        }
        Ok(())
    }
    pub fn page_scroll_up_by_pane_id(&mut self, pane_id: PaneId) {
        let fictitious_client_id = 1;
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            let scroll_rows = pane.rows().max(1).saturating_sub(1);
            pane.scroll_up(scroll_rows, fictitious_client_id);
        }
    }
    pub fn page_scroll_down_by_pane_id(&mut self, pane_id: PaneId) -> Result<()> {
        let fictitious_client_id = 1;
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            let scroll_rows = pane.get_content_rows();
            pane.scroll_down(scroll_rows, fictitious_client_id);
            if !pane.is_scrolled() {
                if let PaneId::Terminal(raw_fd) = pane.pid() {
                    self.process_pending_vte_events(raw_fd)?;
                }
            }
        }
        Ok(())
    }
    pub fn half_page_scroll_up_by_pane_id(&mut self, pane_id: PaneId) {
        let fictitious_client_id = 1;
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            let scroll_rows = (pane.rows().max(1).saturating_sub(1)) / 2;
            pane.scroll_up(scroll_rows, fictitious_client_id);
        }
    }
    pub fn half_page_scroll_down_by_pane_id(&mut self, pane_id: PaneId) -> Result<()> {
        let fictitious_client_id = 1;
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            let scroll_rows = (pane.rows().max(1).saturating_sub(1)) / 2;
            pane.scroll_down(scroll_rows, fictitious_client_id);
            if !pane.is_scrolled() {
                if let PaneId::Terminal(raw_fd) = pane.pid() {
                    self.process_pending_vte_events(raw_fd)?;
                }
            }
        }
        Ok(())
    }
    pub fn resize_by_pane_id(&mut self, pane_id: PaneId, strategy: ResizeStrategy) {
        self.resize_pane_with_id(strategy, pane_id).non_fatal();
    }
    pub fn move_pane_by_pane_id(&mut self, pane_id: PaneId, direction: Option<Direction>) {
        if !self.has_selectable_panes() {
            return;
        }
        if self.tiled_panes.fullscreen_is_active() {
            return;
        }
        if !self.floating_panes.panes_contain(&pane_id) {
            self.dissolve_stack_lists_for_classic_mutation();
        }
        match direction {
            Some(Direction::Left) => {
                if self.floating_panes.panes_contain(&pane_id) {
                    self.floating_panes.move_pane_left(pane_id);
                    self.swap_layouts.set_is_floating_damaged();
                    self.set_force_render();
                } else {
                    self.tiled_panes.move_pane_left(pane_id);
                }
            },
            Some(Direction::Right) => {
                if self.floating_panes.panes_contain(&pane_id) {
                    self.floating_panes.move_pane_right(pane_id);
                    self.swap_layouts.set_is_floating_damaged();
                    self.set_force_render();
                } else {
                    self.tiled_panes.move_pane_right(pane_id);
                }
            },
            Some(Direction::Up) => {
                if self.floating_panes.panes_contain(&pane_id) {
                    self.floating_panes.move_pane_up(pane_id);
                    self.swap_layouts.set_is_floating_damaged();
                    self.set_force_render();
                } else {
                    self.tiled_panes.move_pane_up(pane_id);
                }
            },
            Some(Direction::Down) => {
                if self.floating_panes.panes_contain(&pane_id) {
                    self.floating_panes.move_pane_down(pane_id);
                    self.swap_layouts.set_is_floating_damaged();
                    self.set_force_render();
                } else {
                    self.tiled_panes.move_pane_down(pane_id);
                }
            },
            None => {
                let search_backwards = false;
                if self.floating_panes.panes_contain(&pane_id) {
                    self.floating_panes.move_pane(search_backwards, pane_id);
                } else {
                    self.tiled_panes.move_pane(search_backwards, pane_id);
                }
            },
        }
    }
    pub fn move_pane_backwards_by_pane_id(&mut self, pane_id: PaneId) {
        if !self.has_selectable_panes() {
            return;
        }
        if self.tiled_panes.fullscreen_is_active() {
            return;
        }
        let search_backwards = true;
        if self.floating_panes.panes_contain(&pane_id) {
            self.floating_panes.move_pane(search_backwards, pane_id);
        } else {
            self.dissolve_stack_lists_for_classic_mutation();
            self.tiled_panes.move_pane(search_backwards, pane_id);
        }
    }
    pub fn clear_screen_by_pane_id(&mut self, pane_id: PaneId) -> Result<()> {
        self.clear_screen_for_pane_id(pane_id);
        Ok(())
    }
    pub fn toggle_fullscreen_by_pane_id(&mut self, pane_id: PaneId) {
        self.toggle_pane_fullscreen(pane_id);
    }
    pub fn toggle_no_ui_fullscreen_by_pane_id(&mut self, pane_id: PaneId) {
        self.toggle_pane_no_ui_fullscreen(pane_id);
    }
    pub fn close_pane_by_pane_id(
        &mut self,
        pane_id: PaneId,
        completion_tx: Option<NotificationEnd>,
    ) -> Result<()> {
        self.close_pane(pane_id, false, None);
        self.senders
            .send_to_pty(PtyInstruction::ClosePane(pane_id, completion_tx))?;
        Ok(())
    }
    pub fn rename_pane_by_pane_id(&mut self, pane_id: PaneId, name: Vec<u8>) -> Result<()> {
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            pane.rename(name);
        }
        Ok(())
    }
    pub fn undo_rename_pane_by_pane_id(&mut self, pane_id: PaneId) {
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            pane.load_pane_name();
        }
    }
    pub fn toggle_pane_pinned_by_pane_id(&mut self, pane_id: PaneId) {
        if let Some(pane) = self.get_pane_with_id_mut(pane_id) {
            pane.toggle_pinned();
            self.set_force_render();
        }
    }
}

pub fn pane_info_for_pane(
    pane_id: &PaneId,
    pane: &Box<dyn Pane>,
    current_pane_group: &HashMap<ClientId, Vec<PaneId>>,
) -> PaneInfo {
    let mut pane_info = PaneInfo::default();
    pane_info.pane_x = pane.x();
    pane_info.pane_content_x = pane.get_content_x();
    pane_info.pane_y = pane.y();
    pane_info.pane_content_y = pane.get_content_y();
    pane_info.pane_rows = pane.rows();
    pane_info.pane_content_rows = pane.get_content_rows();
    pane_info.pane_columns = pane.cols();
    pane_info.pane_content_columns = pane.get_content_columns();
    pane_info.cursor_coordinates_in_pane = pane
        .cursor_coordinates(None)
        .and_then(|(x, y, is_visible)| if is_visible { Some((x, y)) } else { None });
    pane_info.is_selectable = pane.selectable();
    pane_info.title = pane.current_title();
    pane_info.exited = pane.exited();
    pane_info.exit_status = pane.exit_status();
    pane_info.is_held = pane.is_held();
    let index_in_pane_group: BTreeMap<ClientId, usize> = current_pane_group
        .iter()
        .filter_map(|(client_id, pane_ids)| {
            if let Some(position) = pane_ids.iter().position(|p_id| p_id == &pane.pid()) {
                Some((*client_id, position))
            } else {
                None
            }
        })
        .collect();
    pane_info.index_in_pane_group = index_in_pane_group;

    let (default_fg, default_bg) = pane.get_pane_default_colors();
    pane_info.default_fg = default_fg;
    pane_info.default_bg = default_bg;

    match pane_id {
        PaneId::Terminal(terminal_id) => {
            pane_info.id = *terminal_id;
            pane_info.is_plugin = false;
            pane_info.terminal_command = pane.invoked_with().as_ref().and_then(|c| match c {
                Run::Command(run_command) => Some(run_command.to_string()),
                _ => None,
            });
        },
        PaneId::Plugin(plugin_id) => {
            pane_info.id = *plugin_id;
            pane_info.is_plugin = true;
            pane_info.plugin_url = pane.invoked_with().as_ref().and_then(|c| match c {
                Run::Plugin(run_plugin_or_alias) => Some(run_plugin_or_alias.location_string()),
                _ => None,
            });
        },
    }
    pane_info
}

#[cfg(test)]
#[path = "./unit/tab_tests.rs"]
mod tab_tests;

#[cfg(test)]
#[path = "./unit/tab_integration_tests.rs"]
mod tab_integration_tests;

#[cfg(test)]
#[path = "./unit/layout_applier_tests.rs"]
mod layout_applier_tests;