ztmux 3.7.20

A Rust port of tmux — the full terminal multiplexer, server and client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
// Copyright (c) 2017 Nicholas Marriott <nicholas.marriott@gmail.com>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
// IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
// OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use crate::*;

pub type mode_tree_build_cb = Option<
    unsafe fn(_: NonNull<c_void>, _: *mut mode_tree_sort_criteria, _: *mut u64, _: *const u8),
>;
pub type mode_tree_draw_cb = Option<
    unsafe fn(
        _: *mut c_void,
        _: Option<NonNull<c_void>>,
        _: *mut screen_write_ctx,
        _: c_uint,
        _: c_uint,
    ),
>;
pub type mode_tree_search_cb =
    Option<unsafe fn(_: *mut c_void, _: NonNull<c_void>, _: *const u8) -> bool>;
pub type mode_tree_menu_cb = Option<unsafe fn(_: NonNull<c_void>, _: *mut client, _: key_code)>;
pub type mode_tree_height_cb = Option<unsafe fn(_: *mut c_void, _: c_uint) -> c_uint>;
pub type mode_tree_key_cb =
    Option<unsafe fn(_: NonNull<c_void>, _: NonNull<c_void>, _: c_uint) -> key_code>;
pub type mode_tree_each_cb =
    Option<unsafe fn(_: NonNull<c_void>, _: NonNull<c_void>, _: *mut client, _: key_code)>;

#[repr(C)]
#[derive(Copy, Clone, Eq, PartialEq)]
enum mode_tree_search_dir {
    MODE_TREE_SEARCH_FORWARD,
    MODE_TREE_SEARCH_BACKWARD,
}

pub type mode_tree_list = tailq_head<mode_tree_item>;

#[repr(C)]
pub struct mode_tree_data {
    dead: i32,
    references: u32,
    zoomed: i32,

    wp: *mut window_pane,
    modedata: *mut c_void,
    menu: &'static [menu_item],

    sort_list: &'static [&'static str],
    sort_crit: mode_tree_sort_criteria,

    buildcb: mode_tree_build_cb,
    drawcb: mode_tree_draw_cb,
    searchcb: mode_tree_search_cb,
    menucb: mode_tree_menu_cb,
    heightcb: mode_tree_height_cb,
    keycb: mode_tree_key_cb,

    children: mode_tree_list,
    saved: mode_tree_list,

    line_list: Vec<mode_tree_line>,

    depth: u32,

    width: u32,
    height: u32,

    offset: u32,
    current: u32,

    screen: screen,

    preview: bool,
    search: *mut u8,
    filter: *mut u8,
    no_matches: i32,
    search_dir: mode_tree_search_dir,
}

#[repr(C)]
pub struct mode_tree_item {
    parent: *mut mode_tree_item,
    itemdata: *mut c_void,
    line: u32,

    key: key_code,
    keystr: *mut u8,
    keylen: usize,

    tag: u64,
    name: *mut u8,
    text: *mut u8,

    expanded: bool,
    tagged: i32,

    draw_as_parent: i32,
    no_tag: i32,

    children: mode_tree_list,
    entry: tailq_entry<mode_tree_item>,
}
impl_tailq_entry!(mode_tree_item, entry, tailq_entry<mode_tree_item>);

#[repr(C)]
struct mode_tree_line {
    item: *mut mode_tree_item,
    depth: u32,
    last: i32,
    flat: i32,
}

#[repr(C)]
struct mode_tree_menu {
    data: *mut mode_tree_data,
    c: *mut client,
    line: u32,
}

static MODE_TREE_MENU_ITEMS: [menu_item; 4] = [
    menu_item::new("Scroll Left", '<' as u64, null_mut()),
    menu_item::new("Scroll Right", '>' as u64, null_mut()),
    menu_item::new("", KEYC_NONE, null_mut()),
    menu_item::new("Cancel", 'q' as u64, null_mut()),
];

/// C `vendor/tmux/mode-tree.c:241`: `static struct mode_tree_item *mode_tree_find_item(struct mode_tree_list *mtl, uint64_t tag)`
unsafe fn mode_tree_find_item(mtl: *mut mode_tree_list, tag: u64) -> *mut mode_tree_item {
    unsafe {
        for mti in tailq_foreach(mtl).map(NonNull::as_ptr) {
            if (*mti).tag == tag {
                return mti;
            }

            if let Some(child) = NonNull::new(mode_tree_find_item(&raw mut (*mti).children, tag)) {
                return child.as_ptr();
            }
        }
        null_mut()
    }
}

/// C `vendor/tmux/mode-tree.c:256`: `static void mode_tree_free_item(struct mode_tree_item *mti)`
unsafe fn mode_tree_free_item(mti: *mut mode_tree_item) {
    unsafe {
        mode_tree_free_items(&raw mut (*mti).children);

        free_((*mti).name);
        free_((*mti).text);
        free_((*mti).keystr);

        free_(mti);
    }
}

/// C `vendor/tmux/mode-tree.c:268`: `static void mode_tree_free_items(struct mode_tree_list *mtl)`
unsafe fn mode_tree_free_items(mtl: *mut mode_tree_list) {
    unsafe {
        for mti in tailq_foreach(mtl).map(NonNull::as_ptr) {
            tailq_remove(mtl, mti);
            mode_tree_free_item(mti);
        }
    }
}

/// C `vendor/tmux/mode-tree.c:279`: `static void mode_tree_check_selected(struct mode_tree_data *mtd)`
unsafe fn mode_tree_check_selected(mtd: *mut mode_tree_data) {
    unsafe {
        // If the current line would now be off screen reset the offset to the
        // last visible line.
        if (*mtd).current > (*mtd).height - 1 {
            (*mtd).offset = (*mtd).current - (*mtd).height + 1;
        }
    }
}

/// C `vendor/tmux/mode-tree.c:290`: `static void mode_tree_clear_lines(struct mode_tree_data *mtd)`
unsafe fn mode_tree_clear_lines(mtd: *mut mode_tree_data) {
    unsafe {
        (*mtd).line_list = Vec::new();
    }
}

