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
// Copyright (c) 2020 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::*;
use crate::options_::*;

bitflags::bitflags! {
    #[repr(transparent)]
    #[derive(Copy, Clone, Eq, PartialEq)]
    pub struct popup_flag : i32 {
        const POPUP_CLOSEEXIT = 0x1;
        const POPUP_CLOSEEXITZERO = 0x2;
        const POPUP_INTERNAL = 0x4;
    }
}

pub type popup_close_cb = Option<unsafe fn(_: i32, _: *mut c_void)>;
pub type popup_finish_edit_cb = Option<unsafe fn(_: *mut u8, _: usize, _: *mut c_void)>;

#[repr(i32)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum dragging_state {
    Off,
    Move,
    Size,
}

#[repr(C)]
pub struct popup_data {
    pub c: *mut client,
    pub item: *mut cmdq_item,
    pub flags: popup_flag,
    pub title: *mut u8,

    pub border_cell: grid_cell,
    pub border_lines: box_lines,

    pub s: screen,
    pub defaults: grid_cell,
    pub palette: colour_palette,

    pub job: *mut job,
    pub ictx: *mut input_ctx,
    pub status: i32,
    pub cb: popup_close_cb,
    pub arg: *mut c_void,

    pub menu: *mut menu,
    pub md: *mut menu_data,
    pub close: i32,

    // Current position and size
    pub px: u32,
    pub py: u32,
    pub sx: u32,
    pub sy: u32,

    // Preferred position and size
    pub ppx: u32,
    pub ppy: u32,
    pub psx: u32,
    pub psy: u32,

    pub dragging: dragging_state,
    pub dx: u32,
    pub dy: u32,

    pub lx: u32,
    pub ly: u32,
    pub lb: u32,
}

#[repr(C)]
pub struct popup_editor {
    pub path: *mut u8,
    pub cb: popup_finish_edit_cb,
    pub arg: *mut c_void,
}

static POPUP_MENU_ITEMS: [menu_item; 8] = [
    menu_item::new("Close", 'q' as u64, null_mut()),
    menu_item::new(
        "#{?buffer_name,Paste #[underscore]#{buffer_name},}",
        'p' as u64,
        null_mut(),
    ),
    menu_item::new("", KEYC_NONE, null_mut()),
    menu_item::new("Fill Space", 'F' as u64, null_mut()),
    menu_item::new("Centre", 'C' as u64, null_mut()),
    menu_item::new("", KEYC_NONE, null_mut()),
    menu_item::new("To Horizontal Pane", 'h' as u64, null_mut()),
    menu_item::new("To Vertical Pane", 'v' as u64, null_mut()),
];

static POPUP_INTERNAL_MENU_ITEMS: [menu_item; 4] = [
    menu_item::new("Close", 'q' as u64, null_mut()),
    menu_item::new("", KEYC_NONE, null_mut()),
    menu_item::new("Fill Space", 'F' as u64, null_mut()),
    menu_item::new("Centre", 'C' as u64, null_mut()),
];

/// C `vendor/tmux/popup.c:156`: `static void popup_redraw_cb(const struct tty_ctx *ttyctx)`
pub unsafe fn popup_redraw_cb(ttyctx: *const tty_ctx) {
    unsafe {
        let pd = (*ttyctx).arg.cast::<popup_data>();
        (*(*pd).c).flags |= client_flag::REDRAWOVERLAY;
    }
}

/// C `vendor/tmux/popup.c:164`: `static int popup_set_client_cb(struct tty_ctx *ttyctx, struct client *c)`
pub unsafe fn popup_set_client_cb(ttyctx: *mut tty_ctx, c: *mut client) -> i32 {
    unsafe {
        let pd = (*ttyctx).arg.cast::<popup_data>();

        if c != (*pd).c {
            return 0;
        }
        if (*(*pd).c).flags.intersects(client_flag::REDRAWOVERLAY) {
            return 0;
        }

        (*ttyctx).bigger = 0;
        (*ttyctx).wox = 0;
        (*ttyctx).woy = 0;
        (*ttyctx).wsx = (*c).tty.sx;
        (*ttyctx).wsy = (*c).tty.sy;

        if (*pd).border_lines == box_lines::BOX_LINES_NONE {
            (*ttyctx).xoff = (*pd).px;
            (*ttyctx).rxoff = (*pd).px;
            (*ttyctx).yoff = (*pd).py;
            (*ttyctx).ryoff = (*pd).py;
        } else {
            (*ttyctx).xoff = (*pd).px + 1;
            (*ttyctx).rxoff = (*pd).px + 1;
            (*ttyctx).yoff = (*pd).py + 1;
            (*ttyctx).ryoff = (*pd).py + 1;
        }

        1
    }
}

