aboutsummaryrefslogtreecommitdiff
path: root/sixel.c
blob: c6fe1a10a7f9269229665c058e3be27c9e0c9793 (plain)
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
#include "sixel.h"

#include <string.h>
#include <limits.h>

#define LOG_MODULE "sixel"
#define LOG_ENABLE_DBG 0
#include "log.h"
#include "render.h"
#include "sixel-hls.h"
#include "util.h"
#include "xmalloc.h"

static size_t count;

void
sixel_fini(struct terminal *term)
{
    free(term->sixel.palette);
}

static uint32_t
color_with_alpha(const struct terminal *term, uint32_t color)
{
    uint16_t alpha = color == term->colors.bg ? term->colors.alpha : 0xffff;
    return (alpha / 256u) << 24 | color;
}

void
sixel_init(struct terminal *term)
{
    assert(term->sixel.image.data == NULL);
    assert(term->sixel.palette_size <= SIXEL_MAX_COLORS);

    term->sixel.state = SIXEL_DECSIXEL;
    term->sixel.pos = (struct coord){0, 0};
    term->sixel.color_idx = 0;
    term->sixel.max_col = 0;
    term->sixel.param = 0;
    term->sixel.param_idx = 0;
    memset(term->sixel.params, 0, sizeof(term->sixel.params));
    term->sixel.image.data = xmalloc(1 * 6 * sizeof(term->sixel.image.data[0]));
    term->sixel.image.width = 1;
    term->sixel.image.height = 6;
    term->sixel.image.autosize = true;

    if (term->sixel.palette == NULL) {
        term->sixel.palette = xcalloc(
            term->sixel.palette_size, sizeof(term->sixel.palette[0]));
    }

    for (size_t i = 0; i < 1 * 6; i++)
        term->sixel.image.data[i] = color_with_alpha(term, term->colors.bg);

    count = 0;

    /* TODO: default palette */
}

void
sixel_destroy(struct sixel *sixel)
{
    pixman_image_unref(sixel->pix);
    free(sixel->data);

    sixel->pix = NULL;
    sixel->data = NULL;
}

void
sixel_destroy_all(struct terminal *term)
{
    tll_foreach(term->normal.sixel_images, it)
        sixel_destroy(&it->item);
    tll_foreach(term->alt.sixel_images, it)
        sixel_destroy(&it->item);
    tll_free(term->normal.sixel_images);
    tll_free(term->alt.sixel_images);
}

static void
sixel_erase(struct terminal *term, struct sixel *sixel)
{
    for (int i = 0; i < sixel->rows; i++) {
        int r = (sixel->pos.row + i) & (term->grid->num_rows - 1);

        struct row *row = term->grid->rows[r];
        if (row == NULL) {
            /* A resize/reflow may cause row to now be unallocated */
            continue;
        }

        row->dirty = true;

        for (int c = 0; c < term->grid->num_cols; c++)
            row->cells[c].attrs.clean = 0;
    }

    sixel_destroy(sixel);
}

static int
rebase_row(const struct terminal *term, int abs_row)
{
    int scrollback_start = term->grid->offset + term->rows;
    int rebased_row = abs_row - scrollback_start + term->grid->num_rows;

    rebased_row &= term->grid->num_rows - 1;
    return rebased_row;
}

static bool
verify_sixel_list_order(const struct terminal *term)
{
#if defined(_DEBUG)
    int prev_row = INT_MAX;
    int prev_col = -1;
    int prev_col_count = 0;

    tll_foreach(term->grid->sixel_images, it) {
        int row = rebase_row(term, it->item.pos.row + it->item.rows - 1);
        int col = it->item.pos.col;
        int col_count = it->item.cols;

        assert(row <= prev_row);
        if (row > prev_row)
            return false;

        if (row == prev_row) {
            /* Allowed to be on the same row only if their columns
             * don't overlap */

            assert(col + col_count <= prev_col ||
                   prev_col + prev_col_count <= col);

            if (!(col + col_count <= prev_col ||
                  prev_col + prev_col_count <= col))
                return false;
        }

        prev_row = row;
        prev_col = col;
        prev_col_count = col_count;
    }
#endif
    return true;
}