/// C `vendor/tmux/mode-tree.c:298`: `static void mode_tree_build_lines(struct mode_tree_data *mtd, struct mode_tree_list *mtl, u_int depth)`
unsafe fn mode_tree_build_lines(mtd: *mut mode_tree_data, mtl: *mut mode_tree_list, depth: u32) {
    unsafe {
        let mut flat = 1;

        (*mtd).depth = depth;
        for mti in tailq_foreach(mtl).map(NonNull::as_ptr) {
            (*mtd).line_list.push(mode_tree_line {
                item: mti,
                depth,
                last: (mti == tailq_last(mtl)) as i32,
                flat: 0,
            });

            (*mti).line = (*mtd).line_list.len() as u32 - 1;
            if !tailq_empty(&raw const (*mti).children) {
                flat = 0;
            }
            if (*mti).expanded {
                mode_tree_build_lines(mtd, &raw mut (*mti).children, depth + 1);
            }

            if let Some(keycb) = (*mtd).keycb {
                (*mti).key = keycb(
                    NonNull::new((*mtd).modedata).unwrap(),
                    NonNull::new((*mti).itemdata).unwrap(),
                    (*mti).line,
                );
                if (*mti).key == KEYC_UNKNOWN {
                    (*mti).key = KEYC_NONE;
                }
            } else if (*mti).line < 10 {
                (*mti).key = (b'0' as u32 + (*mti).line) as u64;
            } else if (*mti).line < 36 {
                (*mti).key = KEYC_META | (b'a' as u32 + (*mti).line - 10) as u64;
            } else {
                (*mti).key = KEYC_NONE;
            }
            if (*mti).key != KEYC_NONE {
                (*mti).keystr = xstrdup(key_string_lookup_key((*mti).key, 0)).as_ptr();
                (*mti).keylen = strlen((*mti).keystr);
            } else {
                (*mti).keystr = null_mut();
                (*mti).keylen = 0;
            }
        }
        for mti in tailq_foreach(mtl).map(NonNull::as_ptr) {
            for line in &mut (*mtd).line_list {
                if line.item == mti {
                    line.flat = flat;
                }
            }
        }
    }
}

/// C `vendor/tmux/mode-tree.c:354`: `static void mode_tree_clear_tagged(struct mode_tree_list *mtl)`
unsafe fn mode_tree_clear_tagged(mtl: *mut mode_tree_list) {
    unsafe {
        for mti in tailq_foreach(mtl).map(NonNull::as_ptr) {
            (*mti).tagged = 0;
            mode_tree_clear_tagged(&raw mut (*mti).children);
        }
    }
}

/// C `vendor/tmux/mode-tree.c:365`: `void mode_tree_up(struct mode_tree_data *mtd, int wrap)`
pub unsafe fn mode_tree_up(mtd: *mut mode_tree_data, wrap: i32) {
    unsafe {
        if (*mtd).line_list.is_empty() {
            return;
        }
        if (*mtd).current == 0 {
            if wrap != 0 {
                (*mtd).current = (*mtd).line_list.len() as u32 - 1;
                if (*mtd).line_list.len() as u32 >= (*mtd).height {
                    (*mtd).offset = (*mtd).line_list.len() as u32 - (*mtd).height;
                }
            }
        } else {
            (*mtd).current -= 1;
            if (*mtd).current < (*mtd).offset {
                (*mtd).offset -= 1;
            }
        }
    }
}

/// C `vendor/tmux/mode-tree.c:383`: `int mode_tree_down(struct mode_tree_data *mtd, int wrap)`
pub unsafe fn mode_tree_down(mtd: *mut mode_tree_data, wrap: i32) -> bool {
    unsafe {
        if (*mtd).line_list.is_empty() {
            return false;
        }
        if (*mtd).current == (*mtd).line_list.len() as u32 - 1 {
            if wrap != 0 {
                (*mtd).current = 0;
                (*mtd).offset = 0;
            } else {
                return false;
            }
        } else {
            (*mtd).current += 1;
            if (*mtd).current > (*mtd).offset + (*mtd).height - 1 {
                (*mtd).offset += 1;
            }
        }

        true
    }
}

/// C `vendor/tmux/mode-tree.c:431`: `void *mode_tree_get_current(struct mode_tree_data *mtd)`
pub unsafe fn mode_tree_get_current(mtd: *mut mode_tree_data) -> NonNull<c_void> {
    // C `mode-tree.c:433-434` returns NULL when `mtd->line_size == 0`. The Rust
    // return type is `NonNull`, so a faithful null-return would require changing
    // the signature to `Option<NonNull>` and updating all callers across
    // window_customize.rs / window_client.rs / window_tree.rs / window_buffer.rs.
    // Those callers cannot reach this on an empty list: mode_tree_up/down/key
    // (mode-tree.c:367/385/1506) all short-circuit on `line_size == 0`, so
    // `current` is only advanced when the list is non-empty. The debug assert
    // pins that invariant instead of panicking silently via the index below.
    debug_assert!(
        !unsafe { (*mtd).line_list.is_empty() },
        "mode_tree_get_current on empty line_list (C returns NULL here)"
    );
    NonNull::new(unsafe { (*(&mut (*mtd).line_list)[(*mtd).current as usize].item).itemdata })
        .unwrap()
}

/// C `vendor/tmux/mode-tree.c:439`: `const char *mode_tree_get_current_name(struct mode_tree_data *mtd)`
pub unsafe fn mode_tree_get_current_name(mtd: *mut mode_tree_data) -> *const u8 {
    unsafe { (*(&(*mtd).line_list)[(*mtd).current as usize].item).name }
}

/// C `vendor/tmux/mode-tree.c:452`: `void mode_tree_expand_current(struct mode_tree_data *mtd)`
pub unsafe fn mode_tree_expand_current(mtd: *mut mode_tree_data) {
    unsafe {
        if !(*(&(*mtd).line_list)[(*mtd).current as usize].item).expanded {
            (*(&mut (*mtd).line_list)[(*mtd).current as usize].item).expanded = true;
            mode_tree_build(mtd);
        }
    }
}

/// C `vendor/tmux/mode-tree.c:461`: `void mode_tree_collapse_current(struct mode_tree_data *mtd)`
pub unsafe fn mode_tree_collapse_current(mtd: *mut mode_tree_data) {
    unsafe {
        if (*(&(*mtd).line_list)[(*mtd).current as usize].item).expanded {
            (*(&mut (*mtd).line_list)[(*mtd).current as usize].item).expanded = false;
            mode_tree_build(mtd);
        }
    }
}

/// C `vendor/tmux/mode-tree.c:470`: `static int mode_tree_get_tag(struct mode_tree_data *mtd, uint64_t tag, u_int *found)`
pub unsafe fn mode_tree_get_tag(mtd: &mode_tree_data, tag: u64) -> Option<usize> {
    unsafe {
        mtd.line_list
            .iter()
            .position(|line| (*line.item).tag == tag)
    }
}

/// C `vendor/tmux/mode-tree.c:486`: `void mode_tree_expand(struct mode_tree_data *mtd, uint64_t tag)`
pub unsafe fn mode_tree_expand(mtd: *mut mode_tree_data, tag: u64) {
    unsafe {
        let Some(found) = mode_tree_get_tag(&*mtd, tag) else {
            return;
        };
        if !(*(&(*mtd).line_list)[found].item).expanded {
            (*(&mut (*mtd).line_list)[found].item).expanded = true;
            mode_tree_build(mtd);
        }
    }
}