/// C `vendor/tmux/popup.c:190`: `static void popup_init_ctx_cb(struct screen_write_ctx *ctx, struct tty_ctx *ttyctx)`
pub unsafe fn popup_init_ctx_cb(ctx: *mut screen_write_ctx, ttyctx: *mut tty_ctx) {
    unsafe {
        let pd = (*ctx).arg.cast::<popup_data>();

        memcpy__(&raw mut (*ttyctx).defaults, &raw const (*pd).defaults);
        (*ttyctx).palette = &raw const (*pd).palette;
        (*ttyctx).redraw_cb = Some(popup_redraw_cb);
        (*ttyctx).set_client_cb = Some(popup_set_client_cb);
        (*ttyctx).arg = pd.cast();
    }
}

/// C `vendor/tmux/popup.c:204`: `static struct screen *popup_mode_cb(__unused struct client *c, void *data, u_int *cx, u_int *cy)`
pub unsafe fn popup_mode_cb(
    c: *mut client,
    data: *mut c_void,
    cx: *mut u32,
    cy: *mut u32,
) -> *mut screen {
    unsafe {
        let pd = data.cast::<popup_data>();

        if !(*pd).md.is_null() {
            return menu_mode_cb(c, (*pd).md.cast(), cx, cy);
        }

        if (*pd).border_lines == box_lines::BOX_LINES_NONE {
            *cx = (*pd).px + (*pd).s.cx;
            *cy = (*pd).py + (*pd).s.cy;
        } else {
            *cx = (*pd).px + 1 + (*pd).s.cx;
            *cy = (*pd).py + 1 + (*pd).s.cy;
        }
        &raw mut (*pd).s
    }
}

/// Return parts of the input range which are not obstructed by the popup.
/// C `vendor/tmux/popup.c:223`: `static struct visible_ranges *popup_check_cb(struct client* c, void *data, u_int px, u_int py, u_int nx)`
pub unsafe fn popup_check_cb(
    c: *mut client,
    data: *mut c_void,
    px: u32,
    py: u32,
    nx: u32,
    r: *mut overlay_ranges,
) {
    unsafe {
        let pd = data.cast::<popup_data>();
        let mut or = MaybeUninit::<[overlay_ranges; 2]>::uninit();
        let or: *mut overlay_ranges = or.as_mut_ptr().cast();

        let mut k = 0;

        if !(*pd).md.is_null() {
            // Check each returned range for the menu against the popup
            menu_check_cb(c, (*pd).md.cast(), px, py, nx, r);

            for i in 0..2 {
                server_client_overlay_range(
                    (*pd).px,
                    (*pd).py,
                    (*pd).sx,
                    (*pd).sy,
                    (*r).px[i],
                    py,
                    (*r).nx[i],
                    or.add(i),
                );
            }

            // or has up to OVERLAY_MAX_RANGES non-overlapping ranges,
            // ordered from left to right. Collect them in the output.
            for i in 0..2 {
                // Each or[i] only has 2 ranges
                for j in 0..2 {
                    if (*or.add(i)).nx[j] > 0 {
                        (*r).px[k] = (*or.add(i)).px[j];
                        (*r).nx[k] = (*or.add(i)).nx[j];
                        k += 1;
                    }
                }
            }

            // Zero remaining ranges if any
            for i in k..OVERLAY_MAX_RANGES {
                (*r).px[i] = 0;
                (*r).nx[i] = 0;
            }

            return;
        }

        server_client_overlay_range((*pd).px, (*pd).py, (*pd).sx, (*pd).sy, px, py, nx, r);
    }
}