static void
sixel_insert(struct terminal *term, struct sixel sixel)
{
    int end_row = rebase_row(term, sixel.pos.row + sixel.rows - 1);

    tll_foreach(term->grid->sixel_images, it) {
        if (rebase_row(term, it->item.pos.row + it->item.rows - 1) < end_row) {
            tll_insert_before(term->grid->sixel_images, it, sixel);
            goto out;
        }
    }

    tll_push_back(term->grid->sixel_images, sixel);

out:
#if defined(LOG_ENABLE_DBG) && LOG_ENABLE_DBG
    LOG_DBG("sixel list after insertion:");
    tll_foreach(term->grid->sixel_images, it) {
        LOG_DBG("  rows=%d+%d", it->item.pos.row, it->item.rows);
    }
#else
    verify_sixel_list_order(term);
#endif
}

void
sixel_scroll_up(struct terminal *term, int rows)
{
    tll_rforeach(term->grid->sixel_images, it) {
        struct sixel *six = &it->item;

        int six_start = rebase_row(term, six->pos.row);
        if (six_start < rows) {
            sixel_destroy(six);
            tll_remove(term->grid->sixel_images, it);
        } else
            break;
    }

    verify_sixel_list_order(term);
}

void
sixel_scroll_down(struct terminal *term, int rows)
{
    assert(term->grid->num_rows >= rows);

    tll_foreach(term->grid->sixel_images, it) {
        struct sixel *six = &it->item;

        int six_end = rebase_row(term, six->pos.row + six->rows - 1);
        if (six_end >= term->grid->num_rows - rows) {
            sixel_destroy(six);
            tll_remove(term->grid->sixel_images, it);
        } else
            break;
    }

    verify_sixel_list_order(term);
}

static void
sixel_overwrite(struct terminal *term, struct sixel *six,
                int row, int col, int height, int width)
{
    assert(row >= 0);
    assert(row + height <= term->grid->num_rows);
    assert(col >= 0);
    assert(col + width <= term->grid->num_cols);

    int rel_above = min(max(row - six->pos.row, 0), six->rows);
    int rel_below = max(min(row + height - six->pos.row, six->rows), 0);
    int rel_left = min(max(col - six->pos.col, 0), six->cols);
    int rel_right = max(min(col + width - six->pos.col, six->cols), 0);

    assert(rel_above >= 0);
    assert(rel_below >= 0);
    assert(rel_left >= 0);
    assert(rel_right >= 0);

    LOG_DBG("SPLIT: six (%p): %dx%d-%dx%d, %dx%d-%dx%d, rel: above=%d, below=%d, left=%d, right=%d",
            (void *)six, six->pos.row, six->pos.col, six->rows, six->cols,
            row, col, height, width,
            rel_above, rel_below, rel_left, rel_right);

    struct sixel imgs[4] = {0};

    if (rel_above > 0) {
        imgs[0] =  (struct sixel){
            .width = six->width,
            .height = rel_above * term->cell_height,
            .rows = rel_above,
            .cols = six->cols,
            .pos = six->pos,
        };
        imgs[0].data = xmalloc(imgs[0].width * imgs[0].height * sizeof(uint32_t));
        memcpy(imgs[0].data, six->data, imgs[0].width * imgs[0].height * sizeof(uint32_t));
    }

    if (rel_below < six->rows) {
        imgs[1] = (struct sixel){
            .width = six->width,
            .height = six->height - rel_below * term->cell_height,
            .rows = six->rows - rel_below,
            .cols = six->cols,
            .pos = (struct coord){
                six->pos.col,
                (six->pos.row + rel_below) & (term->grid->num_rows - 1)},
        };
        imgs[1].data = xmalloc(imgs[1].width * imgs[1].height * sizeof(uint32_t));
        memcpy(
            imgs[1].data,
            &((const uint32_t *)six->data)[rel_below * term->cell_height * six->width],
            imgs[1].width * imgs[1].height * sizeof(uint32_t));
    }

    if (rel_left > 0) {
        imgs[2] = (struct sixel){
            .width = rel_left * term->cell_width,
            .height = min(term->cell_height, six->height - rel_above * term->cell_height),
            .rows = 1,
            .cols = rel_left,
            .pos = (struct coord){
                six->pos.col,
                (six->pos.row + rel_above) & (term->grid->num_rows - 1)},
        };
        imgs[2].data = xmalloc(imgs[2].width * imgs[2].height * sizeof(uint32_t));
        for (size_t i = 0; i < imgs[2].height; i++)
            memcpy(
                &((uint32_t *)imgs[2].data)[i * imgs[2].width],
                &((const uint32_t *)six->data)[(rel_above * term->cell_height + i) * six->width],
                imgs[2].width * sizeof(uint32_t));
    }

    if (rel_right < six->cols) {
        imgs[3] = (struct sixel){
            .width = six->width - rel_right * term->cell_width,
            .height = min(term->cell_height, six->height - rel_above * term->cell_height),
            .rows = 1,
            .cols = six->cols - rel_right,
            .pos = (struct coord){
                six->pos.col + rel_right,
                (six->pos.row + rel_above) & (term->grid->num_rows - 1)},
        };
        imgs[3].data = xmalloc(imgs[3].width * imgs[3].height * sizeof(uint32_t));
        for (size_t i = 0; i < imgs[3].height; i++)
            memcpy(
                &((uint32_t *)imgs[3].data)[i * imgs[3].width],
                &((const uint32_t *)six->data)[(rel_above * term->cell_height + i) * six->width + rel_right * term->cell_width],
                imgs[3].width * sizeof(uint32_t));
    }

    for (size_t i = 0; i < sizeof(imgs) / sizeof(imgs[0]); i++) {
        if (imgs[i].data == NULL)
            continue;

        imgs[i].pix = pixman_image_create_bits_no_clear(
            PIXMAN_a8r8g8b8,
            imgs[i].width, imgs[i].height,
            imgs[i].data, imgs[i].width * sizeof(uint32_t));
        sixel_insert(term, imgs[i]);
    }
}