/// C `vendor/tmux/mode-tree.c:499`: `int mode_tree_set_current(struct mode_tree_data *mtd, uint64_t tag)`
pub unsafe fn mode_tree_set_current(mtd: *mut mode_tree_data, tag: u64) -> bool {
    unsafe {
        if let Some(found) = mode_tree_get_tag(&*mtd, tag) {
            (*mtd).current = found as u32;
            // TODO does this same problem exist in upstream?
            if (*mtd).current > (*mtd).height.saturating_sub(1) {
                (*mtd).offset = (*mtd).current - (*mtd).height + 1;
            } else {
                (*mtd).offset = 0;
            }
            return true;
        }
        if (*mtd).current >= (*mtd).line_list.len() as u32 {
            if (*mtd).line_list.is_empty() {
                return false;
            }
            (*mtd).current = (*mtd).line_list.len() as u32 - 1;
            if (*mtd).current > (*mtd).height.saturating_sub(1) {
                (*mtd).offset = (*mtd).current - (*mtd).height + 1;
            } else {
                (*mtd).offset = 0;
            }
        }
        false
    }
}

/// C `vendor/tmux/mode-tree.c:524`: `u_int mode_tree_count_tagged(struct mode_tree_data *mtd)`
pub unsafe fn mode_tree_count_tagged(mtd: *mut mode_tree_data) -> u32 {
    unsafe {
        (*mtd)
            .line_list
            .iter()
            .filter(|line| (*line.item).tagged != 0)
            .count() as u32
    }
}

/// C `vendor/tmux/mode-tree.c:539`: `void mode_tree_each_tagged(struct mode_tree_data *mtd, mode_tree_each_cb cb, struct client *c, key_code key, int current)`
pub unsafe fn mode_tree_each_tagged(
    mtd: *mut mode_tree_data,
    cb: mode_tree_each_cb,
    c: *mut client,
    key: key_code,
    current: i32,
) {
    unsafe {
        let mut fired = false;
        for line in &mut (*mtd).line_list {
            let mti = line.item;
            if (*mti).tagged != 0 {
                fired = true;
                cb.unwrap()(
                    NonNull::new((*mtd).modedata).unwrap(),
                    NonNull::new((*mti).itemdata).unwrap(),
                    c,
                    key,
                );
            }
        }
        if !fired && current != 0 {
            let mti = (&(*mtd).line_list)[(*mtd).current as usize].item;
            cb.unwrap()(
                NonNull::new((*mtd).modedata).unwrap(),
                NonNull::new((*mti).itemdata).unwrap(),
                c,
                key,
            );
        }
    }
}

pub unsafe fn mode_tree_start(
    wp: *mut window_pane,
    args: *mut args,
    buildcb: mode_tree_build_cb,
    drawcb: mode_tree_draw_cb,
    searchcb: mode_tree_search_cb,
    menucb: mode_tree_menu_cb,
    heightcb: mode_tree_height_cb,
    keycb: mode_tree_key_cb,
    modedata: *mut c_void,
    menu: &'static [menu_item],
    sort_list: &'static [&'static str],
    s: *mut *mut screen,
) -> *mut mode_tree_data {
    unsafe {
        let mut mtd = Box::new(mode_tree_data {
            references: 1,
            wp,
            modedata,
            menu,
            sort_list,
            preview: !args_has(args, 'N'),

            buildcb,
            drawcb,
            searchcb,
            menucb,
            heightcb,
            keycb,
            dead: 0,
            zoomed: 0,
            sort_crit: mode_tree_sort_criteria::default(),
            children: zeroed(),
            saved: zeroed(),
            line_list: Vec::default(),
            depth: Default::default(),
            width: Default::default(),
            height: Default::default(),
            offset: Default::default(),
            current: Default::default(),
            screen: zeroed(),
            search: Default::default(),
            filter: if args_has(args, 'f') {
                xstrdup(args_get_(args, 'f')).as_ptr()
            } else {
                null_mut()
            },
            no_matches: Default::default(),
            search_dir: zeroed(),
        });

        let sort = args_get_(args, 'O');
        if !sort.is_null()
            && let Some(pos) = mtd.sort_list.iter().position(|e| strcaseeq_(sort, e))
        {
            mtd.sort_crit.field = pos as u32;
        }
        mtd.sort_crit.reversed = args_has(args, 'r');

        tailq_init(&mut mtd.children);

        *s = &raw mut mtd.screen;
        screen_init(
            *s,
            screen_size_x(&raw mut (*wp).base),
            screen_size_y(&raw mut (*wp).base),
            0,
        );
        (*(*s)).mode &= !mode_flag::MODE_CURSOR;

        Box::leak(mtd)
    }
}

/// C `vendor/tmux/mode-tree.c:615`: `void mode_tree_zoom(struct mode_tree_data *mtd, struct args *args)`
pub unsafe fn mode_tree_zoom(mtd: *mut mode_tree_data, args: *mut args) {
    unsafe {
        let wp: *mut window_pane = (*mtd).wp;

        if args_has(args, 'Z') {
            (*mtd).zoomed = ((*(*wp).window).flags & window_flag::ZOOMED).bits();
            if (*mtd).zoomed == 0 && window_zoom(wp) == 0 {
                server_redraw_window((*wp).window);
            }
        } else {
            (*mtd).zoomed = -1;
        }
    }
}

/// C `vendor/tmux/mode-tree.c:628`: `static void mode_tree_set_height(struct mode_tree_data *mtd)`
pub unsafe fn mode_tree_set_height(mtd: *mut mode_tree_data) {
    unsafe {
        let s: *mut screen = &raw mut (*mtd).screen;

        if let Some(heightcb) = (*mtd).heightcb {
            let height = heightcb(mtd.cast(), screen_size_y(s));
            if height < screen_size_y(s) {
                (*mtd).height = screen_size_y(s) - height;
            }
        } else {
            (*mtd).height = (screen_size_y(s) / 3) * 2;
            if (*mtd).height > (*mtd).line_list.len() as u32 {
                (*mtd).height = screen_size_y(s) / 2;
            }
        }
        if (*mtd).height < 10 {
            (*mtd).height = screen_size_y(s);
        }
        if screen_size_y(s) - (*mtd).height < 2 {
            (*mtd).height = screen_size_y(s);
        }
    }
}