/// C `vendor/tmux/popup.c:276`: `static void popup_draw_cb(struct client *c, void *data)`
pub unsafe fn popup_draw_cb(c: *mut client, data: *mut c_void, rctx: *mut screen_redraw_ctx) {
    unsafe {
        let pd = data.cast::<popup_data>();
        let tty = &mut (*c).tty;
        let mut s = MaybeUninit::<screen>::uninit();
        let mut ctx = MaybeUninit::<screen_write_ctx>::uninit();
        let (px, py) = ((*pd).px, (*pd).py);
        let palette = &raw mut (*pd).palette;
        let mut defaults = MaybeUninit::<grid_cell>::uninit();
        let defaults = defaults.as_mut_ptr();

        screen_init(s.as_mut_ptr(), (*pd).sx, (*pd).sy, 0);
        screen_write_start(ctx.as_mut_ptr(), s.as_mut_ptr());
        screen_write_clearscreen(ctx.as_mut_ptr(), 8);

        if (*pd).border_lines == box_lines::BOX_LINES_NONE {
            screen_write_cursormove(ctx.as_mut_ptr(), 0, 0, 0);
            screen_write_fast_copy(ctx.as_mut_ptr(), &raw mut (*pd).s, 0, 0, (*pd).sx, (*pd).sy);
        } else if (*pd).sx > 2 && (*pd).sy > 2 {
            screen_write_box(
                ctx.as_mut_ptr(),
                (*pd).sx,
                (*pd).sy,
                (*pd).border_lines,
                &(*pd).border_cell,
                cstr_to_str_((*pd).title),
            );
            screen_write_cursormove(ctx.as_mut_ptr(), 1, 1, 0);
            screen_write_fast_copy(
                ctx.as_mut_ptr(),
                &raw mut (*pd).s,
                0,
                0,
                (*pd).sx - 2,
                (*pd).sy - 2,
            );
        }
        screen_write_stop(ctx.as_mut_ptr());

        memcpy__(defaults, &raw const (*pd).defaults);
        if (*defaults).fg == 8 {
            (*defaults).fg = (*palette).fg;
        }
        if (*defaults).bg == 8 {
            (*defaults).bg = (*palette).bg;
        }

        if !(*pd).md.is_null() {
            (*c).overlay_check = Some(menu_check_cb);
            (*c).overlay_data = (*pd).md.cast();
        } else {
            (*c).overlay_check = None;
            (*c).overlay_data = null_mut();
        }

        for i in 0..(*pd).sy {
            tty_draw_line(
                tty,
                s.as_mut_ptr(),
                0,
                i,
                (*pd).sx,
                px,
                py + i,
                defaults,
                palette,
            );
        }

        screen_free(s.as_mut_ptr());

        if !(*pd).md.is_null() {
            (*c).overlay_check = None;
            (*c).overlay_data = null_mut();
            menu_draw_cb(c, (*pd).md.cast(), rctx);
        }

        (*c).overlay_check = Some(popup_check_cb);
        (*c).overlay_data = pd.cast();
    }
}

/// C `vendor/tmux/popup.c:338`: `static void popup_free_cb(struct client *c, void *data)`
pub fn popup_free_cb(c: *mut client, data: *mut c_void) {
    unsafe {
        let pd = data as *mut popup_data;
        let item = (*pd).item;

        if !(*pd).md.is_null() {
            menu_free_cb(c, (*pd).md.cast());
        }

        if let Some(cb) = (*pd).cb {
            cb((*pd).status, (*pd).arg);
        }

        if !item.is_null() {
            let client = cmdq_get_client(item);
            if !client.is_null() && (*client).session.is_null() {
                (*client).retval = (*pd).status;
            }
            cmdq_continue(item);
        }
        server_client_unref((*pd).c);

        if !(*pd).job.is_null() {
            job_free((*pd).job);
        }
        input_free((*pd).ictx);

        screen_free(&mut (*pd).s);
        colour_palette_free(Some(&mut (*pd).palette));

        free_((*pd).title);
        free_(pd);
    }
}

/// C `vendor/tmux/popup.c:360`: `static void popup_resize_cb(__unused struct client *c, void *data)`
pub fn popup_resize_cb(c: *mut client, data: *mut c_void) {
    unsafe {
        let pd = data as *mut popup_data;
        if pd.is_null() {
            return;
        }

        let tty = &raw mut (*(*pd).c).tty;

        if !(*pd).md.is_null() {
            menu_free_cb(c, (*pd).md.cast());
        }

        // Adjust position and size
        (*pd).sy = (*pd).psy.min((*tty).sy);
        (*pd).sx = (*pd).psx.min((*tty).sx);

        (*pd).py = if (*pd).ppy + (*pd).sy > (*tty).sy {
            (*tty).sy - (*pd).sy
        } else {
            (*pd).ppy
        };

        (*pd).px = if (*pd).ppx + (*pd).sx > (*tty).sx {
            (*tty).sx - (*pd).sx
        } else {
            (*pd).ppx
        };

        // Avoid zero size screens
        if (*pd).border_lines == box_lines::BOX_LINES_NONE {
            screen_resize(&mut (*pd).s, (*pd).sx, (*pd).sy, 0);
            if !(*pd).job.is_null() {
                job_resize((*pd).job, (*pd).sx, (*pd).sy);
            }
        } else if (*pd).sx > 2 && (*pd).sy > 2 {
            screen_resize(&mut (*pd).s, (*pd).sx - 2, (*pd).sy - 2, 0);
            if !(*pd).job.is_null() {
                job_resize((*pd).job, (*pd).sx - 2, (*pd).sy - 2);
            }
        }
    }
}