/* Row numbers are absolute */
static void
_sixel_overwrite_by_rectangle(
    struct terminal *term, int row, int col, int height, int width)
{
    assert(row >= 0);
    assert(row + height <= term->grid->num_rows);
    assert(col >= 0);
    assert(col + width <= term->grid->num_cols);

    const int start = row;
    const int end = row + height - 1;

    const int scrollback_rel_start = rebase_row(term, start);

    tll_foreach(term->grid->sixel_images, it) {
        struct sixel *six = &it->item;

        const int six_start = six->pos.row;
        const int six_end = (six_start + six->rows - 1) & (term->grid->num_rows - 1);
        const int six_scrollback_rel_end = rebase_row(term, six_end);

        if (six_scrollback_rel_end < scrollback_rel_start) {
            /* All remaining sixels are *before* our rectangle */
            break;
        }

        /* We should never generate scrollback wrapping sixels */
        assert(six_end >= six_start);

        if ((start <= six_start && end >= six_start) ||  /* Crosses sixel start boundary */
            (start <= six_end && end >= six_end) ||      /* Crosses sixel end boundary */
            (start >= six_start && end <= six_end))      /* Fully within sixel range */
        {
            const int col_start = six->pos.col;
            const int col_end = six->pos.col + six->cols - 1;

            if ((col <= col_start && col + width - 1 >= col_start) ||
                (col <= col_end && col + width - 1 >= col_end) ||
                (col >= col_start && col + width - 1 <= col_end))
            {
                struct sixel to_be_erased = *six;
                tll_remove(term->grid->sixel_images, it);

                sixel_overwrite(term, &to_be_erased, start, col, height, width);
                sixel_erase(term, &to_be_erased);
            }
        }
    }
}

void
sixel_overwrite_by_rectangle(
    struct terminal *term, int row, int col, int height, int width)
{
    if (likely(tll_length(term->grid->sixel_images) == 0))
        return;

    const int start = (term->grid->offset + row) & (term->grid->num_rows - 1);
    const int end = (start + height - 1) & (term->grid->num_rows - 1);
    const bool wraps = end < start;

