summaryrefslogtreecommitdiff
path: root/src/sixel-test.cc
blob: 3f9fd312c9faabbf73bf7e29d9e3ad84086d65ae (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
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
/*
 * Copyright © 2020 Christian Persch
 *
 * This library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library.  If not, see <https://www.gnu.org/licenses/>.
 */

#include "config.h"

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <initializer_list>
#include <string>
#include <variant>
#include <vector>

#include <glib.h>

#include "sixel-parser.hh"
#include "sixel-context.hh"

using namespace std::literals;

using Command = vte::sixel::Command;
using Context = vte::sixel::Context;
using Mode = vte::sixel::Parser::Mode;
using ParseStatus = vte::sixel::Parser::ParseStatus;

// Parser tests

static inline constexpr auto
param_to_color_register(unsigned reg)
{
        return reg + 2; /* Public colour registers start at 2 */
}

static char const*
cmd_to_str(Command command)
{
        switch (command) {
        case Command::DECGRI: return "DECGRI";
        case Command::DECGRA: return "DECGRA";
        case Command::DECGCI: return "DECGCI";
        case Command::DECGCR: return "DECGCR";
        case Command::DECGNL: return "DECGNL";
        case Command::NONE:   return "NONE";
        default:
                static char buf[32];
                snprintf(buf, sizeof(buf), "UNKOWN(%d/%02d)",
                         (int)command / 16,
                         (int)command % 16);
                return buf;
        }
}

enum class StType {
        C0,
        C1_UTF8,
        C1_EIGHTBIT
};

inline constexpr auto
ST(StType type)
{
        switch (type) {
        case StType::C0:          return "\e\\"sv;
        case StType::C1_UTF8:     return "\xc2\x9c"sv;
        case StType::C1_EIGHTBIT: return "\x9c"sv;
        default: __builtin_unreachable();
        }
}

inline constexpr auto
ST(Mode mode)
{
        switch (mode) {
        case Mode::UTF8:     return ST(StType::C1_UTF8);
        case Mode::EIGHTBIT: return ST(StType::C1_EIGHTBIT);
        case Mode::SEVENBIT: return ST(StType::C0);
        default: __builtin_unreachable();
        }
}

class Sequence : public vte::sixel::Sequence {
public:
        using Base = vte::sixel::Sequence;

        Sequence(Base const& seq)
                : Base{seq}
        {
        }

        Sequence(Command cmd,
                 std::vector<int> const& params) noexcept
                : Base{cmd}
        {
                assert(params.size() <= (sizeof(m_args) / sizeof(m_args[0])));
                for (auto p : params)
                        m_args[m_n_args++] = vte_seq_arg_init(std::min(p, 0xffff));
        }

        void append(std::string& str) const
        {
                if (command() != Command::NONE)
                        str.append(1, char(command()));
                for (auto i = 0u; i < size(); ++i) {
                        auto const p = param(i);
                        if (p != -1) {
                                char buf[12];
                                auto const len = g_snprintf(buf, sizeof(buf), "%d", p);
                                str.append(buf, len);
                        }
                        if ((i + 1) < size())
                                str.append(1, ';');
                }
        }

        void prettyprint(std::string& str) const
        {
                str.append("Sequence(");
                str.append(cmd_to_str(command()));
                if (size()) {
                        str.append(" ");
                        for (auto i = 0u; i < size(); ++i) {
                                auto const p = param(i);

                                char buf[12];
                                auto const len = g_snprintf(buf, sizeof(buf), "%d", p);
                                str.append(buf, len);

                                if ((i + 1) < size())
                                        str.append(1, ';');
                        }
                }
                str.append(")");
        }
};

constexpr bool operator==(Sequence const& lhs, Sequence const& rhs) noexcept
{
        if (lhs.command() != rhs.command())
                return false;

        auto const m = std::min(lhs.size(), rhs.size());
        for (auto n = 0u; n < m; ++n)
                if (lhs.param(n) != rhs.param(n))
                        return false;

        if (lhs.size() == rhs.size())
                return true;

        if ((lhs.size() == (rhs.size() + 1)) && lhs.param(rhs.size()) == -1)
                return true;

        if (((lhs.size() + 1) == rhs.size()) && rhs.param(lhs.size()) == -1)
                return true;

        return false;
}

class Sixel {
public:
        constexpr Sixel(uint8_t sixel)
                : m_sixel(sixel)
        {
                assert(m_sixel < 0b100'0000);
        }

        ~Sixel() = default;

        constexpr auto sixel() const noexcept { return m_sixel; }

        void append(std::string& str) const { str.append(1, char(m_sixel + 0x3f)); }

        void prettyprint(std::string& str) const
        {
                str.append("Sixel(");
                char buf[3];
                auto const len = g_snprintf(buf, sizeof(buf), "%02x", sixel());
                str.append(buf, len);
                str.append(")");
        }

private:
        uint8_t m_sixel{0};
};

constexpr bool operator==(Sixel const& lhs, Sixel const& rhs) noexcept
{
        return lhs.sixel() == rhs.sixel();
}

class Unicode {
public:
        Unicode(char32_t c) :
                m_c{c}
        {
                m_utf8_len = g_unichar_to_utf8(c, m_utf8_buf);
        }
        ~Unicode() = default;

        constexpr auto unicode() const noexcept { return m_c; }

        void append(std::string& str) const { str.append(m_utf8_buf, m_utf8_len); }

        void prettyprint(std::string& str) const
        {
                str.append("Unicode(");
                char buf[7];
                auto const len = g_snprintf(buf, sizeof(buf), "%04X", unicode());
                str.append(buf, len);
                str.append(")");
        }

private:
        char32_t m_c{0};
        size_t m_utf8_len{0};
        char m_utf8_buf[4]{0, 0, 0, 0};
};

constexpr bool operator==(Unicode const& lhs, Unicode const& rhs) noexcept
{
        return lhs.unicode() == rhs.unicode();
}

class C0Control {
public:
        C0Control(uint8_t c) :
                m_control{c}
        {
                assert(c < 0x20 || c == 0x7f);
        }
        ~C0Control() = default;

        constexpr auto control() const noexcept { return m_control; }

        void append(std::string& str) const { str.append(1, char(m_control)); }

        void prettyprint(std::string& str) const
        {
                str.append("C0(");
                char buf[3];
                auto const len = g_snprintf(buf, sizeof(buf), "%02X", control());
                str.append(buf, len);
                str.append(")");
        }

private:
        uint8_t m_control{0};
};

constexpr bool operator==(C0Control const& lhs, C0Control const& rhs) noexcept
{
        return lhs.control() == rhs.control();
}

class C1Control {
public:
        C1Control(uint8_t c) :
                m_control{c}
        {
                assert(c >= 0x80 && c < 0xa0);
                auto const len = g_unichar_to_utf8(c, m_utf8_buf);
                assert(len == 2);
        }
        ~C1Control() = default;

        constexpr auto control() const noexcept { return m_control; }

        void append(std::string& str,
                    Mode mode) const {
                switch (mode) {
                case Mode::UTF8:
                        str += std::string_view(m_utf8_buf, 2);
                        break;
                case Mode::EIGHTBIT:
                        str.append(1, char(m_control));
                        break;
                case Mode::SEVENBIT:
                        str.append(1, char(0x1b));
                        str.append(1, char(m_control - 0x40));
                        break;
                }
        }

        void prettyprint(std::string& str) const
        {
                str.append("C1(");
                char buf[3];
                auto const len = g_snprintf(buf, sizeof(buf), "%02X", control());
                str.append(buf, len);
                str.append(")");
        }

private:
        uint8_t m_control{0};
        char m_utf8_buf[2]{0, 0};
};

constexpr bool operator==(C1Control const& lhs, C1Control const& rhs) noexcept
{
        return lhs.control() == rhs.control();
}

class Raw {
public:
        Raw(uint8_t raw) :
                m_raw{raw}
        {
        }
        ~Raw() = default;

        constexpr auto raw() const noexcept { return m_raw; }

        void append(std::string& str) const { str += char(m_raw); }

        void prettyprint(std::string& str) const
        {
                str.append("Raw(");
                char buf[3];
                auto const len = g_snprintf(buf, sizeof(buf), "%02X", raw());
                str.append(buf, len);
                str.append(")");
        }

private:
        uint8_t m_raw{0};
};

constexpr bool operator==(Raw const& lhs, Raw const& rhs) noexcept
{
        return lhs.raw() == rhs.raw();
}

inline auto
DECGRI(int count) noexcept
{
        return Sequence{Command::DECGRI, {count}};
}

inline auto
DECGRA(int an,
       int ad,
       int w,
       int h) noexcept
{
        return Sequence{Command::DECGRA, {an, ad, w, h}};
}

inline auto
DECGCI(int reg) noexcept
{
        return Sequence{Command::DECGCI, {reg}};
}

inline auto
DECGCI_HLS(int reg,
           int h,
           int l,
           int s) noexcept
{
        return Sequence{Command::DECGCI, {reg, 1, h, l, s}};
}

inline auto
DECGCI_RGB(int reg,
           int r,
           int g,
           int b) noexcept
{
        return Sequence{Command::DECGCI, {reg, 2, r, g, b}};
}

inline auto
DECGCR() noexcept
{
        return Sequence{Command::DECGCR};
}

inline auto
DECGNL() noexcept
{
        return Sequence{Command::DECGNL};
}

using Item = std::variant<Sequence, Sixel, C0Control, C1Control, Unicode, Raw>;
using ItemList = std::vector<Item>;

#if 0

class ItemPrinter {
public:
        ItemPrinter(Item const& item)
        {
                std::visit(*this, item);
        }

        ~ItemPrinter() = default;

        std::string const& string()    const noexcept { return m_str; }
        std::string_view string_view() const noexcept { return m_str; }

        void operator()(Sequence const& seq)      { seq.prettyprint(m_str);     }
        void operator()(Sixel const& sixel)       { sixel.prettyprint(m_str);   }
        void operator()(C0Control const& control) { control.prettyprint(m_str); }
        void operator()(C1Control const& control) { control.prettyprint(m_str); }
        void operator()(Unicode const& unicode)   { unicode.prettyprint(m_str); }
        void operator()(Raw const& raw)           { raw.prettyprint(m_str);     }

private:
        std::string m_str{};
};

static void
print_items(char const* intro,
            ItemList const& items)
{
        auto str = std::string{};

        for (auto const& item : items) {
                str += ItemPrinter{item}.string();
                str += " ";
        }

        g_printerr("%s: %s\n", intro, str.c_str());
}

#endif

class ItemStringifier {
public:
        ItemStringifier(Mode mode = Mode::UTF8) :
                m_mode{mode}
        { }

        ItemStringifier(Item const& item,
                        Mode mode = Mode::UTF8) :
                m_mode{mode}
        {
                std::visit(*this, item);
        }

        ItemStringifier(ItemList const& items,
                        Mode mode = Mode::UTF8) :
                m_mode{mode}
        {
                for (auto&& i : items)
                        std::visit(*this, i);
        }

        ~ItemStringifier() = default;

        std::string string() const noexcept { return m_str; }
        std::string_view string_view() const noexcept { return m_str; }

        void operator()(Sequence const& seq)      { seq.append(m_str);             }
        void operator()(Sixel const& sixel)       { sixel.append(m_str);           }
        void operator()(C0Control const& control) { control.append(m_str);         }
        void operator()(C1Control const& control) { control.append(m_str, m_mode); }
        void operator()(Unicode const& unicode)   { unicode.append(m_str);         }
        void operator()(Raw const& raw)           { raw.append(m_str);             }

private:
        std::string m_str{};
        Mode m_mode;
};

class SimpleContext {

        friend class Parser;
public:
        SimpleContext() = default;
        ~SimpleContext() = default;

        auto parse(std::string_view const& str,
                   size_t end_pos = size_t(-1))
        {
                auto const beginptr = reinterpret_cast<uint8_t const*>(str.data());
                auto const endptr = reinterpret_cast<uint8_t const*>(beginptr + str.size());
                return m_parser.parse(beginptr, endptr, true, *this);
        }

        auto parse(Item const& item,
                   Mode input_mode)
        {
                return parse(ItemStringifier{{item}, input_mode}.string_view());
        }

        auto parse(ItemList const& list,
                   Mode input_mode)
        {
                return parse(ItemStringifier{list, input_mode}.string_view());
        }

        void set_mode(Mode mode)
        {
                m_parser.set_mode(mode);
        }

        void reset_mode()
        {
                set_mode(Mode::UTF8);
        }

        void reset()
        {
                m_parser.reset();
                m_parsed_items.clear();
                m_st = 0;
        }

        auto const& parsed_items() const noexcept { return m_parsed_items; }

        void SIXEL(uint8_t raw) noexcept
        {
                m_parsed_items.push_back(Sixel(raw));
        }

        void SIXEL_CMD(vte::sixel::Sequence const& seq) noexcept
        {
                m_parsed_items.push_back(Sequence(seq));
        }

        void SIXEL_ST(char32_t st) noexcept
        {
                m_st = st;
        }

        vte::sixel::Parser m_parser{};
        ItemList m_parsed_items{};
        char32_t m_st{0};

}; // class SimpleContext

/*
 * assert_parse:
 * @context:
 * @mode:
 * @str:
 * @str_size:
 * @expected_parsed_len:
 * @expected_status:
 *
 * Asserts that parsing @str (up to @str_size, or until its size if @str_size is -1)
 * in mode @mode results in @expected_status, with the endpointer pointing to the end
 * of @str if @expected_parsed_len is -1, or to @expected_parsed_len otherwise.
 */
template<class C>
static void
assert_parse(C& context,
             Mode mode,
             std::string_view const& str,
             size_t str_size = size_t(-1),
             size_t expected_parse_end = size_t(-1),
             ParseStatus expected_status = ParseStatus::COMPLETE,
             int line = __builtin_LINE())
{
        context.reset();
        context.set_mode(mode);

        auto const beginptr = reinterpret_cast<uint8_t const*>(str.data());
        auto const len = str_size == size_t(-1) ? str.size() : str_size;
        auto const [status, ip] = context.parse(str, len);
        auto const parsed_len = size_t(ip - beginptr);

        g_assert_cmpint(int(status), ==, int(expected_status));
        g_assert_cmpint(parsed_len, ==, expected_parse_end == size_t(-1) ? len : expected_parse_end);
}

/*
 * assert_parse:
 * @context:
 * @mode:
 * @str:
 * @expected_items:
 * @str_size:
 * @expected_parsed_len:
 * @expected_status:
 *
 * Asserts that parsing @str (up to @str_size, or until its size if @str_size is -1)
 * in mode @mode results in @expected_status, with the parsed items equal to
 * @expected_items, and the endpointer pointing to the end of @str if @expected_parsed_len
 * is -1, or to @expected_parsed_len otherwise.
 */
template<class C>
static void
assert_parse(C& context,
             Mode mode,
             std::string_view const& str,
             ItemList const& expected_items,
             size_t str_size = size_t(-1),
             size_t expected_parse_end = size_t(-1),
             ParseStatus expected_status = ParseStatus::COMPLETE,
             int line = __builtin_LINE())
{
        assert_parse(context, mode, str, str_size, expected_parse_end, expected_status, line);

        g_assert_true(context.parsed_items() == expected_items);
}

/*
 * assert_parse_st:
 *
 * Like assert_parse above, but ST-terminates the passed string.
 */
template<class C>
static void
assert_parse_st(C& context,
                Mode mode,
                std::string_view const& str,
                size_t str_size = size_t(-1),
                size_t expected_parse_end = size_t(-1),
                ParseStatus expected_status = ParseStatus::COMPLETE,
                StType st = StType::C0,
                int line = __builtin_LINE())
{
        auto str_st = std::string{str};
        str_st.append(ST(st));
        auto str_st_size = str_size;

        assert_parse(context, mode, str_st, str_st_size, expected_parse_end, expected_status, line);
}

/*
 * assert_parse_st:
 *
 * Like assert_parse above, but ST-terminates the passed string.
 */
template<class C>
static void
assert_parse_st(C& context,
                Mode mode,
                std::string_view const& str,
                ItemList const& expected_items,
                size_t str_size = size_t(-1),
                size_t expected_parse_end = size_t(-1),
                ParseStatus expected_status = ParseStatus::COMPLETE,
                StType st = StType::C0,
                int line = __builtin_LINE())
{
        auto str_st = std::string{str};
        str_st.append(ST(st));
        auto str_st_size = str_size == size_t(-1) ? str_st.size() : str_size;

        assert_parse(context, mode, str_st, expected_items, str_st_size, expected_parse_end, expected_status, line);
}

/*
 * assert_parse_st:
 *
 * Like assert_parse above, but ST-terminates the passed string.
 */
template<class C>
static void
assert_parse_st(C& context,
                Mode mode,
                ItemList const& items,
                ItemList const& expected_items,
                ParseStatus expected_status = ParseStatus::COMPLETE,
                StType st = StType::C0,
                int line = __builtin_LINE())
{
        assert_parse_st(context, mode, ItemStringifier{items, mode}.string_view(), expected_items, -1, -1, expected_status, st, line);
}

static void
test_parser_seq_params(SimpleContext& context,
                       Mode mode,
                       std::vector<int> const& params)
{
        for (auto i = 0x20; i < 0x3f; ++i) {
                if (i >= 0x30 && i < 0x3c) // Parameter characters
                        continue;


                auto const items = ItemList{Sequence{Command(i), params}};
                assert_parse_st(context, mode, items,
                                (i == 0x20) ? ItemList{} /* 0x20 is ignored */ : items);
        }
}

static void
test_parser_seq_params(SimpleContext& context,
                       vte_seq_arg_t params[8],
                       bool as_is = false)
{
        for (auto mode : {Mode::UTF8, Mode::EIGHTBIT, Mode::SEVENBIT}) {
                context.set_mode(mode);

                for (auto n = 0; n <= 8; ++n) {
                        auto pv = std::vector<int>(&params[0], &params[n]);

                        test_parser_seq_params(context, mode, pv);

                        if (n > 0 && !as_is) {
                                pv[n - 1] = -1;
                                test_parser_seq_params(context, mode, pv);
                        }
                }
        }

        context.reset_mode();
}

static void
test_parser_seq_params(void)
{
        auto context = SimpleContext{};

        /* Tests sixel commands, which have the form I P...P with an initial byte
         * in the 2/0..2/15, 3/12..3/14 range, and parameter bytes P from 3/0..3/11.
         */
        vte_seq_arg_t params1[8]{1, 0, 1000, 10000, 65534, 65535, 65536, 1};
        test_parser_seq_params(context, params1);

        vte_seq_arg_t params2[8]{1, -1, -1, -1, 1, -1, 1, 1};
        test_parser_seq_params(context, params2, true);
}

static void
test_parser_seq_subparams(void)
{
        // Test that subparams cause the whole sequence to be ignored

        auto context = SimpleContext{};

        for (auto mode : {Mode::UTF8, Mode::EIGHTBIT, Mode::SEVENBIT}) {

                assert_parse_st(context, mode, "#0;1:2;#:#;1;3:#;:;;"sv, ItemList{});
        }
}

static void
test_parser_seq_params_clear(void)
{
        /* Check that parameters are cleared from the last sequence */

        auto context = SimpleContext{};

        for (auto mode : {Mode::UTF8, Mode::EIGHTBIT, Mode::SEVENBIT}) {
                auto items = ItemList{Sequence{Command::DECGCI, {0, 1, 2, 3, 4, 5, 6, 7}},
                                      Sequence{Command::DECGRI, {5, 3}},
                                      Sequence{Command::DECGNL}};
                assert_parse_st(context, mode, items, items);

                auto parsed_items = context.parsed_items();

                /* Verify that non-specified paramaters have default value */
                auto& item1 = std::get<Sequence>(parsed_items[1]);
                for (auto n = 2; n < 8; ++n)
                        g_assert_cmpint(item1.param(n), ==, -1);


                auto& item2 = std::get<Sequence>(parsed_items[2]);
                for (auto n = 0; n < 8; ++n)
                        g_assert_cmpint(item2.param(n), ==, -1);
        }
}

static void
test_parser_seq_params_max(void)
{
        /* Check that an excessive number of parameters causes the
         * sequence to be ignored.
         */

        auto context = SimpleContext{};

        auto items = ItemList{Sequence{Command::DECGRA, {0, 1, 2, 3, 4, 5, 6, 7}}};
        auto str = ItemStringifier{items, Mode::SEVENBIT}.string();

        /* The sequence with VTE_SIXEL_PARSER_ARG_MAX args must be parsed */
        assert_parse_st(context, Mode::UTF8, str, items);

        /* Now test that adding one more parameter (whether with an
         * explicit value, or default), causes the sequence to be ignored.
         */
        assert_parse_st(context, Mode::UTF8, str + ";8"s, ItemList{});
        assert_parse_st(context, Mode::UTF8, str + ";"s, ItemList{});
}

static void
test_parser_seq_glue_arg(void)
{
        /* The sixel Sequence's parameter accessors are copied from the main parser's
         * Sequence class, so we don't need to test them here again.
         */
}

static void
test_parser_st(void)
{
        /* Test that ST is recognised in all forms and from all states, and
         * that different-mode C1 ST is not recognised.
         */

        auto context = SimpleContext{};

        assert_parse(context, Mode::UTF8, "?\x9c\e\\"sv, {Sixel{0}});
        assert_parse(context, Mode::UTF8, "!5\x9c\e\\"sv, {Sequence{Command::DECGRI, {5}}});
        assert_parse(context, Mode::UTF8, "5\x9c\e\\"sv, ItemList{});
        assert_parse(context, Mode::UTF8, "\x9c\xc2\e\\"sv, ItemList{});

        assert_parse(context, Mode::UTF8, "?\x9c\xc2\x9c"sv, {Sixel{0}});
        assert_parse(context, Mode::UTF8, "!5\x9c\xc2\x9c"sv, {Sequence{Command::DECGRI, {5}}});
        assert_parse(context, Mode::UTF8, "5\x9c\xc2\x9c"sv, ItemList{});
        assert_parse(context, Mode::UTF8, "\x9c\xc2\xc2\x9c"sv, ItemList{});

        assert_parse(context, Mode::EIGHTBIT, "?\e\\"sv, {Sixel{0}});
        assert_parse(context, Mode::EIGHTBIT, "!5\e\\"sv, {Sequence{Command::DECGRI, {5}}});
        assert_parse(context, Mode::EIGHTBIT, "5\e\\"sv, ItemList{});
        assert_parse(context, Mode::EIGHTBIT, "\xc2\e\\"sv, ItemList{});

        assert_parse(context, Mode::EIGHTBIT, "?\xc2\x9c"sv, {Sixel{0}});
        assert_parse(context, Mode::EIGHTBIT, "!5\xc2\x9c"sv, {Sequence{Command::DECGRI, {5}}});
        assert_parse(context, Mode::EIGHTBIT, "5\xc2\x9c"sv, ItemList{});
        assert_parse(context, Mode::EIGHTBIT, "\xc2\xc2\x9c"sv, ItemList{});

        assert_parse(context, Mode::SEVENBIT, "?\xc2\x9c\e\\"sv, {Sixel{0}});
        assert_parse(context, Mode::SEVENBIT, "!5\xc2\x9c\e\\"sv, {Sequence{Command::DECGRI, {5}}});
        assert_parse(context, Mode::SEVENBIT, "5\xc2\x9c\e\\"sv, ItemList{});
        assert_parse(context, Mode::SEVENBIT, "\xc2\x9c\xc2\e\\"sv, ItemList{});
}

static constexpr auto
test_string()
{
        return "a#22a#22\xc2z22a22\xc2"sv;
}

template<class C>
static void
test_parser_insert(C& context,
                   Mode mode,
                   std::string_view const& str,
                   std::string_view const& insert_str,
                   ParseStatus expected_status = ParseStatus::COMPLETE,
                   int line = __builtin_LINE())
{
        for (auto pos = 0u; pos <= str.size(); ++pos) {
                auto estr = std::string{str};
                estr.insert(pos, insert_str);

                assert_parse_st(context, mode, estr, -1,
                                expected_status == ParseStatus::COMPLETE ? size_t(-1) : size_t(pos),
                                expected_status, StType::C0, line);

                if (expected_status == ParseStatus::COMPLETE) {
                        auto items = context.parsed_items(); // copy

                        assert_parse_st(context, mode, str);
                        assert(items == context.parsed_items());
                }
        }
}

template<class C>
static void
test_parser_insert(C& context,
                   std::string_view const& str,
                   std::string_view const& insert_str,
                   ParseStatus expected_status = ParseStatus::COMPLETE,
                   int line = __builtin_LINE())
{
        for (auto mode : {Mode::UTF8, Mode::EIGHTBIT, Mode::SEVENBIT}) {
                test_parser_insert(context, mode, str, insert_str, expected_status, line);
        }
}

static void
test_parser_controls_c0_esc(void)
{
        /* Test that ESC (except C0 ST) always aborts the parsing at the position of the ESC */

        auto context = SimpleContext{};
        auto const str = test_string();

        for (auto c = 0x20; c < 0x7f; ++c) {
                if (c == 0x5c) /* '\' */
                        continue;

                char esc[2] = {0x1b, char(c)};
                test_parser_insert(context, str, {esc, 2}, ParseStatus::ABORT);
        }
}

static void
test_parser_controls_c0_can(void)
{
        /* Test that CAN is handled correctly in all states */

        auto context = SimpleContext{};

        for (auto mode : {Mode::UTF8, Mode::EIGHTBIT, Mode::SEVENBIT}) {

                assert_parse_st(context, mode, "@\x18"sv, {Sixel{1}}, -1, 1, ParseStatus::ABORT);
                assert_parse_st(context, mode, "!5\x18"sv, {Sequence{Command::DECGRI, {5}}}, -1, 2, ParseStatus::ABORT);
                assert_parse_st(context, mode, "5\x18"sv, ItemList{}, -1, 1, ParseStatus::ABORT);
                assert_parse_st(context, mode, "\xc2\x18"sv, ItemList{}, -1, 1, ParseStatus::ABORT);
        }
}

static void
test_parser_controls_c0_sub(void)
{
        /* Test that SUB is handled correctly in all states */

        auto context = SimpleContext{};

        for (auto mode : {Mode::UTF8, Mode::EIGHTBIT, Mode::SEVENBIT}) {

                assert_parse_st(context, mode, "@\x1a"sv, {Sixel{1}, Sixel{0}});

                /* The parser chooses to not dispatch the current sequence on SUB; see the
                 * comment in the Parser class. Otherwise there'd be a
                 * Sequence{Command::DECGRI, {5}} as the first expected item here.
                 */
                assert_parse_st(context, mode, "!5\x1a"sv, {Sixel{0}});

                assert_parse_st(context, mode, "5\x1a"sv, {Sixel{0}});
                assert_parse_st(context, mode, "\xc2\x1a"sv, {Sixel{0}});
        }
}

static void
test_parser_controls_c0_ignored(void)
{
        /* Test that all C0 controls except ESC, CAN, and SUB, are ignored,
         * that is, parsing a string results in the same parsed item when inserting
         * the C0 control at any position (except after \xc2 + 0x80..0x9f in UTF-8 mode,
         * where the \xc2 + C0 produces an U+FFFD (which is ignored) plus the raw C1 which
         * is itself ignored).
         */

        auto context = SimpleContext{};
        auto const str = test_string();

        for (auto c0 = 0; c0 < 0x20; ++c0) {
                if (c0 == 0x18 /* CAN */ ||
                    c0 == 0x1a /* SUB */ ||
                    c0 == 0x1b /* ESC */)
                        continue;

                char c[1] = {char(c0)};
                test_parser_insert(context, str, {c, 1});

                assert_parse_st(context, Mode::UTF8, "?\xc2"s + std::string{c, 1} + "\x80@"s, {Sixel{0}, Sixel{1}});
        }
}

static void
test_parser_controls_del(void)
{
        /* Test that DEL is ignored (except between 0xc2 and 0x80..0x9f in UTF-8 mode) */

        auto context = SimpleContext{};

        for (auto mode : {Mode::UTF8, Mode::EIGHTBIT, Mode::SEVENBIT}) {

                assert_parse_st(context, mode, "!2\x7f;3"sv, {Sequence{Command::DECGRI, {2, 3}}});
                assert_parse_st(context, mode, "2\x7f;3"sv, ItemList{});
        }

        assert_parse_st(context, Mode::UTF8, "?\xc2\x7f\x9c", {Sixel{0}});
}

static void
test_parser_controls_c1(void)
{
        /* Test that any C1 control aborts the parsing at the insertion position,
         * except in 7-bit mode where C1 controls are ignored.
         */

        auto context = SimpleContext{};
        auto const str = test_string();
        for (auto c1 = 0x80; c1 < 0xa0; ++c1) {
                if (c1 == 0x9c /* ST */)
                        continue;

                char c1_utf8[2] = {char(0xc2), char(c1)};
                test_parser_insert(context, Mode::UTF8, str, {c1_utf8, 2}, ParseStatus::ABORT);
                test_parser_insert(context, Mode::SEVENBIT, str, {c1_utf8, 2});

                char c1_raw[1] = {char(c1)};
                test_parser_insert(context, Mode::EIGHTBIT, str, {c1_raw, 2}, ParseStatus::ABORT);
                test_parser_insert(context, Mode::SEVENBIT, str, {c1_utf8, 2});
        }
}

// Context tests

class TestContext: public Context {
public:
        using base_type = Context;
        using base_type::base_type;

        auto parse(std::string_view const& str)
        {
                auto const beginptr = reinterpret_cast<uint8_t const*>(str.data());
                auto const endptr = reinterpret_cast<uint8_t const*>(beginptr + str.size());
                return Context::parse(beginptr, endptr, true);
        }

}; // class TestContext

template<class C>
static void
parse_image(C& context,
            std::string_view const& str,
            unsigned fg_red,
            unsigned fg_green,
            unsigned fg_blue,
            unsigned bg_red,
            unsigned bg_green,
            unsigned bg_blue,
            bool private_color_registers = true,
            int line = __builtin_LINE())
{
        context.reset();
        context.prepare(0x50 /* C0 DCS */,
                        fg_red, fg_green, fg_blue,
                        bg_red, bg_green, bg_blue,
                        false /* bg transparent */,
                        private_color_registers);

        auto str_st = std::string{str};
        str_st.append(ST(StType::C0));
        auto [status, ip] = context.parse(str_st);
        g_assert_cmpint(int(status), ==, int(ParseStatus::COMPLETE));
}

template<class C>
static void
parse_image(C& context,
            ItemList const& items,
            unsigned fg_red,
            unsigned fg_green,
            unsigned fg_blue,
            unsigned bg_red,
            unsigned bg_green,
            unsigned bg_blue,
            bool private_color_registers = true,
            int line = __builtin_LINE())
{
        parse_image(context, ItemStringifier(items).string(),
                    fg_red, fg_green, fg_blue,
                    bg_red, bg_green, bg_blue,
                    private_color_registers,
                    line);
}

template<class C>
static void
parse_image(C& context,
            std::string_view const& str,
            int line = __builtin_LINE())
{
        parse_image(context, str, 0xffu, 0xffu, 0xffu, 0xff8, 0xffu, 0xffu, true, line);
}

template<class C>
static void
parse_image(C& context,
            ItemList const& items,
            int line = __builtin_LINE())
{
        parse_image(context, ItemStringifier{items, Mode::UTF8}.string_view(), line);
}

template<class C>
static auto
parse_pixels(C& context,
             std::string_view const& str,
             unsigned extra_width_stride = 0,
             int line = __builtin_LINE())
{
        parse_image(context, str, line);
        auto size = size_t{};
        auto ptr = vte::glib::take_free_ptr(context.image_data_indexed(&size, extra_width_stride));
        return std::pair{std::move(ptr), size};
}

/* BEGIN */

/* The following code is copied from xterm/graphics.c where it is under the
 * licence below; and modified and used here under the GNU Lesser General Public
 * Licence, version 3 (or, at your option), any later version.
 */

/*
 * Copyright 2013-2019,2020 by Ross Combs
 * Copyright 2013-2019,2020 by Thomas E. Dickey
 *
 *                         All Rights Reserved
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name(s) of the above copyright
 * holders shall not be used in advertising or otherwise to promote the
 * sale, use or other dealings in this Software without prior written
 * authorization.
 */

static void
hls2rgb_double(int
               h,
               int l,
               int s,
               int* r,
               int* g,
               int* b) noexcept
{
    const int hs = ((h + 240) / 60) % 6;
    const double lv = l / 100.0;
    const double sv = s / 100.0;
    double c, x, m, c2;
    double r1, g1, b1;

    if (s == 0) {
            *r = *g = *b = (short) (lv * 255. + 0.5);
        return;
    }

    c2 = (2.0 * lv) - 1.0;
    if (c2 < 0.0)
        c2 = -c2;
    c = (1.0 - c2) * sv;
    x = (hs & 1) ? c : 0.0;
    m = lv - 0.5 * c;

    switch (hs) {
    case 0:
        r1 = c;
        g1 = x;
        b1 = 0.0;
        break;
    case 1:
        r1 = x;
        g1 = c;
        b1 = 0.0;
        break;
    case 2:
        r1 = 0.0;
        g1 = c;
        b1 = x;
        break;
    case 3:
        r1 = 0.0;
        g1 = x;
        b1 = c;
        break;
    case 4:
        r1 = x;
        g1 = 0.0;
        b1 = c;
        break;
    case 5:
        r1 = c;
        g1 = 0.0;
        b1 = x;
        break;
    default:
        *r = (short) 255;
        *g = (short) 255;
        *b = (short) 255;
        return;
    }

    *r = (short) ((r1 + m) * 255.0 + 0.5);
    *g = (short) ((g1 + m) * 255.0 + 0.5);
    *b = (short) ((b1 + m) * 255.0 + 0.5);

    if (*r < 0)
        *r = 0;
    else if (*r > 255)
        *r = 255;
    if (*g < 0)
        *g = 0;
    else if (*g > 255)
        *g = 255;
    if (*b < 0)
        *b = 0;
    else if (*b > 255)
        *b = 255;
}

/* This is essentially Context::make_color_hls from sixel-context.cc,
 * only changed to return the colour components separately.
 */
static void
hls2rgb_int(int h,
            int l,
            int s,
            int* r,
            int* g,
            int* b) noexcept
{
        auto const c2p = std::abs(2 * l - 100);
        auto const cp = ((100 - c2p) * s) << 1;
        auto const hs = ((h + 240) / 60) % 6;
        auto const xp = (hs & 1) ? cp : 0;
        auto const mp = 200 * l - (cp >> 1);

        int r1p, g1p, b1p;
        switch (hs) {
        case 0:
                r1p = cp;
                g1p = xp;
                b1p = 0;
                break;
        case 1:
                r1p = xp;
                g1p = cp;
                b1p = 0;
                break;
        case 2:
                r1p = 0;
                g1p = cp;
                b1p = xp;
                break;
        case 3:
                r1p = 0;
                g1p = xp;
                b1p = cp;
                break;
        case 4:
                r1p = xp;
                g1p = 0;
                b1p = cp;
                break;
        case 5:
                r1p = cp;
                g1p = 0;
                b1p = xp;
                break;
        default:
                __builtin_unreachable();
        }

        *r = ((r1p + mp) * 255 + 10000) / 20000;
        *g = ((g1p + mp) * 255 + 10000) / 20000;
        *b = ((b1p + mp) * 255 + 10000) / 20000;
}

/* END */

static void
test_context_color_hls(void)
{
        /* Test that our HLS colour conversion gives the right results
         * by comparing it against the xterm/libsixel implementation.
         *
         * The values may differ by 1, which happen only for (L, S) in
         * {(5, 100), (40, 75), (50, 80), (60, 75), (75, 60), (95, 100)}.
         * There, one or more of the R, G, B components' unscaled values,
         * times 255, produces an exact fraction of .5 in hsl2rgb_double,
         * which, plus 0.5,, and due to inexactness, result in the truncated
         * value "(short)v" being one less than the result of the integer
         * computation.
         */

        for (auto h = 0; h <= 360; ++h) {
                for (auto l = 0; l <= 100; ++l) {
                        for (auto s = 0; s <= 100; ++s) {
                                int rd, gd, bd, ri, gi, bi;

                                hls2rgb_double(h, l, s, &rd, &gd, &bd);
                                hls2rgb_int(h, l, s, &ri, &gi, &bi);

                                g_assert_true((rd == ri || (rd + 1) == ri) &&
                                              (gd == gi || (gd + 1) == gi) &&
                                              (bd == bi || (bd + 1) == bi));
                        }
                }
        }
}

template<class C>
static void
assert_image_dimensions(C& context,
                        unsigned width,
                        unsigned height,
                        int line = __builtin_LINE())
{
        g_assert_cmpuint(context.image_width(), ==, width);
        g_assert_cmpuint(context.image_height(), ==, height);
}

static void
test_context_raster_attributes(void)
{
        /* Test that DECGRA sets the image dimensions */

        auto context = TestContext{};
        parse_image(context, "\"0;0;64;128"sv);
        assert_image_dimensions(context, 64, 128);
}

static void
test_context_repeat(void)
{
        /* Test that DECGRI repetition works */

        auto context = TestContext{};
        auto [pixels, size] = parse_pixels(context, "#1!5@"sv);
        assert_image_dimensions(context, 5, 1);

        auto data = pixels.get();
        auto const v = *data++;
        for (auto x = 1u; x < context.image_width(); ++x)
                g_assert_cmpuint(*data++, ==, v);

        g_assert_cmpuint(size_t(data - pixels.get()), <=, size);
}

static void
test_context_scanlines_grow(void)
{
        /* Test that scanlines grow on demand */

        auto context = TestContext{};
        parse_image(context, "@$AA$?$??~-~"sv);
        assert_image_dimensions(context, 3, 12);
}

static void
test_context_scanlines_underfull(void)
{
        /* Test that the image height is determined by the last set sixel, not
         * necessarily the number of scanlines.
         */

        auto context = TestContext{};

        parse_image(context, "?"sv);
        assert_image_dimensions(context, 1, 0);

        for (auto n = 0; n < 6; ++n) {
                parse_image(context, {Sixel(1u << n)});
                assert_image_dimensions(context, 1, n + 1);

                parse_image(context, {Sixel(0), Sixel(0), DECGNL(), Sixel(1u << n)});
                assert_image_dimensions(context, 2, 6 + n + 1);
        }
}

static void
test_context_scanlines_max_width(void)
{
        /* Test that scanlines up to max_width() work, and scanlines longer than that
         * are accepted but do not write outside the maximum width.
         */

        auto context = TestContext{};

        parse_image(context, {Sixel(1u << 0), DECGNL(), DECGRI(context.max_width() - 1), Sixel(0x3f)});
        assert_image_dimensions(context, context.max_width() - 1, 12);

        parse_image(context, {Sixel(1u << 0), DECGNL(), DECGRI(context.max_width()), Sixel(0x3f)});
        assert_image_dimensions(context, context.max_width(), 12);

        parse_image(context, {Sixel(1u << 0), DECGNL(), DECGRI(context.max_width() + 1), Sixel(0x3f)});
        assert_image_dimensions(context, context.max_width(), 12);
}

static void
test_context_scanlines_max_height(void)
{
        /* Test that scanlines up to max_height() work, and scanlines beyond that
         * are accepted but do nothing.
         */

        auto context = TestContext{};

        auto items = ItemList{};
        for (auto n = 0u; n < (context.max_height() / 6 - 1); ++n) {
                if (n > 0)
                        items.emplace_back(DECGNL());
                items.emplace_back(Sixel(1u << 5));
        }

        parse_image(context, items);
        assert_image_dimensions(context, 1, context.max_height() - 6);

        items.emplace_back(DECGNL());
        items.emplace_back(Sixel(1u << 4));

        parse_image(context, items);
        assert_image_dimensions(context, 1, context.max_height() - 1);

        items.emplace_back(DECGCR());
        items.emplace_back(Sixel(1u << 5));

        parse_image(context, items);
        assert_image_dimensions(context, 1, context.max_height());

        /* Image cannot grow further */

        items.emplace_back(DECGNL());
        items.emplace_back(Sixel(1u << 0));

        parse_image(context, items);
        assert_image_dimensions(context, 1, context.max_height());

        items.emplace_back(DECGNL());
        items.emplace_back(Sixel(1u << 5));

        parse_image(context, items);
        assert_image_dimensions(context, 1, context.max_height());
}

static void
test_context_image_stride(void)
{
        /* Test that data in the stride padding is set to background */

        auto context = TestContext{};

        auto const extra_stride = 3u;
        auto [pixels, size] = parse_pixels(context, "#1~~-~~"sv, extra_stride);
        assert_image_dimensions(context, 2, 12);

        auto data = pixels.get();
        auto const reg = param_to_color_register(1);

        for (auto y = 0u; y < context.image_height(); ++y) {
                for (auto x = 0u; x < context.image_width(); ++x)
                        g_assert_cmpuint(*data++, ==, unsigned(reg));
                for (auto e = 0u; e < extra_stride; ++e)
                        g_assert_cmpuint(*data++, ==, 0);
        }

        g_assert_cmpuint(size_t(data - pixels.get()), <=, size);
}

class RGB {
public:
        uint8_t r{0};
        uint8_t g{0};
        uint8_t b{0};

        RGB() = default;
        ~RGB() = default;

        RGB(int rv, int gv, int bv)
                : r(rv), g(gv), b(bv)
        {
        }
};

static void
test_context_image_palette(void)
{
        /* Test that the colour palette is recognised, and that colour registers
         * wrap around.
         */

        auto make_color_rgb = [](unsigned rp,
                                 unsigned gp,
                                 unsigned bp) constexpr noexcept -> auto
        {
                auto scale = [](unsigned value) constexpr noexcept -> auto
                {
                        return (value * 255u + 50u) / 100u;
                };

                auto make_color = [](unsigned r,
                                     unsigned g,
                                     unsigned b) constexpr noexcept -> Context::color_t
                {
                        if constexpr (std::endian::native == std::endian::little) {
                                return b | g << 8 | r << 16 | 0xffu << 24 /* opaque */;
                        } else if constexpr (std::endian::native == std::endian::big) {
                                return 0xffu /* opaque */ | r << 8 | g << 16 | b << 24;
                        } else {
                                __builtin_unreachable();
                        }
                };

                return make_color(scale(rp), scale(gp), scale(bp));
        };

        auto context = TestContext{};

        std::array<RGB, context.num_colors()> palette;
        for (auto& p : palette) {
                p = RGB(g_test_rand_int_range(0, 100),
                        g_test_rand_int_range(0, 100),
                        g_test_rand_int_range(0, 100));
        }

        auto items = ItemList{};
        auto reg = context.num_colors();
        for (auto const& p : palette) {
                items.emplace_back(DECGCI_RGB(reg++, p.r, p.g, p.b));
        }

        parse_image(context, items);

        for (auto n = 0; n < context.num_colors(); ++n) {
                g_assert_cmpuint(make_color_rgb(palette[n].r, palette[n].g, palette[n].b),
                                 ==,
                                 context.color(param_to_color_register(n)));
        }
}

static void
test_context_image_compositing(void)
{
        /* Test that multiple sixels in different colours are composited. */

        auto context = TestContext{};

        auto [pixels, size] = parse_pixels(context,
                                           "#256!24F$#257!24w-#258!24F$#259!24w-#260!24F$#261!24w"sv);

        auto data = pixels.get();
        for (auto y = 0u; y < context.image_height(); ++y) {
                auto const reg = param_to_color_register((256 + y / 3));
                for (auto x = 0u; x < context.image_width(); ++x)
                        g_assert_cmpuint(*data++, ==, reg);
        }


        g_assert_cmpuint(size_t(data - pixels.get()), <=, size);
}

// Main

int
main(int argc,
     char* argv[])
{
        g_test_init(&argc, &argv, nullptr);

        g_test_add_func("/vte/sixel/parser/sequences/parameters", test_parser_seq_params);
        g_test_add_func("/vte/sixel/parser/sequences/subparameters", test_parser_seq_subparams);
        g_test_add_func("/vte/sixel/parser/sequences/parameters-clear", test_parser_seq_params_clear);
        g_test_add_func("/vte/sixel/parser/sequences/parameters-max", test_parser_seq_params_max);
        g_test_add_func("/vte/sixel/parser/sequences/glue/arg", test_parser_seq_glue_arg);
        g_test_add_func("/vte/sixel/parser/st", test_parser_st);
        g_test_add_func("/vte/sixel/parser/controls/c0/escape", test_parser_controls_c0_esc);
        g_test_add_func("/vte/sixel/parser/controls/c0/can", test_parser_controls_c0_can);
        g_test_add_func("/vte/sixel/parser/controls/c0/sub", test_parser_controls_c0_sub);
        g_test_add_func("/vte/sixel/parser/controls/c0/ignored", test_parser_controls_c0_ignored);
        g_test_add_func("/vte/sixel/parser/controls/del", test_parser_controls_del);
        g_test_add_func("/vte/sixel/parser/controls/c1", test_parser_controls_c1);
        g_test_add_func("/vte/sixel/context/color/hls", test_context_color_hls);
        g_test_add_func("/vte/sixel/context/raster-attributes", test_context_raster_attributes);
        g_test_add_func("/vte/sixel/context/repeat", test_context_repeat);
        g_test_add_func("/vte/sixel/context/scanlines/grow", test_context_scanlines_grow);
        g_test_add_func("/vte/sixel/context/scanlines/underfull", test_context_scanlines_underfull);
        g_test_add_func("/vte/sixel/context/scanlines/max-width", test_context_scanlines_max_width);
        g_test_add_func("/vte/sixel/context/scanlines/max-height", test_context_scanlines_max_height);
        g_test_add_func("/vte/sixel/context/image/stride", test_context_image_stride);
        g_test_add_func("/vte/sixel/context/image/palette", test_context_image_palette);
        g_test_add_func("/vte/sixel/context/image/compositing", test_context_image_compositing);

        return g_test_run();
}