/// C `vendor/tmux/mode-tree.c:658`: `void mode_tree_build(struct mode_tree_data *mtd)`
pub unsafe fn mode_tree_build(mtd: *mut mode_tree_data) {
    unsafe {
        let s = &raw mut (*mtd).screen;

        let mut tag = if !(*mtd).line_list.is_empty() {
            (*(&(*mtd).line_list)[(*mtd).current as usize].item).tag
        } else {
            u64::MAX
        };

        tailq_concat(&raw mut (*mtd).saved, &raw mut (*mtd).children);
        tailq_init(&raw mut (*mtd).children);

        (*mtd).buildcb.unwrap()(
            NonNull::new((*mtd).modedata).unwrap(),
            &raw mut (*mtd).sort_crit,
            &raw mut tag,
            (*mtd).filter,
        );
        (*mtd).no_matches = tailq_empty(&raw mut (*mtd).children) as i32;
        if (*mtd).no_matches != 0 {
            (*mtd).buildcb.unwrap()(
                NonNull::new((*mtd).modedata).unwrap(),
                &raw mut (*mtd).sort_crit,
                &raw mut tag,
                null_mut(),
            );
        }

        mode_tree_free_items(&raw mut (*mtd).saved);
        tailq_init(&raw mut (*mtd).saved);

        mode_tree_clear_lines(mtd);
        mode_tree_build_lines(mtd, &raw mut (*mtd).children, 0);

        if !(*mtd).line_list.is_empty() && tag == u64::MAX {
            tag = (*(&(*mtd).line_list)[(*mtd).current as usize].item).tag;
        }
        mode_tree_set_current(mtd, tag);

        (*mtd).width = screen_size_x(s);
        if (*mtd).preview {
            mode_tree_set_height(mtd);
        } else {
            (*mtd).height = screen_size_y(s);
        }
        mode_tree_check_selected(mtd);
    }
}

/// C `vendor/tmux/mode-tree.c:698`: `static void mode_tree_remove_ref(struct mode_tree_data *mtd)`
pub unsafe fn mode_tree_remove_ref(mtd: *mut mode_tree_data) {
    unsafe {
        (*mtd).references -= 1;
        if (*mtd).references == 0 {
            free_(mtd);
        }
    }
}

/// C `vendor/tmux/mode-tree.c:705`: `void mode_tree_free(struct mode_tree_data *mtd)`
pub unsafe fn mode_tree_free(mtd: *mut mode_tree_data) {
    unsafe {
        let wp = (*mtd).wp;

        if (*mtd).zoomed == 0 {
            server_unzoom_window((*wp).window);
        }

        mode_tree_free_items(&raw mut (*mtd).children);
        mode_tree_clear_lines(mtd);
        screen_free(&raw mut (*mtd).screen);

        free_((*mtd).search);
        free_((*mtd).filter);

        (*mtd).dead = 1;
        mode_tree_remove_ref(mtd);
    }
}

/// C `vendor/tmux/mode-tree.c:725`: `void mode_tree_resize(struct mode_tree_data *mtd, u_int sx, u_int sy)`
pub unsafe fn mode_tree_resize(mtd: *mut mode_tree_data, sx: u32, sy: u32) {
    unsafe {
        let s: *mut screen = &raw mut (*mtd).screen;

        screen_resize(s, sx, sy, 0);

        mode_tree_build(mtd);
        mode_tree_draw(&mut *mtd);

        (*(*mtd).wp).flags |= window_pane_flags::PANE_REDRAW;
    }
}

/// C `vendor/tmux/mode-tree.c:738`: `struct mode_tree_item *mode_tree_add(struct mode_tree_data *mtd, struct mode_tree_item *parent, void *itemdata, uint64_t tag, const char *name, const char *text, int expanded)`
pub unsafe fn mode_tree_add(
    mtd: *mut mode_tree_data,
    parent: *mut mode_tree_item,
    itemdata: *mut c_void,
    tag: u64,
    name: &str,
    text: *const u8,
    expanded: Option<bool>,
) -> *mut mode_tree_item {
    unsafe {
        // log_debug("%s: %llu, %s %s", __func__, (unsigned long long)tag, name, (text == NULL ? "" : text));

        let mti: *mut mode_tree_item = xcalloc1::<mode_tree_item>() as *mut mode_tree_item;
        (*mti).parent = parent;
        (*mti).itemdata = itemdata;

        (*mti).tag = tag;
        (*mti).name = xstrdup__(name);
        if !text.is_null() {
            (*mti).text = xstrdup(text).as_ptr();
        }

        let saved = mode_tree_find_item(&raw mut (*mtd).saved, tag);
        if !saved.is_null() {
            if parent.is_null() || (*parent).expanded {
                (*mti).tagged = (*saved).tagged;
            }
            (*mti).expanded = (*saved).expanded;
        } else {
            (*mti).expanded = expanded.unwrap_or(true);
        }

        tailq_init(&raw mut (*mti).children);

        if !parent.is_null() {
            tailq_insert_tail(&raw mut (*parent).children, mti);
        } else {
            tailq_insert_tail(&raw mut (*mtd).children, mti);
        }

        mti
    }
}

/// C `vendor/tmux/mode-tree.c:783`: `void mode_tree_draw_as_parent(struct mode_tree_item *mti)`
pub unsafe fn mode_tree_draw_as_parent(mti: *mut mode_tree_item) {
    unsafe {
        (*mti).draw_as_parent = 1;
    }
}

/// C `vendor/tmux/mode-tree.c:789`: `void mode_tree_no_tag(struct mode_tree_item *mti)`
pub unsafe fn mode_tree_no_tag(mti: *mut mode_tree_item) {
    unsafe {
        (*mti).no_tag = 1;
    }
}

/// C `vendor/tmux/mode-tree.c:805`: `void mode_tree_remove(struct mode_tree_data *mtd, struct mode_tree_item *mti)`
pub unsafe fn mode_tree_remove(mtd: *mut mode_tree_data, mti: *mut mode_tree_item) {
    unsafe {
        let parent: *mut mode_tree_item = (*mti).parent;

        if !parent.is_null() {
            tailq_remove(&raw mut (*parent).children, mti);
        } else {
            tailq_remove(&raw mut (*mtd).children, mti);
        }
        mode_tree_free_item(mti);
    }
}

