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
// Copyright (c) 2019 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::{xmalloc::xrecallocarray__, *};

pub const SIXEL_COLOUR_REGISTERS: u32 = 1024;
const SIXEL_WIDTH_LIMIT: u32 = 10000;
const SIXEL_HEIGHT_LIMIT: u32 = 10000;

#[repr(C)]
struct sixel_line {
    x: u32,
    data: *mut u16,
}

#[repr(C)]
pub struct sixel_image {
    x: u32,
    y: u32,
    xpixel: u32,
    ypixel: u32,

    colours: Vec<u32>,
    dx: u32,
    dy: u32,
    dc: u32,

    lines: *mut sixel_line,
}

/// C `vendor/tmux/image-sixel.c:70`: `static int sixel_parse_expand_lines(struct sixel_image *si, u_int y)`
unsafe fn sixel_parse_expand_lines(si: *mut sixel_image, y: u32) -> bool {
    unsafe {
        if y <= (*si).y {
            return false;
        }
        if y > SIXEL_HEIGHT_LIMIT {
            return true;
        }
        (*si).lines = xrecallocarray__((*si).lines, (*si).y as usize, y as usize).as_ptr();
        (*si).y = y;
        false
    }
}

/// C `vendor/tmux/image-sixel.c:82`: `static int sixel_parse_expand_line(struct sixel_image *si, struct sixel_line *sl, u_int x)`
unsafe fn sixel_parse_expand_line(si: *mut sixel_image, sl: *mut sixel_line, x: u32) -> bool {
    unsafe {
        if x <= (*sl).x {
            return false;
        }
        if x > SIXEL_WIDTH_LIMIT {
            return true;
        }
        if x > (*si).x {
            (*si).x = x;
        }
        (*sl).data = xrecallocarray__((*sl).data, (*sl).x as usize, (*si).x as usize).as_ptr();
        (*sl).x = (*si).x;
        false
    }
}

/// C `vendor/tmux/image-sixel.c:96`: `static u_int sixel_get_pixel(struct sixel_image *si, u_int x, u_int y)`
unsafe fn sixel_get_pixel(si: *mut sixel_image, x: u32, y: u32) -> u32 {
    unsafe {
        if y >= (*si).y {
            return 0;
        }
        let sl = (*si).lines.add(y as usize);
        if x >= (*sl).x {
            return 0;
        }
        *(*sl).data.add(x as usize) as u32
    }
}

/// C `vendor/tmux/image-sixel.c:109`: `static int sixel_set_pixel(struct sixel_image *si, u_int x, u_int y, u_int c)`
unsafe fn sixel_set_pixel(si: *mut sixel_image, x: u32, y: u32, c: u32) -> bool {
    unsafe {
        if sixel_parse_expand_lines(si, y + 1) {
            return true;
        }
        let sl = (*si).lines.add(y as usize);
        if sixel_parse_expand_line(si, sl, x + 1) {
            return true;
        }
        *(*sl).data.add(x as usize) = c as u16;

        false
    }
}

/// C `vendor/tmux/image-sixel.c:123`: `static int sixel_parse_write(struct sixel_image *si, u_int ch)`
unsafe fn sixel_parse_write(si: *mut sixel_image, ch: u32) -> bool {
    unsafe {
        if sixel_parse_expand_lines(si, (*si).dy + 6) {
            return true;
        }
        let mut sl = (*si).lines.add((*si).dy as usize);

        for i in 0..6 {
            if sixel_parse_expand_line(si, sl, (*si).dx + 1) {
                return true;
            }
            if ch & (1 << i) != 0 {
                *(*sl).data.add((*si).dx as usize) = (*si).dc as u16;
            }
            sl = sl.add(1);
        }
        false
    }
}