    if (wraps) {
        int rows_to_wrap_around = term->grid->num_rows - start;
        assert(height - rows_to_wrap_around > 0);
        _sixel_overwrite_by_rectangle(term, start, col, rows_to_wrap_around, width);
        _sixel_overwrite_by_rectangle(term, 0, col, height - rows_to_wrap_around, width);
    } else
        _sixel_overwrite_by_rectangle(term, start, col, height, width);
}

/* Row numbers are relative to grid offset */
void
sixel_overwrite_by_row(struct terminal *term, int _row, int col, int width)
{
    assert(col >= 0);

    assert(_row >= 0);
    assert(_row < term->rows);
    assert(col >= 0);
    assert(col < term->grid->num_cols);

    if (likely(tll_length(term->grid->sixel_images) == 0))
        return;

    if (col + width > term->grid->num_cols)
        width = term->grid->num_cols - col;

    const int row = (term->grid->offset + _row) & (term->grid->num_rows - 1);
    const int scrollback_rel_row = rebase_row(term, row);

    tll_foreach(term->grid->sixel_images, it) {
        struct sixel *six = &it->item;
        const int six_start = six->pos.row;
        const int six_end = (six_start + six->rows - 1) & (term->grid->num_rows - 1);

        /* We should never generate scrollback wrapping sixels */
        assert(six_end >= six_start);

        const int six_scrollback_rel_end = rebase_row(term, six_end);

        if (six_scrollback_rel_end < scrollback_rel_row) {
            /* All remaining sixels are *before* "our" row */
            break;
        }

        if (row >= six_start && row <= six_end) {
            const int col_start = six->pos.col;
            const int col_end = six->pos.col + six->cols - 1;

            if ((col <= col_start && col + width - 1 >= col_start) ||
                (col <= col_end && col + width - 1 >= col_end) ||
                (col >= col_start && col + width - 1 <= col_end))
            {
                struct sixel to_be_erased = *six;
                tll_remove(term->grid->sixel_images, it);

                sixel_overwrite(term, &to_be_erased, row, col, 1, width);
                sixel_erase(term, &to_be_erased);
            }
        }
    }
}

void
sixel_overwrite_at_cursor(struct terminal *term, int width)
{
    sixel_overwrite_by_row(
        term, term->grid->cursor.point.row, term->grid->cursor.point.col, width);
}

void
sixel_unhook(struct terminal *term)
{
    int pixel_row_idx = 0;
    int pixel_rows_left = term->sixel.image.height;
    const int stride = term->sixel.image.width * sizeof(uint32_t);

    /* We do not allow sixels to cross the scrollback wrap-around, as
     * this makes intersection calculations much more complicated */
    while (pixel_rows_left > 0) {
        const struct coord *cursor = &term->grid->cursor.point;

        const int cur_row = (term->grid->offset + cursor->row) & (term->grid->num_rows - 1);
        const int rows_avail = term->grid->num_rows - cur_row;

        const int pixel_rows_avail = rows_avail * term->cell_height;

        const int width = term->sixel.image.width;
        const int height = min(pixel_rows_left, pixel_rows_avail);

        uint32_t *img_data;
        if (pixel_row_idx == 0)
            img_data = term->sixel.image.data;
        else {
            img_data = xmalloc(height * stride);
            memcpy(
                img_data,
                &((uint8_t *)term->sixel.image.data)[pixel_row_idx * stride],
                height * stride);
        }

        struct sixel image = {
            .data = img_data,
            .width = width,
            .height = height,
            .rows = (height + term->cell_height - 1) / term->cell_height,
            .cols = (width + term->cell_width - 1) / term->cell_width,
            .pos = (struct coord){cursor->col, cur_row},
        };

        sixel_overwrite_by_rectangle(
            term, cursor->row, image.pos.col, image.rows, image.cols);

        LOG_DBG("generating %dx%d pixman image at %d-%d", image.width, image.height, image.pos.row, image.pos.row + image.rows);

        image.pix = pixman_image_create_bits_no_clear(
            PIXMAN_a8r8g8b8,
            image.width, image.height,
            img_data, stride);


        for (size_t i = 0; i < image.rows; i++)
            term_linefeed(term);
        term_carriage_return(term);
        render_refresh(term);

        sixel_insert(term, image);

        pixel_row_idx += height;
        pixel_rows_left -= height;
    }

    term->sixel.image.data = NULL;
    term->sixel.image.width = 0;
    term->sixel.image.height = 0;
    term->sixel.max_col = 0;
    term->sixel.pos = (struct coord){0, 0};
}