/// C `vendor/tmux/popup.c:401`: `static void popup_make_pane(struct popup_data *pd, enum layout_type type)`
pub fn popup_make_pane(pd: *mut popup_data, type_: layout_type) {
    unsafe {
        let c = (*pd).c;
        let s = (*c).session;
        let w = (*(*s).curw).window;
        let wp = (*w).active;

        window_unzoom(w, 1);

        let lc = layout_split_pane(wp, type_, -1, spawn_flags::empty());
        let hlimit = options_get_number_((*s).options, "history-limit") as u32;
        let new_wp = window_add_pane((*wp).window, null_mut(), hlimit, spawn_flags::empty());
        layout_assign_pane(lc, new_wp, 0);

        (*new_wp).fd = job_transfer(
            (*pd).job,
            &mut (*new_wp).pid,
            (*new_wp).tty.as_mut_ptr(),
            TTY_NAME_MAX,
        );
        (*pd).job = null_mut();

        screen_set_title(&raw mut (*pd).s, (*new_wp).base.title_ptr());
        screen_free(&raw mut (*new_wp).base);
        memcpy__(&raw mut (*new_wp).base, &raw const (*pd).s);
        screen_resize(&raw mut (*new_wp).base, (*new_wp).sx, (*new_wp).sy, 1);
        screen_init(&raw mut (*pd).s, 1, 1, 0);

        let mut shell = options_get_string_((*s).options, "default-shell");
        if !checkshell_(shell) {
            shell = _PATH_BSHELL;
        }
        (*new_wp).shell = Some(std::ffi::CStr::from_ptr(shell.cast()).to_owned());

        window_pane_set_event(new_wp);
        window_set_active_pane(w, new_wp, 1);
        (*new_wp).flags |= window_pane_flags::PANE_CHANGED;

        (*pd).close = 1;
    }
}

/// C `vendor/tmux/popup.c:445`: `static void popup_menu_done(__unused struct menu *menu, __unused u_int choice, key_code key, void *data)`
pub fn popup_menu_done(_menu: *mut menu, _choice: u32, key: key_code, data: *mut c_void) {
    unsafe {
        let pd = data as *mut popup_data;
        let c = (*pd).c;

        (*pd).md = null_mut();
        (*pd).menu = null_mut();
        server_redraw_client((*pd).c);

        // C switches on the full key_code. Truncating to u8 lets a KEYC_* code alias an
        // ASCII command here: KEYC_MOUSEUP11_STATUS_DEFAULT ends in 0x78 ('x', the Kill
        // prompt) and KEYC_DOUBLECLICK11_PANE ends in 0x58 ('X', Kill Tagged). Only a key
        // that really is a bare ASCII byte may match these arms.
        let key_byte = if key < 0x80 { key as u8 } else { 0 };
        match key_byte {
            b'p' => {
                if let Some(pb) = NonNull::new(paste_get_top(null_mut())) {
                    let mut len: usize = 0;
                    let buf = paste_buffer_data_(pb, &mut len);
                    bufferevent_write(job_get_event((*pd).job), buf as *const c_void, len);
                }
            }
            b'F' => {
                (*pd).sx = (*c).tty.sx;
                (*pd).sy = (*c).tty.sy;
                (*pd).px = 0;
                (*pd).py = 0;
                server_redraw_client(c);
            }
            b'C' => {
                (*pd).px = (*c).tty.sx / 2 - (*pd).sx / 2;
                (*pd).py = (*c).tty.sy / 2 - (*pd).sy / 2;
                server_redraw_client(c);
            }
            b'h' => popup_make_pane(pd, layout_type::LAYOUT_LEFTRIGHT),
            b'v' => popup_make_pane(pd, layout_type::LAYOUT_TOPBOTTOM),
            b'q' => (*pd).close = 1,
            _ => {}
        }
    }
}