/// C `vendor/tmux/image-sixel.c:137`: `static const char *sixel_parse_attributes(struct sixel_image *si, const char *cp, const char *end)`
unsafe fn sixel_parse_attributes(si: *mut sixel_image, cp: *const u8, end: *const u8) -> *const u8 {
    unsafe {
        let mut endptr: *mut u8 = null_mut();

        let mut last = cp;
        while last != end {
            if *last != b';' && (*last < b'0' || *last > b'9') {
                break;
            }
            last = last.add(1);
        }
        libc::strtoul(cp, &raw mut endptr, 10);
        if endptr.cast_const() == last || *endptr != b';' {
            return last;
        }
        libc::strtoul(endptr.add(1), &raw mut endptr, 10);
        if endptr.cast_const() == last {
            return last;
        }
        if *endptr != b';' {
            // log_debug("%s: missing ;", __func__);
            return null_mut();
        }

        let x = libc::strtoul(endptr.add(1), &raw mut endptr, 10) as u32;
        if endptr.cast_const() == last || *endptr != b';' {
            // log_debug("%s: missing ;", __func__);
            return null_mut();
        }
        if x > SIXEL_WIDTH_LIMIT {
            // log_debug("%s: image is too wide", __func__);
            return null_mut();
        }
        let y = libc::strtoul(endptr.add(1), &raw mut endptr, 10) as u32;
        if endptr.cast_const() != last {
            // log_debug("%s: extra ;", __func__);
            return null_mut();
        }
        if y > SIXEL_HEIGHT_LIMIT {
            // log_debug("%s: image is too tall", __func__);
            return null_mut();
        }

        (*si).x = x;
        sixel_parse_expand_lines(si, y);

        last
    }
}

/// C `vendor/tmux/image-sixel.c:190`: `static const char *sixel_parse_colour(struct sixel_image *si, const char *cp, const char *end)`
unsafe fn sixel_parse_colour(si: *mut sixel_image, cp: *const u8, end: *const u8) -> *const u8 {
    unsafe {
        let mut endptr: *mut u8 = null_mut();

        let mut last = cp;
        while last != end {
            if *last != b';' && (*last < b'0' || *last > b'9') {
                break;
            }
            last = last.add(1);
        }

        let c = libc::strtoul(cp, &raw mut endptr, 10) as u32;
        if c > SIXEL_COLOUR_REGISTERS {
            log_debug!("sixel_parse_colour: too many colours");
            return null_mut();
        }
        (*si).dc = c + 1;
        if endptr.cast_const() == last || *endptr != b';' {
            return last;
        }

        let type_ = libc::strtoul(endptr.add(1), &raw mut endptr, 10) as u32;
        if endptr.cast_const() == last || *endptr != b';' {
            log_debug!("sixel_parse_colour: missing ;");
            return null_mut();
        }
        let r = libc::strtoul(endptr.add(1), &raw mut endptr, 10) as u32;
        if endptr.cast_const() == last || *endptr != b';' {
            log_debug!("sixel_parse_colour: missing ;");
            return null_mut();
        }
        let g = libc::strtoul(endptr.add(1), &raw mut endptr, 10) as u32;
        if endptr.cast_const() == last || *endptr != b';' {
            log_debug!("sixel_parse_colour: missing ;");
            return null_mut();
        }
        let b = libc::strtoul(endptr.add(1), &raw mut endptr, 10) as u32;
        if endptr.cast_const() != last {
            log_debug!("sixel_parse_colour: missing ;");
            return null_mut();
        }

        if type_ != 1 && type_ != 2 {
            log_debug!("sixel_parse_colour: invalid type_ {}", type_);
            return null_mut();
        }

        if c as usize + 1 > (*si).colours.len() {
            (*si).colours.resize(c as usize + 1, 0);
        }
        (&mut *(*si).colours)[c as usize] = (type_ << 24) | (r << 16) | (g << 8) | b;
        last
    }
}

/// C `vendor/tmux/image-sixel.c:253`: `static const char *sixel_parse_repeat(struct sixel_image *si, const char *cp, const char *end)`
unsafe fn sixel_parse_repeat(si: *mut sixel_image, cp: *const u8, end: *const u8) -> *const u8 {
    unsafe {
        const SIZE_OF_TMP: usize = 32;
        let mut tmp: [u8; SIZE_OF_TMP] = [0; SIZE_OF_TMP];

        let mut n: u32 = 0;

        let mut last = cp;
        while last != end {
            if *last < b'0' || *last > b'9' {
                break;
            }
            tmp[n as usize] = *last;
            n += 1;
            last = last.add(1);
            if n == (SIZE_OF_TMP as u32) - 1 {
                log_debug!("sixel_parse_repeat: repeat not terminated");
                return null_mut();
            }
        }
        if n == 0 || last == end {
            log_debug!("sixel_parse_repeat: repeat not terminated");
            return null_mut();
        }
        tmp[n as usize] = b'\0';

        let Ok(n) = strtonum((&raw const tmp) as *const u8, 1, SIXEL_WIDTH_LIMIT) else {
            log_debug!("sixel_parse_repeat: repeat too wide");
            return null_mut();
        };

        let ch = (*last) - 0x3f;
        last = last.add(1);
        for _ in 0..n {
            if sixel_parse_write(si, ch as u32) {
                log_debug!("sixel_parse_repeat: width limit reached");
                return null_mut();
            }
            (*si).dx += 1;
        }

        last
    }
}