static unsigned
max_width(const struct terminal *term)
{
    /* foot extension - treat 0 to mean current terminal size */
    return term->sixel.max_width == 0
        ? term->cols * term->cell_width
        : term->sixel.max_width;
}

static unsigned
max_height(const struct terminal *term)
{
    /* foot extension - treat 0 to mean current terminal size */
    return term->sixel.max_height == 0
        ? term->rows * term->cell_height
        : term->sixel.max_height;
}

static bool
resize(struct terminal *term, int new_width, int new_height)
{
    if (!term->sixel.image.autosize)
        return false;

    LOG_DBG("resizing image: %dx%d -> %dx%d",
            term->sixel.image.width, term->sixel.image.height,
            new_width, new_height);

    uint32_t *old_data = term->sixel.image.data;
    const int old_width = term->sixel.image.width;
    const int old_height = term->sixel.image.height;

    int alloc_new_width = new_width;
    int alloc_new_height = (new_height + 6 - 1) / 6 * 6;
    assert(alloc_new_height >= new_height);
    assert(alloc_new_height - new_height < 6);

    assert(new_width >= old_width);
    assert(new_height >= old_height);

    uint32_t *new_data = NULL;

    if (new_width == old_width) {
        /* Width (and thus stride) is the same, so we can simply
         * re-alloc the existing buffer */

        new_data = realloc(old_data, alloc_new_width * alloc_new_height * sizeof(uint32_t));
        if (new_data == NULL) {
            LOG_ERRNO("failed to reallocate sixel image buffer");
            return false;
        }

        assert(new_height > old_height);

    } else {
        /* Width (and thus stride) change - need to allocate a new buffer */
        assert(new_width > old_width);
        new_data = xmalloc(alloc_new_width * alloc_new_height * sizeof(uint32_t));

        /* Copy old rows, and initialize new columns to background color */
        for (int r = 0; r < old_height; r++) {
            memcpy(&new_data[r * new_width], &old_data[r * old_width], old_width * sizeof(uint32_t));

            for (int c = old_width; c < new_width; c++)
                new_data[r * new_width + c] = color_with_alpha(term, term->colors.bg);
        }
        free(old_data);
    }

    /* Initialize new rows to background color */
    for (int r = old_height; r < new_height; r++) {
        for (int c = 0; c < new_width; c++)
            new_data[r * new_width + c] = color_with_alpha(term, term->colors.bg);
    }

    assert(new_data != NULL);
    term->sixel.image.data = new_data;
    term->sixel.image.width = new_width;
    term->sixel.image.height = new_height;

    return true;
}

static void
sixel_add(struct terminal *term, uint32_t color, uint8_t sixel)
{
    //LOG_DBG("adding sixel %02hhx using color 0x%06x", sixel, color);

    if (term->sixel.pos.col >= max_width(term) ||
        term->sixel.pos.row * 6 + 5 >= max_height(term))
    {
        return;
    }

    if (term->sixel.pos.col >= term->sixel.image.width ||
        term->sixel.pos.row * 6 + 5 >= (term->sixel.image.height + 6 - 1) / 6 * 6)
    {
        int width = max(
            term->sixel.image.width,
            max(term->sixel.max_col, term->sixel.pos.col + 1));

        int height = max(
            term->sixel.image.height,
            (term->sixel.pos.row + 1) * 6);

        if (!resize(term, width, height))
            return;
    }

    for (int i = 0; i < 6; i++, sixel >>= 1) {
        if (sixel & 1) {
            size_t pixel_row = term->sixel.pos.row * 6 + i;
            size_t stride = term->sixel.image.width;
            size_t idx = pixel_row * stride + term->sixel.pos.col;
            term->sixel.image.data[idx] = color_with_alpha(term, color);
        }
    }

    assert(sixel == 0);
    term->sixel.pos.col++;
}