/// C `vendor/tmux/popup.c:491`: `static void popup_handle_drag(struct client *c, struct popup_data *pd, struct mouse_event *m)`
pub unsafe fn popup_handle_drag(c: *mut client, pd: *mut popup_data, m: *mut mouse_event) {
    unsafe {
        let px: u32;
        let py: u32;

        if !MOUSE_DRAG((*m).b) {
            (*pd).dragging = dragging_state::Off;
        } else if (*pd).dragging == dragging_state::Move {
            if (*m).x < (*pd).dx {
                px = 0;
            } else if (*m).x - (*pd).dx + (*pd).sx > (*c).tty.sx {
                px = (*c).tty.sx - (*pd).sx;
            } else {
                px = (*m).x - (*pd).dx;
            }
            if (*m).y < (*pd).dy {
                py = 0;
            } else if (*m).y - (*pd).dy + (*pd).sy > (*c).tty.sy {
                py = (*c).tty.sy - (*pd).sy;
            } else {
                py = (*m).y - (*pd).dy;
            }
            (*pd).px = px;
            (*pd).py = py;
            (*pd).dx = (*m).x - (*pd).px;
            (*pd).dy = (*m).y - (*pd).py;
            (*pd).ppx = px;
            (*pd).ppy = py;
            server_redraw_client(c);
        } else if (*pd).dragging == dragging_state::Size {
            if (*pd).border_lines == box_lines::BOX_LINES_NONE {
                if (*m).x < (*pd).px + 1 {
                    return;
                }
                if (*m).y < (*pd).py + 1 {
                    return;
                }
            } else {
                if (*m).x < (*pd).px + 3 {
                    return;
                }
                if (*m).y < (*pd).py + 3 {
                    return;
                }
            }
            (*pd).sx = (*m).x - (*pd).px;
            (*pd).sy = (*m).y - (*pd).py;
            (*pd).psx = (*pd).sx;
            (*pd).psy = (*pd).sy;

            if (*pd).border_lines == box_lines::BOX_LINES_NONE {
                screen_resize(&raw mut (*pd).s, (*pd).sx, (*pd).sy, 0);
                if !(*pd).job.is_null() {
                    job_resize((*pd).job, (*pd).sx, (*pd).sy);
                }
            } else {
                screen_resize(&raw mut (*pd).s, (*pd).sx - 2, (*pd).sy - 2, 0);
                if !(*pd).job.is_null() {
                    job_resize((*pd).job, (*pd).sx - 2, (*pd).sy - 2);
                }
            }
            server_redraw_client(c);
        }
    }
}