/// C `vendor/tmux/image-sixel.c:294`: `struct sixel_image *sixel_parse(const char *buf, size_t len, u_int p2, u_int xpixel, u_int ypixel)`
pub unsafe fn sixel_parse(
    buf: *const u8,
    len: usize,
    xpixel: u32,
    ypixel: u32,
) -> *mut sixel_image {
    unsafe {
        let si: *mut sixel_image;
        let mut cp = buf;
        let end = buf.add(len);

        'bad: {
            if len == 0 || len == 1 || *cp != b'q' {
                log_debug!("sixel_parse: empty image");
                return null_mut();
            }
            cp = cp.add(1);

            // xcalloc would leave `colours` as an all-zero Vec, whose null data pointer
            // breaks Vec's non-null invariant. Box it so every field starts out valid.
            si = Box::into_raw(Box::new(sixel_image {
                x: 0,
                y: 0,
                xpixel,
                ypixel,
                colours: Vec::new(),
                dx: 0,
                dy: 0,
                dc: 0,
                lines: null_mut(),
            }));

            while cp != end {
                let ch = *cp;
                cp = cp.add(1);
                match ch {
                    b'"' => {
                        cp = sixel_parse_attributes(si, cp, end);
                        if cp.is_null() {
                            break 'bad;
                        }
                    }
                    b'#' => {
                        cp = sixel_parse_colour(si, cp, end);
                        if cp.is_null() {
                            break 'bad;
                        }
                    }
                    b'!' => {
                        cp = sixel_parse_repeat(si, cp, end);
                        if cp.is_null() {
                            break 'bad;
                        }
                    }
                    b'-' => {
                        (*si).dx = 0;
                        (*si).dy += 6;
                    }
                    b'$' => (*si).dx = 0,
                    _ => {
                        if ch >= 0x20 {
                            if !(0x3f..=0x7e).contains(&ch) {
                                break 'bad;
                            }
                            if sixel_parse_write(si, (ch - 0x3f) as u32) {
                                // log_debug("%s: width limit reached", __func__);
                                break 'bad;
                            }
                            (*si).dx += 1;
                        }
                    }
                }
            }

            if (*si).x == 0 || (*si).y == 0 {
                break 'bad;
            }
            return si;
        } // 'bad:
        free_(si);

        null_mut()
    }
}

/// C `vendor/tmux/image-sixel.c:359`: `void sixel_free(struct sixel_image *si)`
pub unsafe fn sixel_free(si: *mut sixel_image) {
    unsafe {
        for y in 0..(*si).y {
            free_((*(*si).lines.add(y as usize)).data);
        }
        free_((*si).lines);

        // Dropping the Box frees the owned colour table; `lines` is a C array and is
        // still freed by hand above.
        drop(Box::from_raw(si));
    }
}

#[expect(dead_code)]
/// C `vendor/tmux/image-sixel.c:372`: `void sixel_log(struct sixel_image *si)`
unsafe fn sixel_log(si: *mut sixel_image) {
    unsafe {
        let mut s: [u8; SIXEL_WIDTH_LIMIT as usize + 1] = [0; SIXEL_WIDTH_LIMIT as usize + 1];

        let (cx, cy) = sixel_size_in_cells(&*si);
        log_debug!("sixel_log: image {}x{} ({cx}x{cy})", (*si).x, (*si).y);
        for (i, c) in (*si).colours.iter().copied().enumerate() {
            log_debug!("sixel_log: colour {i} is {c:07x}");
        }

        let mut xx: u32 = 0;
        for y in 0..(*si).y {
            let sl = (*si).lines.add(y as usize);
            for x in 0..(*si).x {
                s[x as usize] = if x >= (*sl).x {
                    b'_'
                } else if *(*sl).data.add(x as usize) != 0 {
                    b'0' + ((*(*sl).data.add(x as usize) - 1) % 10) as u8
                } else {
                    b'.'
                };
                xx = x;
            }
            s[xx as usize] = b'\0';
            // log_debug!("sixel_log: {y:04}: {}", s);
        }
    }
}