/// C `vendor/tmux/mode-tree.c:817`: `void mode_tree_draw(struct mode_tree_data *mtd)`
pub unsafe fn mode_tree_draw(mtd: &mut mode_tree_data) {
    unsafe {
        let wp = mtd.wp;
        let s = &raw mut mtd.screen;
        let oo = (*(*wp).window).options;
        let mut ctx: screen_write_ctx = zeroed();

        let mut gc0: grid_cell = zeroed();
        let mut gc: grid_cell = zeroed();

        'done: {
            if mtd.line_list.is_empty() {
                return;
            }

            memcpy__(&raw mut gc0, &raw const GRID_DEFAULT_CELL);
            memcpy__(&raw mut gc, &raw const GRID_DEFAULT_CELL);
            style_apply(&raw mut gc, oo, c!("mode-style"), null_mut());

            let w = mtd.width;
            let h = mtd.height;

            screen_write_start(&raw mut ctx, s);
            screen_write_clearscreen(&raw mut ctx, 8);

            let mut keylen: i32 = 0;
            for line in &mtd.line_list {
                let mti = line.item;
                if (*mti).key == KEYC_NONE {
                    continue;
                }
                if (*mti).keylen as i32 + 3 > keylen {
                    keylen = (*mti).keylen as i32 + 3;
                }
            }

            for i in 0..mtd.line_list.len() {
                // line = &mtd.line_list[i] // but we don't want to borrow
                if (i as u32) < mtd.offset {
                    continue;
                }
                if i as u32 > mtd.offset + h - 1 {
                    break;
                }
                let mti = mtd.line_list[i].item;

                screen_write_cursormove(&raw mut ctx, 0, i as i32 - mtd.offset as i32, 0);

                let pad = keylen - 2 - (*mti).keylen as i32;
                let key = if (*mti).key != KEYC_NONE {
                    format_nul!("({0}){2:>1$}", _s((*mti).keystr), pad as usize, "")
                } else {
                    xstrdup_(c"").as_ptr()
                };

                let symbol = if mtd.line_list[i].flat != 0 {
                    c!("")
                } else if tailq_empty(&raw const (*mti).children) {
                    c!("  ")
                } else if (*mti).expanded {
                    c!("- ")
                } else {
                    c!("+ ")
                };

                let start: *mut u8;
                if mtd.line_list[i].depth == 0 {
                    start = xstrdup(symbol).as_ptr();
                } else {
                    let size = (4 * mtd.line_list[i].depth as usize) + 32;

                    start = xcalloc(1, size).as_ptr().cast();
                    for _ in 1..mtd.line_list[i].depth {
                        if !(*mti).parent.is_null()
                            && mtd.line_list[(*(*mti).parent).line as usize].last != 0
                        {
                            strlcat(start, c!("    "), size);
                        } else {
                            strlcat(start, c!("\x01x\x01   "), size);
                        }
                    }
                    if mtd.line_list[i].last != 0 {
                        strlcat(start, c!("\x01mq\x01> "), size);
                    } else {
                        strlcat(start, c!("\x01tq\x01> "), size);
                    }
                    strlcat(start, symbol, size);
                }

                let tag = if (*mti).tagged != 0 { c!("*") } else { c!("") };
                let text = format_nul!(
                    "{1:<0$}{2}{3}{4}{5}",
                    keylen as usize,
                    _s(key),
                    _s(start),
                    _s((*mti).name),
                    _s(tag),
                    if !(*mti).text.is_null() { ": " } else { "" },
                );
                let mut width = utf8_cstrwidth(text);
                if width > w {
                    width = w;
                }
                free_(start);

                if (*mti).tagged != 0 {
                    gc.attr ^= grid_attr::GRID_ATTR_BRIGHT;
                    gc0.attr ^= grid_attr::GRID_ATTR_BRIGHT;
                }

                if i as u32 != mtd.current {
                    screen_write_clearendofline(&raw mut ctx, 8);
                    screen_write_nputs!(&raw mut ctx, w as isize, &raw mut gc0, "{}", _s(text),);
                    if let Some(text) = cstr_to_str_((*mti).text) {
                        format_draw(
                            &raw mut ctx,
                            &raw mut gc0,
                            w - width,
                            text,
                            null_mut(),
                            0,
                        );
                    }
                } else {
                    screen_write_clearendofline(&raw mut ctx, gc.bg as u32);
                    screen_write_nputs!(&raw mut ctx, w as isize, &raw mut gc, "{}", _s(text));
                    if !(*mti).text.is_null() {
                        format_draw(
                            &raw mut ctx,
                            &raw mut gc,
                            w - width,
                            cstr_to_str((*mti).text),
                            null_mut(),
                            0,
                        );
                    }
                }
                free_(text);
                free_(key);

                if (*mti).tagged != 0 {
                    gc.attr ^= grid_attr::GRID_ATTR_BRIGHT;
                    gc0.attr ^= grid_attr::GRID_ATTR_BRIGHT;
                }
            }

            let sy = screen_size_y(s);
            if !mtd.preview || sy <= 4 || h <= 4 || sy - h <= 4 || w <= 4 {
                break 'done;
            }

            let line = &mtd.line_list[mtd.current as usize];
            let mut mti = line.item;
            if (*mti).draw_as_parent != 0 {
                mti = (*mti).parent;
            }

            screen_write_cursormove(&raw mut ctx, 0, h as i32, 0);
            screen_write_box(
                &raw mut ctx,
                w,
                sy - h,
                box_lines::BOX_LINES_DEFAULT,
                null(),
                None,
            );

            let text = if !mtd.sort_list.is_empty() {
                format_nul!(
                    " {} (sort: {}{})",
                    _s((*mti).name),
                    mtd.sort_list[mtd.sort_crit.field as usize],
                    if mtd.sort_crit.reversed {
                        ", reversed"
                    } else {
                        ""
                    },
                )
            } else {
                format_nul!(" {}", _s((*mti).name))
            };
            if w - 2 >= strlen(text) as u32 {
                screen_write_cursormove(&raw mut ctx, 1, h as i32, 0);
                screen_write_puts!(&raw mut ctx, &raw mut gc0, "{}", _s(text));

                let n = if mtd.no_matches != 0 {
                    "no matches".len()
                } else {
                    "active".len()
                };

                if !mtd.filter.is_null() && w as usize - 2 >= strlen(text) + 10 + n + 2 {
                    screen_write_puts!(&raw mut ctx, &raw mut gc0, " (filter: ");
                    if mtd.no_matches != 0 {
                        screen_write_puts!(&raw mut ctx, &raw mut gc, "no matches");
                    } else {
                        screen_write_puts!(&raw mut ctx, &raw mut gc0, "active");
                    }
                    screen_write_puts!(&raw mut ctx, &raw mut gc0, ") ");
                } else {
                    screen_write_puts!(&raw mut ctx, &raw mut gc0, " ");
                }
            }
            free_(text);

            let box_x = w - 4;
            let box_y = sy - h - 2;

            if box_x != 0 && box_y != 0 {
                screen_write_cursormove(&raw mut ctx, 2, h as i32 + 1, 0);
                mtd.drawcb.unwrap()(
                    mtd.modedata,
                    NonNull::new((*mti).itemdata),
                    &raw mut ctx,
                    box_x,
                    box_y,
                );
            }
        }
        // done:
        screen_write_cursormove(&raw mut ctx, 0, mtd.current as i32 - mtd.offset as i32, 0);
        screen_write_stop(&raw mut ctx);
    }
}