static void
decsixel(struct terminal *term, uint8_t c)
{
    switch (c) {
    case '"':
        term->sixel.state = SIXEL_DECGRA;
        term->sixel.param = 0;
        term->sixel.param_idx = 0;
        break;

    case '!':
        term->sixel.state = SIXEL_DECGRI;
        term->sixel.param = 0;
        term->sixel.param_idx = 0;
        break;

    case '#':
        term->sixel.state = SIXEL_DECGCI;
        term->sixel.color_idx = 0;
        term->sixel.param = 0;
        term->sixel.param_idx = 0;
        break;

    case '$':
        if (term->sixel.pos.col > term->sixel.max_col)
            term->sixel.max_col = term->sixel.pos.col;
        term->sixel.pos.col = 0;
        break;

    case '-':
        if (term->sixel.pos.col > term->sixel.max_col)
            term->sixel.max_col = term->sixel.pos.col;
        term->sixel.pos.row++;
        term->sixel.pos.col = 0;
        break;

    case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E':
    case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
    case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S':
    case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
    case '[': case '\\': case ']': case '^': case '_': case '`': case 'a':
    case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h':
    case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o':
    case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v':
    case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}':
    case '~':
        sixel_add(term, term->sixel.palette[term->sixel.color_idx], c - 63);
        break;

    case ' ':
    case '\n':
    case '\r':
        break;

    default:
        LOG_WARN("invalid sixel character: '%c' at idx=%zu", c, count);
        break;
    }
}

static void
decgra(struct terminal *term, uint8_t c)
{
    switch (c) {
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9':
        term->sixel.param *= 10;
        term->sixel.param += c - '0';
        break;

    case ';':
        if (term->sixel.param_idx < ALEN(term->sixel.params))
            term->sixel.params[term->sixel.param_idx++] = term->sixel.param;
        term->sixel.param = 0;
        break;

    default: {
        if (term->sixel.param_idx < ALEN(term->sixel.params))
            term->sixel.params[term->sixel.param_idx++] = term->sixel.param;

        int nparams = term->sixel.param_idx;
        unsigned pan = nparams > 0 ? term->sixel.params[0] : 0;
        unsigned pad = nparams > 1 ? term->sixel.params[1] : 0;
        unsigned ph = nparams > 2 ? term->sixel.params[2] : 0;
        unsigned pv = nparams > 3 ? term->sixel.params[3] : 0;

        pan = pan > 0 ? pan : 1;
        pad = pad > 0 ? pad : 1;

        LOG_DBG("pan=%u, pad=%u (aspect ratio = %u), size=%ux%u",
                pan, pad, pan / pad, ph, pv);

        if (ph >= term->sixel.image.height && pv >= term->sixel.image.width &&
            ph <= max_height(term) && pv <= max_width(term))
        {
            if (resize(term, ph, pv))
                term->sixel.image.autosize = false;
        }

        term->sixel.state = SIXEL_DECSIXEL;
        sixel_put(term, c);
        break;
    }
    }
}

static void
decgri(struct terminal *term, uint8_t c)
{
    switch (c) {
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9':
        term->sixel.param *= 10;
        term->sixel.param += c - '0';
        break;

    default:
        //LOG_DBG("repeating '%c' %u times", c, term->sixel.param);
        for (unsigned i = 0; i < term->sixel.param; i++)
            decsixel(term, c);
        term->sixel.state = SIXEL_DECSIXEL;
        break;
    }
}