/// C `vendor/tmux/image-sixel.c:398`: `void sixel_size_in_cells(struct sixel_image *si, u_int *x, u_int *y)`
pub fn sixel_size_in_cells(si: &sixel_image) -> (u32, u32) {
    (si.x.div_ceil(si.xpixel), si.y.div_ceil(si.ypixel))
}

/// C `vendor/tmux/image-sixel.c:411`: `struct sixel_image *sixel_scale(struct sixel_image *si, u_int xpixel, u_int ypixel, u_int ox, u_int oy, u_int sx, u_int sy, int colours)`
pub unsafe fn sixel_scale(
    si: *mut sixel_image,
    mut xpixel: u32,
    mut ypixel: u32,
    ox: u32,
    oy: u32,
    mut sx: u32,
    mut sy: u32,
    colours: i32,
) -> *mut sixel_image {
    log_debug!("sixel_scale");
    unsafe {
        // We want to get the section of the image at ox,oy in image cells and
        // map it onto the same size in terminal cells, remembering that we
        // can only draw vertical sections of six pixels.

        let (cx, cy) = sixel_size_in_cells(&*si);
        if ox >= cx {
            return null_mut();
        }
        if oy >= cy {
            return null_mut();
        }
        if ox + sx >= cx {
            sx = cx - ox;
        }
        if oy + sy >= cy {
            sy = cy - oy;
        }

        if xpixel == 0 {
            xpixel = (*si).xpixel;
        }
        if ypixel == 0 {
            ypixel = (*si).ypixel;
        }

        let pox = ox * (*si).xpixel;
        let poy = oy * (*si).ypixel;
        let psx = sx * (*si).xpixel;
        let psy = sy * (*si).ypixel;

        let tsx = sx * xpixel;
        let tsy = ((sy * ypixel) / 6) * 6;

        let new = Box::into_raw(Box::new(sixel_image {
            x: 0,
            y: 0,
            xpixel,
            ypixel,
            colours: Vec::new(),
            dx: 0,
            dy: 0,
            dc: 0,
            lines: null_mut(),
        }));

        for y in 0..tsy {
            let py: u32 = poy + ((y as f64) * psy as f64 / tsy as f64) as u32;
            for x in 0..tsx {
                let px: u32 = pox + (x as f64 * psx as f64 / tsx as f64) as u32;
                sixel_set_pixel(new, x, y, sixel_get_pixel(si, px, py));
            }
        }

        if colours != 0 {
            (*new).colours.clone_from(&(*si).colours);
        }
        new
    }
}

#[inline]
#[track_caller]
/// C `vendor/tmux/image-sixel.c:481`: `static void sixel_print_add(char **buf, size_t *len, size_t *used, const char *s, size_t slen)`
pub(crate) unsafe fn sixel_print_add(
    buf: *mut *mut u8,
    len: *mut usize,
    used: *mut usize,
    s: *const u8,
    slen: usize,
) {
    log_debug!("sixel_print_add begin");
    unsafe {
        if *used + slen > *len {
            *len *= 2;
            *buf = xrealloc_(*buf, *len).as_ptr();
        }
        libc::memcpy((*buf).add(*used).cast(), s.cast(), slen);
        *used += slen;
    }
    log_debug!("sixel_print_add end");
}

/// C `vendor/tmux/image-sixel.c:493`: `static void sixel_print_repeat(char **buf, size_t *len, size_t *used, u_int count, char ch)`
unsafe fn sixel_print_repeat(
    buf: *mut *mut u8,
    len: *mut usize,
    used: *mut usize,
    count: u32,
    ch: u8,
) {
    log_debug!("sixel_print_repeat");
    unsafe {
        if count == 1 {
            sixel_print_add(buf, len, used, &raw const ch, 1);
        } else if count == 2 {
            sixel_print_add(buf, len, used, &raw const ch, 1);
            sixel_print_add(buf, len, used, &raw const ch, 1);
        } else if count == 3 {
            sixel_print_add(buf, len, used, &raw const ch, 1);
            sixel_print_add(buf, len, used, &raw const ch, 1);
            sixel_print_add(buf, len, used, &raw const ch, 1);
        } else if count != 0 {
            let tmp = CString::new(format!("!{count}{}", ch as char)).unwrap();
            sixel_print_add(buf, len, used, tmp.as_ptr().cast(), tmp.to_bytes().len());
        }
    }
}