/// C `vendor/tmux/mode-tree.c:1175`: `static struct mode_tree_item *mode_tree_search_backward(struct mode_tree_data *mtd)`
pub unsafe fn mode_tree_search_backward(mtd: *mut mode_tree_data) -> *mut mode_tree_item {
    unsafe {
        if (*mtd).search.is_null() {
            return null_mut();
        }

        let last = (&(*mtd).line_list)[(*mtd).current as usize].item;
        let mut mti = last;

        loop {
            let mut prev = tailq_prev(mti);
            if !prev.is_null() {
                // Point to the last child in the previous subtree.
                while !tailq_empty(&raw mut (*prev).children) {
                    prev = tailq_last(&raw mut (*prev).children);
                }
                mti = prev;
            } else {
                // If prev is NULL, jump to the parent.
                mti = (*mti).parent;
            }

            if mti.is_null() {
                // Point to the last child in the last root subtree.
                prev = tailq_last(&raw mut (*mtd).children);
                while !tailq_empty(&raw mut (*prev).children) {
                    prev = tailq_last(&raw mut (*prev).children);
                }
                mti = prev;
            }
            if mti == last {
                break;
            }

            let Some(searchcb) = (*mtd).searchcb else {
                if cstr_to_str((*mti).name).contains(cstr_to_str((*mtd).search)) {
                    return mti;
                }
                continue;
            };
            if searchcb(
                (*mtd).modedata,
                NonNull::new((*mti).itemdata).unwrap(),
                (*mtd).search,
            ) {
                return mti;
            }
        }
        null_mut()
    }
}

/// C `vendor/tmux/mode-tree.c:1224`: `static struct mode_tree_item *mode_tree_search_forward(struct mode_tree_data *mtd)`
pub unsafe fn mode_tree_search_forward(mtd: *mut mode_tree_data) -> *mut mode_tree_item {
    unsafe {
        if (*mtd).search.is_null() {
            return null_mut();
        }

        let last = (&(*mtd).line_list)[(*mtd).current as usize].item;
        let mut mti = last;
        loop {
            if !tailq_empty(&raw mut (*mti).children) {
                mti = tailq_first(&raw mut (*mti).children);
            } else if let Some(next) = NonNull::new(tailq_next(mti)) {
                mti = next.as_ptr();
            } else {
                loop {
                    mti = (*mti).parent;
                    if mti.is_null() {
                        break;
                    }

                    if let Some(next) = NonNull::new(tailq_next(mti)) {
                        mti = next.as_ptr();
                        break;
                    }
                }
            }
            if mti.is_null() {
                mti = tailq_first(&raw mut (*mtd).children);
            }
            if mti == last {
                break;
            }

            let Some(searchcb) = (*mtd).searchcb else {
                if cstr_to_str((*mti).name).contains(cstr_to_str((*mtd).search)) {
                    return mti;
                }
                continue;
            };
            if searchcb(
                (*mtd).modedata,
                NonNull::new((*mti).itemdata).unwrap(),
                (*mtd).search,
            ) {
                return mti;
            }
        }
        null_mut()
    }
}

/// C `vendor/tmux/mode-tree.c:1269`: `static void mode_tree_search_set(struct mode_tree_data *mtd)`
pub unsafe fn mode_tree_search_set(mtd: *mut mode_tree_data) {
    unsafe {
        let mti = match (*mtd).search_dir {
            mode_tree_search_dir::MODE_TREE_SEARCH_FORWARD => mode_tree_search_forward(mtd),
            mode_tree_search_dir::MODE_TREE_SEARCH_BACKWARD => mode_tree_search_backward(mtd),
        };
        if mti.is_null() {
            return;
        }
        let tag = (*mti).tag;

        let mut loop_ = (*mti).parent;
        while !loop_.is_null() {
            (*loop_).expanded = true;
            loop_ = (*loop_).parent;
        }

        mode_tree_build(mtd);
        mode_tree_set_current(mtd, tag);
        mode_tree_draw(&mut *mtd);
        (*(*mtd).wp).flags |= window_pane_flags::PANE_REDRAW;
    }
}

/// C `vendor/tmux/mode-tree.c:1295`: `static enum prompt_result mode_tree_search_callback(__unused struct client *c, void *data, const char *s, enum prompt_key_result key)`
pub unsafe fn mode_tree_search_callback(
    _c: *mut client,
    mtd: NonNull<mode_tree_data>,
    s: *const u8,
    _done: i32,
) -> i32 {
    unsafe {
        let mtd: *mut mode_tree_data = mtd.as_ptr();

        if (*mtd).dead != 0 {
            return 0;
        }

        free_((*mtd).search);
        if s.is_null() || *s == b'\0' {
            (*mtd).search = null_mut();
            return 0;
        }
        (*mtd).search = xstrdup(s).as_ptr();
        mode_tree_search_set(mtd);

        0
    }
}

pub unsafe fn mode_tree_search_free(data: NonNull<mode_tree_data>) {
    unsafe {
        mode_tree_remove_ref(data.cast().as_ptr());
    }
}

/// C `vendor/tmux/mode-tree.c:1318`: `static enum prompt_result mode_tree_filter_callback(__unused struct client *c, void *data, const char *s, enum prompt_key_result key)`
pub unsafe fn mode_tree_filter_callback(
    _c: *mut client,
    data: NonNull<mode_tree_data>,
    s: *const u8,
    _done: i32,
) -> i32 {
    unsafe {
        let mtd: *mut mode_tree_data = data.as_ptr();

        if (*mtd).dead != 0 {
            return 0;
        }

        if !(*mtd).filter.is_null() {
            free_((*mtd).filter);
        }
        if s.is_null() || *s == b'\0' {
            (*mtd).filter = null_mut();
        } else {
            (*mtd).filter = xstrdup(s).as_ptr();
        }

        mode_tree_build(mtd);
        mode_tree_draw(&mut *mtd);
        (*(*mtd).wp).flags |= window_pane_flags::PANE_REDRAW;

        0
    }
}

pub unsafe fn mode_tree_filter_free(data: NonNull<mode_tree_data>) {
    unsafe {
        mode_tree_remove_ref(data.cast().as_ptr());
    }
}

/// C `vendor/tmux/mode-tree.c:1354`: `static void mode_tree_menu_callback(__unused struct menu *menu, __unused u_int idx, key_code key, void *data)`
pub unsafe fn mode_tree_menu_callback(
    _menu: *mut menu,
    _idx: u32,
    key: key_code,
    data: *mut c_void,
) {
    unsafe {
        let mtm: *mut mode_tree_menu = data.cast();
        let mtd: *mut mode_tree_data = (*mtm).data.cast();

        'out: {
            if (*mtd).dead != 0 || key == KEYC_NONE {
                break 'out;
            }

            if (*mtm).line >= (*mtd).line_list.len() as u32 {
                break 'out;
            }
            (*mtd).current = (*mtm).line;
            (*mtd).menucb.unwrap()(NonNull::new((*mtd).modedata).unwrap(), (*mtm).c, key);
        }
        // out:
        mode_tree_remove_ref(mtd);
        free_(mtm);
    }
}