static void
decgci(struct terminal *term, uint8_t c)
{
    switch (c) {
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9':
        term->sixel.param *= 10;
        term->sixel.param += c - '0';
        break;

    case ';':
        if (term->sixel.param_idx < ALEN(term->sixel.params))
            term->sixel.params[term->sixel.param_idx++] = term->sixel.param;
        term->sixel.param = 0;
        break;

    default: {
        if (term->sixel.param_idx < ALEN(term->sixel.params))
            term->sixel.params[term->sixel.param_idx++] = term->sixel.param;

        int nparams = term->sixel.param_idx;

        if (nparams > 0)
            term->sixel.color_idx = min(term->sixel.params[0], term->sixel.palette_size - 1);

        if (nparams > 4) {
            unsigned format = term->sixel.params[1];
            unsigned c1 = term->sixel.params[2];
            unsigned c2 = term->sixel.params[3];
            unsigned c3 = term->sixel.params[4];

            switch (format) {
            case 1: { /* HLS */
                uint32_t rgb = hls_to_rgb(c1, c2, c3);
                LOG_DBG("setting palette #%d = HLS %hhu/%hhu/%hhu (0x%06x)",
                        term->sixel.color_idx, c1, c2, c3, rgb);
                term->sixel.palette[term->sixel.color_idx] = rgb;
                break;
            }

            case 2: {  /* RGB */
                uint8_t r = 255 * c1 / 100;
                uint8_t g = 255 * c2 / 100;
                uint8_t b = 255 * c3 / 100;

                LOG_DBG("setting palette #%d = RGB %hhu/%hhu/%hhu",
                        term->sixel.color_idx, r, g, b);

                term->sixel.palette[term->sixel.color_idx] = r << 16 | g << 8 | b;
                break;
            }
            }
        }

        term->sixel.state = SIXEL_DECSIXEL;
        sixel_put(term, c);
        break;
    }
    }
}

void
sixel_put(struct terminal *term, uint8_t c)
{
    switch (term->sixel.state) {
    case SIXEL_DECSIXEL: decsixel(term, c); break;
    case SIXEL_DECGRA: decgra(term, c); break;
    case SIXEL_DECGRI: decgri(term, c); break;
    case SIXEL_DECGCI: decgci(term, c); break;
    }

    count++;
}

void
sixel_colors_report_current(struct terminal *term)
{
    char reply[24];
    snprintf(reply, sizeof(reply), "\033[?1;0;%uS", term->sixel.palette_size);
    term_to_slave(term, reply, strlen(reply));
    LOG_DBG("query response for current color count: %u", term->sixel.palette_size);
}

void
sixel_colors_reset(struct terminal *term)
{
    LOG_DBG("sixel palette size reset to %u", SIXEL_MAX_COLORS);

    free(term->sixel.palette);
    term->sixel.palette = NULL;

    term->sixel.palette_size = SIXEL_MAX_COLORS;
    sixel_colors_report_current(term);
}

void
sixel_colors_set(struct terminal *term, unsigned count)
{
    unsigned new_palette_size = min(max(2, count), SIXEL_MAX_COLORS);
    LOG_DBG("sixel palette size set to %u", new_palette_size);

    free(term->sixel.palette);
    term->sixel.palette = NULL;

    term->sixel.palette_size = new_palette_size;
    sixel_colors_report_current(term);
}

void
sixel_colors_report_max(struct terminal *term)
{
    char reply[24];
    snprintf(reply, sizeof(reply), "\033[?1;0;%uS", SIXEL_MAX_COLORS);
    term_to_slave(term, reply, strlen(reply));
    LOG_DBG("query response for max color count: %u", SIXEL_MAX_COLORS);
}

void
sixel_geometry_report_current(struct terminal *term)
{
    char reply[64];
    snprintf(reply, sizeof(reply), "\033[?2;0;%u;%uS",
             max_width(term), max_height(term));
    term_to_slave(term, reply, strlen(reply));

    LOG_DBG("query response for current sixel geometry: %ux%u",
            max_width(term), max_height(term));
}

void
sixel_geometry_reset(struct terminal *term)
{
    LOG_DBG("sixel geometry reset to %ux%u", max_width(term), max_height(term));
    term->sixel.max_width = 0;
    term->sixel.max_height = 0;
    sixel_geometry_report_current(term);
}

void
sixel_geometry_set(struct terminal *term, unsigned width, unsigned height)
{
    LOG_DBG("sixel geometry set to %ux%u", width, height);
    term->sixel.max_width = width;
    term->sixel.max_height = height;
    sixel_geometry_report_current(term);
}

void
sixel_geometry_report_max(struct terminal *term)
{
    unsigned max_width = term->cols * term->cell_width;
    unsigned max_height = term->rows * term->cell_height;

    char reply[64];
    snprintf(reply, sizeof(reply), "\033[?2;0;%u;%uS", max_width, max_height);
    term_to_slave(term, reply, strlen(reply));

    LOG_DBG("query response for max sixel geometry: %ux%u",
            max_width, max_height);
}