/// C `vendor/tmux/image-sixel.c:566`: `char *sixel_print(struct sixel_image *si, struct sixel_image *map, size_t *size)`
pub(crate) unsafe fn sixel_print(
    si: *mut sixel_image,
    map: *mut sixel_image,
    size: *mut usize,
) -> *mut u8 {
    log_debug!("sixel_print");
    unsafe {
        let mut buf: *mut u8;
        let mut data: u8 = b'\0';
        let mut last = 0;

        let mut len: usize;
        let mut used: usize = 0;

        let colours = if !map.is_null() {
            &(*map).colours
        } else {
            &(*si).colours
        };

        if colours.is_empty() {
            return null_mut();
        }

        len = 8192;
        buf = xmalloc(len).as_ptr().cast();

        sixel_print_add(&raw mut buf, &raw mut len, &raw mut used, c!("\x1bPq"), 3);

        let tmp = CString::new(format!("\"1;1;{};{}", (*si).x, (*si).y)).unwrap();
        sixel_print_add(
            &raw mut buf,
            &raw mut len,
            &raw mut used,
            tmp.as_ptr().cast(),
            tmp.as_bytes().len(),
        );

        log_debug!("sixel_print before colours");
        for (i, c) in colours.iter().copied().enumerate() {
            let tmp = CString::new(format!(
                "#{};{};{};{};{}",
                i,
                c >> 24,
                (c >> 16) & 0xff,
                (c >> 8) & 0xff,
                c & 0xff,
            ))
            .unwrap();
            sixel_print_add(
                &raw mut buf,
                &raw mut len,
                &raw mut used,
                tmp.as_ptr().cast(),
                tmp.as_bytes().len(),
            );
        }

        let mut contains: Vec<bool> = vec![false; colours.len()];
        let mut y = 0;
        while y < (*si).y {
            contains.fill(false);
            for x in 0..(*si).x {
                for i in 0..6 {
                    if y + i >= (*si).y {
                        break;
                    }
                    let sl = (*si).lines.add((y + i) as usize);
                    if x < (*sl).x && *(*sl).data.add(x as usize) != 0 {
                        contains[*(*sl).data.add(x as usize) as usize - 1] = true;
                    }
                }
            }

            log_debug!("sixel_print mid {y}");
            for (c, contains_c) in contains.iter().copied().enumerate() {
                if !contains_c {
                    continue;
                }
                let tmp = CString::new(format!("#{c}")).unwrap();
                sixel_print_add(
                    &raw mut buf,
                    &raw mut len,
                    &raw mut used,
                    tmp.as_ptr().cast(),
                    tmp.as_bytes().len(),
                );

                let mut count = 0;
                for x in 0..(*si).x {
                    data = 0;
                    for i in 0..6 {
                        if y + i >= (*si).y {
                            break;
                        }
                        let sl = (*si).lines.add((y + i) as usize);
                        if x < (*sl).x && *(*sl).data.add(x as usize) as u32 == c as u32 + 1 {
                            data |= 1 << i;
                        }
                    }
                    data += 0x3f;
                    if data != last {
                        sixel_print_repeat(&raw mut buf, &raw mut len, &raw mut used, count, last);
                        last = data;
                        count = 1;
                    } else {
                        count += 1;
                    }
                }
                sixel_print_repeat(&raw mut buf, &raw mut len, &raw mut used, count, data);
                sixel_print_add(&raw mut buf, &raw mut len, &raw mut used, c!("$"), 1);
            }

            if *buf.add(used - 1) == b'$' {
                used -= 1;
            }
            if *buf.add(used - 1) != b'-' {
                sixel_print_add(&raw mut buf, &raw mut len, &raw mut used, c!("-"), 1);
            }

            y += 6;
        }
        if *buf.add(used - 1) == b'$' || *buf.add(used - 1) == b'-' {
            used -= 1;
        }

        log_debug!("sixel_print near end");
        sixel_print_add(&raw mut buf, &raw mut len, &raw mut used, c!("\x1b\\"), 2);

        *buf.add(used) = b'\0';
        if !size.is_null() {
            *size = used;
        }

        buf
    }
}