/// C `vendor/tmux/mode-tree.c:1374`: `static void mode_tree_display_menu(struct mode_tree_data *mtd, struct client *c, u_int x, u_int y, int outside)`
pub unsafe fn mode_tree_display_menu(
    mtd: *mut mode_tree_data,
    c: *mut client,
    mut x: u32,
    y: u32,
    outside: i32,
) {
    unsafe {
        let line = if (*mtd).offset + y > (*mtd).line_list.len() as u32 - 1 {
            (*mtd).current
        } else {
            (*mtd).offset + y
        };
        let mti = (&(*mtd).line_list)[line as usize].item;

        let (items, title) = if outside == 0 {
            (
                (*mtd).menu,
                format!("#[align=centre]{}", _s((*mti).name)),
            )
        } else {
            (MODE_TREE_MENU_ITEMS.as_slice(), String::new())
        };
        let menu = Box::leak(menu_create(&title));
        menu_add_items(menu, items, null_mut(), c, null_mut());

        let mtm = Box::leak(Box::new(mode_tree_menu {
            data: mtd,
            c,
            line,
        })) as *mut mode_tree_menu;
        (*mtd).references += 1;

        #[expect(clippy::manual_midpoint, reason = "not really being used as midpoint calculation")]
        if x >= (menu.width + 4) / 2 {
            x -= (menu.width + 4) / 2;
        } else {
            x = 0;
        }
        if menu_display(
            menu,
            menu_flags::empty(),
            0,
            null_mut(),
            x,
            y,
            c,
            box_lines::BOX_LINES_DEFAULT,
            null_mut(),
            null_mut(),
            null_mut(),
            null_mut(),
            Some(mode_tree_menu_callback),
            mtm.cast(),
        ) != 0
        {
            menu_free(menu);
        }
    }
}