/// C `vendor/tmux/popup.c:549`: `static int popup_key_cb(struct client *c, void *data, struct key_event *event)`
pub unsafe fn popup_key_cb(c: *mut client, data: *mut c_void, event: *mut key_event) -> i32 {
    unsafe {
        let pd = data as *mut popup_data;
        let m = &raw mut (*event).m;
        let mut buf = null();
        let mut len = 0;

        'menu: {
            'out: {
                #[repr(i32)]
                #[derive(Copy, Clone, Eq, PartialEq)]
                enum Border {
                    None,
                    Left,
                    Right,
                    Top,
                    Bottom,
                }
                let mut border = Border::None;

                if !(*pd).md.is_null() {
                    if menu_key_cb(c, (*pd).md.cast(), event) == 1 {
                        (*pd).md = null_mut();
                        (*pd).menu = null_mut();
                        if (*pd).close != 0 {
                            server_client_clear_overlay(c);
                        } else {
                            server_redraw_client(c);
                        }
                    }
                    return 0;
                }

                if KEYC_IS_MOUSE((*event).key) {
                    if (*pd).dragging != dragging_state::Off {
                        popup_handle_drag(c, pd, m);
                        break 'out;
                    }
                    if (*m).x < (*pd).px
                        || (*m).x > (*pd).px + (*pd).sx - 1
                        || (*m).y < (*pd).py
                        || (*m).y > (*pd).py + (*pd).sy - 1
                    {
                        if MOUSE_BUTTONS((*m).b) == MOUSE_BUTTON_3 {
                            break 'menu;
                        }
                        return 0;
                    }
                    if (*pd).border_lines != box_lines::BOX_LINES_NONE {
                        if (*m).x == (*pd).px {
                            border = Border::Left;
                        } else if (*m).x == (*pd).px + (*pd).sx - 1 {
                            border = Border::Right;
                        } else if (*m).y == (*pd).py {
                            border = Border::Top;
                        } else if (*m).y == (*pd).py + (*pd).sy - 1 {
                            border = Border::Bottom;
                        }
                    }
                    if ((*m).b & MOUSE_MASK_MODIFIERS) == 0
                        && MOUSE_BUTTONS((*m).b) == MOUSE_BUTTON_3
                        && (border == Border::Left || border == Border::Top)
                    {
                        break 'menu;
                    }
                    if (((*m).b & MOUSE_MASK_MODIFIERS) == MOUSE_MASK_META)
                        || border != Border::None
                    {
                        if !MOUSE_DRAG((*m).b) {
                            break 'out;
                        }
                        if MOUSE_BUTTONS((*m).lb) == MOUSE_BUTTON_1 {
                            (*pd).dragging = dragging_state::Move;
                        } else if MOUSE_BUTTONS((*m).lb) == MOUSE_BUTTON_3 {
                            (*pd).dragging = dragging_state::Size;
                        }
                        (*pd).dx = (*m).lx - (*pd).px;
                        (*pd).dy = (*m).ly - (*pd).py;
                        break 'out;
                    }
                }
                if ((!(*pd)
                    .flags
                    .intersects(popup_flag::POPUP_CLOSEEXIT | popup_flag::POPUP_CLOSEEXITZERO))
                    || (*pd).job.is_null())
                    && ((*event).key == b'\x1b' as u64 || (*event).key == (b'c' as u64 | KEYC_CTRL))
                {
                    return 1;
                }
                if !(*pd).job.is_null() {
                    if KEYC_IS_MOUSE((*event).key) {
                        // Must be inside, checked already.
                        let (px, py) = if (*pd).border_lines == box_lines::BOX_LINES_NONE {
                            ((*m).x - (*pd).px, (*m).y - (*pd).py)
                        } else {
                            ((*m).x - (*pd).px - 1, (*m).y - (*pd).py - 1)
                        };
                        if input_key_get_mouse(
                            &raw mut (*pd).s,
                            m,
                            px,
                            py,
                            &raw mut buf,
                            &raw mut len,
                        ) == 0
                        {
                            return 0;
                        }
                        bufferevent_write(job_get_event((*pd).job), buf.cast(), len);
                        return 0;
                    }
                    input_key(&raw mut (*pd).s, job_get_event((*pd).job), (*event).key);
                }
                return 0;
            }
            // menu:
            (*pd).menu = Box::leak(menu_create(""));
            if (*pd).flags.intersects(popup_flag::POPUP_INTERNAL) {
                menu_add_items(
                    (*pd).menu,
                    POPUP_INTERNAL_MENU_ITEMS.as_slice(),
                    null_mut(),
                    c,
                    null_mut(),
                );
            } else {
                menu_add_items((*pd).menu, &POPUP_MENU_ITEMS, null_mut(), c, null_mut());
            }
            #[expect(clippy::manual_midpoint, reason = "not really being used as midpoint calculation")]
            let x = (*m).x.saturating_sub(((*(*pd).menu).width + 4) / 2);
            (*pd).md = menu_prepare(
                (*pd).menu,
                menu_flags::empty(),
                0,
                null_mut(),
                x,
                (*m).y,
                c,
                box_lines::BOX_LINES_DEFAULT,
                null_mut(),
                null_mut(),
                null_mut(),
                null_mut(),
                Some(popup_menu_done),
                pd.cast(),
            );
            (*c).flags |= client_flag::REDRAWOVERLAY;
        }
        // out:
        (*pd).lx = (*m).x;
        (*pd).ly = (*m).y;
        (*pd).lb = (*m).b;
        0
    }
}

/// C `vendor/tmux/popup.c:655`: `static void popup_job_update_cb(struct job *job)`
pub unsafe fn popup_job_update_cb(job: *mut job) {
    unsafe {
        let pd = job_get_data(job) as *mut popup_data;
        let evb = (*job_get_event(job)).input;
        let c = (*pd).c;
        let s = &raw mut (*pd).s;
        let data = EVBUFFER_DATA(evb);
        let size = EVBUFFER_LENGTH(evb);

        if size == 0 {
            return;
        }

        if !(*pd).md.is_null() {
            (*c).overlay_check = Some(menu_check_cb);
            (*c).overlay_data = (*pd).md.cast();
        } else {
            (*c).overlay_check = None;
            (*c).overlay_data = null_mut();
        }
        input_parse_screen(
            (*pd).ictx,
            s,
            Some(popup_init_ctx_cb),
            pd.cast(),
            data,
            size,
        );
        (*c).overlay_check = Some(popup_check_cb);
        (*c).overlay_data = pd.cast();

        evbuffer_drain(evb, size);
    }
}

/// C `vendor/tmux/popup.c:682`: `static void popup_job_complete_cb(struct job *job)`
pub unsafe fn popup_job_complete_cb(job: *mut job) {
    unsafe {
        let pd = job_get_data(job) as *mut popup_data;
        let status = job_get_status((*pd).job);

        if WIFEXITED(status) {
            (*pd).status = WEXITSTATUS(status);
        } else if WIFSIGNALED(status) {
            (*pd).status = WTERMSIG(status);
        } else {
            (*pd).status = 0;
        }
        (*pd).job = null_mut();

        if (*pd).flags.intersects(popup_flag::POPUP_CLOSEEXIT)
            || ((*pd).flags.intersects(popup_flag::POPUP_CLOSEEXITZERO) && (*pd).status == 0)
        {
            server_client_clear_overlay((*pd).c);
        }
    }
}