#[expect(dead_code)]
/// C `vendor/tmux/image-sixel.c:653`: `struct screen *sixel_to_screen(struct sixel_image *si)`
unsafe fn sixel_to_screen(si: *mut sixel_image) -> *mut screen {
    unsafe {
        let mut ctx: screen_write_ctx = zeroed();
        let mut gc: grid_cell = zeroed();

        let (sx, sy) = sixel_size_in_cells(&*si);

        let s = Box::leak(Box::new(zeroed())) as *mut screen;
        screen_init(s, sx, sy, 0);

        memcpy__(&raw mut gc, &raw const GRID_DEFAULT_CELL);
        gc.attr |= grid_attr::GRID_ATTR_CHARSET | grid_attr::GRID_ATTR_DIM;
        utf8_set(&raw mut gc.data, b'~');

        screen_write_start(&raw mut ctx, s);
        if sx == 1 || sy == 1 {
            for y in 0..sy {
                for x in 0..sx {
                    grid_view_set_cell((*s).grid, x, y, &gc);
                }
            }
        } else {
            screen_write_box(
                &raw mut ctx,
                sx,
                sy,
                box_lines::BOX_LINES_DEFAULT,
                null(),
                None,
            );
            for y in 1..(sy - 1) {
                for x in 1..(sx - 1) {
                    grid_view_set_cell((*s).grid, x, y, &raw const gc);
                }
            }
        }
        screen_write_stop(&raw mut ctx);
        s
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Helper: run sixel_parse over a byte body and hand the parsed image
    // (or null) to the closure, then free it. Lives inside mod tests so the
    // anti-drift gate (no non-test free fns) is satisfied.
    unsafe fn with_parsed<R>(
        body: &[u8],
        xpixel: u32,
        ypixel: u32,
        f: impl FnOnce(*mut sixel_image) -> R,
    ) -> R {
        unsafe {
            // sixel_parse relies on the C contract that buf is NUL-terminated
            // at buf[len] (vendor/tmux/input.c:1275); its strtoul scans stop at
            // that NUL. Byte-slice literals are not NUL-terminated, so append
            // one here to keep strtoul from reading past the buffer.
            let mut buf = body.to_vec();
            buf.push(0);
            let si = sixel_parse(buf.as_ptr(), body.len(), xpixel, ypixel);
            let r = f(si);
            if !si.is_null() {
                sixel_free(si);
            }
            r
        }
    }

    // A single all-bits-set sixel column (0x7e - 0x3f == 0x3f) draws six
    // vertical pixels in one column. sixel_parse_write expands lines to
    // dy + 6 == 6 and the line width to dx + 1 == 1, then dx++ leaves dx=1.
    // See vendor/tmux/image-sixel.c:123 (sixel_parse_write) and
    // image-sixel.c:294 (sixel_parse).
    #[test]
    fn test_parse_single_column() {
        unsafe {
            with_parsed(b"q~", 10, 20, |si| {
                assert!(!si.is_null());
                assert_eq!((*si).x, 1);
                assert_eq!((*si).y, 6);
                assert_eq!((*si).xpixel, 10);
                assert_eq!((*si).ypixel, 20);
            });
        }
    }

    // Three consecutive sixel data chars advance dx three times, so the
    // image is 3 pixels wide and 6 tall (one sixel band).
    #[test]
    fn test_parse_three_columns() {
        unsafe {
            with_parsed(b"q~~~", 1, 1, |si| {
                assert!(!si.is_null());
                assert_eq!((*si).x, 3);
                assert_eq!((*si).y, 6);
            });
        }
    }

    // '-' is a graphics new-line: dx=0, dy+=6. Two bands of one column each
    // give x=1, y=12. vendor/tmux/image-sixel.c:328 ('-' case).
    #[test]
    fn test_parse_newline_two_bands() {
        unsafe {
            with_parsed(b"q~-~", 1, 6, |si| {
                assert!(!si.is_null());
                assert_eq!((*si).x, 1);
                assert_eq!((*si).y, 12);
            });
        }
    }

    // Raster attributes "Pan;Pad;Ph;Pv set si->x = Ph and expand lines to Pv
    // even with no pixel data. Here Ph=4, Pv=12.
    // vendor/tmux/image-sixel.c:137 (sixel_parse_attributes) sets si->x and
    // calls sixel_parse_expand_lines(si, y).
    #[test]
    fn test_parse_attributes_dimensions() {
        unsafe {
            with_parsed(b"q\"1;1;4;12", 2, 6, |si| {
                assert!(!si.is_null());
                assert_eq!((*si).x, 4);
                assert_eq!((*si).y, 12);
                // size in cells: div_ceil(4,2)=2, div_ceil(12,6)=2
                let (cx, cy) = sixel_size_in_cells(&*si);
                assert_eq!((cx, cy), (2, 2));
            });
        }
    }

    // sixel_size_in_cells rounds up (div_ceil). image-sixel.c:398.
    #[test]
    fn test_size_in_cells_rounds_up() {
        unsafe {
            // x=1,y=6 with xpixel=10,ypixel=20 -> ceil(1/10)=1, ceil(6/20)=1
            with_parsed(b"q~", 10, 20, |si| {
                let (cx, cy) = sixel_size_in_cells(&*si);
                assert_eq!((cx, cy), (1, 1));
            });
            // x=3,y=6 with xpixel=2,ypixel=4 -> ceil(3/2)=2, ceil(6/4)=2
            with_parsed(b"q~~~", 2, 4, |si| {
                let (cx, cy) = sixel_size_in_cells(&*si);
                assert_eq!((cx, cy), (2, 2));
            });
        }
    }

    // A repeat introducer "!5~" draws the same column five times: dx ends at 5.
    // vendor/tmux/image-sixel.c:253 (sixel_parse_repeat).
    #[test]
    fn test_parse_repeat() {
        unsafe {
            with_parsed(b"q!5~", 1, 1, |si| {
                assert!(!si.is_null());
                assert_eq!((*si).x, 5);
                assert_eq!((*si).y, 6);
            });
        }
    }

    // A colour selection then data. "#1" sets dc = 2 (c+1). Drawing one
    // column writes value 2 into the six pixels. The image is still 1x6.
    // vendor/tmux/image-sixel.c:190 (sixel_parse_colour).
    #[test]
    fn test_parse_colour_then_data() {
        unsafe {
            with_parsed(b"q#1~", 1, 6, |si| {
                assert!(!si.is_null());
                assert_eq!((*si).x, 1);
                assert_eq!((*si).y, 6);
                assert_eq!((*si).dc, 2);
                // pixel (0,0) holds the colour register value dc == 2.
                assert_eq!(sixel_get_pixel(si, 0, 0), 2);
            });
        }
    }

    // Parse a byte body under the NUL-termination contract (see with_parsed)
    // and return whether the result was NULL, freeing any image produced.
    unsafe fn parse_is_null(body: &[u8], xpixel: u32, ypixel: u32) -> bool {
        unsafe {
            let mut buf = body.to_vec();
            buf.push(0);
            let si = sixel_parse(buf.as_ptr(), body.len(), xpixel, ypixel);
            let null = si.is_null();
            if !null {
                sixel_free(si);
            }
            null
        }
    }

    // Empty / malformed inputs return NULL. image-sixel.c:300.
    #[test]
    fn test_parse_empty_and_bad() {
        unsafe {
            // len == 0
            assert!(parse_is_null(b"", 1, 1));
            // len == 1
            assert!(parse_is_null(b"q", 1, 1));
            // does not start with 'q'
            assert!(parse_is_null(b"xy", 1, 1));
            // 'q' but no pixels drawn: x==0 || y==0 -> bad -> NULL
            assert!(parse_is_null(b"q$", 1, 1));
            assert!(parse_is_null(b"q-", 1, 1));
        }
    }

    // A char outside the sixel data range (>= 0x20 but not 0x3f..=0x7e) is
    // invalid and aborts the parse -> NULL. image-sixel.c:331.
    #[test]
    fn test_parse_out_of_range_char() {
        unsafe {
            // 0x20 (space) is >= 0x20 but below 0x3f -> bad.
            assert!(parse_is_null(b"q ", 1, 1));
        }
    }
}