summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibVT/Terminal.cpp
blob: 5d3700d603ed8ea6d1bfb7ad49587eb02f8a8907 (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
/*
 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
 * Copyright (c) 2021, Daniel Bertalan <dani@danielbertalan.dev>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "Terminal.h"
#include <AK/Debug.h>
#include <AK/StringBuilder.h>
#include <AK/StringView.h>
#include <LibVT/Color.h>
#include <LibVT/Terminal.h>
#ifdef KERNEL
#    include <Kernel/TTY/VirtualConsole.h>
#endif

namespace VT {

#ifndef KERNEL
Terminal::Terminal(TerminalClient& client)
#else
Terminal::Terminal(Kernel::VirtualConsole& client)
#endif
    : m_client(client)
    , m_parser(*this)
{
}

#ifndef KERNEL
void Terminal::clear()
{
    for (size_t i = 0; i < rows(); ++i)
        active_buffer()[i].clear(m_current_state.attribute);
    set_cursor(0, 0);
}

void Terminal::clear_including_history()
{
    m_history.clear();
    m_history_start = 0;

    clear();

    m_client.terminal_history_changed();
}
#endif

void Terminal::alter_mode(bool should_set, Parameters params, Intermediates intermediates)
{
    auto steady_cursor_to_blinking = [](CursorStyle style) {
        switch (style) {
        case SteadyBar:
            return BlinkingBar;
        case SteadyBlock:
            return BlinkingBlock;
        case SteadyUnderline:
            return BlinkingUnderline;
        default:
            return style;
        }
    };

    auto blinking_cursor_to_steady = [](CursorStyle style) {
        switch (style) {
        case BlinkingBar:
            return SteadyBar;
        case BlinkingBlock:
            return SteadyBlock;
        case BlinkingUnderline:
            return SteadyUnderline;
        default:
            return style;
        }
    };

    if (intermediates.size() > 0 && intermediates[0] == '?') {
        for (auto mode : params) {
            switch (mode) {
            case 3: {
                // 80/132-column mode (DECCOLM)
                unsigned new_columns = should_set ? 132 : 80;
                dbgln_if(TERMINAL_DEBUG, "Setting {}-column mode", new_columns);
                set_size(new_columns, rows());
                clear();
                break;
            }
            case 12:
                if (should_set) {
                    // Start blinking cursor
                    m_cursor_style = steady_cursor_to_blinking(m_cursor_style);
                } else {
                    // Stop blinking cursor
                    m_cursor_style = blinking_cursor_to_steady(m_cursor_style);
                }
                m_client.set_cursor_style(m_cursor_style);
                break;
            case 25:
                if (should_set) {
                    // Show cursor
                    m_cursor_style = m_saved_cursor_style;
                    m_client.set_cursor_style(m_cursor_style);
                } else {
                    // Hide cursor
                    m_saved_cursor_style = m_cursor_style;
                    m_cursor_style = None;
                    m_client.set_cursor_style(None);
                }
                break;
            case 1047:
#ifndef KERNEL
                if (should_set) {
                    dbgln_if(TERMINAL_DEBUG, "Switching to Alternate Screen Buffer");
                    m_use_alternate_screen_buffer = true;
                    clear();
                } else {
                    dbgln_if(TERMINAL_DEBUG, "Switching to Normal Screen Buffer");
                    m_use_alternate_screen_buffer = false;
                }
                m_need_full_flush = true;
#else
                dbgln("Alternate Screen Buffer is not supported");
#endif
                break;
            case 1048:
                if (should_set)
                    SCOSC();
                else
                    SCORC();
                break;
            case 1049:
#ifndef KERNEL
                if (should_set) {
                    dbgln_if(TERMINAL_DEBUG, "Switching to Alternate Screen Buffer and saving state");
                    m_normal_saved_state = m_current_state;
                    m_use_alternate_screen_buffer = true;
                    clear();
                } else {
                    dbgln_if(TERMINAL_DEBUG, "Switching to Normal Screen Buffer and restoring state");
                    m_current_state = m_normal_saved_state;
                    m_use_alternate_screen_buffer = false;
                    set_cursor(cursor_row(), cursor_column());
                }
                m_need_full_flush = true;
#else
                dbgln("Alternate Screen Buffer is not supported");
#endif
                break;
            case 2004:
                dbgln_if(TERMINAL_DEBUG, "Setting bracketed mode enabled={}", should_set);
                m_needs_bracketed_paste = should_set;
                break;
            default:
                dbgln("Terminal::alter_mode: Unimplemented private mode {} (should_set={})", mode, should_set);
                break;
            }
        }
    } else {
        for (auto mode : params) {
            switch (mode) {
            // FIXME: implement *something* for this
            default:
                dbgln("Terminal::alter_mode: Unimplemented mode {} (should_set={})", mode, should_set);
                break;
            }
        }
    }
}

void Terminal::RM(Parameters params, Intermediates intermediates)
{
    alter_mode(false, params, intermediates);
}

void Terminal::SM(Parameters params, Intermediates intermediates)
{
    alter_mode(true, params, intermediates);
}

void Terminal::SGR(Parameters params)
{
    if (params.is_empty()) {
        m_current_state.attribute.reset();
        return;
    }
    auto parse_color = [&]() -> Optional<Color> {
        if (params.size() < 2) {
            dbgln("Color code has no type");
            return {};
        }
        u32 rgb = 0;
        switch (params[1]) {
        case 5: // 8-bit
            if (params.size() < 3) {
                dbgln("8-bit color code has too few parameters");
                return {};
            }
            if (params[2] > 255) {
                dbgln("8-bit color code has out-of-bounds value");
                return {};
            }
            return Color::indexed(params[2]);
        case 2: // 24-bit
            if (params.size() < 5) {
                dbgln("24-bit color code has too few parameters");
                return {};
            }
            for (size_t i = 0; i < 3; ++i) {
                rgb <<= 8;
                rgb |= params[i + 2];
            }
            return Color::rgb(rgb);
        default:
            dbgln("Unknown color type {}", params[1]);
            return {};
        }
    };

    if (params[0] == 38) {
        m_current_state.attribute.foreground_color = parse_color().value_or(m_current_state.attribute.foreground_color);
    } else if (params[0] == 48) {
        m_current_state.attribute.background_color = parse_color().value_or(m_current_state.attribute.background_color);
    } else {
        // A single escape sequence may set multiple parameters.
        for (auto param : params) {
            switch (param) {
            case 0:
                // Reset
                m_current_state.attribute.reset();
                break;
            case 1:
                m_current_state.attribute.flags |= Attribute::Bold;
                break;
            case 3:
                m_current_state.attribute.flags |= Attribute::Italic;
                break;
            case 4:
                m_current_state.attribute.flags |= Attribute::Underline;
                break;
            case 5:
                m_current_state.attribute.flags |= Attribute::Blink;
                break;
            case 7:
                m_current_state.attribute.flags |= Attribute::Negative;
                break;
            case 22:
                m_current_state.attribute.flags &= ~Attribute::Bold;
                break;
            case 23:
                m_current_state.attribute.flags &= ~Attribute::Italic;
                break;
            case 24:
                m_current_state.attribute.flags &= ~Attribute::Underline;
                break;
            case 25:
                m_current_state.attribute.flags &= ~Attribute::Blink;
                break;
            case 27:
                m_current_state.attribute.flags &= ~Attribute::Negative;
                break;
            case 30:
            case 31:
            case 32:
            case 33:
            case 34:
            case 35:
            case 36:
            case 37:
                // Foreground color
                m_current_state.attribute.foreground_color = Color::named(static_cast<Color::ANSIColor>(param - 30));
                break;
            case 39:
                // reset foreground
                m_current_state.attribute.foreground_color = Attribute::default_foreground_color;
                break;
            case 40:
            case 41:
            case 42:
            case 43:
            case 44:
            case 45:
            case 46:
            case 47:
                // Background color
                m_current_state.attribute.background_color = Color::named(static_cast<Color::ANSIColor>(param - 40));
                break;
            case 49:
                // reset background
                m_current_state.attribute.background_color = Attribute::default_background_color;
                break;
            case 90:
            case 91:
            case 92:
            case 93:
            case 94:
            case 95:
            case 96:
            case 97:
                // Bright foreground color
                m_current_state.attribute.foreground_color = Color::named(static_cast<Color::ANSIColor>(8 + param - 90));
                break;
            case 100:
            case 101:
            case 102:
            case 103:
            case 104:
            case 105:
            case 106:
            case 107:
                // Bright background color
                m_current_state.attribute.background_color = Color::named(static_cast<Color::ANSIColor>(8 + param - 100));
                break;
            default:
                dbgln("FIXME: SGR: p: {}", param);
            }
        }
    }
}

void Terminal::SCOSC()
{
    dbgln_if(TERMINAL_DEBUG, "Save cursor position");
    m_saved_cursor_position = m_current_state.cursor;
}

void Terminal::SCORC()
{
    dbgln_if(TERMINAL_DEBUG, "Restore cursor position");
    m_current_state.cursor = m_saved_cursor_position;
    set_cursor(cursor_row(), cursor_column());
}

void Terminal::DECSC()
{
    dbgln_if(TERMINAL_DEBUG, "Save cursor (and other state)");
    if (m_use_alternate_screen_buffer) {
        m_alternate_saved_state = m_current_state;
    } else {
        m_normal_saved_state = m_current_state;
    }
}

void Terminal::DECRC()
{
    dbgln_if(TERMINAL_DEBUG, "Restore cursor (and other state)");
    if (m_use_alternate_screen_buffer) {
        m_current_state = m_alternate_saved_state;
    } else {
        m_current_state = m_normal_saved_state;
    }
    set_cursor(cursor_row(), cursor_column());
}

void Terminal::XTERM_WM(Parameters params)
{
    if (params.size() < 1)
        return;
    switch (params[0]) {
    case 22: {
        if (params.size() > 1 && params[1] == 1) {
            dbgln("FIXME: we don't support icon titles");
            return;
        }
        dbgln_if(TERMINAL_DEBUG, "Title stack push: {}", m_current_window_title);
        [[maybe_unused]] auto rc = m_title_stack.try_append(move(m_current_window_title));
        break;
    }
    case 23: {
        if (params.size() > 1 && params[1] == 1)
            return;
        if (m_title_stack.is_empty()) {
            dbgln("Shenanigans: Tried to pop from empty title stack");
            return;
        }
        m_current_window_title = m_title_stack.take_last();
        dbgln_if(TERMINAL_DEBUG, "Title stack pop: {}", m_current_window_title);
        m_client.set_window_title(m_current_window_title);
        break;
    }
    default:
        dbgln("FIXME: XTERM_WM: Ps: {} (param count: {})", params[0], params.size());
    }
}

void Terminal::DECSTBM(Parameters params)
{
    unsigned top = 1;
    unsigned bottom = m_rows;
    if (params.size() >= 1 && params[0] != 0)
        top = params[0];
    if (params.size() >= 2 && params[1] != 0)
        bottom = params[1];
    if ((bottom - top) < 2 || bottom > m_rows) {
        dbgln("Error: DECSTBM: scrolling region invalid: {}-{}", top, bottom);
        return;
    }
    m_scroll_region_top = top - 1;
    m_scroll_region_bottom = bottom - 1;
    set_cursor(0, 0);
    dbgln_if(TERMINAL_DEBUG, "Set scrolling region: {}-{}", m_scroll_region_top, m_scroll_region_bottom);
}

void Terminal::CUP(Parameters params)
{
    // CUP – Cursor Position
    unsigned row = 1;
    unsigned col = 1;
    if (params.size() >= 1 && params[0] != 0)
        row = params[0];
    if (params.size() >= 2 && params[1] != 0)
        col = params[1];
    set_cursor(row - 1, col - 1);
}

void Terminal::HVP(Parameters params)
{
    unsigned row = 1;
    unsigned col = 1;
    if (params.size() >= 1 && params[0] != 0)
        row = params[0];
    if (params.size() >= 2 && params[1] != 0)
        col = params[1];
    set_cursor(row - 1, col - 1);
}

void Terminal::CUU(Parameters params)
{
    unsigned num = 1;
    if (params.size() >= 1 && params[0] != 0)
        num = params[0];
    int new_row = cursor_row() - num;
    if (new_row < 0)
        new_row = 0;
    set_cursor(new_row, cursor_column());
}

void Terminal::CUD(Parameters params)
{
    unsigned num = 1;
    if (params.size() >= 1 && params[0] != 0)
        num = params[0];
    unsigned new_row = cursor_row() + num;
    if (new_row >= m_rows)
        new_row = m_rows - 1;
    set_cursor(new_row, cursor_column());
}

void Terminal::CUF(Parameters params)
{
    unsigned num = 1;
    if (params.size() >= 1 && params[0] != 0)
        num = params[0];
    unsigned new_column = cursor_column() + num;
    if (new_column >= m_columns)
        new_column = m_columns - 1;
    set_cursor(cursor_row(), new_column);
}

void Terminal::CUB(Parameters params)
{
    unsigned num = 1;
    if (params.size() >= 1 && params[0] != 0)
        num = params[0];
    int new_column = (int)cursor_column() - num;
    if (new_column < 0)
        new_column = 0;
    set_cursor(cursor_row(), new_column);
}

void Terminal::CNL(Parameters params)
{
    unsigned num = 1;
    if (params.size() >= 1 && params[0] != 0)
        num = params[0];
    unsigned new_row = cursor_row() + num;
    if (new_row >= m_columns)
        new_row = m_columns - 1;
    set_cursor(new_row, 0);
}

void Terminal::CPL(Parameters params)
{
    unsigned num = 1;
    if (params.size() >= 1 && params[0] != 0)
        num = params[0];
    int new_row = (int)cursor_row() - num;
    if (new_row < 0)
        new_row = 0;
    set_cursor(new_row, 0);
}

void Terminal::CHA(Parameters params)
{
    unsigned new_column = 1;
    if (params.size() >= 1 && params[0] != 0)
        new_column = params[0];
    if (new_column > m_columns)
        new_column = m_columns;
    set_cursor(cursor_row(), new_column - 1);
}

void Terminal::REP(Parameters params)
{
    unsigned count = 1;
    if (params.size() >= 1 && params[0] != 0)
        count = params[0];

    for (unsigned i = 0; i < count; ++i)
        put_character_at(m_current_state.cursor.row, m_current_state.cursor.column++, m_last_code_point);
}

void Terminal::VPA(Parameters params)
{
    unsigned new_row = 1;
    if (params.size() >= 1 && params[0] != 0)
        new_row = params[0];
    if (new_row > m_rows)
        new_row = m_rows;
    set_cursor(new_row - 1, cursor_column());
}

void Terminal::VPR(Parameters params)
{
    unsigned num = 1;
    if (params.size() >= 1 && params[0] != 0)
        num = params[0];
    int new_row = cursor_row() + num;
    if (new_row >= m_rows)
        new_row = m_rows - 1;
    set_cursor(new_row, cursor_column());
}

void Terminal::HPA(Parameters params)
{
    unsigned new_column = 1;
    if (params.size() >= 1 && params[0] != 0)
        new_column = params[0];
    if (new_column > m_columns)
        new_column = m_columns;
    set_cursor(cursor_row(), new_column - 1);
}

void Terminal::HPR(Parameters params)
{
    unsigned num = 1;
    if (params.size() >= 1 && params[0] != 0)
        num = params[0];
    unsigned new_column = cursor_column() + num;
    if (new_column >= m_columns)
        new_column = m_columns - 1;
    set_cursor(cursor_row(), new_column);
}

void Terminal::ECH(Parameters params)
{
    // Erase characters (without moving cursor)
    unsigned num = 1;
    if (params.size() >= 1 && params[0] != 0)
        num = params[0];
    // Clear from cursor to end of line.
    for (unsigned i = cursor_column(); i < num; ++i) {
        put_character_at(cursor_row(), i, ' ');
    }
}

void Terminal::EL(Parameters params)
{
    unsigned mode = 0;
    if (params.size() >= 1)
        mode = params[0];
    switch (mode) {
    case 0:
        // Clear from cursor to end of line.
        for (int i = cursor_column(); i < m_columns; ++i) {
            put_character_at(cursor_row(), i, ' ');
        }
        break;
    case 1:
        // Clear from cursor to beginning of line.
        for (int i = 0; i <= cursor_column(); ++i) {
            put_character_at(cursor_row(), i, ' ');
        }
        break;
    case 2:
        // Clear the complete line
        for (int i = 0; i < m_columns; ++i) {
            put_character_at(cursor_row(), i, ' ');
        }
        break;
    default:
        unimplemented_csi_sequence(params, {}, 'K');
        break;
    }
}

void Terminal::ED(Parameters params)
{
    unsigned mode = 0;
    if (params.size() >= 1)
        mode = params[0];
    switch (mode) {
    case 0:
        // Clear from cursor to end of screen.
        for (int i = cursor_column(); i < m_columns; ++i)
            put_character_at(cursor_row(), i, ' ');
        for (int row = cursor_row() + 1; row < m_rows; ++row) {
            for (int column = 0; column < m_columns; ++column) {
                put_character_at(row, column, ' ');
            }
        }
        break;
    case 1:
        // Clear from cursor to beginning of screen.
        for (int i = cursor_column(); i >= 0; --i)
            put_character_at(cursor_row(), i, ' ');
        for (int row = cursor_row() - 1; row >= 0; --row) {
            for (int column = 0; column < m_columns; ++column) {
                put_character_at(row, column, ' ');
            }
        }
        break;
    case 2:
        clear();
        break;
    case 3:
        // FIXME: <esc>[3J should also clear the scrollback buffer.
        clear();
        break;
    default:
        unimplemented_csi_sequence(params, {}, 'J');
        break;
    }
}

void Terminal::SU(Parameters params)
{
    unsigned count = 1;
    if (params.size() >= 1 && params[0] != 0)
        count = params[0];

    for (u16 i = 0; i < count; i++)
        scroll_up();
}

void Terminal::SD(Parameters params)
{
    unsigned count = 1;
    if (params.size() >= 1 && params[0] != 0)
        count = params[0];

    for (u16 i = 0; i < count; i++)
        scroll_down();
}

void Terminal::DECSCUSR(Parameters params)
{
    unsigned style = 1;
    if (params.size() >= 1 && params[0] != 0)
        style = params[0];
    switch (style) {
    case 1:
        m_client.set_cursor_style(BlinkingBlock);
        break;
    case 2:
        m_client.set_cursor_style(SteadyBlock);
        break;
    case 3:
        m_client.set_cursor_style(BlinkingUnderline);
        break;
    case 4:
        m_client.set_cursor_style(SteadyUnderline);
        break;
    case 5:
        m_client.set_cursor_style(BlinkingBar);
        break;
    case 6:
        m_client.set_cursor_style(SteadyBar);
        break;
    default:
        dbgln("Unknown cursor style {}", style);
    }
}

#ifndef KERNEL
void Terminal::IL(Parameters params)
{
    unsigned count = 1;
    if (params.size() >= 1 && params[0] != 0)
        count = params[0];
    invalidate_cursor();
    for (; count > 0; --count) {
        active_buffer().insert(cursor_row(), make<Line>(m_columns));
        if (m_scroll_region_bottom + 1 < active_buffer().size())
            active_buffer().remove(m_scroll_region_bottom + 1);
        else
            active_buffer().remove(active_buffer().size() - 1);
    }

    m_need_full_flush = true;
}
#endif

void Terminal::DA(Parameters)
{
    emit_string("\033[?1;0c");
}

#ifndef KERNEL
void Terminal::DL(Parameters params)
{
    int count = 1;
    if (params.size() >= 1 && params[0] != 0)
        count = params[0];

    if (count == 1 && cursor_row() == 0) {
        scroll_up();
        return;
    }

    int max_count = m_rows - (m_scroll_region_top + cursor_row());
    count = min(count, max_count);

    for (int c = count; c > 0; --c) {
        active_buffer().remove(cursor_row());
        if (m_scroll_region_bottom < active_buffer().size())
            active_buffer().insert(m_scroll_region_bottom, make<Line>(m_columns));
        else
            active_buffer().append(make<Line>(m_columns));
    }
}

void Terminal::DCH(Parameters params)
{
    int num = 1;
    if (params.size() >= 1 && params[0] != 0)
        num = params[0];

    auto& line = active_buffer()[cursor_row()];
    num = min(num, static_cast<int>(line.length()) - cursor_column());

    // Move n characters of line to the left
    for (size_t i = cursor_column(); i < line.length() - num; i++)
        line.cell_at(i) = line.cell_at(i + num);

    // Fill remainder of line with blanks
    for (size_t i = line.length() - num; i < line.length(); i++)
        line.set_code_point(i, ' ');

    line.set_dirty(true);
}
#endif

void Terminal::linefeed()
{
    u16 new_row = cursor_row();
    if (cursor_row() == m_scroll_region_bottom) {
        scroll_up();
    } else {
        ++new_row;
    };
    // We shouldn't jump to the first column after receiving a line feed.
    // The TTY will take care of generating the carriage return.
    set_cursor(new_row, cursor_column());
}

void Terminal::carriage_return()
{
    set_cursor(cursor_row(), 0);
}

#ifndef KERNEL
void Terminal::scroll_up()
{
    dbgln_if(TERMINAL_DEBUG, "Scroll up 1 line");
    // NOTE: We have to invalidate the cursor first.
    invalidate_cursor();
    if (m_scroll_region_top == 0 && !m_use_alternate_screen_buffer) {
        auto line = move(active_buffer().ptr_at(m_scroll_region_top));
        add_line_to_history(move(line));
        m_client.terminal_history_changed();
    }
    active_buffer().remove(m_scroll_region_top);
    active_buffer().insert(m_scroll_region_bottom, make<Line>(m_columns));
    m_need_full_flush = true;
}

void Terminal::scroll_down()
{
    dbgln_if(TERMINAL_DEBUG, "Scroll down 1 line");
    // NOTE: We have to invalidate the cursor first.
    invalidate_cursor();
    active_buffer().remove(m_scroll_region_bottom);
    active_buffer().insert(m_scroll_region_top, make<Line>(m_columns));
    m_need_full_flush = true;
}

void Terminal::put_character_at(unsigned row, unsigned column, u32 code_point)
{
    VERIFY(row < rows());
    VERIFY(column < columns());
    auto& line = active_buffer()[row];
    line.set_code_point(column, code_point);
    line.attribute_at(column) = m_current_state.attribute;
    line.attribute_at(column).flags |= Attribute::Touched;
    line.set_dirty(true);

    m_last_code_point = code_point;
}
#endif

void Terminal::set_cursor(unsigned a_row, unsigned a_column, bool skip_debug)
{
    unsigned row = min(a_row, m_rows - 1u);
    unsigned column = min(a_column, m_columns - 1u);
    if (row == cursor_row() && column == cursor_column())
        return;
    VERIFY(row < rows());
    VERIFY(column < columns());
    invalidate_cursor();
    m_current_state.cursor.row = row;
    m_current_state.cursor.column = column;
    m_stomp = false;
    invalidate_cursor();
    if (!skip_debug)
        dbgln_if(TERMINAL_DEBUG, "Set cursor position: {},{}", cursor_row(), cursor_column());
}

void Terminal::NEL()
{
    if (cursor_row() == m_scroll_region_bottom)
        scroll_up();
    else
        set_cursor(cursor_row() + 1, 0);
}

void Terminal::IND()
{
    // Not equivalent to CUD: if we are at the bottom margin, we have to scroll up.
    if (cursor_row() == m_scroll_region_bottom)
        scroll_up();
    else
        set_cursor(cursor_row() + 1, cursor_column());
}

void Terminal::RI()
{
    // Not equivalent to CUU : if we at the top margin , we have to scroll down.
    if (cursor_row() == m_scroll_region_top)
        scroll_down();
    else
        set_cursor(cursor_row() - 1, cursor_column());
}

void Terminal::DSR(Parameters params)
{
    if (params.size() == 1 && params[0] == 5) {
        // Device status
        emit_string("\033[0n"); // Terminal status OK!
    } else if (params.size() == 1 && params[0] == 6) {
        // Cursor position query
        emit_string(String::formatted("\e[{};{}R", cursor_row() + 1, cursor_column() + 1));
    } else {
        dbgln("Unknown DSR");
    }
}

#ifndef KERNEL
void Terminal::ICH(Parameters params)
{
    unsigned num = 1;
    if (params.size() >= 1 && params[0] != 0)
        num = params[0];
    auto& line = active_buffer()[cursor_row()];

    auto max_insert = static_cast<unsigned>(line.length()) - cursor_column();
    num = min(num, max_insert);
    // Move characters after cursor to the right
    for (int i = line.length() - num - 1; i >= cursor_column(); --i)
        line.cell_at(i + num) = line.cell_at(i);

    // Fill n characters after cursor with blanks
    for (unsigned i = 0; i < num; ++i)
        line.set_code_point(cursor_column() + i, ' ');

    line.set_dirty(true);
}
#endif

void Terminal::on_input(u8 byte)
{
    m_parser.on_input(byte);
}

void Terminal::emit_code_point(u32 code_point)
{
    auto new_column = cursor_column() + 1;
    if (new_column < columns()) {
        put_character_at(cursor_row(), cursor_column(), code_point);
        set_cursor(cursor_row(), new_column, true);
        return;
    }
    if (m_stomp) {
        m_stomp = false;
        carriage_return();
        linefeed();
        put_character_at(cursor_row(), cursor_column(), code_point);
        set_cursor(cursor_row(), 1);
    } else {
        // Curious: We wait once on the right-hand side
        m_stomp = true;
        put_character_at(cursor_row(), cursor_column(), code_point);
    }
}

void Terminal::execute_control_code(u8 code)
{
    switch (code) {
    case '\a':
        m_client.beep();
        return;
    case '\b':
        if (cursor_column()) {
            set_cursor(cursor_row(), cursor_column() - 1);
            return;
        }
        return;
    case '\t': {
        for (unsigned i = cursor_column() + 1; i < columns(); ++i) {
            if (m_horizontal_tabs[i]) {
                set_cursor(cursor_row(), i);
                return;
            }
        }
        return;
    }
    case '\n':
    case '\v':
    case '\f':
        linefeed();
        return;
    case '\r':
        carriage_return();
        return;
    default:
        unimplemented_control_code(code);
    }
}

void Terminal::execute_escape_sequence(Intermediates intermediates, bool ignore, u8 last_byte)
{
    // FIXME: Handle it somehow?
    if (ignore)
        dbgln("Escape sequence has its ignore flag set.");

    if (intermediates.size() == 0) {
        switch (last_byte) {
        case 'D':
            IND();
            return;
        case 'E':
            NEL();
            return;
        case 'M':
            RI();
            return;
        case '\\':
            // ST (string terminator) -- do nothing
            return;
        case '7':
            DECSC();
            return;
        case '8':
            DECRC();
            return;
        }
    } else if (intermediates[0] == '#') {
        switch (last_byte) {
        case '8':
            // Confidence Test - Fill screen with E's
            for (size_t row = 0; row < m_rows; ++row) {
                for (size_t column = 0; column < m_columns; ++column) {
                    put_character_at(row, column, 'E');
                }
            }
            return;
        }
    }
    unimplemented_escape_sequence(intermediates, last_byte);
}

void Terminal::execute_csi_sequence(Parameters parameters, Intermediates intermediates, bool ignore, u8 last_byte)
{
    // FIXME: Handle it somehow?
    if (ignore)
        dbgln("CSI sequence has its ignore flag set.");

    switch (last_byte) {
    case '@':
        ICH(parameters);
        break;
    case 'A':
        CUU(parameters);
        break;
    case 'B':
        CUD(parameters);
        break;
    case 'C':
        CUF(parameters);
        break;
    case 'D':
        CUB(parameters);
        break;
    case 'E':
        CNL(parameters);
        break;
    case 'F':
        CPL(parameters);
        break;
    case 'G':
        CHA(parameters);
        break;
    case 'H':
        CUP(parameters);
        break;
    case 'J':
        ED(parameters);
        break;
    case 'K':
        EL(parameters);
        break;
    case 'L':
        IL(parameters);
        break;
    case 'M':
        DL(parameters);
        break;
    case 'P':
        DCH(parameters);
        break;
    case 'S':
        SU(parameters);
        break;
    case 'T':
        SD(parameters);
        break;
    case 'X':
        ECH(parameters);
        break;
    case '`':
        HPA(parameters);
        break;
    case 'a':
        HPR(parameters);
        break;
    case 'b':
        REP(parameters);
        break;
    case 'c':
        DA(parameters);
        break;
    case 'd':
        VPA(parameters);
        break;
    case 'e':
        VPR(parameters);
        break;
    case 'f':
        HVP(parameters);
        break;
    case 'h':
        SM(parameters, intermediates);
        break;
    case 'l':
        RM(parameters, intermediates);
        break;
    case 'm':
        SGR(parameters);
        break;
    case 'n':
        DSR(parameters);
        break;
    case 'q':
        if (intermediates.size() >= 1 && intermediates[0] == ' ')
            DECSCUSR(parameters);
        else
            unimplemented_csi_sequence(parameters, intermediates, last_byte);
        break;
    case 'r':
        DECSTBM(parameters);
        break;
    case 's':
        SCOSC();
        break;
    case 't':
        XTERM_WM(parameters);
        break;
    case 'u':
        SCORC();
        break;
    default:
        unimplemented_csi_sequence(parameters, intermediates, last_byte);
    }
}

void Terminal::execute_osc_sequence(OscParameters parameters, u8 last_byte)
{
    auto stringview_ify = [&](size_t param_idx) {
        return StringView(parameters[param_idx]);
    };

    if (parameters.size() == 0 || parameters[0].is_empty()) {
        unimplemented_osc_sequence(parameters, last_byte);
        return;
    }

    auto command_number = stringview_ify(0).to_uint();
    if (!command_number.has_value()) {
        unimplemented_osc_sequence(parameters, last_byte);
        return;
    }

    switch (command_number.value()) {
    case 0:
    case 1:
    case 2:
        if (parameters.size() < 2) {
            dbgln("Attempted to set window title without any parameters");
        } else {
            // FIXME: the split breaks titles containing semicolons.
            // Should we expose the raw OSC string from the parser? Or join by semicolon?
            m_current_window_title = stringview_ify(1).to_string();
            m_client.set_window_title(m_current_window_title);
        }
        break;
    case 8:
#ifndef KERNEL
        if (parameters.size() < 3) {
            dbgln("Attempted to set href but gave too few parameters");
        } else if (parameters[1].is_empty() && parameters[2].is_empty()) {
            // Clear hyperlink
            m_current_state.attribute.href = String();
            m_current_state.attribute.href_id = String();
        } else {
            m_current_state.attribute.href = stringview_ify(2);
            // FIXME: Respect the provided ID
            m_current_state.attribute.href_id = String::number(m_next_href_id++);
        }
#endif
        break;
    case 9:
        if (parameters.size() < 2)
            dbgln("Atttempted to set window progress but gave too few parameters");
        else if (parameters.size() == 2)
            m_client.set_window_progress(stringview_ify(1).to_int().value_or(-1), 0);
        else
            m_client.set_window_progress(stringview_ify(1).to_int().value_or(-1), stringview_ify(2).to_int().value_or(0));
        break;
    default:
        unimplemented_osc_sequence(parameters, last_byte);
    }
}

void Terminal::dcs_hook(Parameters, Intermediates, bool, u8)
{
    dbgln("Received DCS parameters, but we don't support it yet");
}

void Terminal::receive_dcs_char(u8 byte)
{
    dbgln_if(TERMINAL_DEBUG, "DCS string character {:c}", byte);
}

void Terminal::execute_dcs_sequence()
{
}

void Terminal::inject_string(const StringView& str)
{
    for (size_t i = 0; i < str.length(); ++i)
        on_input(str[i]);
}

void Terminal::emit_string(const StringView& string)
{
    m_client.emit((const u8*)string.characters_without_null_termination(), string.length());
}

void Terminal::handle_key_press(KeyCode key, u32 code_point, u8 flags)
{
    bool ctrl = flags & Mod_Ctrl;
    bool alt = flags & Mod_Alt;
    bool shift = flags & Mod_Shift;
    unsigned modifier_mask = int(shift) + (int(alt) << 1) + (int(ctrl) << 2);

    auto emit_final_with_modifier = [this, modifier_mask](char final) {
        if (modifier_mask)
            emit_string(String::formatted("\e[1;{}{:c}", modifier_mask + 1, final));
        else
            emit_string(String::formatted("\e[{:c}", final));
    };
    auto emit_tilde_with_modifier = [this, modifier_mask](unsigned num) {
        if (modifier_mask)
            emit_string(String::formatted("\e[{};{}~", num, modifier_mask + 1));
        else
            emit_string(String::formatted("\e[{}~", num));
    };

    switch (key) {
    case KeyCode::Key_Up:
        emit_final_with_modifier('A');
        return;
    case KeyCode::Key_Down:
        emit_final_with_modifier('B');
        return;
    case KeyCode::Key_Right:
        emit_final_with_modifier('C');
        return;
    case KeyCode::Key_Left:
        emit_final_with_modifier('D');
        return;
    case KeyCode::Key_Insert:
        emit_tilde_with_modifier(2);
        return;
    case KeyCode::Key_Delete:
        emit_tilde_with_modifier(3);
        return;
    case KeyCode::Key_Home:
        emit_final_with_modifier('H');
        return;
    case KeyCode::Key_End:
        emit_final_with_modifier('F');
        return;
    case KeyCode::Key_PageUp:
        emit_tilde_with_modifier(5);
        return;
    case KeyCode::Key_PageDown:
        emit_tilde_with_modifier(6);
        return;
    case KeyCode::Key_Return:
        // The standard says that CR should be generated by the return key.
        // The TTY will take care of translating it to CR LF for the terminal.
        emit_string("\r");
        return;
    default:
        break;
    }

    if (!code_point) {
        // Probably a modifier being pressed.
        return;
    }

    if (shift && key == KeyCode::Key_Tab) {
        emit_string("\033[Z");
        return;
    }

    // Key event was not one of the above special cases,
    // attempt to treat it as a character...
    if (ctrl) {
        if (code_point >= 'a' && code_point <= 'z') {
            code_point = code_point - 'a' + 1;
        } else if (code_point == '\\') {
            code_point = 0x1c;
        }
    }

    // Alt modifier sends escape prefix.
    if (alt)
        emit_string("\033");

    StringBuilder sb;
    sb.append_code_point(code_point);

    emit_string(sb.to_string());
}

void Terminal::unimplemented_control_code(u8 code)
{
    dbgln("Unimplemented control code {:02x}", code);
}

void Terminal::unimplemented_escape_sequence(Intermediates intermediates, u8 last_byte)
{
    StringBuilder builder;
    builder.appendff("Unimplemented escape sequence {:c}", last_byte);
    if (!intermediates.is_empty()) {
        builder.append(", intermediates: ");
        for (size_t i = 0; i < intermediates.size(); ++i)
            builder.append((char)intermediates[i]);
    }
    dbgln("{}", builder.string_view());
}

void Terminal::unimplemented_csi_sequence(Parameters parameters, Intermediates intermediates, u8 last_byte)
{
    StringBuilder builder;
    builder.appendff("Unimplemented CSI sequence: {:c}", last_byte);
    if (!parameters.is_empty()) {
        builder.append(", parameters: [");
        for (size_t i = 0; i < parameters.size(); ++i)
            builder.appendff("{}{}", (i == 0) ? "" : ", ", parameters[i]);
        builder.append("]");
    }
    if (!intermediates.is_empty()) {
        builder.append(", intermediates:");
        for (size_t i = 0; i < intermediates.size(); ++i)
            builder.append((char)intermediates[i]);
    }
    dbgln("{}", builder.string_view());
}

void Terminal::unimplemented_osc_sequence(OscParameters parameters, u8 last_byte)
{
    StringBuilder builder;
    builder.appendff("Unimplemented OSC sequence parameters: (bel_terminated={}) [ ", last_byte == '\a');
    bool first = true;
    for (auto parameter : parameters) {
        if (!first)
            builder.append(", ");
        builder.append("[");
        for (auto character : parameter)
            builder.append((char)character);
        builder.append("]");
        first = false;
    }

    builder.append(" ]");
    dbgln("{}", builder.string_view());
}

#ifndef KERNEL
void Terminal::set_size(u16 columns, u16 rows)
{
    if (!columns)
        columns = 1;
    if (!rows)
        rows = 1;

    if (columns == m_columns && rows == m_rows)
        return;

    if (rows > m_rows) {
        while (m_normal_screen_buffer.size() < rows)
            m_normal_screen_buffer.append(make<Line>(columns));
        while (m_alternate_screen_buffer.size() < rows)
            m_alternate_screen_buffer.append(make<Line>(columns));
    } else {
        m_normal_screen_buffer.shrink(rows);
        m_alternate_screen_buffer.shrink(rows);
    }

    for (int i = 0; i < rows; ++i) {
        m_normal_screen_buffer[i].set_length(columns);
        m_alternate_screen_buffer[i].set_length(columns);
    }

    m_columns = columns;
    m_rows = rows;

    m_scroll_region_top = 0;
    m_scroll_region_bottom = rows - 1;

    m_current_state.cursor.clamp(m_rows - 1, m_columns - 1);
    m_normal_saved_state.cursor.clamp(m_rows - 1, m_columns - 1);
    m_alternate_saved_state.cursor.clamp(m_rows - 1, m_columns - 1);
    m_saved_cursor_position.clamp(m_rows - 1, m_columns - 1);

    m_horizontal_tabs.resize(columns);
    for (unsigned i = 0; i < columns; ++i)
        m_horizontal_tabs[i] = (i % 8) == 0;
    // Rightmost column is always last tab on line.
    m_horizontal_tabs[columns - 1] = 1;

    m_client.terminal_did_resize(m_columns, m_rows);

    dbgln_if(TERMINAL_DEBUG, "Set terminal size: {}x{}", m_rows, m_columns);
}
#endif

#ifndef KERNEL
void Terminal::invalidate_cursor()
{
    active_buffer()[cursor_row()].set_dirty(true);
}

Attribute Terminal::attribute_at(const Position& position) const
{
    if (!position.is_valid())
        return {};
    if (position.row() >= static_cast<int>(line_count()))
        return {};
    auto& line = this->line(position.row());
    if (static_cast<size_t>(position.column()) >= line.length())
        return {};
    return line.attribute_at(position.column());
}
#endif

}