/// C `vendor/tmux/popup.c:757`: `int popup_display(int flags, enum box_lines lines, struct cmdq_item *item, u_int px, u_int py, u_int sx, u_int sy, struct environ *env, const char *shellcmd, int argc, char **argv, const char *cwd, const char *title, struct client *c, struct session *s, const char *style, const char *border_style, popup_close_cb cb, void *arg)`
pub unsafe fn popup_display(
    flags: popup_flag,
    mut lines: box_lines,
    item: *mut cmdq_item,
    px: c_uint,
    py: c_uint,
    sx: c_uint,
    sy: c_uint,
    env: *mut environ,
    shellcmd: *const u8,
    argc: c_int,
    argv: *mut *mut u8,
    cwd: *const u8,
    title: *const u8,
    c: *mut client,
    s: *mut session,
    style: *const u8,
    border_style: *const u8,
    cb: popup_close_cb,
    arg: *mut c_void,
) -> c_int {
    unsafe {
        let o = if !s.is_null() {
            (*(*(*s).curw).window).options
        } else {
            (*(*(*(*c).session).curw).window).options
        };

        lines = if lines == box_lines::BOX_LINES_DEFAULT {
            (options_get_number_(o, "popup-border-lines") as i32)
                .try_into()
                .unwrap_or(box_lines::BOX_LINES_ROUNDED) // TODO
        } else {
            lines
        };

        let (jx, jy) = if lines == box_lines::BOX_LINES_NONE {
            if sx < 1 || sy < 1 {
                return -1;
            }
            (sx, sy)
        } else {
            if sx < 3 || sy < 3 {
                return -1;
            }
            (sx - 2, sy - 2)
        };

        if (*c).tty.sx < sx || (*c).tty.sy < sy {
            return -1;
        }

        let pd = xcalloc1::<popup_data>() as *mut popup_data;
        (*pd).item = item;
        (*pd).flags = flags;
        if !title.is_null() {
            (*pd).title = xstrdup(title).as_ptr();
        }

        (*pd).c = c;
        (*(*pd).c).references += 1;

        (*pd).cb = cb;
        (*pd).arg = arg;
        (*pd).status = 128 + SIGHUP;

        (*pd).border_lines = lines;
        memcpy__(&raw mut (*pd).border_cell, &raw const GRID_DEFAULT_CELL);
        style_apply(
            &raw mut (*pd).border_cell,
            o,
            c!("popup-border-style"),
            null_mut(),
        );

        if !border_style.is_null() {
            let mut sytmp = MaybeUninit::<style>::uninit();
            style_set(sytmp.as_mut_ptr(), &raw const GRID_DEFAULT_CELL);
            if style_parse(sytmp.as_mut_ptr(), &raw mut (*pd).border_cell, border_style) == 0 {
                (*pd).border_cell.fg = (*sytmp.as_ptr()).gc.fg;
                (*pd).border_cell.bg = (*sytmp.as_ptr()).gc.bg;
            }
        }
        (*pd).border_cell.attr = grid_attr::empty();

        screen_init(&raw mut (*pd).s, jx, jy, 0);
        (*pd).palette = colour_palette_init();
        colour_palette_from_option(Some(&mut (*pd).palette), GLOBAL_W_OPTIONS);

        memcpy__(&raw mut (*pd).defaults, &raw const GRID_DEFAULT_CELL);
        style_apply(
            &raw mut (*pd).defaults,
            o,
            c!("popup-style").cast(),
            null_mut(),
        );
        if !style.is_null() {
            let mut sytmp = MaybeUninit::<style>::uninit();
            style_set(sytmp.as_mut_ptr(), &raw const GRID_DEFAULT_CELL);
            if style_parse(sytmp.as_mut_ptr(), &raw mut (*pd).defaults, style) == 0 {
                (*pd).defaults.fg = (*sytmp.as_ptr()).gc.fg;
                (*pd).defaults.bg = (*sytmp.as_ptr()).gc.bg;
            }
        }
        (*pd).defaults.attr = grid_attr::empty();

        (*pd).px = px;
        (*pd).py = py;
        (*pd).sx = sx;
        (*pd).sy = sy;

        (*pd).ppx = px;
        (*pd).ppy = py;
        (*pd).psx = sx;
        (*pd).psy = sy;

        (*pd).job = job_run(
            shellcmd,
            argc,
            argv,
            env,
            s,
            cwd,
            Some(popup_job_update_cb),
            Some(popup_job_complete_cb),
            None,
            pd.cast(),
            job_flag::JOB_NOWAIT
                | job_flag::JOB_PTY
                | job_flag::JOB_KEEPWRITE
                | job_flag::JOB_DEFAULTSHELL,
            jx as i32,
            jy as i32,
        );
        (*pd).ictx = input_init(null_mut(), job_get_event((*pd).job), &raw mut (*pd).palette);

        server_client_set_overlay(
            c,
            0,
            Some(popup_check_cb),
            Some(popup_mode_cb),
            Some(popup_draw_cb),
            Some(popup_key_cb),
            Some(popup_free_cb),
            Some(popup_resize_cb),
            pd.cast(),
        );
        0
    }
}

