forked from termux/termux-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TerminalEmulator.java
2797 lines (2632 loc) · 136 KB
/
TerminalEmulator.java
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
package com.termux.terminal;
import android.util.Base64;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import java.util.Objects;
import java.util.Stack;
/**
* Renders text into a screen. Contains all the terminal-specific knowledge and state. Emulates a subset of the X Window
* System xterm terminal, which in turn is an emulator for a subset of the Digital Equipment Corporation vt100 terminal.
* <p>
* References:
* <ul>
* <li>http://invisible-island.net/xterm/ctlseqs/ctlseqs.html</li>
* <li>http://en.wikipedia.org/wiki/ANSI_escape_code</li>
* <li>http://man.he.net/man4/console_codes</li>
* <li>http://bazaar.launchpad.net/~leonerd/libvterm/trunk/view/head:/src/state.c</li>
* <li>http://www.columbia.edu/~kermit/k95manual/iso2022.html</li>
* <li>http://www.vt100.net/docs/vt510-rm/chapter4</li>
* <li>http://en.wikipedia.org/wiki/ISO/IEC_2022 - for 7-bit and 8-bit GL GR explanation</li>
* <li>http://bjh21.me.uk/all-escapes/all-escapes.txt - extensive!</li>
* <li>http://woldlab.caltech.edu/~diane/kde4.10/workingdir/kubuntu/konsole/doc/developer/old-documents/VT100/techref.
* html - document for konsole - accessible!</li>
* </ul>
*/
public final class TerminalEmulator {
/** Log unknown or unimplemented escape sequences received from the shell process. */
private static final boolean LOG_ESCAPE_SEQUENCES = false;
public static final int MOUSE_LEFT_BUTTON = 0;
/** Mouse moving while having left mouse button pressed. */
public static final int MOUSE_LEFT_BUTTON_MOVED = 32;
public static final int MOUSE_WHEELUP_BUTTON = 64;
public static final int MOUSE_WHEELDOWN_BUTTON = 65;
/** Used for invalid data - http://en.wikipedia.org/wiki/Replacement_character#Replacement_character */
public static final int UNICODE_REPLACEMENT_CHAR = 0xFFFD;
/** Escape processing: Not currently in an escape sequence. */
private static final int ESC_NONE = 0;
/** Escape processing: Have seen an ESC character - proceed to {@link #doEsc(int)} */
private static final int ESC = 1;
/** Escape processing: Have seen ESC POUND */
private static final int ESC_POUND = 2;
/** Escape processing: Have seen ESC and a character-set-select ( char */
private static final int ESC_SELECT_LEFT_PAREN = 3;
/** Escape processing: Have seen ESC and a character-set-select ) char */
private static final int ESC_SELECT_RIGHT_PAREN = 4;
/** Escape processing: "ESC [" or CSI (Control Sequence Introducer). */
private static final int ESC_CSI = 6;
/** Escape processing: ESC [ ? */
private static final int ESC_CSI_QUESTIONMARK = 7;
/** Escape processing: ESC [ $ */
private static final int ESC_CSI_DOLLAR = 8;
/** Escape processing: ESC % */
private static final int ESC_PERCENT = 9;
/** Escape processing: ESC ] (AKA OSC - Operating System Controls) */
private static final int ESC_OSC = 10;
/** Escape processing: ESC ] (AKA OSC - Operating System Controls) ESC */
private static final int ESC_OSC_ESC = 11;
/** Escape processing: ESC [ > */
private static final int ESC_CSI_BIGGERTHAN = 12;
/** Escape procession: "ESC P" or Device Control String (DCS) */
private static final int ESC_P = 13;
/** Escape processing: CSI > */
private static final int ESC_CSI_QUESTIONMARK_ARG_DOLLAR = 14;
/** Escape processing: CSI $ARGS ' ' */
private static final int ESC_CSI_ARGS_SPACE = 15;
/** Escape processing: CSI $ARGS '*' */
private static final int ESC_CSI_ARGS_ASTERIX = 16;
/** Escape processing: CSI " */
private static final int ESC_CSI_DOUBLE_QUOTE = 17;
/** Escape processing: CSI ' */
private static final int ESC_CSI_SINGLE_QUOTE = 18;
/** Escape processing: CSI ! */
private static final int ESC_CSI_EXCLAMATION = 19;
/** Escape processing: APC */
private static final int ESC_APC = 20;
private static final int ESC_APC_ESC = 21;
/** The number of parameter arguments. This name comes from the ANSI standard for terminal escape codes. */
private static final int MAX_ESCAPE_PARAMETERS = 16;
/** Needs to be large enough to contain reasonable OSC 52 pastes. */
private static final int MAX_OSC_STRING_LENGTH = 8192;
/** DECSET 1 - application cursor keys. */
private static final int DECSET_BIT_APPLICATION_CURSOR_KEYS = 1;
private static final int DECSET_BIT_REVERSE_VIDEO = 1 << 1;
/**
* http://www.vt100.net/docs/vt510-rm/DECOM: "When DECOM is set, the home cursor position is at the upper-left
* corner of the screen, within the margins. The starting point for line numbers depends on the current top margin
* setting. The cursor cannot move outside of the margins. When DECOM is reset, the home cursor position is at the
* upper-left corner of the screen. The starting point for line numbers is independent of the margins. The cursor
* can move outside of the margins."
*/
private static final int DECSET_BIT_ORIGIN_MODE = 1 << 2;
/**
* http://www.vt100.net/docs/vt510-rm/DECAWM: "If the DECAWM function is set, then graphic characters received when
* the cursor is at the right border of the page appear at the beginning of the next line. Any text on the page
* scrolls up if the cursor is at the end of the scrolling region. If the DECAWM function is reset, then graphic
* characters received when the cursor is at the right border of the page replace characters already on the page."
*/
private static final int DECSET_BIT_AUTOWRAP = 1 << 3;
/** DECSET 25 - if the cursor should be enabled, {@link #isCursorEnabled()}. */
private static final int DECSET_BIT_CURSOR_ENABLED = 1 << 4;
private static final int DECSET_BIT_APPLICATION_KEYPAD = 1 << 5;
/** DECSET 1000 - if to report mouse press&release events. */
private static final int DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE = 1 << 6;
/** DECSET 1002 - like 1000, but report moving mouse while pressed. */
private static final int DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT = 1 << 7;
/** DECSET 1004 - NOT implemented. */
private static final int DECSET_BIT_SEND_FOCUS_EVENTS = 1 << 8;
/** DECSET 1006 - SGR-like mouse protocol (the modern sane choice). */
private static final int DECSET_BIT_MOUSE_PROTOCOL_SGR = 1 << 9;
/** DECSET 2004 - see {@link #paste(String)} */
private static final int DECSET_BIT_BRACKETED_PASTE_MODE = 1 << 10;
/** Toggled with DECLRMM - http://www.vt100.net/docs/vt510-rm/DECLRMM */
private static final int DECSET_BIT_LEFTRIGHT_MARGIN_MODE = 1 << 11;
/** Not really DECSET bit... - http://www.vt100.net/docs/vt510-rm/DECSACE */
private static final int DECSET_BIT_RECTANGULAR_CHANGEATTRIBUTE = 1 << 12;
private String mTitle;
private final Stack<String> mTitleStack = new Stack<>();
/** If processing first character of first parameter of {@link #ESC_CSI}. */
private boolean mIsCSIStart;
/** The last character processed of a parameter of {@link #ESC_CSI}. */
private Integer mLastCSIArg;
/** The cursor position. Between (0,0) and (mRows-1, mColumns-1). */
private int mCursorRow, mCursorCol;
/** The number of character rows and columns in the terminal screen. */
public int mRows, mColumns;
/** The number of terminal transcript rows that can be scrolled back to. */
public static final int TERMINAL_TRANSCRIPT_ROWS_MIN = 100;
public static final int TERMINAL_TRANSCRIPT_ROWS_MAX = 50000;
public static final int DEFAULT_TERMINAL_TRANSCRIPT_ROWS = 2000;
/* The supported terminal cursor styles. */
public static final int TERMINAL_CURSOR_STYLE_BLOCK = 0;
public static final int TERMINAL_CURSOR_STYLE_UNDERLINE = 1;
public static final int TERMINAL_CURSOR_STYLE_BAR = 2;
public static final int DEFAULT_TERMINAL_CURSOR_STYLE = TERMINAL_CURSOR_STYLE_BLOCK;
public static final Integer[] TERMINAL_CURSOR_STYLES_LIST = new Integer[]{TERMINAL_CURSOR_STYLE_BLOCK, TERMINAL_CURSOR_STYLE_UNDERLINE, TERMINAL_CURSOR_STYLE_BAR};
/** The terminal cursor styles. */
private int mCursorStyle = DEFAULT_TERMINAL_CURSOR_STYLE;
/** The normal screen buffer. Stores the characters that appear on the screen of the emulated terminal. */
private final TerminalBuffer mMainBuffer;
/**
* The alternate screen buffer, exactly as large as the display and contains no additional saved lines (so that when
* the alternate screen buffer is active, you cannot scroll back to view saved lines).
* <p>
* See http://www.xfree86.org/current/ctlseqs.html#The%20Alternate%20Screen%20Buffer
*/
final TerminalBuffer mAltBuffer;
/** The current screen buffer, pointing at either {@link #mMainBuffer} or {@link #mAltBuffer}. */
private TerminalBuffer mScreen;
/** The terminal session this emulator is bound to. */
private final TerminalOutput mSession;
TerminalSessionClient mClient;
/** Keeps track of the current argument of the current escape sequence. Ranges from 0 to MAX_ESCAPE_PARAMETERS-1. */
private int mArgIndex;
/** Holds the arguments of the current escape sequence. */
private final int[] mArgs = new int[MAX_ESCAPE_PARAMETERS];
/** Holds OSC and device control arguments, which can be strings. */
private final StringBuilder mOSCOrDeviceControlArgs = new StringBuilder();
/**
* True if the current escape sequence should continue, false if the current escape sequence should be terminated.
* Used when parsing a single character.
*/
private boolean mContinueSequence;
/** The current state of the escape sequence state machine. One of the ESC_* constants. */
private int mEscapeState;
private boolean ESC_P_escape = false;
private boolean ESC_P_sixel = false;
private ArrayList<Byte> ESC_OSC_data;
private int ESC_OSC_colon = 0;
private final SavedScreenState mSavedStateMain = new SavedScreenState();
private final SavedScreenState mSavedStateAlt = new SavedScreenState();
/** http://www.vt100.net/docs/vt102-ug/table5-15.html */
private boolean mUseLineDrawingG0, mUseLineDrawingG1, mUseLineDrawingUsesG0 = true;
/**
* @see TerminalEmulator#mapDecSetBitToInternalBit(int)
*/
private int mCurrentDecSetFlags, mSavedDecSetFlags;
/**
* If insert mode (as opposed to replace mode) is active. In insert mode new characters are inserted, pushing
* existing text to the right. Characters moved past the right margin are lost.
*/
private boolean mInsertMode;
/** An array of tab stops. mTabStop[i] is true if there is a tab stop set for column i. */
private boolean[] mTabStop;
/**
* Top margin of screen for scrolling ranges from 0 to mRows-2. Bottom margin ranges from mTopMargin + 2 to mRows
* (Defines the first row after the scrolling region). Left/right margin in [0, mColumns].
*/
private int mTopMargin, mBottomMargin, mLeftMargin, mRightMargin;
/**
* If the next character to be emitted will be automatically wrapped to the next line. Used to disambiguate the case
* where the cursor is positioned on the last column (mColumns-1). When standing there, a written character will be
* output in the last column, the cursor not moving but this flag will be set. When outputting another character
* this will move to the next line.
*/
private boolean mAboutToAutoWrap;
/**
* If the cursor blinking is enabled. It requires cursor itself to be enabled, which is controlled
* byt whether {@link #DECSET_BIT_CURSOR_ENABLED} bit is set or not.
*/
private boolean mCursorBlinkingEnabled;
/**
* If currently cursor should be in a visible state or not if {@link #mCursorBlinkingEnabled}
* is {@code true}.
*/
private boolean mCursorBlinkState;
/**
* Current foreground and background colors. Can either be a color index in [0,259] or a truecolor (24-bit) value.
* For a 24-bit value the top byte (0xff000000) is set.
*
* @see TextStyle
*/
int mForeColor, mBackColor;
/** Current {@link TextStyle} effect. */
private int mEffect;
/**
* The number of scrolled lines since last calling {@link #clearScrollCounter()}. Used for moving selection up along
* with the scrolling text.
*/
private int mScrollCounter = 0;
/** If automatic scrolling of terminal is disabled */
private boolean mAutoScrollDisabled;
private byte mUtf8ToFollow, mUtf8Index;
private final byte[] mUtf8InputBuffer = new byte[4];
private int mLastEmittedCodePoint = -1;
public final TerminalColors mColors = new TerminalColors();
private static final String LOG_TAG = "TerminalEmulator";
private int cellW = 12, cellH = 12;
public void setCellSize(int w, int h) {
cellW = w;
cellH = h;
}
private boolean isDecsetInternalBitSet(int bit) {
return (mCurrentDecSetFlags & bit) != 0;
}
private void setDecsetinternalBit(int internalBit, boolean set) {
if (set) {
// The mouse modes are mutually exclusive.
if (internalBit == DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE) {
setDecsetinternalBit(DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT, false);
} else if (internalBit == DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT) {
setDecsetinternalBit(DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE, false);
}
}
if (set) {
mCurrentDecSetFlags |= internalBit;
} else {
mCurrentDecSetFlags &= ~internalBit;
}
}
static int mapDecSetBitToInternalBit(int decsetBit) {
switch (decsetBit) {
case 1:
return DECSET_BIT_APPLICATION_CURSOR_KEYS;
case 5:
return DECSET_BIT_REVERSE_VIDEO;
case 6:
return DECSET_BIT_ORIGIN_MODE;
case 7:
return DECSET_BIT_AUTOWRAP;
case 25:
return DECSET_BIT_CURSOR_ENABLED;
case 66:
return DECSET_BIT_APPLICATION_KEYPAD;
case 69:
return DECSET_BIT_LEFTRIGHT_MARGIN_MODE;
case 1000:
return DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE;
case 1002:
return DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT;
case 1004:
return DECSET_BIT_SEND_FOCUS_EVENTS;
case 1006:
return DECSET_BIT_MOUSE_PROTOCOL_SGR;
case 2004:
return DECSET_BIT_BRACKETED_PASTE_MODE;
default:
return -1;
// throw new IllegalArgumentException("Unsupported decset: " + decsetBit);
}
}
public TerminalEmulator(TerminalOutput session, int columns, int rows, Integer transcriptRows, TerminalSessionClient client) {
mSession = session;
mScreen = mMainBuffer = new TerminalBuffer(columns, getTerminalTranscriptRows(transcriptRows), rows);
mAltBuffer = new TerminalBuffer(columns, rows, rows);
mClient = client;
mRows = rows;
mColumns = columns;
mTabStop = new boolean[mColumns];
reset();
}
public void updateTerminalSessionClient(TerminalSessionClient client) {
mClient = client;
setCursorStyle();
setCursorBlinkState(true);
}
public TerminalBuffer getScreen() {
return mScreen;
}
public boolean isAlternateBufferActive() {
return mScreen == mAltBuffer;
}
private int getTerminalTranscriptRows(Integer transcriptRows) {
if (transcriptRows == null || transcriptRows < TERMINAL_TRANSCRIPT_ROWS_MIN || transcriptRows > TERMINAL_TRANSCRIPT_ROWS_MAX)
return DEFAULT_TERMINAL_TRANSCRIPT_ROWS;
else
return transcriptRows;
}
/**
* @param mouseButton one of the MOUSE_* constants of this class.
*/
public void sendMouseEvent(int mouseButton, int column, int row, boolean pressed) {
if (column < 1) column = 1;
if (column > mColumns) column = mColumns;
if (row < 1) row = 1;
if (row > mRows) row = mRows;
if (mouseButton == MOUSE_LEFT_BUTTON_MOVED && !isDecsetInternalBitSet(DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT)) {
// Do not send tracking.
} else if (isDecsetInternalBitSet(DECSET_BIT_MOUSE_PROTOCOL_SGR)) {
mSession.write(String.format("\033[<%d;%d;%d" + (pressed ? 'M' : 'm'), mouseButton, column, row));
} else {
mouseButton = pressed ? mouseButton : 3; // 3 for release of all buttons.
// Clip to screen, and clip to the limits of 8-bit data.
boolean out_of_bounds = column > 255 - 32 || row > 255 - 32;
if (!out_of_bounds) {
byte[] data = {'\033', '[', 'M', (byte) (32 + mouseButton), (byte) (32 + column), (byte) (32 + row)};
mSession.write(data, 0, data.length);
}
}
}
public void resize(int columns, int rows) {
if (mRows == rows && mColumns == columns) {
return;
} else if (columns < 2 || rows < 2) {
throw new IllegalArgumentException("rows=" + rows + ", columns=" + columns);
}
if (mRows != rows) {
mRows = rows;
mTopMargin = 0;
mBottomMargin = mRows;
}
if (mColumns != columns) {
int oldColumns = mColumns;
mColumns = columns;
boolean[] oldTabStop = mTabStop;
mTabStop = new boolean[mColumns];
setDefaultTabStops();
int toTransfer = Math.min(oldColumns, columns);
System.arraycopy(oldTabStop, 0, mTabStop, 0, toTransfer);
mLeftMargin = 0;
mRightMargin = mColumns;
}
resizeScreen();
}
private void resizeScreen() {
final int[] cursor = {mCursorCol, mCursorRow};
int newTotalRows = (mScreen == mAltBuffer) ? mRows : mMainBuffer.mTotalRows;
mScreen.resize(mColumns, mRows, newTotalRows, cursor, getStyle(), isAlternateBufferActive());
mCursorCol = cursor[0];
mCursorRow = cursor[1];
}
public int getCursorRow() {
return mCursorRow;
}
public int getCursorCol() {
return mCursorCol;
}
/** Get the terminal cursor style. It will be one of {@link #TERMINAL_CURSOR_STYLES_LIST} */
public int getCursorStyle() {
return mCursorStyle;
}
/** Set the terminal cursor style. */
public void setCursorStyle() {
Integer cursorStyle = null;
if (mClient != null)
cursorStyle = mClient.getTerminalCursorStyle();
if (cursorStyle == null || !Arrays.asList(TERMINAL_CURSOR_STYLES_LIST).contains(cursorStyle))
mCursorStyle = DEFAULT_TERMINAL_CURSOR_STYLE;
else
mCursorStyle = cursorStyle;
}
public boolean isReverseVideo() {
return isDecsetInternalBitSet(DECSET_BIT_REVERSE_VIDEO);
}
public boolean isCursorEnabled() {
return isDecsetInternalBitSet(DECSET_BIT_CURSOR_ENABLED);
}
public boolean shouldCursorBeVisible() {
if (!isCursorEnabled())
return false;
else
return mCursorBlinkingEnabled ? mCursorBlinkState : true;
}
public void setCursorBlinkingEnabled(boolean cursorBlinkingEnabled) {
this.mCursorBlinkingEnabled = cursorBlinkingEnabled;
}
public void setCursorBlinkState(boolean cursorBlinkState) {
this.mCursorBlinkState = cursorBlinkState;
}
public boolean isKeypadApplicationMode() {
return isDecsetInternalBitSet(DECSET_BIT_APPLICATION_KEYPAD);
}
public boolean isCursorKeysApplicationMode() {
return isDecsetInternalBitSet(DECSET_BIT_APPLICATION_CURSOR_KEYS);
}
/** If mouse events are being sent as escape codes to the terminal. */
public boolean isMouseTrackingActive() {
return isDecsetInternalBitSet(DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE) || isDecsetInternalBitSet(DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT);
}
private void setDefaultTabStops() {
for (int i = 0; i < mColumns; i++)
mTabStop[i] = (i & 7) == 0 && i != 0;
}
/**
* Accept bytes (typically from the pseudo-teletype) and process them.
*
* @param buffer a byte array containing the bytes to be processed
* @param length the number of bytes in the array to process
*/
public void append(byte[] buffer, int length) {
for (int i = 0; i < length; i++)
processByte(buffer[i]);
}
private void processByte(byte byteToProcess) {
if (mUtf8ToFollow > 0) {
if ((byteToProcess & 0b11000000) == 0b10000000) {
// 10xxxxxx, a continuation byte.
mUtf8InputBuffer[mUtf8Index++] = byteToProcess;
if (--mUtf8ToFollow == 0) {
byte firstByteMask = (byte) (mUtf8Index == 2 ? 0b00011111 : (mUtf8Index == 3 ? 0b00001111 : 0b00000111));
int codePoint = (mUtf8InputBuffer[0] & firstByteMask);
for (int i = 1; i < mUtf8Index; i++)
codePoint = ((codePoint << 6) | (mUtf8InputBuffer[i] & 0b00111111));
if (((codePoint <= 0b1111111) && mUtf8Index > 1) || (codePoint < 0b11111111111 && mUtf8Index > 2)
|| (codePoint < 0b1111111111111111 && mUtf8Index > 3)) {
// Overlong encoding.
codePoint = UNICODE_REPLACEMENT_CHAR;
}
mUtf8Index = mUtf8ToFollow = 0;
if (codePoint >= 0x80 && codePoint <= 0x9F) {
// Sequence decoded to a C1 control character which we ignore. They are
// not used nowadays and increases the risk of messing up the terminal state
// on binary input. XTerm does not allow them in utf-8:
// "It is not possible to use a C1 control obtained from decoding the
// UTF-8 text" - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
} else {
switch (Character.getType(codePoint)) {
case Character.UNASSIGNED:
case Character.SURROGATE:
codePoint = UNICODE_REPLACEMENT_CHAR;
}
processCodePoint(codePoint);
}
}
} else {
// Not a UTF-8 continuation byte so replace the entire sequence up to now with the replacement char:
mUtf8Index = mUtf8ToFollow = 0;
emitCodePoint(UNICODE_REPLACEMENT_CHAR);
// The Unicode Standard Version 6.2 – Core Specification
// (http://www.unicode.org/versions/Unicode6.2.0/ch03.pdf):
// "If the converter encounters an ill-formed UTF-8 code unit sequence which starts with a valid first
// byte, but which does not continue with valid successor bytes (see Table 3-7), it must not consume the
// successor bytes as part of the ill-formed subsequence
// whenever those successor bytes themselves constitute part of a well-formed UTF-8 code unit
// subsequence."
processByte(byteToProcess);
}
} else {
if ((byteToProcess & 0b10000000) == 0) { // The leading bit is not set so it is a 7-bit ASCII character.
processCodePoint(byteToProcess);
return;
} else if ((byteToProcess & 0b11100000) == 0b11000000) { // 110xxxxx, a two-byte sequence.
mUtf8ToFollow = 1;
} else if ((byteToProcess & 0b11110000) == 0b11100000) { // 1110xxxx, a three-byte sequence.
mUtf8ToFollow = 2;
} else if ((byteToProcess & 0b11111000) == 0b11110000) { // 11110xxx, a four-byte sequence.
mUtf8ToFollow = 3;
} else {
// Not a valid UTF-8 sequence start, signal invalid data:
processCodePoint(UNICODE_REPLACEMENT_CHAR);
return;
}
mUtf8InputBuffer[mUtf8Index++] = byteToProcess;
}
}
public void processCodePoint(int b) {
mScreen.bitmapGC(300000);
switch (b) {
case 0: // Null character (NUL, ^@). Do nothing.
break;
case 7: // Bell (BEL, ^G, \a). If in an OSC sequence, BEL may terminate a string; otherwise signal bell.
if (mEscapeState == ESC_OSC)
doOsc(b);
else {
if (mEscapeState == ESC_APC) {
doApc(b);
}
mSession.onBell();
}
break;
case 8: // Backspace (BS, ^H).
if (mLeftMargin == mCursorCol) {
// Jump to previous line if it was auto-wrapped.
int previousRow = mCursorRow - 1;
if (previousRow >= 0 && mScreen.getLineWrap(previousRow)) {
mScreen.clearLineWrap(previousRow);
setCursorRowCol(previousRow, mRightMargin - 1);
}
} else {
setCursorCol(mCursorCol - 1);
}
break;
case 9: // Horizontal tab (HT, \t) - move to next tab stop, but not past edge of screen
// XXX: Should perhaps use color if writing to new cells. Try with
// printf "\033[41m\tXX\033[0m\n"
// The OSX Terminal.app colors the spaces from the tab red, but xterm does not.
// Note that Terminal.app only colors on new cells, in e.g.
// printf "\033[41m\t\r\033[42m\tXX\033[0m\n"
// the first cells are created with a red background, but when tabbing over
// them again with a green background they are not overwritten.
mCursorCol = nextTabStop(1);
break;
case 10: // Line feed (LF, \n).
case 11: // Vertical tab (VT, \v).
case 12: // Form feed (FF, \f).
if((mEscapeState != ESC_P || !ESC_P_sixel) && ESC_OSC_colon <= 0) {
// Ignore CR/LF inside sixels or iterm2 data
doLinefeed();
}
break;
case 13: // Carriage return (CR, \r).
if((mEscapeState != ESC_P || !ESC_P_sixel) && ESC_OSC_colon <= 0) {
// Ignore CR/LF inside sixels or iterm2 data
setCursorCol(mLeftMargin);
}
break;
case 14: // Shift Out (Ctrl-N, SO) → Switch to Alternate Character Set. This invokes the G1 character set.
mUseLineDrawingUsesG0 = false;
break;
case 15: // Shift In (Ctrl-O, SI) → Switch to Standard Character Set. This invokes the G0 character set.
mUseLineDrawingUsesG0 = true;
break;
case 24: // CAN.
case 26: // SUB.
if (mEscapeState != ESC_NONE) {
// FIXME: What is this??
mEscapeState = ESC_NONE;
emitCodePoint(127);
}
break;
case 27: // ESC
// Starts an escape sequence unless we're parsing a string
if (mEscapeState == ESC_P) {
// XXX: Ignore escape when reading device control sequence, since it may be part of string terminator.
ESC_P_escape = true;
return;
} else if (mEscapeState != ESC_OSC) {
if (mEscapeState != ESC_APC) {
startEscapeSequence();
} else {
doApc(b);
}
} else {
doOsc(b);
}
break;
default:
mContinueSequence = false;
switch (mEscapeState) {
case ESC_NONE:
if (b >= 32) emitCodePoint(b);
break;
case ESC:
doEsc(b);
break;
case ESC_POUND:
doEscPound(b);
break;
case ESC_SELECT_LEFT_PAREN: // Designate G0 Character Set (ISO 2022, VT100).
mUseLineDrawingG0 = (b == '0');
break;
case ESC_SELECT_RIGHT_PAREN: // Designate G1 Character Set (ISO 2022, VT100).
mUseLineDrawingG1 = (b == '0');
break;
case ESC_CSI:
doCsi(b);
break;
case ESC_CSI_EXCLAMATION:
if (b == 'p') { // Soft terminal reset (DECSTR, http://vt100.net/docs/vt510-rm/DECSTR).
reset();
} else {
unknownSequence(b);
}
break;
case ESC_CSI_QUESTIONMARK:
doCsiQuestionMark(b);
break;
case ESC_CSI_BIGGERTHAN:
doCsiBiggerThan(b);
break;
case ESC_CSI_DOLLAR:
boolean originMode = isDecsetInternalBitSet(DECSET_BIT_ORIGIN_MODE);
int effectiveTopMargin = originMode ? mTopMargin : 0;
int effectiveBottomMargin = originMode ? mBottomMargin : mRows;
int effectiveLeftMargin = originMode ? mLeftMargin : 0;
int effectiveRightMargin = originMode ? mRightMargin : mColumns;
switch (b) {
case 'v': // ${CSI}${SRC_TOP}${SRC_LEFT}${SRC_BOTTOM}${SRC_RIGHT}${SRC_PAGE}${DST_TOP}${DST_LEFT}${DST_PAGE}$v"
// Copy rectangular area (DECCRA - http://vt100.net/docs/vt510-rm/DECCRA):
// "If Pbs is greater than Pts, or Pls is greater than Prs, the terminal ignores DECCRA.
// The coordinates of the rectangular area are affected by the setting of origin mode (DECOM).
// DECCRA is not affected by the page margins.
// The copied text takes on the line attributes of the destination area.
// If the value of Pt, Pl, Pb, or Pr exceeds the width or height of the active page, then the value
// is treated as the width or height of that page.
// If the destination area is partially off the page, then DECCRA clips the off-page data.
// DECCRA does not change the active cursor position."
int topSource = Math.min(getArg(0, 1, true) - 1 + effectiveTopMargin, mRows);
int leftSource = Math.min(getArg(1, 1, true) - 1 + effectiveLeftMargin, mColumns);
// Inclusive, so do not subtract one:
int bottomSource = Math.min(Math.max(getArg(2, mRows, true) + effectiveTopMargin, topSource), mRows);
int rightSource = Math.min(Math.max(getArg(3, mColumns, true) + effectiveLeftMargin, leftSource), mColumns);
// int sourcePage = getArg(4, 1, true);
int destionationTop = Math.min(getArg(5, 1, true) - 1 + effectiveTopMargin, mRows);
int destinationLeft = Math.min(getArg(6, 1, true) - 1 + effectiveLeftMargin, mColumns);
// int destinationPage = getArg(7, 1, true);
int heightToCopy = Math.min(mRows - destionationTop, bottomSource - topSource);
int widthToCopy = Math.min(mColumns - destinationLeft, rightSource - leftSource);
mScreen.blockCopy(leftSource, topSource, widthToCopy, heightToCopy, destinationLeft, destionationTop);
break;
case '{': // ${CSI}${TOP}${LEFT}${BOTTOM}${RIGHT}${"
// Selective erase rectangular area (DECSERA - http://www.vt100.net/docs/vt510-rm/DECSERA).
case 'x': // ${CSI}${CHAR};${TOP}${LEFT}${BOTTOM}${RIGHT}$x"
// Fill rectangular area (DECFRA - http://www.vt100.net/docs/vt510-rm/DECFRA).
case 'z': // ${CSI}$${TOP}${LEFT}${BOTTOM}${RIGHT}$z"
// Erase rectangular area (DECERA - http://www.vt100.net/docs/vt510-rm/DECERA).
boolean erase = b != 'x';
boolean selective = b == '{';
// Only DECSERA keeps visual attributes, DECERA does not:
boolean keepVisualAttributes = erase && selective;
int argIndex = 0;
int fillChar = erase ? ' ' : getArg(argIndex++, -1, true);
// "Pch can be any value from 32 to 126 or from 160 to 255. If Pch is not in this range, then the
// terminal ignores the DECFRA command":
if ((fillChar >= 32 && fillChar <= 126) || (fillChar >= 160 && fillChar <= 255)) {
// "If the value of Pt, Pl, Pb, or Pr exceeds the width or height of the active page, the value
// is treated as the width or height of that page."
int top = Math.min(getArg(argIndex++, 1, true) + effectiveTopMargin, effectiveBottomMargin + 1);
int left = Math.min(getArg(argIndex++, 1, true) + effectiveLeftMargin, effectiveRightMargin + 1);
int bottom = Math.min(getArg(argIndex++, mRows, true) + effectiveTopMargin, effectiveBottomMargin);
int right = Math.min(getArg(argIndex, mColumns, true) + effectiveLeftMargin, effectiveRightMargin);
long style = getStyle();
for (int row = top - 1; row < bottom; row++)
for (int col = left - 1; col < right; col++)
if (!selective || (TextStyle.decodeEffect(mScreen.getStyleAt(row, col)) & TextStyle.CHARACTER_ATTRIBUTE_PROTECTED) == 0)
mScreen.setChar(col, row, fillChar, keepVisualAttributes ? mScreen.getStyleAt(row, col) : style);
}
break;
case 'r': // "${CSI}${TOP}${LEFT}${BOTTOM}${RIGHT}${ATTRIBUTES}$r"
// Change attributes in rectangular area (DECCARA - http://vt100.net/docs/vt510-rm/DECCARA).
case 't': // "${CSI}${TOP}${LEFT}${BOTTOM}${RIGHT}${ATTRIBUTES}$t"
// Reverse attributes in rectangular area (DECRARA - http://www.vt100.net/docs/vt510-rm/DECRARA).
boolean reverse = b == 't';
// FIXME: "coordinates of the rectangular area are affected by the setting of origin mode (DECOM)".
int top = Math.min(getArg(0, 1, true) - 1, effectiveBottomMargin) + effectiveTopMargin;
int left = Math.min(getArg(1, 1, true) - 1, effectiveRightMargin) + effectiveLeftMargin;
int bottom = Math.min(getArg(2, mRows, true) + 1, effectiveBottomMargin - 1) + effectiveTopMargin;
int right = Math.min(getArg(3, mColumns, true) + 1, effectiveRightMargin - 1) + effectiveLeftMargin;
if (mArgIndex >= 4) {
if (mArgIndex >= mArgs.length) mArgIndex = mArgs.length - 1;
for (int i = 4; i <= mArgIndex; i++) {
int bits = 0;
boolean setOrClear = true; // True if setting, false if clearing.
switch (getArg(i, 0, false)) {
case 0: // Attributes off (no bold, no underline, no blink, positive image).
bits = (TextStyle.CHARACTER_ATTRIBUTE_BOLD | TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE | TextStyle.CHARACTER_ATTRIBUTE_BLINK
| TextStyle.CHARACTER_ATTRIBUTE_INVERSE);
if (!reverse) setOrClear = false;
break;
case 1: // Bold.
bits = TextStyle.CHARACTER_ATTRIBUTE_BOLD;
break;
case 4: // Underline.
bits = TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE;
break;
case 5: // Blink.
bits = TextStyle.CHARACTER_ATTRIBUTE_BLINK;
break;
case 7: // Negative image.
bits = TextStyle.CHARACTER_ATTRIBUTE_INVERSE;
break;
case 22: // No bold.
bits = TextStyle.CHARACTER_ATTRIBUTE_BOLD;
setOrClear = false;
break;
case 24: // No underline.
bits = TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE;
setOrClear = false;
break;
case 25: // No blink.
bits = TextStyle.CHARACTER_ATTRIBUTE_BLINK;
setOrClear = false;
break;
case 27: // Positive image.
bits = TextStyle.CHARACTER_ATTRIBUTE_INVERSE;
setOrClear = false;
break;
}
if (reverse && !setOrClear) {
// Reverse attributes in rectangular area ignores non-(1,4,5,7) bits.
} else {
mScreen.setOrClearEffect(bits, setOrClear, reverse, isDecsetInternalBitSet(DECSET_BIT_RECTANGULAR_CHANGEATTRIBUTE),
effectiveLeftMargin, effectiveRightMargin, top, left, bottom, right);
}
}
} else {
// Do nothing.
}
break;
default:
unknownSequence(b);
}
break;
case ESC_CSI_DOUBLE_QUOTE:
if (b == 'q') {
// http://www.vt100.net/docs/vt510-rm/DECSCA
int arg = getArg0(0);
if (arg == 0 || arg == 2) {
// DECSED and DECSEL can erase characters.
mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_PROTECTED;
} else if (arg == 1) {
// DECSED and DECSEL cannot erase characters.
mEffect |= TextStyle.CHARACTER_ATTRIBUTE_PROTECTED;
} else {
unknownSequence(b);
}
} else {
unknownSequence(b);
}
break;
case ESC_CSI_SINGLE_QUOTE:
if (b == '}') { // Insert Ps Column(s) (default = 1) (DECIC), VT420 and up.
int columnsAfterCursor = mRightMargin - mCursorCol;
int columnsToInsert = Math.min(getArg0(1), columnsAfterCursor);
int columnsToMove = columnsAfterCursor - columnsToInsert;
mScreen.blockCopy(mCursorCol, 0, columnsToMove, mRows, mCursorCol + columnsToInsert, 0);
blockClear(mCursorCol, 0, columnsToInsert, mRows);
} else if (b == '~') { // Delete Ps Column(s) (default = 1) (DECDC), VT420 and up.
int columnsAfterCursor = mRightMargin - mCursorCol;
int columnsToDelete = Math.min(getArg0(1), columnsAfterCursor);
int columnsToMove = columnsAfterCursor - columnsToDelete;
mScreen.blockCopy(mCursorCol + columnsToDelete, 0, columnsToMove, mRows, mCursorCol, 0);
} else {
unknownSequence(b);
}
break;
case ESC_PERCENT:
break;
case ESC_APC:
doApc(b);
break;
case ESC_APC_ESC:
doApcEsc(b);
break;
case ESC_OSC:
doOsc(b);
break;
case ESC_OSC_ESC:
doOscEsc(b);
break;
case ESC_P:
doDeviceControl(b);
break;
case ESC_CSI_QUESTIONMARK_ARG_DOLLAR:
if (b == 'p') {
// Request DEC private mode (DECRQM).
int mode = getArg0(0);
int value;
if (mode == 47 || mode == 1047 || mode == 1049) {
// This state is carried by mScreen pointer.
value = (mScreen == mAltBuffer) ? 1 : 2;
} else {
int internalBit = mapDecSetBitToInternalBit(mode);
if (internalBit != -1) {
value = isDecsetInternalBitSet(internalBit) ? 1 : 2; // 1=set, 2=reset.
} else {
Logger.logError(mClient, LOG_TAG, "Got DECRQM for unrecognized private DEC mode=" + mode);
value = 0; // 0=not recognized, 3=permanently set, 4=permanently reset
}
}
mSession.write(String.format(Locale.US, "\033[?%d;%d$y", mode, value));
} else {
unknownSequence(b);
}
break;
case ESC_CSI_ARGS_SPACE:
int arg = getArg0(0);
switch (b) {
case 'q': // "${CSI}${STYLE} q" - set cursor style (http://www.vt100.net/docs/vt510-rm/DECSCUSR).
switch (arg) {
case 0: // Blinking block.
case 1: // Blinking block.
case 2: // Steady block.
mCursorStyle = TERMINAL_CURSOR_STYLE_BLOCK;
break;
case 3: // Blinking underline.
case 4: // Steady underline.
mCursorStyle = TERMINAL_CURSOR_STYLE_UNDERLINE;
break;
case 5: // Blinking bar (xterm addition).
case 6: // Steady bar (xterm addition).
mCursorStyle = TERMINAL_CURSOR_STYLE_BAR;
break;
}
break;
case 't':
case 'u':
// Set margin-bell volume - ignore.
break;
default:
unknownSequence(b);
}
break;
case ESC_CSI_ARGS_ASTERIX:
int attributeChangeExtent = getArg0(0);
if (b == 'x' && (attributeChangeExtent >= 0 && attributeChangeExtent <= 2)) {
// Select attribute change extent (DECSACE - http://www.vt100.net/docs/vt510-rm/DECSACE).
setDecsetinternalBit(DECSET_BIT_RECTANGULAR_CHANGEATTRIBUTE, attributeChangeExtent == 2);
} else {
unknownSequence(b);
}
break;
default:
unknownSequence(b);
break;
}
if (!mContinueSequence) mEscapeState = ESC_NONE;
break;
}
}
/** When in {@link #ESC_P} ("device control") sequence. */
private void doDeviceControl(int b) {
boolean firstSixel = false;
if (!ESC_P_sixel && (b=='$' || b=='-' || b=='#')) {
//Check if sixel sequence that needs breaking
String dcs = mOSCOrDeviceControlArgs.toString();
if (dcs.matches("[0-9;]*q.*")) {
firstSixel = true;
}
}
if (firstSixel || (ESC_P_escape && b == '\\') || (ESC_P_sixel && (b=='$' || b=='-' || b=='#')))
// ESC \ terminates OSC
// Sixel sequences may be very long. '$' and '!' are natural for breaking the sequence.
{
String dcs = mOSCOrDeviceControlArgs.toString();
// DCS $ q P t ST. Request Status String (DECRQSS)
if (dcs.startsWith("$q")) {
if (dcs.equals("$q\"p")) {
// DECSCL, conformance level, http://www.vt100.net/docs/vt510-rm/DECSCL:
String csiString = "64;1\"p";
mSession.write("\033P1$r" + csiString + "\033\\");
} else {
finishSequenceAndLogError("Unrecognized DECRQSS string: '" + dcs + "'");
}
} else if (dcs.startsWith("+q")) {
// Request Termcap/Terminfo String. The string following the "q" is a list of names encoded in
// hexadecimal (2 digits per character) separated by ; which correspond to termcap or terminfo key
// names.
// Two special features are also recognized, which are not key names: Co for termcap colors (or colors
// for terminfo colors), and TN for termcap name (or name for terminfo name).
// xterm responds with DCS 1 + r P t ST for valid requests, adding to P t an = , and the value of the
// corresponding string that xterm would send, or DCS 0 + r P t ST for invalid requests. The strings are
// encoded in hexadecimal (2 digits per character).
// Example:
// :kr=\EOC: ks=\E[?1h\E=: ku=\EOA: le=^H:mb=\E[5m:md=\E[1m:\
// where
// kd=down-arrow key
// kl=left-arrow key
// kr=right-arrow key
// ku=up-arrow key
// #2=key_shome, "shifted home"
// #4=key_sleft, "shift arrow left"
// %i=key_sright, "shift arrow right"
// *7=key_send, "shifted end"
// k1=F1 function key
// Example: Request for ku is "ESC P + q 6 b 7 5 ESC \", where 6b7d=ku in hexadecimal.
// Xterm response in normal cursor mode:
// "<27> P 1 + r 6 b 7 5 = 1 B 5 B 4 1" where 0x1B 0x5B 0x41 = 27 91 65 = ESC [ A
// Xterm response in application cursor mode:
// "<27> P 1 + r 6 b 7 5 = 1 B 5 B 4 1" where 0x1B 0x4F 0x41 = 27 91 65 = ESC 0 A
// #4 is "shift arrow left":
// *** Device Control (DCS) for '#4'- 'ESC P + q 23 34 ESC \'
// Response: <27> P 1 + r 2 3 3 4 = 1 B 5 B 3 1 3 B 3 2 4 4 <27> \
// where 0x1B 0x5B 0x31 0x3B 0x32 0x44 = ESC [ 1 ; 2 D
// which we find in: TermKeyListener.java: KEY_MAP.put(KEYMOD_SHIFT | KEYCODE_DPAD_LEFT, "\033[1;2D");
// See http://h30097.www3.hp.com/docs/base_doc/DOCUMENTATION/V40G_HTML/MAN/MAN4/0178____.HTM for what to
// respond, as well as http://www.freebsd.org/cgi/man.cgi?query=termcap&sektion=5#CAPABILITIES for
// the meaning of e.g. "ku", "kd", "kr", "kl"
for (String part : dcs.substring(2).split(";")) {
if (part.length() % 2 == 0) {
StringBuilder transBuffer = new StringBuilder();
char c;
for (int i = 0; i < part.length(); i += 2) {
try {
c = (char) Long.decode("0x" + part.charAt(i) + "" + part.charAt(i + 1)).longValue();
} catch (NumberFormatException e) {
Logger.logStackTraceWithMessage(mClient, LOG_TAG, "Invalid device termcap/terminfo encoded name \"" + part + "\"", e);
continue;
}
transBuffer.append(c);
}