/// C `vendor/tmux/mode-tree.c:1494`: `int mode_tree_key(struct mode_tree_data *mtd, struct client *c, key_code *key, struct mouse_event *m, u_int *xp, u_int *yp)`
pub unsafe fn mode_tree_key(
    mtd: *mut mode_tree_data,
    c: *mut client,
    key: *mut key_code,
    m: *mut mouse_event,
    xp: *mut u32,
    yp: *mut u32,
) -> i32 {
    unsafe {
        let mut x: u32 = 0;
        let mut y: u32 = 0;

        if (*mtd).line_list.is_empty() {
            *key = KEYC_NONE;
            return 1;
        }

        if KEYC_IS_MOUSE(*key) && !m.is_null() {
            if cmd_mouse_at((*mtd).wp, m, &raw mut x, &raw mut y, 0) != 0 {
                *key = KEYC_NONE;
                return 0;
            }
            if !xp.is_null() {
                *xp = x;
            }
            if !yp.is_null() {
                *yp = y;
            }
            if x > (*mtd).width || y > (*mtd).height {
                if *key == keyc::KEYC_MOUSEDOWN3_PANE as u64 {
                    mode_tree_display_menu(mtd, c, x, y, 1);
                }
                if !(*mtd).preview {
                    *key = KEYC_NONE;
                }
                return 0;
            }
            if (*mtd).offset + y < (*mtd).line_list.len() as u32 {
                if *key == keyc::KEYC_MOUSEDOWN1_PANE as u64
                    || *key == keyc::KEYC_MOUSEDOWN3_PANE as u64
                    || *key == keyc::KEYC_DOUBLECLICK1_PANE as u64
                {
                    (*mtd).current = (*mtd).offset + y;
                }
                if *key == keyc::KEYC_DOUBLECLICK1_PANE as u64 {
                    *key = b'\r' as u64;
                } else {
                    if *key == keyc::KEYC_MOUSEDOWN3_PANE as u64 {
                        mode_tree_display_menu(mtd, c, x, y, 0);
                    }
                    *key = KEYC_NONE;
                }
            } else {
                if *key == keyc::KEYC_MOUSEDOWN3_PANE as u64 {
                    mode_tree_display_menu(mtd, c, x, y, 0);
                }
                *key = KEYC_NONE;
            }
            return 0;
        }

        let line = &((&(*mtd).line_list)[(*mtd).current as usize]);
        let mut current = line.item;

        if let Some(choice) = (*mtd)
            .line_list
            .iter()
            .position(|line| *key == (*line.item).key)
        {
            if (choice as u32) > (*mtd).line_list.len() as u32 - 1 {
                *key = KEYC_NONE;
                return 0;
            }
            (*mtd).current = choice as u32;
            *key = b'\r' as u64;
            return 0;
        }

        mod code {
            use super::*;

            pub const Q: u64 = 'q' as u64;
            pub const ESC: u64 = '\x1b' as u64;
            pub const G_CTRL: u64 = 'g' as u64 | KEYC_CTRL;

            pub const K: u64 = 'k' as u64;
            pub const P_CTRL: u64 = 'p' as u64 | KEYC_CTRL;

            pub const J: u64 = 'j' as u64;

            pub const F: u64 = 'f' as u64;
            pub const V: u64 = 'v' as u64;

            pub const N: u64 = 'n' as u64;
            pub const N_UPPER: u64 = 'N' as u64;
            pub const N_CTRL: u64 = 'n' as u64 | KEYC_CTRL;

            pub const B_CTRL: u64 = 'b' as u64 | KEYC_CTRL;

            pub const F_CTRL: u64 = 'f' as u64 | KEYC_CTRL;

            pub const G: u64 = 'g' as u64;
            pub const G_UPPER: u64 = 'G' as u64;

            pub const T: u64 = 't' as u64;
            pub const T_CTRL: u64 = 't' as u64 | KEYC_CTRL;
            pub const T_UPPER: u64 = 'T' as u64;

            pub const O_UPPER: u64 = 'O' as u64;
            pub const R: u64 = 'r' as u64;

            pub const L: u64 = 'l' as u64;
            pub const H: u64 = 'h' as u64;
            pub const MINUS: u64 = '-' as u64;
            pub const PLUS: u64 = '+' as u64;

            pub const MINUS_META: u64 = '-' as u64 | KEYC_META;
            pub const PLUS_META: u64 = '+' as u64 | KEYC_META;

            pub const QUESTION_MARK: u64 = '?' as u64;
            pub const SLASH: u64 = '/' as u64;
            pub const S_CTRL: u64 = 's' as u64 | KEYC_CTRL;

            pub const KEYC_UP: u64 = keyc::KEYC_UP as u64;
            pub const KEYC_DOWN: u64 = keyc::KEYC_DOWN as u64;

            pub const KEYC_WHEELUP_PANE: u64 = keyc::KEYC_WHEELUP_PANE as u64;
            pub const KEYC_WHEELDOWN_PANE: u64 = keyc::KEYC_WHEELDOWN_PANE as u64;

            pub const KEYC_PPAGE: u64 = keyc::KEYC_PPAGE as u64;
            pub const KEYC_NPAGE: u64 = keyc::KEYC_NPAGE as u64;

            pub const KEYC_HOME: u64 = keyc::KEYC_HOME as u64;
            pub const KEYC_END: u64 = keyc::KEYC_END as u64;
            pub const KEYC_LEFT: u64 = keyc::KEYC_LEFT as u64;
            pub const KEYC_RIGHT: u64 = keyc::KEYC_RIGHT as u64;
        }

        match *key {
            code::Q | code::ESC | code::G_CTRL => return 1,

            code::KEYC_UP | code::K | code::KEYC_WHEELUP_PANE | code::P_CTRL => {
                mode_tree_up(mtd, 1);
            }

            code::KEYC_DOWN | code::J | code::KEYC_WHEELDOWN_PANE | code::N_CTRL => {
                mode_tree_down(mtd, 1);
            }

            code::KEYC_PPAGE | code::B_CTRL => {
                for _ in 0..(*mtd).height {
                    if (*mtd).current == 0 {
                        break;
                    }
                    mode_tree_up(mtd, 1);
                }
            }
            code::KEYC_NPAGE | code::F_CTRL => {
                for _ in 0..(*mtd).height {
                    if (*mtd).current == (*mtd).line_list.len() as u32 - 1 {
                        break;
                    }
                    mode_tree_down(mtd, 1);
                }
            }
            code::G | code::KEYC_HOME => {
                (*mtd).current = 0;
                (*mtd).offset = 0;
            }
            code::G_UPPER | code::KEYC_END => {
                (*mtd).current = (*mtd).line_list.len() as u32 - 1;
                if (*mtd).current > (*mtd).height - 1 {
                    (*mtd).offset = (*mtd).current - (*mtd).height + 1;
                } else {
                    (*mtd).offset = 0;
                }
            }
            code::T => {
                // Do not allow parents and children to both be tagged: untag
                // all parents and children of current.
                if (*current).no_tag == 0 {
                    if (*current).tagged == 0 {
                        let mut parent = (*current).parent;
                        while !parent.is_null() {
                            (*parent).tagged = 0;
                            parent = (*parent).parent;
                        }
                        mode_tree_clear_tagged(&raw mut (*current).children);
                        (*current).tagged = 1;
                    } else {
                        (*current).tagged = 0;
                    }
                    if !m.is_null() {
                        mode_tree_down(mtd, 0);
                    }
                }
            }
            code::T_UPPER => {
                for line in &mut (*mtd).line_list {
                    (*line.item).tagged = 0;
                }
            }
            code::T_CTRL => {
                for line in &mut (*mtd).line_list {
                    if ((*line.item).parent.is_null() && (*line.item).no_tag == 0)
                        || (!(*line.item).parent.is_null() && (*(*line.item).parent).no_tag != 0)
                    {
                        (*line.item).tagged = 1;
                    } else {
                        (*line.item).tagged = 0;
                    }
                }
            }
            #[expect(clippy::needless_borrow, reason = "false positive")]
            code::O_UPPER => {
                (*mtd).sort_crit.field += 1;
                if (*mtd).sort_crit.field >= (&(*mtd).sort_list).len() as u32 {
                    (*mtd).sort_crit.field = 0;
                }
                mode_tree_build(mtd);
            }
            code::R => {
                (*mtd).sort_crit.reversed = !(*mtd).sort_crit.reversed;
                mode_tree_build(mtd);
            }
            code::KEYC_LEFT | code::H | code::MINUS => {
                if line.flat != 0 || !(*current).expanded {
                    current = (*current).parent;
                }
                if current.is_null() {
                    mode_tree_up(mtd, 0);
                } else {
                    (*current).expanded = false;
                    (*mtd).current = (*current).line;
                    mode_tree_build(mtd);
                }
            }
            code::KEYC_RIGHT | code::L | code::PLUS => {
                if line.flat != 0 || (*current).expanded {
                    mode_tree_down(mtd, 0);
                } else if line.flat == 0 {
                    (*current).expanded = true;
                    mode_tree_build(mtd);
                }
            }
            code::MINUS_META => {
                for mti in tailq_foreach(&raw mut (*mtd).children).map(NonNull::as_ptr) {
                    (*mti).expanded = false;
                }
                mode_tree_build(mtd);
            }
            code::PLUS_META => {
                for mti in tailq_foreach(&raw mut (*mtd).children).map(NonNull::as_ptr) {
                    (*mti).expanded = true;
                }
                mode_tree_build(mtd);
            }
            code::QUESTION_MARK | code::SLASH | code::S_CTRL => {
                (*mtd).references += 1;
                status_prompt_set(
                    c,
                    null_mut(),
                    c!("(search) "),
                    c!(""),
                    mode_tree_search_callback,
                    mode_tree_search_free,
                    mtd,
                    prompt_flags::PROMPT_NOFORMAT,
                    prompt_type::PROMPT_TYPE_SEARCH,
                );
            }
            code::N => {
                (*mtd).search_dir = mode_tree_search_dir::MODE_TREE_SEARCH_FORWARD;
                mode_tree_search_set(mtd);
            }
            code::N_UPPER => {
                (*mtd).search_dir = mode_tree_search_dir::MODE_TREE_SEARCH_BACKWARD;
                mode_tree_search_set(mtd);
            }
            code::F => {
                (*mtd).references += 1;
                status_prompt_set(
                    c,
                    null_mut(),
                    c!("(filter) "),
                    (*mtd).filter,
                    mode_tree_filter_callback,
                    mode_tree_filter_free,
                    mtd,
                    prompt_flags::PROMPT_NOFORMAT,
                    prompt_type::PROMPT_TYPE_SEARCH,
                );
            }
            code::V => {
                (*mtd).preview = !(*mtd).preview;
                mode_tree_build(mtd);
                if (*mtd).preview {
                    mode_tree_check_selected(mtd);
                }
            }
            _ => (),
        }
        0
    }
}

/// C `vendor/tmux/mode-tree.c:1812`: `void mode_tree_run_command(struct client *c, struct cmd_find_state *fs, const char *template, const char *name)`
pub unsafe fn mode_tree_run_command(
    c: *mut client,
    fs: *mut cmd_find_state,
    template: *const u8,
    name: Option<&str>,
) {
    unsafe {
        let mut error: *mut u8 = null_mut();

        let command = cmd_template_replace(template, name, 1);
        if !command.is_null() && *command != b'\0' {
            let state = cmdq_new_state(fs, null_mut(), cmdq_state_flags::empty());
            let status = cmd_parse_and_append(cstr_to_str(command), None, c, state, &raw mut error);
            if status == cmd_parse_status::CMD_PARSE_ERROR {
                if !c.is_null() {
                    *error = (*error).to_ascii_uppercase();
                    status_message_set!(c, -1, 1, false, 0, "{}", _s(error));
                }
                free_(error);
            }
            cmdq_free_state(state);
        }
        free_(command);
    }
}