pub unsafe fn popup_editor_free(pe: *mut popup_editor) {
    unsafe {
        unlink((*pe).path.cast());
        free_((*pe).path);
        free_(pe);
    }
}

pub unsafe fn popup_editor_close_cb(status: i32, arg: *mut c_void) {
    unsafe {
        let pe = arg as *mut popup_editor;
        let mut buf: *mut u8 = null_mut();
        let mut len: libc::off_t = 0;

        if status != 0 {
            ((*pe).cb.unwrap())(null_mut(), 0, (*pe).arg);
            popup_editor_free(pe);
            return;
        }

        let f = fopen((*pe).path, c!("r"));
        if !f.is_null() {
            fseeko(f, 0, SEEK_END);
            len = ftello(f);
            fseeko(f, 0, SEEK_SET);

            // TODO SIZE_MAX is used in C, this check is essentially useless
            if len == 0
                || len as usize > usize::MAX
                || {
                    buf = malloc(len as usize).cast();
                    buf.is_null()
                }
                || fread(buf.cast(), len as usize, 1, f) != 1
            {
                free_(buf);
                buf = null_mut();
                len = 0;
            }
            fclose(f);
        }
        ((*pe).cb.unwrap())(buf, len as usize, (*pe).arg); // callback now owns buffer
        popup_editor_free(pe);
    }
}

// https://blog.orhun.dev/zero-deps-random-in-rust/
pub fn random_seed() -> u64 {
    use std::collections::hash_map::RandomState;
    use std::hash::{BuildHasher, Hasher};
    RandomState::new().build_hasher().finish()
}

fn create_temp_file() -> std::path::PathBuf {
    let mut seed = random_seed();
    let mut filename = String::from("tmux.");
    for _ in 0..8 {
        let ch = (b'a' + (seed % 26) as u8) as char;
        filename.push(ch);
        seed = seed.wrapping_mul(1103515245).wrapping_add(12345);
    }
    std::env::temp_dir().join(filename)
}

pub unsafe fn popup_editor(
    c: *mut client,
    buf: &[u8],
    cb: popup_finish_edit_cb,
    arg: *mut c_void,
) -> c_int {
    unsafe {
        let editor = options_get_string_(GLOBAL_OPTIONS, "editor");
        if *editor == b'\0' {
            return -1;
        }

        let path = create_temp_file();
        if std::fs::write(&path, buf).is_err() {
            return -1;
        }

        let pe = xcalloc1::<popup_editor>();
        pe.path = xstrdup__(
            path.to_str()
                .expect("fixme: temporary path SHOULD be valid string; or should store path buf"),
        );
        pe.cb = cb;
        pe.arg = arg;

        let sx = (*c).tty.sx * 9 / 10;
        let sy = (*c).tty.sy * 9 / 10;
        let px = ((*c).tty.sx / 2).wrapping_sub(sx / 2);
        let py = ((*c).tty.sy / 2).wrapping_sub(sy / 2);

        let cmd = format_nul!("{} {}", _s(editor), path.display());
        if popup_display(
            popup_flag::POPUP_INTERNAL | popup_flag::POPUP_CLOSEEXIT,
            box_lines::BOX_LINES_DEFAULT,
            null_mut(),
            px,
            py,
            sx,
            sy,
            null_mut(),
            cmd,
            0,
            null_mut(),
            c!("/tmp/"),
            null(),
            c,
            null_mut(),
            null(),
            null(),
            Some(popup_editor_close_cb),
            pe as *mut popup_editor as *mut c_void,
        ) != 0
        {
            popup_editor_free(pe);
            free_(cmd);
            return -1;
        }
        free_(cmd);
        0
    }
}