performance
[fanfix.git] / src / jexer / tterminal / ECMA48.java
1 /*
2 * Jexer - Java Text User Interface
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (C) 2019 Kevin Lamonte
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
25 *
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
27 * @version 1
28 */
29 package jexer.tterminal;
30
31 import java.awt.Graphics2D;
32 import java.awt.image.BufferedImage;
33 import java.io.BufferedInputStream;
34 import java.io.BufferedOutputStream;
35 import java.io.CharArrayWriter;
36 import java.io.InputStream;
37 import java.io.InputStreamReader;
38 import java.io.IOException;
39 import java.io.OutputStream;
40 import java.io.OutputStreamWriter;
41 import java.io.PrintWriter;
42 import java.io.Reader;
43 import java.io.UnsupportedEncodingException;
44 import java.io.Writer;
45 import java.util.ArrayList;
46 import java.util.Collections;
47 import java.util.HashMap;
48 import java.util.List;
49
50 import jexer.TKeypress;
51 import jexer.backend.GlyphMaker;
52 import jexer.bits.Color;
53 import jexer.bits.Cell;
54 import jexer.bits.CellAttributes;
55 import jexer.bits.StringUtils;
56 import jexer.event.TInputEvent;
57 import jexer.event.TKeypressEvent;
58 import jexer.event.TMouseEvent;
59 import jexer.io.ReadTimeoutException;
60 import jexer.io.TimeoutInputStream;
61 import static jexer.TKeypress.*;
62
63 /**
64 * This implements a complex ECMA-48/ISO 6429/ANSI X3.64 type console,
65 * including a scrollback buffer.
66 *
67 * <p>
68 * It currently implements VT100, VT102, VT220, and XTERM with the following
69 * caveats:
70 *
71 * <p>
72 * - The vttest scenario for VT220 8-bit controls (11.1.2.3) reports a
73 * failure with XTERM. This is due to vttest failing to decode the UTF-8
74 * stream.
75 *
76 * <p>
77 * - Smooth scrolling, printing, keyboard locking, keyboard leds, and tests
78 * from VT100 are not supported.
79 *
80 * <p>
81 * - User-defined keys (DECUDK), downloadable fonts (DECDLD), and VT100/ANSI
82 * compatibility mode (DECSCL) from VT220 are not supported. (Also,
83 * because DECSCL is not supported, it will fail the last part of the
84 * vttest "Test of VT52 mode" if DeviceType is set to VT220.)
85 *
86 * <p>
87 * - Numeric/application keys from the number pad are not supported because
88 * they are not exposed from the TKeypress API.
89 *
90 * <p>
91 * - VT52 HOLD SCREEN mode is not supported.
92 *
93 * <p>
94 * - In VT52 graphics mode, the 3/, 5/, and 7/ characters (fraction
95 * numerators) are not rendered correctly.
96 *
97 * <p>
98 * - All data meant for the 'printer' (CSI Pc ? i) is discarded.
99 */
100 public class ECMA48 implements Runnable {
101
102 // ------------------------------------------------------------------------
103 // Constants --------------------------------------------------------------
104 // ------------------------------------------------------------------------
105
106 /**
107 * The emulator can emulate several kinds of terminals.
108 */
109 public enum DeviceType {
110 /**
111 * DEC VT100 but also including the three VT102 functions.
112 */
113 VT100,
114
115 /**
116 * DEC VT102.
117 */
118 VT102,
119
120 /**
121 * DEC VT220.
122 */
123 VT220,
124
125 /**
126 * A subset of xterm.
127 */
128 XTERM
129 }
130
131 /**
132 * Parser character scan states.
133 */
134 private enum ScanState {
135 GROUND,
136 ESCAPE,
137 ESCAPE_INTERMEDIATE,
138 CSI_ENTRY,
139 CSI_PARAM,
140 CSI_INTERMEDIATE,
141 CSI_IGNORE,
142 DCS_ENTRY,
143 DCS_INTERMEDIATE,
144 DCS_PARAM,
145 DCS_PASSTHROUGH,
146 DCS_IGNORE,
147 DCS_SIXEL,
148 SOSPMAPC_STRING,
149 OSC_STRING,
150 VT52_DIRECT_CURSOR_ADDRESS
151 }
152
153 /**
154 * The selected number pad mode (DECKPAM, DECKPNM). We record this, but
155 * can't really use it in keypress() because we do not see number pad
156 * events from TKeypress.
157 */
158 private enum KeypadMode {
159 Application,
160 Numeric
161 }
162
163 /**
164 * Arrow keys can emit three different sequences (DECCKM or VT52
165 * submode).
166 */
167 private enum ArrowKeyMode {
168 VT52,
169 ANSI,
170 VT100
171 }
172
173 /**
174 * Available character sets for GL, GR, G0, G1, G2, G3.
175 */
176 private enum CharacterSet {
177 US,
178 UK,
179 DRAWING,
180 ROM,
181 ROM_SPECIAL,
182 VT52_GRAPHICS,
183 DEC_SUPPLEMENTAL,
184 NRC_DUTCH,
185 NRC_FINNISH,
186 NRC_FRENCH,
187 NRC_FRENCH_CA,
188 NRC_GERMAN,
189 NRC_ITALIAN,
190 NRC_NORWEGIAN,
191 NRC_SPANISH,
192 NRC_SWEDISH,
193 NRC_SWISS
194 }
195
196 /**
197 * Single-shift states used by the C1 control characters SS2 (0x8E) and
198 * SS3 (0x8F).
199 */
200 private enum Singleshift {
201 NONE,
202 SS2,
203 SS3
204 }
205
206 /**
207 * VT220+ lockshift states.
208 */
209 private enum LockshiftMode {
210 NONE,
211 G1_GR,
212 G2_GR,
213 G2_GL,
214 G3_GR,
215 G3_GL
216 }
217
218 /**
219 * XTERM mouse reporting protocols.
220 */
221 public enum MouseProtocol {
222 OFF,
223 X10,
224 NORMAL,
225 BUTTONEVENT,
226 ANYEVENT
227 }
228
229 /**
230 * XTERM mouse reporting encodings.
231 */
232 private enum MouseEncoding {
233 X10,
234 UTF8,
235 SGR
236 }
237
238 // ------------------------------------------------------------------------
239 // Variables --------------------------------------------------------------
240 // ------------------------------------------------------------------------
241
242 /**
243 * The enclosing listening object.
244 */
245 private DisplayListener displayListener;
246
247 /**
248 * When true, the reader thread is expected to exit.
249 */
250 private volatile boolean stopReaderThread = false;
251
252 /**
253 * The reader thread.
254 */
255 private Thread readerThread = null;
256
257 /**
258 * The type of emulator to be.
259 */
260 private final DeviceType type;
261
262 /**
263 * The scrollback buffer characters + attributes.
264 */
265 private volatile ArrayList<DisplayLine> scrollback;
266
267 /**
268 * The raw display buffer characters + attributes.
269 */
270 private volatile ArrayList<DisplayLine> display;
271
272 /**
273 * The maximum number of lines in the scrollback buffer.
274 */
275 private int maxScrollback = 10000;
276
277 /**
278 * The terminal's input. For type == XTERM, this is an InputStreamReader
279 * with UTF-8 encoding.
280 */
281 private Reader input;
282
283 /**
284 * The terminal's raw InputStream. This is used for type != XTERM.
285 */
286 private volatile TimeoutInputStream inputStream;
287
288 /**
289 * The terminal's output. For type == XTERM, this wraps an
290 * OutputStreamWriter with UTF-8 encoding.
291 */
292 private Writer output;
293
294 /**
295 * The terminal's raw OutputStream. This is used for type != XTERM.
296 */
297 private OutputStream outputStream;
298
299 /**
300 * Current scanning state.
301 */
302 private ScanState scanState;
303
304 /**
305 * Which mouse protocol is active.
306 */
307 private MouseProtocol mouseProtocol = MouseProtocol.OFF;
308
309 /**
310 * Which mouse encoding is active.
311 */
312 private MouseEncoding mouseEncoding = MouseEncoding.X10;
313
314 /**
315 * A terminal may request that the mouse pointer be hidden using a
316 * Privacy Message containing either "hideMousePointer" or
317 * "showMousePointer". This is currently only used within Jexer by
318 * TTerminalWindow so that only the bottom-most instance of nested
319 * Jexer's draws the mouse within its application window.
320 */
321 private boolean hideMousePointer = false;
322
323 /**
324 * Physical display width. We start at 80x24, but the user can resize us
325 * bigger/smaller.
326 */
327 private int width;
328
329 /**
330 * Physical display height. We start at 80x24, but the user can resize
331 * us bigger/smaller.
332 */
333 private int height;
334
335 /**
336 * Top margin of the scrolling region.
337 */
338 private int scrollRegionTop;
339
340 /**
341 * Bottom margin of the scrolling region.
342 */
343 private int scrollRegionBottom;
344
345 /**
346 * Right margin column number. This can be selected by the remote side
347 * to be 80/132 (rightMargin values 79/131), or it can be (width - 1).
348 */
349 private int rightMargin;
350
351 /**
352 * Last character printed.
353 */
354 private int repCh;
355
356 /**
357 * VT100-style line wrapping: a character is placed in column 80 (or
358 * 132), but the line does NOT wrap until another character is written to
359 * column 1 of the next line, after which the cursor moves to column 2.
360 */
361 private boolean wrapLineFlag;
362
363 /**
364 * VT220 single shift flag.
365 */
366 private Singleshift singleshift = Singleshift.NONE;
367
368 /**
369 * true = insert characters, false = overwrite.
370 */
371 private boolean insertMode = false;
372
373 /**
374 * VT52 mode as selected by DECANM. True means VT52, false means
375 * ANSI. Default is ANSI.
376 */
377 private boolean vt52Mode = false;
378
379 /**
380 * Visible cursor (DECTCEM).
381 */
382 private boolean cursorVisible = true;
383
384 /**
385 * Screen title as set by the xterm OSC sequence. Lots of applications
386 * send a screenTitle regardless of whether it is an xterm client or not.
387 */
388 private String screenTitle = "";
389
390 /**
391 * Parameter characters being collected.
392 */
393 private List<Integer> csiParams;
394
395 /**
396 * Non-csi collect buffer.
397 */
398 private StringBuilder collectBuffer;
399
400 /**
401 * When true, use the G1 character set.
402 */
403 private boolean shiftOut = false;
404
405 /**
406 * Horizontal tab stop locations.
407 */
408 private List<Integer> tabStops;
409
410 /**
411 * S8C1T. True means 8bit controls, false means 7bit controls.
412 */
413 private boolean s8c1t = false;
414
415 /**
416 * Printer mode. True means send all output to printer, which discards
417 * it.
418 */
419 private boolean printerControllerMode = false;
420
421 /**
422 * LMN line mode. If true, linefeed() puts the cursor on the first
423 * column of the next line. If false, linefeed() puts the cursor one
424 * line down on the current line. The default is false.
425 */
426 private boolean newLineMode = false;
427
428 /**
429 * Whether arrow keys send ANSI, VT100, or VT52 sequences.
430 */
431 private ArrowKeyMode arrowKeyMode;
432
433 /**
434 * Whether number pad keys send VT100 or VT52, application or numeric
435 * sequences.
436 */
437 @SuppressWarnings("unused")
438 private KeypadMode keypadMode;
439
440 /**
441 * When true, the terminal is in 132-column mode (DECCOLM).
442 */
443 private boolean columns132 = false;
444
445 /**
446 * true = reverse video. Set by DECSCNM.
447 */
448 private boolean reverseVideo = false;
449
450 /**
451 * false = echo characters locally.
452 */
453 private boolean fullDuplex = true;
454
455 /**
456 * The current terminal state.
457 */
458 private SaveableState currentState;
459
460 /**
461 * The last saved terminal state.
462 */
463 private SaveableState savedState;
464
465 /**
466 * The 88- or 256-color support RGB colors.
467 */
468 private List<Integer> colors88;
469
470 /**
471 * Sixel collection buffer.
472 */
473 private StringBuilder sixelParseBuffer;
474
475 /**
476 * Sixel shared palette.
477 */
478 private HashMap<Integer, java.awt.Color> sixelPalette;
479
480 /**
481 * The width of a character cell in pixels.
482 */
483 private int textWidth = 16;
484
485 /**
486 * The height of a character cell in pixels.
487 */
488 private int textHeight = 20;
489
490 /**
491 * The last used height of a character cell in pixels, only used for
492 * full-width chars.
493 */
494 private int lastTextHeight = -1;
495
496 /**
497 * The glyph drawer for full-width chars.
498 */
499 private GlyphMaker glyphMaker = null;
500
501 /**
502 * Input queue for keystrokes and mouse events to send to the remote
503 * side.
504 */
505 private ArrayList<TInputEvent> userQueue = new ArrayList<TInputEvent>();
506
507 /**
508 * DECSC/DECRC save/restore a subset of the total state. This class
509 * encapsulates those specific flags/modes.
510 */
511 private class SaveableState {
512
513 /**
514 * When true, cursor positions are relative to the scrolling region.
515 */
516 public boolean originMode = false;
517
518 /**
519 * The current editing X position.
520 */
521 public int cursorX = 0;
522
523 /**
524 * The current editing Y position.
525 */
526 public int cursorY = 0;
527
528 /**
529 * Which character set is currently selected in G0.
530 */
531 public CharacterSet g0Charset = CharacterSet.US;
532
533 /**
534 * Which character set is currently selected in G1.
535 */
536 public CharacterSet g1Charset = CharacterSet.DRAWING;
537
538 /**
539 * Which character set is currently selected in G2.
540 */
541 public CharacterSet g2Charset = CharacterSet.US;
542
543 /**
544 * Which character set is currently selected in G3.
545 */
546 public CharacterSet g3Charset = CharacterSet.US;
547
548 /**
549 * Which character set is currently selected in GR.
550 */
551 public CharacterSet grCharset = CharacterSet.DRAWING;
552
553 /**
554 * The current drawing attributes.
555 */
556 public CellAttributes attr;
557
558 /**
559 * GL lockshift mode.
560 */
561 public LockshiftMode glLockshift = LockshiftMode.NONE;
562
563 /**
564 * GR lockshift mode.
565 */
566 public LockshiftMode grLockshift = LockshiftMode.NONE;
567
568 /**
569 * Line wrap.
570 */
571 public boolean lineWrap = true;
572
573 /**
574 * Reset to defaults.
575 */
576 public void reset() {
577 originMode = false;
578 cursorX = 0;
579 cursorY = 0;
580 g0Charset = CharacterSet.US;
581 g1Charset = CharacterSet.DRAWING;
582 g2Charset = CharacterSet.US;
583 g3Charset = CharacterSet.US;
584 grCharset = CharacterSet.DRAWING;
585 attr = new CellAttributes();
586 glLockshift = LockshiftMode.NONE;
587 grLockshift = LockshiftMode.NONE;
588 lineWrap = true;
589 }
590
591 /**
592 * Copy attributes from another instance.
593 *
594 * @param that the other instance to match
595 */
596 public void setTo(final SaveableState that) {
597 this.originMode = that.originMode;
598 this.cursorX = that.cursorX;
599 this.cursorY = that.cursorY;
600 this.g0Charset = that.g0Charset;
601 this.g1Charset = that.g1Charset;
602 this.g2Charset = that.g2Charset;
603 this.g3Charset = that.g3Charset;
604 this.grCharset = that.grCharset;
605 this.attr = new CellAttributes();
606 this.attr.setTo(that.attr);
607 this.glLockshift = that.glLockshift;
608 this.grLockshift = that.grLockshift;
609 this.lineWrap = that.lineWrap;
610 }
611
612 /**
613 * Public constructor.
614 */
615 public SaveableState() {
616 reset();
617 }
618 }
619
620 // ------------------------------------------------------------------------
621 // Constructors -----------------------------------------------------------
622 // ------------------------------------------------------------------------
623
624 /**
625 * Public constructor.
626 *
627 * @param type one of the DeviceType constants to select VT100, VT102,
628 * VT220, or XTERM
629 * @param inputStream an InputStream connected to the remote side. For
630 * type == XTERM, inputStream is converted to a Reader with UTF-8
631 * encoding.
632 * @param outputStream an OutputStream connected to the remote user. For
633 * type == XTERM, outputStream is converted to a Writer with UTF-8
634 * encoding.
635 * @param displayListener a callback to the outer display, or null for
636 * default VT100 behavior
637 * @throws UnsupportedEncodingException if an exception is thrown when
638 * creating the InputStreamReader
639 */
640 public ECMA48(final DeviceType type, final InputStream inputStream,
641 final OutputStream outputStream, final DisplayListener displayListener)
642 throws UnsupportedEncodingException {
643
644 assert (inputStream != null);
645 assert (outputStream != null);
646
647 csiParams = new ArrayList<Integer>();
648 tabStops = new ArrayList<Integer>();
649 scrollback = new ArrayList<DisplayLine>();
650 display = new ArrayList<DisplayLine>();
651
652 this.type = type;
653 if (inputStream instanceof TimeoutInputStream) {
654 this.inputStream = (TimeoutInputStream)inputStream;
655 } else {
656 this.inputStream = new TimeoutInputStream(inputStream, 2000);
657 }
658 if (type == DeviceType.XTERM) {
659 this.input = new InputStreamReader(new BufferedInputStream(
660 this.inputStream, 1024 * 128), "UTF-8");
661 this.output = new OutputStreamWriter(new
662 BufferedOutputStream(outputStream), "UTF-8");
663 this.outputStream = null;
664 } else {
665 this.output = null;
666 this.outputStream = new BufferedOutputStream(outputStream);
667 }
668 this.displayListener = displayListener;
669
670 reset();
671 for (int i = 0; i < height; i++) {
672 display.add(new DisplayLine(currentState.attr));
673 }
674
675 // Spin up the input reader
676 readerThread = new Thread(this);
677 readerThread.start();
678 }
679
680 // ------------------------------------------------------------------------
681 // Runnable ---------------------------------------------------------------
682 // ------------------------------------------------------------------------
683
684 /**
685 * Read function runs on a separate thread.
686 */
687 public final void run() {
688 boolean utf8 = false;
689 boolean done = false;
690
691 if (type == DeviceType.XTERM) {
692 utf8 = true;
693 }
694
695 // available() will often return > 1, so we need to read in chunks to
696 // stay caught up.
697 char [] readBufferUTF8 = null;
698 byte [] readBuffer = null;
699 if (utf8) {
700 readBufferUTF8 = new char[2048];
701 } else {
702 readBuffer = new byte[2048];
703 }
704
705 while (!done && !stopReaderThread) {
706 synchronized (userQueue) {
707 while (userQueue.size() > 0) {
708 handleUserEvent(userQueue.remove(0));
709 }
710 }
711
712 try {
713 int n = inputStream.available();
714
715 // System.err.printf("available() %d\n", n); System.err.flush();
716 if (utf8) {
717 if (readBufferUTF8.length < n) {
718 // The buffer wasn't big enough, make it huger
719 int newSizeHalf = Math.max(readBufferUTF8.length,
720 n);
721
722 readBufferUTF8 = new char[newSizeHalf * 2];
723 }
724 } else {
725 if (readBuffer.length < n) {
726 // The buffer wasn't big enough, make it huger
727 int newSizeHalf = Math.max(readBuffer.length, n);
728 readBuffer = new byte[newSizeHalf * 2];
729 }
730 }
731 if (n == 0) {
732 try {
733 Thread.sleep(10);
734 } catch (InterruptedException e) {
735 // SQUASH
736 }
737 continue;
738 }
739
740 int rc = -1;
741 try {
742 if (utf8) {
743 rc = input.read(readBufferUTF8, 0,
744 readBufferUTF8.length);
745 } else {
746 rc = inputStream.read(readBuffer, 0,
747 readBuffer.length);
748 }
749 } catch (ReadTimeoutException e) {
750 rc = 0;
751 }
752
753 // System.err.printf("read() %d\n", rc); System.err.flush();
754 if (rc == -1) {
755 // This is EOF
756 done = true;
757 } else {
758 // Don't step on UI events
759 synchronized (this) {
760 if (utf8) {
761 for (int i = 0; i < rc;) {
762 int ch = Character.codePointAt(readBufferUTF8,
763 i);
764 i += Character.charCount(ch);
765
766 // Special case for VT10x: 7-bit characters
767 // only.
768 if ((type == DeviceType.VT100)
769 || (type == DeviceType.VT102)
770 ) {
771 consume(ch & 0x7F);
772 } else {
773 consume(ch);
774 }
775 }
776 } else {
777 for (int i = 0; i < rc; i++) {
778 // Special case for VT10x: 7-bit characters
779 // only.
780 if ((type == DeviceType.VT100)
781 || (type == DeviceType.VT102)
782 ) {
783 consume(readBuffer[i] & 0x7F);
784 } else {
785 consume(readBuffer[i]);
786 }
787 }
788 }
789 }
790 // Permit my enclosing UI to know that I updated.
791 if (displayListener != null) {
792 displayListener.displayChanged();
793 }
794 }
795 // System.err.println("end while loop"); System.err.flush();
796 } catch (IOException e) {
797 done = true;
798
799 // This is an unusual case. We want to see the stack trace,
800 // but it is related to the spawned process rather than the
801 // actual UI. We will generate the stack trace, and consume
802 // it as though it was emitted by the shell.
803 CharArrayWriter writer= new CharArrayWriter();
804 // Send a ST and RIS to clear the emulator state.
805 try {
806 writer.write("\033\\\033c");
807 writer.write("\n-----------------------------------\n");
808 e.printStackTrace(new PrintWriter(writer));
809 writer.write("\n-----------------------------------\n");
810 } catch (IOException e2) {
811 // SQUASH
812 }
813 char [] stackTrace = writer.toCharArray();
814 for (int i = 0; i < stackTrace.length; i++) {
815 if (stackTrace[i] == '\n') {
816 consume('\r');
817 }
818 consume(stackTrace[i]);
819 }
820 }
821
822 } // while ((done == false) && (stopReaderThread == false))
823
824 // Let the rest of the world know that I am done.
825 stopReaderThread = true;
826
827 try {
828 inputStream.cancelRead();
829 inputStream.close();
830 inputStream = null;
831 } catch (IOException e) {
832 // SQUASH
833 }
834 try {
835 input.close();
836 input = null;
837 } catch (IOException e) {
838 // SQUASH
839 }
840
841 // Permit my enclosing UI to know that I updated.
842 if (displayListener != null) {
843 displayListener.displayChanged();
844 }
845
846 // System.err.println("*** run() exiting..."); System.err.flush();
847 }
848
849 // ------------------------------------------------------------------------
850 // ECMA48 -----------------------------------------------------------------
851 // ------------------------------------------------------------------------
852
853 /**
854 * Process keyboard and mouse events from the user.
855 *
856 * @param event the input event to consume
857 */
858 private void handleUserEvent(final TInputEvent event) {
859 if (event instanceof TKeypressEvent) {
860 keypress(((TKeypressEvent) event).getKey());
861 }
862 if (event instanceof TMouseEvent) {
863 mouse((TMouseEvent) event);
864 }
865 }
866
867 /**
868 * Add a keyboard and mouse event from the user to the queue.
869 *
870 * @param event the input event to consume
871 */
872 public void addUserEvent(final TInputEvent event) {
873 synchronized (userQueue) {
874 userQueue.add(event);
875 }
876 }
877
878 /**
879 * Return the proper primary Device Attributes string.
880 *
881 * @return string to send to remote side that is appropriate for the
882 * this.type
883 */
884 private String deviceTypeResponse() {
885 switch (type) {
886 case VT100:
887 // "I am a VT100 with advanced video option" (often VT102)
888 return "\033[?1;2c";
889
890 case VT102:
891 // "I am a VT102"
892 return "\033[?6c";
893
894 case VT220:
895 case XTERM:
896 // "I am a VT220" - 7 bit version
897 if (!s8c1t) {
898 return "\033[?62;1;6;9;4;22c";
899 // return "\033[?62;1;6;9;4;22;444c";
900 }
901 // "I am a VT220" - 8 bit version
902 return "\u009b?62;1;6;9;4;22c";
903 // return "\u009b?62;1;6;9;4;22;444c";
904 default:
905 throw new IllegalArgumentException("Invalid device type: " + type);
906 }
907 }
908
909 /**
910 * Return the proper TERM environment variable for this device type.
911 *
912 * @param deviceType DeviceType.VT100, DeviceType, XTERM, etc.
913 * @return "vt100", "xterm", etc.
914 */
915 public static String deviceTypeTerm(final DeviceType deviceType) {
916 switch (deviceType) {
917 case VT100:
918 return "vt100";
919
920 case VT102:
921 return "vt102";
922
923 case VT220:
924 return "vt220";
925
926 case XTERM:
927 return "xterm";
928
929 default:
930 throw new IllegalArgumentException("Invalid device type: "
931 + deviceType);
932 }
933 }
934
935 /**
936 * Return the proper LANG for this device type. Only XTERM devices know
937 * about UTF-8, the others are defined by their standard to be either
938 * 7-bit or 8-bit characters only.
939 *
940 * @param deviceType DeviceType.VT100, DeviceType, XTERM, etc.
941 * @param baseLang a base language without UTF-8 flag such as "C" or
942 * "en_US"
943 * @return "en_US", "en_US.UTF-8", etc.
944 */
945 public static String deviceTypeLang(final DeviceType deviceType,
946 final String baseLang) {
947
948 switch (deviceType) {
949
950 case VT100:
951 case VT102:
952 case VT220:
953 return baseLang;
954
955 case XTERM:
956 return baseLang + ".UTF-8";
957
958 default:
959 throw new IllegalArgumentException("Invalid device type: "
960 + deviceType);
961 }
962 }
963
964 /**
965 * Write a string directly to the remote side.
966 *
967 * @param str string to send
968 */
969 public void writeRemote(final String str) {
970 if (stopReaderThread) {
971 // Reader hit EOF, bail out now.
972 close();
973 return;
974 }
975
976 // System.err.printf("writeRemote() '%s'\n", str);
977
978 switch (type) {
979 case VT100:
980 case VT102:
981 case VT220:
982 if (outputStream == null) {
983 return;
984 }
985 try {
986 outputStream.flush();
987 for (int i = 0; i < str.length(); i++) {
988 outputStream.write(str.charAt(i));
989 }
990 outputStream.flush();
991 } catch (IOException e) {
992 // Assume EOF
993 close();
994 }
995 break;
996 case XTERM:
997 if (output == null) {
998 return;
999 }
1000 try {
1001 output.flush();
1002 output.write(str);
1003 output.flush();
1004 } catch (IOException e) {
1005 // Assume EOF
1006 close();
1007 }
1008 break;
1009 default:
1010 throw new IllegalArgumentException("Invalid device type: " + type);
1011 }
1012 }
1013
1014 /**
1015 * Close the input and output streams and stop the reader thread. Note
1016 * that it is safe to call this multiple times.
1017 */
1018 public final void close() {
1019
1020 // Tell the reader thread to stop looking at input. It will close
1021 // the input streams.
1022 if (stopReaderThread == false) {
1023 stopReaderThread = true;
1024 try {
1025 readerThread.join(1000);
1026 } catch (InterruptedException e) {
1027 // SQUASH
1028 }
1029 }
1030
1031 // Now close the output stream.
1032 switch (type) {
1033 case VT100:
1034 case VT102:
1035 case VT220:
1036 if (outputStream != null) {
1037 try {
1038 outputStream.close();
1039 } catch (IOException e) {
1040 // SQUASH
1041 }
1042 outputStream = null;
1043 }
1044 break;
1045 case XTERM:
1046 if (outputStream != null) {
1047 try {
1048 outputStream.close();
1049 } catch (IOException e) {
1050 // SQUASH
1051 }
1052 outputStream = null;
1053 }
1054 if (output != null) {
1055 try {
1056 output.close();
1057 } catch (IOException e) {
1058 // SQUASH
1059 }
1060 output = null;
1061 }
1062 break;
1063 default:
1064 throw new IllegalArgumentException("Invalid device type: " +
1065 type);
1066 }
1067 }
1068
1069 /**
1070 * See if the reader thread is still running.
1071 *
1072 * @return if true, we are still connected to / reading from the remote
1073 * side
1074 */
1075 public final boolean isReading() {
1076 return (!stopReaderThread);
1077 }
1078
1079 /**
1080 * Obtain a new blank display line for an external user
1081 * (e.g. TTerminalWindow).
1082 *
1083 * @return new blank line
1084 */
1085 public final DisplayLine getBlankDisplayLine() {
1086 return new DisplayLine(currentState.attr);
1087 }
1088
1089 /**
1090 * Get the scrollback buffer.
1091 *
1092 * @return the scrollback buffer
1093 */
1094 public final List<DisplayLine> getScrollbackBuffer() {
1095 return scrollback;
1096 }
1097
1098 /**
1099 * Get the display buffer.
1100 *
1101 * @return the display buffer
1102 */
1103 public final List<DisplayLine> getDisplayBuffer() {
1104 return display;
1105 }
1106
1107 /**
1108 * Get the visible display + scrollback buffer, offset by a specified
1109 * number of rows from the bottom.
1110 *
1111 * @param visibleHeight the total height of the display to show
1112 * @param scrollBottom the number of rows from the bottom to scroll back
1113 * @return a copy of the display + scrollback buffers
1114 */
1115 public final List<DisplayLine> getVisibleDisplay(final int visibleHeight,
1116 final int scrollBottom) {
1117
1118 assert (visibleHeight >= 0);
1119 assert (scrollBottom >= 0);
1120
1121 int visibleBottom = scrollback.size() + display.size() - scrollBottom;
1122
1123 List<DisplayLine> preceedingBlankLines = new ArrayList<DisplayLine>();
1124 int visibleTop = visibleBottom - visibleHeight;
1125 if (visibleTop < 0) {
1126 for (int i = visibleTop; i < 0; i++) {
1127 preceedingBlankLines.add(getBlankDisplayLine());
1128 }
1129 visibleTop = 0;
1130 }
1131 assert (visibleTop >= 0);
1132
1133 List<DisplayLine> displayLines = new ArrayList<DisplayLine>();
1134 displayLines.addAll(scrollback);
1135 displayLines.addAll(display);
1136
1137 List<DisplayLine> visibleLines = new ArrayList<DisplayLine>();
1138 visibleLines.addAll(preceedingBlankLines);
1139 visibleLines.addAll(displayLines.subList(visibleTop, visibleBottom));
1140
1141 // Fill in the blank lines on bottom
1142 int bottomBlankLines = visibleHeight - visibleLines.size();
1143 assert (bottomBlankLines >= 0);
1144 for (int i = 0; i < bottomBlankLines; i++) {
1145 visibleLines.add(getBlankDisplayLine());
1146 }
1147
1148 return copyBuffer(visibleLines);
1149 }
1150
1151 /**
1152 * Copy a display buffer.
1153 *
1154 * @param buffer the buffer to copy
1155 * @return a deep copy of the buffer's data
1156 */
1157 private List<DisplayLine> copyBuffer(final List<DisplayLine> buffer) {
1158 ArrayList<DisplayLine> result = new ArrayList<DisplayLine>(buffer.size());
1159 for (DisplayLine line: buffer) {
1160 result.add(new DisplayLine(line));
1161 }
1162 return result;
1163 }
1164
1165 /**
1166 * Get the display width.
1167 *
1168 * @return the width (usually 80 or 132)
1169 */
1170 public final int getWidth() {
1171 return width;
1172 }
1173
1174 /**
1175 * Set the display width.
1176 *
1177 * @param width the new width
1178 */
1179 public final synchronized void setWidth(final int width) {
1180 this.width = width;
1181 rightMargin = width - 1;
1182 if (currentState.cursorX >= width) {
1183 currentState.cursorX = width - 1;
1184 }
1185 if (savedState.cursorX >= width) {
1186 savedState.cursorX = width - 1;
1187 }
1188 }
1189
1190 /**
1191 * Get the display height.
1192 *
1193 * @return the height (usually 24)
1194 */
1195 public final int getHeight() {
1196 return height;
1197 }
1198
1199 /**
1200 * Set the display height.
1201 *
1202 * @param height the new height
1203 */
1204 public final synchronized void setHeight(final int height) {
1205 int delta = height - this.height;
1206 this.height = height;
1207 scrollRegionBottom += delta;
1208 if (scrollRegionBottom < 0) {
1209 scrollRegionBottom = height;
1210 }
1211 if (scrollRegionTop >= scrollRegionBottom) {
1212 scrollRegionTop = 0;
1213 }
1214 if (currentState.cursorY >= height) {
1215 currentState.cursorY = height - 1;
1216 }
1217 if (savedState.cursorY >= height) {
1218 savedState.cursorY = height - 1;
1219 }
1220 while (display.size() < height) {
1221 DisplayLine line = new DisplayLine(currentState.attr);
1222 line.setReverseColor(reverseVideo);
1223 display.add(line);
1224 }
1225 while (display.size() > height) {
1226 scrollback.add(display.remove(0));
1227 }
1228 }
1229
1230 /**
1231 * Get visible cursor flag.
1232 *
1233 * @return if true, the cursor is visible
1234 */
1235 public final boolean isCursorVisible() {
1236 return cursorVisible;
1237 }
1238
1239 /**
1240 * Get the screen title as set by the xterm OSC sequence. Lots of
1241 * applications send a screenTitle regardless of whether it is an xterm
1242 * client or not.
1243 *
1244 * @return screen title
1245 */
1246 public final String getScreenTitle() {
1247 return screenTitle;
1248 }
1249
1250 /**
1251 * Get 132 columns value.
1252 *
1253 * @return if true, the terminal is in 132 column mode
1254 */
1255 public final boolean isColumns132() {
1256 return columns132;
1257 }
1258
1259 /**
1260 * Clear the CSI parameters and flags.
1261 */
1262 private void toGround() {
1263 csiParams.clear();
1264 collectBuffer = new StringBuilder(8);
1265 scanState = ScanState.GROUND;
1266 }
1267
1268 /**
1269 * Reset the tab stops list.
1270 */
1271 private void resetTabStops() {
1272 tabStops.clear();
1273 for (int i = 0; (i * 8) <= rightMargin; i++) {
1274 tabStops.add(Integer.valueOf(i * 8));
1275 }
1276 }
1277
1278 /**
1279 * Reset the 88- or 256-colors.
1280 */
1281 private void resetColors() {
1282 colors88 = new ArrayList<Integer>(256);
1283 for (int i = 0; i < 256; i++) {
1284 colors88.add(0);
1285 }
1286
1287 // Set default system colors.
1288 colors88.set(0, 0x00000000);
1289 colors88.set(1, 0x00a80000);
1290 colors88.set(2, 0x0000a800);
1291 colors88.set(3, 0x00a85400);
1292 colors88.set(4, 0x000000a8);
1293 colors88.set(5, 0x00a800a8);
1294 colors88.set(6, 0x0000a8a8);
1295 colors88.set(7, 0x00a8a8a8);
1296
1297 colors88.set(8, 0x00545454);
1298 colors88.set(9, 0x00fc5454);
1299 colors88.set(10, 0x0054fc54);
1300 colors88.set(11, 0x00fcfc54);
1301 colors88.set(12, 0x005454fc);
1302 colors88.set(13, 0x00fc54fc);
1303 colors88.set(14, 0x0054fcfc);
1304 colors88.set(15, 0x00fcfcfc);
1305 }
1306
1307 /**
1308 * Get the RGB value of one of the indexed colors.
1309 *
1310 * @param index the color index
1311 * @return the RGB value
1312 */
1313 private int get88Color(final int index) {
1314 // System.err.print("get88Color: " + index);
1315 if ((index < 0) || (index > colors88.size())) {
1316 // System.err.println(" -- UNKNOWN");
1317 return 0;
1318 }
1319 // System.err.printf(" %08x\n", colors88.get(index));
1320 return colors88.get(index);
1321 }
1322
1323 /**
1324 * Set one of the indexed colors to a color specification.
1325 *
1326 * @param index the color index
1327 * @param spec the specification, typically something like "rgb:aa/bb/cc"
1328 */
1329 private void set88Color(final int index, final String spec) {
1330 // System.err.println("set88Color: " + index + " '" + spec + "'");
1331
1332 if ((index < 0) || (index > colors88.size())) {
1333 return;
1334 }
1335 if (spec.startsWith("rgb:")) {
1336 String [] rgbTokens = spec.substring(4).split("/");
1337 if (rgbTokens.length == 3) {
1338 try {
1339 int rgb = (Integer.parseInt(rgbTokens[0], 16) << 16);
1340 rgb |= Integer.parseInt(rgbTokens[1], 16) << 8;
1341 rgb |= Integer.parseInt(rgbTokens[2], 16);
1342 // System.err.printf(" set to %08x\n", rgb);
1343 colors88.set(index, rgb);
1344 } catch (NumberFormatException e) {
1345 // SQUASH
1346 }
1347 }
1348 return;
1349 }
1350
1351 if (spec.toLowerCase().equals("black")) {
1352 colors88.set(index, 0x00000000);
1353 } else if (spec.toLowerCase().equals("red")) {
1354 colors88.set(index, 0x00a80000);
1355 } else if (spec.toLowerCase().equals("green")) {
1356 colors88.set(index, 0x0000a800);
1357 } else if (spec.toLowerCase().equals("yellow")) {
1358 colors88.set(index, 0x00a85400);
1359 } else if (spec.toLowerCase().equals("blue")) {
1360 colors88.set(index, 0x000000a8);
1361 } else if (spec.toLowerCase().equals("magenta")) {
1362 colors88.set(index, 0x00a800a8);
1363 } else if (spec.toLowerCase().equals("cyan")) {
1364 colors88.set(index, 0x0000a8a8);
1365 } else if (spec.toLowerCase().equals("white")) {
1366 colors88.set(index, 0x00a8a8a8);
1367 }
1368
1369 }
1370
1371 /**
1372 * Reset the emulation state.
1373 */
1374 private void reset() {
1375
1376 currentState = new SaveableState();
1377 savedState = new SaveableState();
1378 scanState = ScanState.GROUND;
1379 width = 80;
1380 height = 24;
1381 scrollRegionTop = 0;
1382 scrollRegionBottom = height - 1;
1383 rightMargin = width - 1;
1384 newLineMode = false;
1385 arrowKeyMode = ArrowKeyMode.ANSI;
1386 keypadMode = KeypadMode.Numeric;
1387 wrapLineFlag = false;
1388 if (displayListener != null) {
1389 width = displayListener.getDisplayWidth();
1390 height = displayListener.getDisplayHeight();
1391 rightMargin = width - 1;
1392 }
1393
1394 // Flags
1395 shiftOut = false;
1396 vt52Mode = false;
1397 insertMode = false;
1398 columns132 = false;
1399 newLineMode = false;
1400 reverseVideo = false;
1401 fullDuplex = true;
1402 cursorVisible = true;
1403
1404 // VT220
1405 singleshift = Singleshift.NONE;
1406 s8c1t = false;
1407 printerControllerMode = false;
1408
1409 // XTERM
1410 mouseProtocol = MouseProtocol.OFF;
1411 mouseEncoding = MouseEncoding.X10;
1412
1413 // Tab stops
1414 resetTabStops();
1415
1416 // Reset extra colors
1417 resetColors();
1418
1419 // Clear CSI stuff
1420 toGround();
1421 }
1422
1423 /**
1424 * Append a new line to the bottom of the display, adding lines off the
1425 * top to the scrollback buffer.
1426 */
1427 private void newDisplayLine() {
1428 // Scroll the top line off into the scrollback buffer
1429 scrollback.add(display.get(0));
1430 if (scrollback.size() > maxScrollback) {
1431 scrollback.remove(0);
1432 scrollback.trimToSize();
1433 }
1434 display.remove(0);
1435 display.trimToSize();
1436 DisplayLine line = new DisplayLine(currentState.attr);
1437 line.setReverseColor(reverseVideo);
1438 display.add(line);
1439 }
1440
1441 /**
1442 * Wraps the current line.
1443 */
1444 private void wrapCurrentLine() {
1445 if (currentState.cursorY == height - 1) {
1446 newDisplayLine();
1447 }
1448 if (currentState.cursorY < height - 1) {
1449 currentState.cursorY++;
1450 }
1451 currentState.cursorX = 0;
1452 }
1453
1454 /**
1455 * Handle a carriage return.
1456 */
1457 private void carriageReturn() {
1458 currentState.cursorX = 0;
1459 wrapLineFlag = false;
1460 }
1461
1462 /**
1463 * Reverse the color of the visible display.
1464 */
1465 private void invertDisplayColors() {
1466 for (DisplayLine line: display) {
1467 line.setReverseColor(!line.isReverseColor());
1468 }
1469 }
1470
1471 /**
1472 * Handle a linefeed.
1473 */
1474 private void linefeed() {
1475
1476 if (currentState.cursorY < scrollRegionBottom) {
1477 // Increment screen y
1478 currentState.cursorY++;
1479 } else {
1480
1481 // Screen y does not increment
1482
1483 /*
1484 * Two cases: either we're inside a scrolling region or not. If
1485 * the scrolling region bottom is the bottom of the screen, then
1486 * push the top line into the buffer. Else scroll the scrolling
1487 * region up.
1488 */
1489 if ((scrollRegionBottom == height - 1) && (scrollRegionTop == 0)) {
1490
1491 // We're at the bottom of the scroll region, AND the scroll
1492 // region is the entire screen.
1493
1494 // New line
1495 newDisplayLine();
1496
1497 } else {
1498 // We're at the bottom of the scroll region, AND the scroll
1499 // region is NOT the entire screen.
1500 scrollingRegionScrollUp(scrollRegionTop, scrollRegionBottom, 1);
1501 }
1502 }
1503
1504 if (newLineMode) {
1505 currentState.cursorX = 0;
1506 }
1507 wrapLineFlag = false;
1508 }
1509
1510 /**
1511 * Prints one character to the display buffer.
1512 *
1513 * @param ch character to display
1514 */
1515 private void printCharacter(final int ch) {
1516 int rightMargin = this.rightMargin;
1517
1518 if (StringUtils.width(ch) == 2) {
1519 // This is a full-width character. Save two spaces, and then
1520 // draw the character as two image halves.
1521 int x0 = currentState.cursorX;
1522 int y0 = currentState.cursorY;
1523 printCharacter(' ');
1524 printCharacter(' ');
1525 if ((currentState.cursorX == x0 + 2)
1526 && (currentState.cursorY == y0)
1527 ) {
1528 // We can draw both halves of the character.
1529 drawHalves(x0, y0, x0 + 1, y0, ch);
1530 } else if ((currentState.cursorX == x0 + 1)
1531 && (currentState.cursorY == y0)
1532 ) {
1533 // VT100 line wrap behavior: we should be at the right
1534 // margin. We can draw both halves of the character.
1535 drawHalves(x0, y0, x0 + 1, y0, ch);
1536 } else {
1537 // The character splits across the line. Draw the entire
1538 // character on the new line, giving one more space for it.
1539 x0 = currentState.cursorX - 1;
1540 y0 = currentState.cursorY;
1541 printCharacter(' ');
1542 drawHalves(x0, y0, x0 + 1, y0, ch);
1543 }
1544 return;
1545 }
1546
1547 // Check if we have double-width, and if so chop at 40/66 instead of
1548 // 80/132
1549 if (display.get(currentState.cursorY).isDoubleWidth()) {
1550 rightMargin = ((rightMargin + 1) / 2) - 1;
1551 }
1552
1553 // Check the unusually-complicated line wrapping conditions...
1554 if (currentState.cursorX == rightMargin) {
1555
1556 if (currentState.lineWrap == true) {
1557 /*
1558 * This case happens when: the cursor was already on the
1559 * right margin (either through printing or by an explicit
1560 * placement command), and a character was printed.
1561 *
1562 * The line wraps only when a new character arrives AND the
1563 * cursor is already on the right margin AND has placed a
1564 * character in its cell. Easier to see than to explain.
1565 */
1566 if (wrapLineFlag == false) {
1567 /*
1568 * This block marks the case that we are in the margin
1569 * and the first character has been received and printed.
1570 */
1571 wrapLineFlag = true;
1572 } else {
1573 /*
1574 * This block marks the case that we are in the margin
1575 * and the second character has been received and
1576 * printed.
1577 */
1578 wrapLineFlag = false;
1579 wrapCurrentLine();
1580 }
1581 }
1582 } else if (currentState.cursorX <= rightMargin) {
1583 /*
1584 * This is the normal case: a character came in and was printed
1585 * to the left of the right margin column.
1586 */
1587
1588 // Turn off VT100 special-case flag
1589 wrapLineFlag = false;
1590 }
1591
1592 // "Print" the character
1593 Cell newCell = new Cell(ch);
1594 CellAttributes newCellAttributes = (CellAttributes) newCell;
1595 newCellAttributes.setTo(currentState.attr);
1596 DisplayLine line = display.get(currentState.cursorY);
1597
1598 if (StringUtils.width(ch) == 1) {
1599 // Insert mode special case
1600 if (insertMode == true) {
1601 line.insert(currentState.cursorX, newCell);
1602 } else {
1603 // Replace an existing character
1604 line.replace(currentState.cursorX, newCell);
1605 }
1606
1607 // Increment horizontal
1608 if (wrapLineFlag == false) {
1609 currentState.cursorX++;
1610 if (currentState.cursorX > rightMargin) {
1611 currentState.cursorX--;
1612 }
1613 }
1614 }
1615 }
1616
1617 /**
1618 * Translate the mouse event to a VT100, VT220, or XTERM sequence and
1619 * send to the remote side.
1620 *
1621 * @param mouse mouse event received from the local user
1622 */
1623 private void mouse(final TMouseEvent mouse) {
1624
1625 /*
1626 System.err.printf("mouse(): protocol %s encoding %s mouse %s\n",
1627 mouseProtocol, mouseEncoding, mouse);
1628 */
1629
1630 if (mouseEncoding == MouseEncoding.X10) {
1631 // We will support X10 but only for (160,94) and smaller.
1632 if ((mouse.getX() >= 160) || (mouse.getY() >= 94)) {
1633 return;
1634 }
1635 }
1636
1637 switch (mouseProtocol) {
1638
1639 case OFF:
1640 // Do nothing
1641 return;
1642
1643 case X10:
1644 // Only report button presses
1645 if (mouse.getType() != TMouseEvent.Type.MOUSE_DOWN) {
1646 return;
1647 }
1648 break;
1649
1650 case NORMAL:
1651 // Only report button presses and releases
1652 if ((mouse.getType() != TMouseEvent.Type.MOUSE_DOWN)
1653 && (mouse.getType() != TMouseEvent.Type.MOUSE_UP)
1654 ) {
1655 return;
1656 }
1657 break;
1658
1659 case BUTTONEVENT:
1660 /*
1661 * Only report button presses, button releases, and motions that
1662 * have a button down (i.e. drag-and-drop).
1663 */
1664 if (mouse.getType() == TMouseEvent.Type.MOUSE_MOTION) {
1665 if (!mouse.isMouse1()
1666 && !mouse.isMouse2()
1667 && !mouse.isMouse3()
1668 && !mouse.isMouseWheelUp()
1669 && !mouse.isMouseWheelDown()
1670 ) {
1671 return;
1672 }
1673 }
1674 break;
1675
1676 case ANYEVENT:
1677 // Report everything
1678 break;
1679 }
1680
1681 // Now encode the event
1682 StringBuilder sb = new StringBuilder(6);
1683 if (mouseEncoding == MouseEncoding.SGR) {
1684 sb.append((char) 0x1B);
1685 sb.append("[<");
1686
1687 if (mouse.isMouse1()) {
1688 if (mouse.getType() == TMouseEvent.Type.MOUSE_MOTION) {
1689 sb.append("32;");
1690 } else {
1691 sb.append("0;");
1692 }
1693 } else if (mouse.isMouse2()) {
1694 if (mouse.getType() == TMouseEvent.Type.MOUSE_MOTION) {
1695 sb.append("33;");
1696 } else {
1697 sb.append("1;");
1698 }
1699 } else if (mouse.isMouse3()) {
1700 if (mouse.getType() == TMouseEvent.Type.MOUSE_MOTION) {
1701 sb.append("34;");
1702 } else {
1703 sb.append("2;");
1704 }
1705 } else if (mouse.isMouseWheelUp()) {
1706 sb.append("64;");
1707 } else if (mouse.isMouseWheelDown()) {
1708 sb.append("65;");
1709 } else {
1710 // This is motion with no buttons down.
1711 sb.append("35;");
1712 }
1713
1714 sb.append(String.format("%d;%d", mouse.getX() + 1,
1715 mouse.getY() + 1));
1716
1717 if (mouse.getType() == TMouseEvent.Type.MOUSE_UP) {
1718 sb.append("m");
1719 } else {
1720 sb.append("M");
1721 }
1722
1723 } else {
1724 // X10 and UTF8 encodings
1725 sb.append((char) 0x1B);
1726 sb.append('[');
1727 sb.append('M');
1728 if (mouse.getType() == TMouseEvent.Type.MOUSE_UP) {
1729 sb.append((char) (0x03 + 32));
1730 } else if (mouse.isMouse1()) {
1731 if (mouse.getType() == TMouseEvent.Type.MOUSE_MOTION) {
1732 sb.append((char) (0x00 + 32 + 32));
1733 } else {
1734 sb.append((char) (0x00 + 32));
1735 }
1736 } else if (mouse.isMouse2()) {
1737 if (mouse.getType() == TMouseEvent.Type.MOUSE_MOTION) {
1738 sb.append((char) (0x01 + 32 + 32));
1739 } else {
1740 sb.append((char) (0x01 + 32));
1741 }
1742 } else if (mouse.isMouse3()) {
1743 if (mouse.getType() == TMouseEvent.Type.MOUSE_MOTION) {
1744 sb.append((char) (0x02 + 32 + 32));
1745 } else {
1746 sb.append((char) (0x02 + 32));
1747 }
1748 } else if (mouse.isMouseWheelUp()) {
1749 sb.append((char) (0x04 + 64));
1750 } else if (mouse.isMouseWheelDown()) {
1751 sb.append((char) (0x05 + 64));
1752 } else {
1753 // This is motion with no buttons down.
1754 sb.append((char) (0x03 + 32));
1755 }
1756
1757 sb.append((char) (mouse.getX() + 33));
1758 sb.append((char) (mouse.getY() + 33));
1759 }
1760
1761 // System.err.printf("Would write: \'%s\'\n", sb.toString());
1762 writeRemote(sb.toString());
1763 }
1764
1765 /**
1766 * Translate the keyboard press to a VT100, VT220, or XTERM sequence and
1767 * send to the remote side.
1768 *
1769 * @param keypress keypress received from the local user
1770 */
1771 private void keypress(final TKeypress keypress) {
1772 writeRemote(keypressToString(keypress));
1773 }
1774
1775 /**
1776 * Build one of the complex xterm keystroke sequences, storing the result in
1777 * xterm_keystroke_buffer.
1778 *
1779 * @param ss3 the prefix to use based on VT100 state.
1780 * @param first the first character, usually a number.
1781 * @param first the last character, one of the following: ~ A B C D F H
1782 * @param ctrl whether or not ctrl is down
1783 * @param alt whether or not alt is down
1784 * @param shift whether or not shift is down
1785 * @return the buffer with the full key sequence
1786 */
1787 private String xtermBuildKeySequence(final String ss3, final char first,
1788 final char last, boolean ctrl, boolean alt, boolean shift) {
1789
1790 StringBuilder sb = new StringBuilder(ss3);
1791 if ((last == '~') || (ctrl == true) || (alt == true)
1792 || (shift == true)
1793 ) {
1794 sb.append(first);
1795 if ( (ctrl == false) && (alt == false) && (shift == true)) {
1796 sb.append(";2");
1797 } else if ((ctrl == false) && (alt == true) && (shift == false)) {
1798 sb.append(";3");
1799 } else if ((ctrl == false) && (alt == true) && (shift == true)) {
1800 sb.append(";4");
1801 } else if ((ctrl == true) && (alt == false) && (shift == false)) {
1802 sb.append(";5");
1803 } else if ((ctrl == true) && (alt == false) && (shift == true)) {
1804 sb.append(";6");
1805 } else if ((ctrl == true) && (alt == true) && (shift == false)) {
1806 sb.append(";7");
1807 } else if ((ctrl == true) && (alt == true) && (shift == true)) {
1808 sb.append(";8");
1809 }
1810 }
1811 sb.append(last);
1812 return sb.toString();
1813 }
1814
1815 /**
1816 * Translate the keyboard press to a VT100, VT220, or XTERM sequence.
1817 *
1818 * @param keypress keypress received from the local user
1819 * @return string to transmit to the remote side
1820 */
1821 @SuppressWarnings("fallthrough")
1822 private String keypressToString(final TKeypress keypress) {
1823
1824 if ((fullDuplex == false) && (!keypress.isFnKey())) {
1825 /*
1826 * If this is a control character, process it like it came from
1827 * the remote side.
1828 */
1829 if (keypress.getChar() < 0x20) {
1830 handleControlChar((char) keypress.getChar());
1831 } else {
1832 // Local echo for everything else
1833 printCharacter(keypress.getChar());
1834 }
1835 if (displayListener != null) {
1836 displayListener.displayChanged();
1837 }
1838 }
1839
1840 if ((newLineMode == true) && (keypress.equals(kbEnter))) {
1841 // NLM: send CRLF
1842 return "\015\012";
1843 }
1844
1845 // Handle control characters
1846 if ((keypress.isCtrl()) && (!keypress.isFnKey())) {
1847 StringBuilder sb = new StringBuilder();
1848 int ch = keypress.getChar();
1849 ch -= 0x40;
1850 sb.append(Character.toChars(ch));
1851 return sb.toString();
1852 }
1853
1854 // Handle alt characters
1855 if ((keypress.isAlt()) && (!keypress.isFnKey())) {
1856 StringBuilder sb = new StringBuilder("\033");
1857 int ch = keypress.getChar();
1858 sb.append(Character.toChars(ch));
1859 return sb.toString();
1860 }
1861
1862 if (keypress.equals(kbBackspaceDel)) {
1863 switch (type) {
1864 case VT100:
1865 return "\010";
1866 case VT102:
1867 return "\010";
1868 case VT220:
1869 return "\177";
1870 case XTERM:
1871 return "\177";
1872 }
1873 }
1874
1875 if (keypress.equalsWithoutModifiers(kbLeft)) {
1876 switch (type) {
1877 case XTERM:
1878 switch (arrowKeyMode) {
1879 case ANSI:
1880 return xtermBuildKeySequence("\033[", '1', 'D',
1881 keypress.isCtrl(), keypress.isAlt(),
1882 keypress.isShift());
1883 case VT52:
1884 return xtermBuildKeySequence("\033", '1', 'D',
1885 keypress.isCtrl(), keypress.isAlt(),
1886 keypress.isShift());
1887 case VT100:
1888 return xtermBuildKeySequence("\033O", '1', 'D',
1889 keypress.isCtrl(), keypress.isAlt(),
1890 keypress.isShift());
1891 }
1892 default:
1893 switch (arrowKeyMode) {
1894 case ANSI:
1895 return "\033[D";
1896 case VT52:
1897 return "\033D";
1898 case VT100:
1899 return "\033OD";
1900 }
1901 }
1902 }
1903
1904 if (keypress.equalsWithoutModifiers(kbRight)) {
1905 switch (type) {
1906 case XTERM:
1907 switch (arrowKeyMode) {
1908 case ANSI:
1909 return xtermBuildKeySequence("\033[", '1', 'C',
1910 keypress.isCtrl(), keypress.isAlt(),
1911 keypress.isShift());
1912 case VT52:
1913 return xtermBuildKeySequence("\033", '1', 'C',
1914 keypress.isCtrl(), keypress.isAlt(),
1915 keypress.isShift());
1916 case VT100:
1917 return xtermBuildKeySequence("\033O", '1', 'C',
1918 keypress.isCtrl(), keypress.isAlt(),
1919 keypress.isShift());
1920 }
1921 default:
1922 switch (arrowKeyMode) {
1923 case ANSI:
1924 return "\033[C";
1925 case VT52:
1926 return "\033C";
1927 case VT100:
1928 return "\033OC";
1929 }
1930 }
1931 }
1932
1933 if (keypress.equalsWithoutModifiers(kbUp)) {
1934 switch (type) {
1935 case XTERM:
1936 switch (arrowKeyMode) {
1937 case ANSI:
1938 return xtermBuildKeySequence("\033[", '1', 'A',
1939 keypress.isCtrl(), keypress.isAlt(),
1940 keypress.isShift());
1941 case VT52:
1942 return xtermBuildKeySequence("\033", '1', 'A',
1943 keypress.isCtrl(), keypress.isAlt(),
1944 keypress.isShift());
1945 case VT100:
1946 return xtermBuildKeySequence("\033O", '1', 'A',
1947 keypress.isCtrl(), keypress.isAlt(),
1948 keypress.isShift());
1949 }
1950 default:
1951 switch (arrowKeyMode) {
1952 case ANSI:
1953 return "\033[A";
1954 case VT52:
1955 return "\033A";
1956 case VT100:
1957 return "\033OA";
1958 }
1959 }
1960 }
1961
1962 if (keypress.equalsWithoutModifiers(kbDown)) {
1963 switch (type) {
1964 case XTERM:
1965 switch (arrowKeyMode) {
1966 case ANSI:
1967 return xtermBuildKeySequence("\033[", '1', 'B',
1968 keypress.isCtrl(), keypress.isAlt(),
1969 keypress.isShift());
1970 case VT52:
1971 return xtermBuildKeySequence("\033", '1', 'B',
1972 keypress.isCtrl(), keypress.isAlt(),
1973 keypress.isShift());
1974 case VT100:
1975 return xtermBuildKeySequence("\033O", '1', 'B',
1976 keypress.isCtrl(), keypress.isAlt(),
1977 keypress.isShift());
1978 }
1979 default:
1980 switch (arrowKeyMode) {
1981 case ANSI:
1982 return "\033[B";
1983 case VT52:
1984 return "\033B";
1985 case VT100:
1986 return "\033OB";
1987 }
1988 }
1989 }
1990
1991 if (keypress.equalsWithoutModifiers(kbHome)) {
1992 switch (type) {
1993 case XTERM:
1994 switch (arrowKeyMode) {
1995 case ANSI:
1996 return xtermBuildKeySequence("\033[", '1', 'H',
1997 keypress.isCtrl(), keypress.isAlt(),
1998 keypress.isShift());
1999 case VT52:
2000 return xtermBuildKeySequence("\033", '1', 'H',
2001 keypress.isCtrl(), keypress.isAlt(),
2002 keypress.isShift());
2003 case VT100:
2004 return xtermBuildKeySequence("\033O", '1', 'H',
2005 keypress.isCtrl(), keypress.isAlt(),
2006 keypress.isShift());
2007 }
2008 default:
2009 switch (arrowKeyMode) {
2010 case ANSI:
2011 return "\033[H";
2012 case VT52:
2013 return "\033H";
2014 case VT100:
2015 return "\033OH";
2016 }
2017 }
2018 }
2019
2020 if (keypress.equalsWithoutModifiers(kbEnd)) {
2021 switch (type) {
2022 case XTERM:
2023 switch (arrowKeyMode) {
2024 case ANSI:
2025 return xtermBuildKeySequence("\033[", '1', 'F',
2026 keypress.isCtrl(), keypress.isAlt(),
2027 keypress.isShift());
2028 case VT52:
2029 return xtermBuildKeySequence("\033", '1', 'F',
2030 keypress.isCtrl(), keypress.isAlt(),
2031 keypress.isShift());
2032 case VT100:
2033 return xtermBuildKeySequence("\033O", '1', 'F',
2034 keypress.isCtrl(), keypress.isAlt(),
2035 keypress.isShift());
2036 }
2037 default:
2038 switch (arrowKeyMode) {
2039 case ANSI:
2040 return "\033[F";
2041 case VT52:
2042 return "\033F";
2043 case VT100:
2044 return "\033OF";
2045 }
2046 }
2047 }
2048
2049 if (keypress.equals(kbF1)) {
2050 // PF1
2051 if (vt52Mode) {
2052 return "\033P";
2053 }
2054 return "\033OP";
2055 }
2056
2057 if (keypress.equals(kbF2)) {
2058 // PF2
2059 if (vt52Mode) {
2060 return "\033Q";
2061 }
2062 return "\033OQ";
2063 }
2064
2065 if (keypress.equals(kbF3)) {
2066 // PF3
2067 if (vt52Mode) {
2068 return "\033R";
2069 }
2070 return "\033OR";
2071 }
2072
2073 if (keypress.equals(kbF4)) {
2074 // PF4
2075 if (vt52Mode) {
2076 return "\033S";
2077 }
2078 return "\033OS";
2079 }
2080
2081 if (keypress.equals(kbF5)) {
2082 switch (type) {
2083 case VT100:
2084 return "\033Ot";
2085 case VT102:
2086 return "\033Ot";
2087 case VT220:
2088 return "\033[15~";
2089 case XTERM:
2090 return "\033[15~";
2091 }
2092 }
2093
2094 if (keypress.equals(kbF6)) {
2095 switch (type) {
2096 case VT100:
2097 return "\033Ou";
2098 case VT102:
2099 return "\033Ou";
2100 case VT220:
2101 return "\033[17~";
2102 case XTERM:
2103 return "\033[17~";
2104 }
2105 }
2106
2107 if (keypress.equals(kbF7)) {
2108 switch (type) {
2109 case VT100:
2110 return "\033Ov";
2111 case VT102:
2112 return "\033Ov";
2113 case VT220:
2114 return "\033[18~";
2115 case XTERM:
2116 return "\033[18~";
2117 }
2118 }
2119
2120 if (keypress.equals(kbF8)) {
2121 switch (type) {
2122 case VT100:
2123 return "\033Ol";
2124 case VT102:
2125 return "\033Ol";
2126 case VT220:
2127 return "\033[19~";
2128 case XTERM:
2129 return "\033[19~";
2130 }
2131 }
2132
2133 if (keypress.equals(kbF9)) {
2134 switch (type) {
2135 case VT100:
2136 return "\033Ow";
2137 case VT102:
2138 return "\033Ow";
2139 case VT220:
2140 return "\033[20~";
2141 case XTERM:
2142 return "\033[20~";
2143 }
2144 }
2145
2146 if (keypress.equals(kbF10)) {
2147 switch (type) {
2148 case VT100:
2149 return "\033Ox";
2150 case VT102:
2151 return "\033Ox";
2152 case VT220:
2153 return "\033[21~";
2154 case XTERM:
2155 return "\033[21~";
2156 }
2157 }
2158
2159 if (keypress.equals(kbF11)) {
2160 return "\033[23~";
2161 }
2162
2163 if (keypress.equals(kbF12)) {
2164 return "\033[24~";
2165 }
2166
2167 if (keypress.equals(kbShiftF1)) {
2168 // Shifted PF1
2169 if (vt52Mode) {
2170 return "\0332P";
2171 }
2172 if (type == DeviceType.XTERM) {
2173 return "\0331;2P";
2174 }
2175 return "\033O2P";
2176 }
2177
2178 if (keypress.equals(kbShiftF2)) {
2179 // Shifted PF2
2180 if (vt52Mode) {
2181 return "\0332Q";
2182 }
2183 if (type == DeviceType.XTERM) {
2184 return "\0331;2Q";
2185 }
2186 return "\033O2Q";
2187 }
2188
2189 if (keypress.equals(kbShiftF3)) {
2190 // Shifted PF3
2191 if (vt52Mode) {
2192 return "\0332R";
2193 }
2194 if (type == DeviceType.XTERM) {
2195 return "\0331;2R";
2196 }
2197 return "\033O2R";
2198 }
2199
2200 if (keypress.equals(kbShiftF4)) {
2201 // Shifted PF4
2202 if (vt52Mode) {
2203 return "\0332S";
2204 }
2205 if (type == DeviceType.XTERM) {
2206 return "\0331;2S";
2207 }
2208 return "\033O2S";
2209 }
2210
2211 if (keypress.equals(kbShiftF5)) {
2212 // Shifted F5
2213 return "\033[15;2~";
2214 }
2215
2216 if (keypress.equals(kbShiftF6)) {
2217 // Shifted F6
2218 return "\033[17;2~";
2219 }
2220
2221 if (keypress.equals(kbShiftF7)) {
2222 // Shifted F7
2223 return "\033[18;2~";
2224 }
2225
2226 if (keypress.equals(kbShiftF8)) {
2227 // Shifted F8
2228 return "\033[19;2~";
2229 }
2230
2231 if (keypress.equals(kbShiftF9)) {
2232 // Shifted F9
2233 return "\033[20;2~";
2234 }
2235
2236 if (keypress.equals(kbShiftF10)) {
2237 // Shifted F10
2238 return "\033[21;2~";
2239 }
2240
2241 if (keypress.equals(kbShiftF11)) {
2242 // Shifted F11
2243 return "\033[23;2~";
2244 }
2245
2246 if (keypress.equals(kbShiftF12)) {
2247 // Shifted F12
2248 return "\033[24;2~";
2249 }
2250
2251 if (keypress.equals(kbCtrlF1)) {
2252 // Control PF1
2253 if (vt52Mode) {
2254 return "\0335P";
2255 }
2256 if (type == DeviceType.XTERM) {
2257 return "\0331;5P";
2258 }
2259 return "\033O5P";
2260 }
2261
2262 if (keypress.equals(kbCtrlF2)) {
2263 // Control PF2
2264 if (vt52Mode) {
2265 return "\0335Q";
2266 }
2267 if (type == DeviceType.XTERM) {
2268 return "\0331;5Q";
2269 }
2270 return "\033O5Q";
2271 }
2272
2273 if (keypress.equals(kbCtrlF3)) {
2274 // Control PF3
2275 if (vt52Mode) {
2276 return "\0335R";
2277 }
2278 if (type == DeviceType.XTERM) {
2279 return "\0331;5R";
2280 }
2281 return "\033O5R";
2282 }
2283
2284 if (keypress.equals(kbCtrlF4)) {
2285 // Control PF4
2286 if (vt52Mode) {
2287 return "\0335S";
2288 }
2289 if (type == DeviceType.XTERM) {
2290 return "\0331;5S";
2291 }
2292 return "\033O5S";
2293 }
2294
2295 if (keypress.equals(kbCtrlF5)) {
2296 // Control F5
2297 return "\033[15;5~";
2298 }
2299
2300 if (keypress.equals(kbCtrlF6)) {
2301 // Control F6
2302 return "\033[17;5~";
2303 }
2304
2305 if (keypress.equals(kbCtrlF7)) {
2306 // Control F7
2307 return "\033[18;5~";
2308 }
2309
2310 if (keypress.equals(kbCtrlF8)) {
2311 // Control F8
2312 return "\033[19;5~";
2313 }
2314
2315 if (keypress.equals(kbCtrlF9)) {
2316 // Control F9
2317 return "\033[20;5~";
2318 }
2319
2320 if (keypress.equals(kbCtrlF10)) {
2321 // Control F10
2322 return "\033[21;5~";
2323 }
2324
2325 if (keypress.equals(kbCtrlF11)) {
2326 // Control F11
2327 return "\033[23;5~";
2328 }
2329
2330 if (keypress.equals(kbCtrlF12)) {
2331 // Control F12
2332 return "\033[24;5~";
2333 }
2334
2335 if (keypress.equalsWithoutModifiers(kbPgUp)) {
2336 switch (type) {
2337 case XTERM:
2338 return xtermBuildKeySequence("\033[", '5', '~',
2339 keypress.isCtrl(), keypress.isAlt(),
2340 keypress.isShift());
2341 default:
2342 return "\033[5~";
2343 }
2344 }
2345
2346 if (keypress.equalsWithoutModifiers(kbPgDn)) {
2347 switch (type) {
2348 case XTERM:
2349 return xtermBuildKeySequence("\033[", '6', '~',
2350 keypress.isCtrl(), keypress.isAlt(),
2351 keypress.isShift());
2352 default:
2353 return "\033[6~";
2354 }
2355 }
2356
2357 if (keypress.equalsWithoutModifiers(kbIns)) {
2358 switch (type) {
2359 case XTERM:
2360 return xtermBuildKeySequence("\033[", '2', '~',
2361 keypress.isCtrl(), keypress.isAlt(),
2362 keypress.isShift());
2363 default:
2364 return "\033[2~";
2365 }
2366 }
2367
2368 if (keypress.equalsWithoutModifiers(kbDel)) {
2369 switch (type) {
2370 case XTERM:
2371 return xtermBuildKeySequence("\033[", '3', '~',
2372 keypress.isCtrl(), keypress.isAlt(),
2373 keypress.isShift());
2374 default:
2375 // Delete sends real delete for VTxxx
2376 return "\177";
2377 }
2378 }
2379
2380 if (keypress.equals(kbEnter)) {
2381 return "\015";
2382 }
2383
2384 if (keypress.equals(kbEsc)) {
2385 return "\033";
2386 }
2387
2388 if (keypress.equals(kbAltEsc)) {
2389 return "\033\033";
2390 }
2391
2392 if (keypress.equals(kbTab)) {
2393 return "\011";
2394 }
2395
2396 if ((keypress.equalsWithoutModifiers(kbBackTab)) ||
2397 (keypress.equals(kbShiftTab))
2398 ) {
2399 switch (type) {
2400 case XTERM:
2401 return "\033[Z";
2402 default:
2403 return "\011";
2404 }
2405 }
2406
2407 // Non-alt, non-ctrl characters
2408 if (!keypress.isFnKey()) {
2409 StringBuilder sb = new StringBuilder();
2410 sb.append(Character.toChars(keypress.getChar()));
2411 return sb.toString();
2412 }
2413 return "";
2414 }
2415
2416 /**
2417 * Map a symbol in any one of the VT100/VT220 character sets to a Unicode
2418 * symbol.
2419 *
2420 * @param ch 8-bit character from the remote side
2421 * @param charsetGl character set defined for GL
2422 * @param charsetGr character set defined for GR
2423 * @return character to display on the screen
2424 */
2425 private char mapCharacterCharset(final int ch,
2426 final CharacterSet charsetGl,
2427 final CharacterSet charsetGr) {
2428
2429 int lookupChar = ch;
2430 CharacterSet lookupCharset = charsetGl;
2431
2432 if (ch >= 0x80) {
2433 assert ((type == DeviceType.VT220) || (type == DeviceType.XTERM));
2434 lookupCharset = charsetGr;
2435 lookupChar &= 0x7F;
2436 }
2437
2438 switch (lookupCharset) {
2439
2440 case DRAWING:
2441 return DECCharacterSets.SPECIAL_GRAPHICS[lookupChar];
2442
2443 case UK:
2444 return DECCharacterSets.UK[lookupChar];
2445
2446 case US:
2447 return DECCharacterSets.US_ASCII[lookupChar];
2448
2449 case NRC_DUTCH:
2450 return DECCharacterSets.NL[lookupChar];
2451
2452 case NRC_FINNISH:
2453 return DECCharacterSets.FI[lookupChar];
2454
2455 case NRC_FRENCH:
2456 return DECCharacterSets.FR[lookupChar];
2457
2458 case NRC_FRENCH_CA:
2459 return DECCharacterSets.FR_CA[lookupChar];
2460
2461 case NRC_GERMAN:
2462 return DECCharacterSets.DE[lookupChar];
2463
2464 case NRC_ITALIAN:
2465 return DECCharacterSets.IT[lookupChar];
2466
2467 case NRC_NORWEGIAN:
2468 return DECCharacterSets.NO[lookupChar];
2469
2470 case NRC_SPANISH:
2471 return DECCharacterSets.ES[lookupChar];
2472
2473 case NRC_SWEDISH:
2474 return DECCharacterSets.SV[lookupChar];
2475
2476 case NRC_SWISS:
2477 return DECCharacterSets.SWISS[lookupChar];
2478
2479 case DEC_SUPPLEMENTAL:
2480 return DECCharacterSets.DEC_SUPPLEMENTAL[lookupChar];
2481
2482 case VT52_GRAPHICS:
2483 return DECCharacterSets.VT52_SPECIAL_GRAPHICS[lookupChar];
2484
2485 case ROM:
2486 return DECCharacterSets.US_ASCII[lookupChar];
2487
2488 case ROM_SPECIAL:
2489 return DECCharacterSets.US_ASCII[lookupChar];
2490
2491 default:
2492 throw new IllegalArgumentException("Invalid character set value: "
2493 + lookupCharset);
2494 }
2495 }
2496
2497 /**
2498 * Map an 8-bit byte into a printable character.
2499 *
2500 * @param ch either 8-bit or Unicode character from the remote side
2501 * @return character to display on the screen
2502 */
2503 private int mapCharacter(final int ch) {
2504 if (ch >= 0x100) {
2505 // Unicode character, just return it
2506 return ch;
2507 }
2508
2509 CharacterSet charsetGl = currentState.g0Charset;
2510 CharacterSet charsetGr = currentState.grCharset;
2511
2512 if (vt52Mode == true) {
2513 if (shiftOut == true) {
2514 // Shifted out character, pull from VT52 graphics
2515 charsetGl = currentState.g1Charset;
2516 charsetGr = CharacterSet.US;
2517 } else {
2518 // Normal
2519 charsetGl = currentState.g0Charset;
2520 charsetGr = CharacterSet.US;
2521 }
2522
2523 // Pull the character
2524 return mapCharacterCharset(ch, charsetGl, charsetGr);
2525 }
2526
2527 // shiftOout
2528 if (shiftOut == true) {
2529 // Shifted out character, pull from G1
2530 charsetGl = currentState.g1Charset;
2531 charsetGr = currentState.grCharset;
2532
2533 // Pull the character
2534 return mapCharacterCharset(ch, charsetGl, charsetGr);
2535 }
2536
2537 // SS2
2538 if (singleshift == Singleshift.SS2) {
2539
2540 singleshift = Singleshift.NONE;
2541
2542 // Shifted out character, pull from G2
2543 charsetGl = currentState.g2Charset;
2544 charsetGr = currentState.grCharset;
2545 }
2546
2547 // SS3
2548 if (singleshift == Singleshift.SS3) {
2549
2550 singleshift = Singleshift.NONE;
2551
2552 // Shifted out character, pull from G3
2553 charsetGl = currentState.g3Charset;
2554 charsetGr = currentState.grCharset;
2555 }
2556
2557 if ((type == DeviceType.VT220) || (type == DeviceType.XTERM)) {
2558 // Check for locking shift
2559
2560 switch (currentState.glLockshift) {
2561
2562 case G1_GR:
2563 throw new IllegalArgumentException("programming bug");
2564
2565 case G2_GR:
2566 throw new IllegalArgumentException("programming bug");
2567
2568 case G3_GR:
2569 throw new IllegalArgumentException("programming bug");
2570
2571 case G2_GL:
2572 // LS2
2573 charsetGl = currentState.g2Charset;
2574 break;
2575
2576 case G3_GL:
2577 // LS3
2578 charsetGl = currentState.g3Charset;
2579 break;
2580
2581 case NONE:
2582 // Normal
2583 charsetGl = currentState.g0Charset;
2584 break;
2585 }
2586
2587 switch (currentState.grLockshift) {
2588
2589 case G2_GL:
2590 throw new IllegalArgumentException("programming bug");
2591
2592 case G3_GL:
2593 throw new IllegalArgumentException("programming bug");
2594
2595 case G1_GR:
2596 // LS1R
2597 charsetGr = currentState.g1Charset;
2598 break;
2599
2600 case G2_GR:
2601 // LS2R
2602 charsetGr = currentState.g2Charset;
2603 break;
2604
2605 case G3_GR:
2606 // LS3R
2607 charsetGr = currentState.g3Charset;
2608 break;
2609
2610 case NONE:
2611 // Normal
2612 charsetGr = CharacterSet.DEC_SUPPLEMENTAL;
2613 break;
2614 }
2615
2616
2617 }
2618
2619 // Pull the character
2620 return mapCharacterCharset(ch, charsetGl, charsetGr);
2621 }
2622
2623 /**
2624 * Scroll the text within a scrolling region up n lines.
2625 *
2626 * @param regionTop top row of the scrolling region
2627 * @param regionBottom bottom row of the scrolling region
2628 * @param n number of lines to scroll
2629 */
2630 private void scrollingRegionScrollUp(final int regionTop,
2631 final int regionBottom, final int n) {
2632
2633 if (regionTop >= regionBottom) {
2634 return;
2635 }
2636
2637 // Sanity check: see if there will be any characters left after the
2638 // scroll
2639 if (regionBottom + 1 - regionTop <= n) {
2640 // There won't be anything left in the region, so just call
2641 // eraseScreen() and return.
2642 eraseScreen(regionTop, 0, regionBottom, width - 1, false);
2643 return;
2644 }
2645
2646 int remaining = regionBottom + 1 - regionTop - n;
2647 List<DisplayLine> displayTop = display.subList(0, regionTop);
2648 List<DisplayLine> displayBottom = display.subList(regionBottom + 1,
2649 display.size());
2650 List<DisplayLine> displayMiddle = display.subList(regionBottom + 1
2651 - remaining, regionBottom + 1);
2652 display = new ArrayList<DisplayLine>(displayTop);
2653 display.addAll(displayMiddle);
2654 for (int i = 0; i < n; i++) {
2655 DisplayLine line = new DisplayLine(currentState.attr);
2656 line.setReverseColor(reverseVideo);
2657 display.add(line);
2658 }
2659 display.addAll(displayBottom);
2660
2661 assert (display.size() == height);
2662 }
2663
2664 /**
2665 * Scroll the text within a scrolling region down n lines.
2666 *
2667 * @param regionTop top row of the scrolling region
2668 * @param regionBottom bottom row of the scrolling region
2669 * @param n number of lines to scroll
2670 */
2671 private void scrollingRegionScrollDown(final int regionTop,
2672 final int regionBottom, final int n) {
2673
2674 if (regionTop >= regionBottom) {
2675 return;
2676 }
2677
2678 // Sanity check: see if there will be any characters left after the
2679 // scroll
2680 if (regionBottom + 1 - regionTop <= n) {
2681 // There won't be anything left in the region, so just call
2682 // eraseScreen() and return.
2683 eraseScreen(regionTop, 0, regionBottom, width - 1, false);
2684 return;
2685 }
2686
2687 int remaining = regionBottom + 1 - regionTop - n;
2688 List<DisplayLine> displayTop = display.subList(0, regionTop);
2689 List<DisplayLine> displayBottom = display.subList(regionBottom + 1,
2690 display.size());
2691 List<DisplayLine> displayMiddle = display.subList(regionTop,
2692 regionTop + remaining);
2693 display = new ArrayList<DisplayLine>(displayTop);
2694 for (int i = 0; i < n; i++) {
2695 DisplayLine line = new DisplayLine(currentState.attr);
2696 line.setReverseColor(reverseVideo);
2697 display.add(line);
2698 }
2699 display.addAll(displayMiddle);
2700 display.addAll(displayBottom);
2701
2702 assert (display.size() == height);
2703 }
2704
2705 /**
2706 * Process a control character.
2707 *
2708 * @param ch 8-bit character from the remote side
2709 */
2710 private void handleControlChar(final char ch) {
2711 assert ((ch <= 0x1F) || ((ch >= 0x7F) && (ch <= 0x9F)));
2712
2713 switch (ch) {
2714
2715 case 0x00:
2716 // NUL - discard
2717 return;
2718
2719 case 0x05:
2720 // ENQ
2721
2722 // Transmit the answerback message.
2723 // Not supported
2724 break;
2725
2726 case 0x07:
2727 // BEL
2728 // Not supported
2729 break;
2730
2731 case 0x08:
2732 // BS
2733 cursorLeft(1, false);
2734 break;
2735
2736 case 0x09:
2737 // HT
2738 advanceToNextTabStop();
2739 break;
2740
2741 case 0x0A:
2742 // LF
2743 linefeed();
2744 break;
2745
2746 case 0x0B:
2747 // VT
2748 linefeed();
2749 break;
2750
2751 case 0x0C:
2752 // FF
2753 linefeed();
2754 break;
2755
2756 case 0x0D:
2757 // CR
2758 carriageReturn();
2759 break;
2760
2761 case 0x0E:
2762 // SO
2763 shiftOut = true;
2764 currentState.glLockshift = LockshiftMode.NONE;
2765 break;
2766
2767 case 0x0F:
2768 // SI
2769 shiftOut = false;
2770 currentState.glLockshift = LockshiftMode.NONE;
2771 break;
2772
2773 case 0x84:
2774 // IND
2775 ind();
2776 break;
2777
2778 case 0x85:
2779 // NEL
2780 nel();
2781 break;
2782
2783 case 0x88:
2784 // HTS
2785 hts();
2786 break;
2787
2788 case 0x8D:
2789 // RI
2790 ri();
2791 break;
2792
2793 case 0x8E:
2794 // SS2
2795 singleshift = Singleshift.SS2;
2796 break;
2797
2798 case 0x8F:
2799 // SS3
2800 singleshift = Singleshift.SS3;
2801 break;
2802
2803 default:
2804 break;
2805 }
2806
2807 }
2808
2809 /**
2810 * Advance the cursor to the next tab stop.
2811 */
2812 private void advanceToNextTabStop() {
2813 if (tabStops.size() == 0) {
2814 // Go to the rightmost column
2815 cursorRight(rightMargin - currentState.cursorX, false);
2816 return;
2817 }
2818 for (Integer stop: tabStops) {
2819 if (stop > currentState.cursorX) {
2820 cursorRight(stop - currentState.cursorX, false);
2821 return;
2822 }
2823 }
2824 /*
2825 * We got here, meaning there isn't a tab stop beyond the current
2826 * cursor position. Place the cursor of the right-most edge of the
2827 * screen.
2828 */
2829 cursorRight(rightMargin - currentState.cursorX, false);
2830 }
2831
2832 /**
2833 * Save a character into the collect buffer.
2834 *
2835 * @param ch character to save
2836 */
2837 private void collect(final char ch) {
2838 collectBuffer.append(ch);
2839 }
2840
2841 /**
2842 * Save a byte into the CSI parameters buffer.
2843 *
2844 * @param ch byte to save
2845 */
2846 private void param(final byte ch) {
2847 if (csiParams.size() == 0) {
2848 csiParams.add(Integer.valueOf(0));
2849 }
2850 Integer x = csiParams.get(csiParams.size() - 1);
2851 if ((ch >= '0') && (ch <= '9')) {
2852 x *= 10;
2853 x += (ch - '0');
2854 csiParams.set(csiParams.size() - 1, x);
2855 }
2856
2857 if ((ch == ';') && (csiParams.size() < 16)) {
2858 csiParams.add(Integer.valueOf(0));
2859 }
2860 }
2861
2862 /**
2863 * Get a CSI parameter value, with a default.
2864 *
2865 * @param position parameter index. 0 is the first parameter.
2866 * @param defaultValue value to use if csiParams[position] doesn't exist
2867 * @return parameter value
2868 */
2869 private int getCsiParam(final int position, final int defaultValue) {
2870 if (csiParams.size() < position + 1) {
2871 return defaultValue;
2872 }
2873 return csiParams.get(position).intValue();
2874 }
2875
2876 /**
2877 * Get a CSI parameter value, clamped to within min/max.
2878 *
2879 * @param position parameter index. 0 is the first parameter.
2880 * @param defaultValue value to use if csiParams[position] doesn't exist
2881 * @param minValue minimum value inclusive
2882 * @param maxValue maximum value inclusive
2883 * @return parameter value
2884 */
2885 private int getCsiParam(final int position, final int defaultValue,
2886 final int minValue, final int maxValue) {
2887
2888 assert (minValue <= maxValue);
2889 int value = getCsiParam(position, defaultValue);
2890 if (value < minValue) {
2891 value = minValue;
2892 }
2893 if (value > maxValue) {
2894 value = maxValue;
2895 }
2896 return value;
2897 }
2898
2899 /**
2900 * Set or unset a toggle.
2901 *
2902 * @param value true for set ('h'), false for reset ('l')
2903 */
2904 private void setToggle(final boolean value) {
2905 boolean decPrivateModeFlag = false;
2906
2907 for (int i = 0; i < collectBuffer.length(); i++) {
2908 if (collectBuffer.charAt(i) == '?') {
2909 decPrivateModeFlag = true;
2910 break;
2911 }
2912 }
2913
2914 for (Integer i: csiParams) {
2915
2916 switch (i) {
2917
2918 case 1:
2919 if (decPrivateModeFlag == true) {
2920 // DECCKM
2921 if (value == true) {
2922 // Use application arrow keys
2923 arrowKeyMode = ArrowKeyMode.VT100;
2924 } else {
2925 // Use ANSI arrow keys
2926 arrowKeyMode = ArrowKeyMode.ANSI;
2927 }
2928 }
2929 break;
2930 case 2:
2931 if (decPrivateModeFlag == true) {
2932 if (value == false) {
2933
2934 // DECANM
2935 vt52Mode = true;
2936 arrowKeyMode = ArrowKeyMode.VT52;
2937
2938 /*
2939 * From the VT102 docs: "You use ANSI mode to select
2940 * most terminal features; the terminal uses the same
2941 * features when it switches to VT52 mode. You
2942 * cannot, however, change most of these features in
2943 * VT52 mode."
2944 *
2945 * In other words, do not reset any other attributes
2946 * when switching between VT52 submode and ANSI.
2947 *
2948 * HOWEVER, the real vt100 does switch the character
2949 * set according to Usenet.
2950 */
2951 currentState.g0Charset = CharacterSet.US;
2952 currentState.g1Charset = CharacterSet.DRAWING;
2953 shiftOut = false;
2954
2955 if ((type == DeviceType.VT220)
2956 || (type == DeviceType.XTERM)) {
2957
2958 // VT52 mode is explicitly 7-bit
2959 s8c1t = false;
2960 singleshift = Singleshift.NONE;
2961 }
2962 }
2963 } else {
2964 // KAM
2965 if (value == true) {
2966 // Turn off keyboard
2967 // Not supported
2968 } else {
2969 // Turn on keyboard
2970 // Not supported
2971 }
2972 }
2973 break;
2974 case 3:
2975 if (decPrivateModeFlag == true) {
2976 // DECCOLM
2977 if (value == true) {
2978 // 132 columns
2979 columns132 = true;
2980 rightMargin = 131;
2981 } else {
2982 // 80 columns
2983 columns132 = false;
2984 if ((displayListener != null)
2985 && (type == DeviceType.XTERM)
2986 ) {
2987 // For xterms, reset to the actual width, not 80
2988 // columns.
2989 width = displayListener.getDisplayWidth();
2990 rightMargin = width - 1;
2991 } else {
2992 rightMargin = 79;
2993 width = rightMargin + 1;
2994 }
2995 }
2996 // Entire screen is cleared, and scrolling region is
2997 // reset
2998 eraseScreen(0, 0, height - 1, width - 1, false);
2999 scrollRegionTop = 0;
3000 scrollRegionBottom = height - 1;
3001 // Also home the cursor
3002 cursorPosition(0, 0);
3003 }
3004 break;
3005 case 4:
3006 if (decPrivateModeFlag == true) {
3007 // DECSCLM
3008 if (value == true) {
3009 // Smooth scroll
3010 // Not supported
3011 } else {
3012 // Jump scroll
3013 // Not supported
3014 }
3015 } else {
3016 // IRM
3017 if (value == true) {
3018 insertMode = true;
3019 } else {
3020 insertMode = false;
3021 }
3022 }
3023 break;
3024 case 5:
3025 if (decPrivateModeFlag == true) {
3026 // DECSCNM
3027 if (value == true) {
3028 /*
3029 * Set selects reverse screen, a white screen
3030 * background with black characters.
3031 */
3032 if (reverseVideo != true) {
3033 /*
3034 * If in normal video, switch it back
3035 */
3036 invertDisplayColors();
3037 }
3038 reverseVideo = true;
3039 } else {
3040 /*
3041 * Reset selects normal screen, a black screen
3042 * background with white characters.
3043 */
3044 if (reverseVideo == true) {
3045 /*
3046 * If in reverse video already, switch it back
3047 */
3048 invertDisplayColors();
3049 }
3050 reverseVideo = false;
3051 }
3052 }
3053 break;
3054 case 6:
3055 if (decPrivateModeFlag == true) {
3056 // DECOM
3057 if (value == true) {
3058 // Origin is relative to scroll region cursor.
3059 // Cursor can NEVER leave scrolling region.
3060 currentState.originMode = true;
3061 cursorPosition(0, 0);
3062 } else {
3063 // Origin is absolute to entire screen. Cursor can
3064 // leave the scrolling region via cup() and hvp().
3065 currentState.originMode = false;
3066 cursorPosition(0, 0);
3067 }
3068 }
3069 break;
3070 case 7:
3071 if (decPrivateModeFlag == true) {
3072 // DECAWM
3073 if (value == true) {
3074 // Turn linewrap on
3075 currentState.lineWrap = true;
3076 } else {
3077 // Turn linewrap off
3078 currentState.lineWrap = false;
3079 }
3080 }
3081 break;
3082 case 8:
3083 if (decPrivateModeFlag == true) {
3084 // DECARM
3085 if (value == true) {
3086 // Keyboard auto-repeat on
3087 // Not supported
3088 } else {
3089 // Keyboard auto-repeat off
3090 // Not supported
3091 }
3092 }
3093 break;
3094 case 12:
3095 if (decPrivateModeFlag == false) {
3096 // SRM
3097 if (value == true) {
3098 // Local echo off
3099 fullDuplex = true;
3100 } else {
3101 // Local echo on
3102 fullDuplex = false;
3103 }
3104 }
3105 break;
3106 case 18:
3107 if (decPrivateModeFlag == true) {
3108 // DECPFF
3109 // Not supported
3110 }
3111 break;
3112 case 19:
3113 if (decPrivateModeFlag == true) {
3114 // DECPEX
3115 // Not supported
3116 }
3117 break;
3118 case 20:
3119 if (decPrivateModeFlag == false) {
3120 // LNM
3121 if (value == true) {
3122 /*
3123 * Set causes a received linefeed, form feed, or
3124 * vertical tab to move cursor to first column of
3125 * next line. RETURN transmits both a carriage return
3126 * and linefeed. This selection is also called new
3127 * line option.
3128 */
3129 newLineMode = true;
3130 } else {
3131 /*
3132 * Reset causes a received linefeed, form feed, or
3133 * vertical tab to move cursor to next line in
3134 * current column. RETURN transmits a carriage
3135 * return.
3136 */
3137 newLineMode = false;
3138 }
3139 }
3140 break;
3141
3142 case 25:
3143 if ((type == DeviceType.VT220) || (type == DeviceType.XTERM)) {
3144 if (decPrivateModeFlag == true) {
3145 // DECTCEM
3146 if (value == true) {
3147 // Visible cursor
3148 cursorVisible = true;
3149 } else {
3150 // Invisible cursor
3151 cursorVisible = false;
3152 }
3153 }
3154 }
3155 break;
3156
3157 case 42:
3158 if ((type == DeviceType.VT220) || (type == DeviceType.XTERM)) {
3159 if (decPrivateModeFlag == true) {
3160 // DECNRCM
3161 if (value == true) {
3162 // Select national mode NRC
3163 // Not supported
3164 } else {
3165 // Select multi-national mode
3166 // Not supported
3167 }
3168 }
3169 }
3170
3171 break;
3172
3173 case 80:
3174 if (type == DeviceType.XTERM) {
3175 if (decPrivateModeFlag == true) {
3176 if (value == true) {
3177 // Enable sixel scrolling (default).
3178 // TODO
3179 } else {
3180 // Disable sixel scrolling.
3181 // TODO
3182 }
3183 }
3184 }
3185
3186 break;
3187
3188 case 1000:
3189 if ((type == DeviceType.XTERM)
3190 && (decPrivateModeFlag == true)
3191 ) {
3192 // Mouse: normal tracking mode
3193 if (value == true) {
3194 mouseProtocol = MouseProtocol.NORMAL;
3195 } else {
3196 mouseProtocol = MouseProtocol.OFF;
3197 }
3198 }
3199 break;
3200
3201 case 1002:
3202 if ((type == DeviceType.XTERM)
3203 && (decPrivateModeFlag == true)
3204 ) {
3205 // Mouse: normal tracking mode
3206 if (value == true) {
3207 mouseProtocol = MouseProtocol.BUTTONEVENT;
3208 } else {
3209 mouseProtocol = MouseProtocol.OFF;
3210 }
3211 }
3212 break;
3213
3214 case 1003:
3215 if ((type == DeviceType.XTERM)
3216 && (decPrivateModeFlag == true)
3217 ) {
3218 // Mouse: Any-event tracking mode
3219 if (value == true) {
3220 mouseProtocol = MouseProtocol.ANYEVENT;
3221 } else {
3222 mouseProtocol = MouseProtocol.OFF;
3223 }
3224 }
3225 break;
3226
3227 case 1005:
3228 if ((type == DeviceType.XTERM)
3229 && (decPrivateModeFlag == true)
3230 ) {
3231 // Mouse: UTF-8 coordinates
3232 if (value == true) {
3233 mouseEncoding = MouseEncoding.UTF8;
3234 } else {
3235 mouseEncoding = MouseEncoding.X10;
3236 }
3237 }
3238 break;
3239
3240 case 1006:
3241 if ((type == DeviceType.XTERM)
3242 && (decPrivateModeFlag == true)
3243 ) {
3244 // Mouse: SGR coordinates
3245 if (value == true) {
3246 mouseEncoding = MouseEncoding.SGR;
3247 } else {
3248 mouseEncoding = MouseEncoding.X10;
3249 }
3250 }
3251 break;
3252
3253 case 1070:
3254 if (type == DeviceType.XTERM) {
3255 if (decPrivateModeFlag == true) {
3256 if (value == true) {
3257 // Use private color registers for each sixel
3258 // graphic (default).
3259 sixelPalette = null;
3260 } else {
3261 // Use shared color registers for each sixel
3262 // graphic.
3263 sixelPalette = new HashMap<Integer, java.awt.Color>();
3264 }
3265 }
3266 }
3267 break;
3268
3269 default:
3270 break;
3271
3272 }
3273 }
3274 }
3275
3276 /**
3277 * DECSC - Save cursor.
3278 */
3279 private void decsc() {
3280 savedState.setTo(currentState);
3281 }
3282
3283 /**
3284 * DECRC - Restore cursor.
3285 */
3286 private void decrc() {
3287 currentState.setTo(savedState);
3288 }
3289
3290 /**
3291 * IND - Index.
3292 */
3293 private void ind() {
3294 // Move the cursor and scroll if necessary. If at the bottom line
3295 // already, a scroll up is supposed to be performed.
3296 if (currentState.cursorY == scrollRegionBottom) {
3297 scrollingRegionScrollUp(scrollRegionTop, scrollRegionBottom, 1);
3298 }
3299 cursorDown(1, true);
3300 }
3301
3302 /**
3303 * RI - Reverse index.
3304 */
3305 private void ri() {
3306 // Move the cursor and scroll if necessary. If at the top line
3307 // already, a scroll down is supposed to be performed.
3308 if (currentState.cursorY == scrollRegionTop) {
3309 scrollingRegionScrollDown(scrollRegionTop, scrollRegionBottom, 1);
3310 }
3311 cursorUp(1, true);
3312 }
3313
3314 /**
3315 * NEL - Next line.
3316 */
3317 private void nel() {
3318 // Move the cursor and scroll if necessary. If at the bottom line
3319 // already, a scroll up is supposed to be performed.
3320 if (currentState.cursorY == scrollRegionBottom) {
3321 scrollingRegionScrollUp(scrollRegionTop, scrollRegionBottom, 1);
3322 }
3323 cursorDown(1, true);
3324
3325 // Reset to the beginning of the next line
3326 currentState.cursorX = 0;
3327 }
3328
3329 /**
3330 * DECKPAM - Keypad application mode.
3331 */
3332 private void deckpam() {
3333 keypadMode = KeypadMode.Application;
3334 }
3335
3336 /**
3337 * DECKPNM - Keypad numeric mode.
3338 */
3339 private void deckpnm() {
3340 keypadMode = KeypadMode.Numeric;
3341 }
3342
3343 /**
3344 * Move up n spaces.
3345 *
3346 * @param n number of spaces to move
3347 * @param honorScrollRegion if true, then do nothing if the cursor is
3348 * outside the scrolling region
3349 */
3350 private void cursorUp(final int n, final boolean honorScrollRegion) {
3351 int top;
3352
3353 /*
3354 * Special case: if a user moves the cursor from the right margin, we
3355 * have to reset the VT100 right margin flag.
3356 */
3357 if (n > 0) {
3358 wrapLineFlag = false;
3359 }
3360
3361 for (int i = 0; i < n; i++) {
3362 if (honorScrollRegion == true) {
3363 // Honor the scrolling region
3364 if ((currentState.cursorY < scrollRegionTop)
3365 || (currentState.cursorY > scrollRegionBottom)
3366 ) {
3367 // Outside region, do nothing
3368 return;
3369 }
3370 // Inside region, go up
3371 top = scrollRegionTop;
3372 } else {
3373 // Non-scrolling case
3374 top = 0;
3375 }
3376
3377 if (currentState.cursorY > top) {
3378 currentState.cursorY--;
3379 }
3380 }
3381 }
3382
3383 /**
3384 * Move down n spaces.
3385 *
3386 * @param n number of spaces to move
3387 * @param honorScrollRegion if true, then do nothing if the cursor is
3388 * outside the scrolling region
3389 */
3390 private void cursorDown(final int n, final boolean honorScrollRegion) {
3391 int bottom;
3392
3393 /*
3394 * Special case: if a user moves the cursor from the right margin, we
3395 * have to reset the VT100 right margin flag.
3396 */
3397 if (n > 0) {
3398 wrapLineFlag = false;
3399 }
3400
3401 for (int i = 0; i < n; i++) {
3402
3403 if (honorScrollRegion == true) {
3404 // Honor the scrolling region
3405 if (currentState.cursorY > scrollRegionBottom) {
3406 // Outside region, do nothing
3407 return;
3408 }
3409 // Inside region, go down
3410 bottom = scrollRegionBottom;
3411 } else {
3412 // Non-scrolling case
3413 bottom = height - 1;
3414 }
3415
3416 if (currentState.cursorY < bottom) {
3417 currentState.cursorY++;
3418 }
3419 }
3420 }
3421
3422 /**
3423 * Move left n spaces.
3424 *
3425 * @param n number of spaces to move
3426 * @param honorScrollRegion if true, then do nothing if the cursor is
3427 * outside the scrolling region
3428 */
3429 private void cursorLeft(final int n, final boolean honorScrollRegion) {
3430 /*
3431 * Special case: if a user moves the cursor from the right margin, we
3432 * have to reset the VT100 right margin flag.
3433 */
3434 if (n > 0) {
3435 wrapLineFlag = false;
3436 }
3437
3438 for (int i = 0; i < n; i++) {
3439 if (honorScrollRegion == true) {
3440 // Honor the scrolling region
3441 if ((currentState.cursorY < scrollRegionTop)
3442 || (currentState.cursorY > scrollRegionBottom)
3443 ) {
3444 // Outside region, do nothing
3445 return;
3446 }
3447 }
3448
3449 if (currentState.cursorX > 0) {
3450 currentState.cursorX--;
3451 }
3452 }
3453 }
3454
3455 /**
3456 * Move right n spaces.
3457 *
3458 * @param n number of spaces to move
3459 * @param honorScrollRegion if true, then do nothing if the cursor is
3460 * outside the scrolling region
3461 */
3462 private void cursorRight(final int n, final boolean honorScrollRegion) {
3463 int rightMargin = this.rightMargin;
3464
3465 /*
3466 * Special case: if a user moves the cursor from the right margin, we
3467 * have to reset the VT100 right margin flag.
3468 */
3469 if (n > 0) {
3470 wrapLineFlag = false;
3471 }
3472
3473 if (display.get(currentState.cursorY).isDoubleWidth()) {
3474 rightMargin = ((rightMargin + 1) / 2) - 1;
3475 }
3476
3477 for (int i = 0; i < n; i++) {
3478 if (honorScrollRegion == true) {
3479 // Honor the scrolling region
3480 if ((currentState.cursorY < scrollRegionTop)
3481 || (currentState.cursorY > scrollRegionBottom)
3482 ) {
3483 // Outside region, do nothing
3484 return;
3485 }
3486 }
3487
3488 if (currentState.cursorX < rightMargin) {
3489 currentState.cursorX++;
3490 }
3491 }
3492 }
3493
3494 /**
3495 * Move cursor to (col, row) where (0, 0) is the top-left corner.
3496 *
3497 * @param row row to move to
3498 * @param col column to move to
3499 */
3500 private void cursorPosition(int row, final int col) {
3501 int rightMargin = this.rightMargin;
3502
3503 assert (col >= 0);
3504 assert (row >= 0);
3505
3506 if (display.get(currentState.cursorY).isDoubleWidth()) {
3507 rightMargin = ((rightMargin + 1) / 2) - 1;
3508 }
3509
3510 // Set column number
3511 currentState.cursorX = col;
3512
3513 // Sanity check, bring column back to margin.
3514 if (currentState.cursorX > rightMargin) {
3515 currentState.cursorX = rightMargin;
3516 }
3517
3518 // Set row number
3519 if (currentState.originMode == true) {
3520 row += scrollRegionTop;
3521 }
3522 if (currentState.cursorY < row) {
3523 cursorDown(row - currentState.cursorY, false);
3524 } else if (currentState.cursorY > row) {
3525 cursorUp(currentState.cursorY - row, false);
3526 }
3527
3528 wrapLineFlag = false;
3529 }
3530
3531 /**
3532 * HTS - Horizontal tabulation set.
3533 */
3534 private void hts() {
3535 for (Integer stop: tabStops) {
3536 if (stop == currentState.cursorX) {
3537 // Already have a tab stop here
3538 return;
3539 }
3540 }
3541
3542 // Append a tab stop to the end of the array and resort them
3543 tabStops.add(currentState.cursorX);
3544 Collections.sort(tabStops);
3545 }
3546
3547 /**
3548 * DECSWL - Single-width line.
3549 */
3550 private void decswl() {
3551 display.get(currentState.cursorY).setDoubleWidth(false);
3552 display.get(currentState.cursorY).setDoubleHeight(0);
3553 }
3554
3555 /**
3556 * DECDWL - Double-width line.
3557 */
3558 private void decdwl() {
3559 display.get(currentState.cursorY).setDoubleWidth(true);
3560 display.get(currentState.cursorY).setDoubleHeight(0);
3561 }
3562
3563 /**
3564 * DECHDL - Double-height + double-width line.
3565 *
3566 * @param topHalf if true, this sets the row to be the top half row of a
3567 * double-height row
3568 */
3569 private void dechdl(final boolean topHalf) {
3570 display.get(currentState.cursorY).setDoubleWidth(true);
3571 if (topHalf == true) {
3572 display.get(currentState.cursorY).setDoubleHeight(1);
3573 } else {
3574 display.get(currentState.cursorY).setDoubleHeight(2);
3575 }
3576 }
3577
3578 /**
3579 * DECALN - Screen alignment display.
3580 */
3581 private void decaln() {
3582 Cell newCell = new Cell('E');
3583 for (DisplayLine line: display) {
3584 for (int i = 0; i < line.length(); i++) {
3585 line.replace(i, newCell);
3586 }
3587 }
3588 }
3589
3590 /**
3591 * DECSCL - Compatibility level.
3592 */
3593 private void decscl() {
3594 int i = getCsiParam(0, 0);
3595 int j = getCsiParam(1, 0);
3596
3597 if (i == 61) {
3598 // Reset fonts
3599 currentState.g0Charset = CharacterSet.US;
3600 currentState.g1Charset = CharacterSet.DRAWING;
3601 s8c1t = false;
3602 } else if (i == 62) {
3603
3604 if ((j == 0) || (j == 2)) {
3605 s8c1t = true;
3606 } else if (j == 1) {
3607 s8c1t = false;
3608 }
3609 }
3610 }
3611
3612 /**
3613 * CUD - Cursor down.
3614 */
3615 private void cud() {
3616 cursorDown(getCsiParam(0, 1, 1, height), true);
3617 }
3618
3619 /**
3620 * CUF - Cursor forward.
3621 */
3622 private void cuf() {
3623 cursorRight(getCsiParam(0, 1, 1, rightMargin + 1), true);
3624 }
3625
3626 /**
3627 * CUB - Cursor backward.
3628 */
3629 private void cub() {
3630 cursorLeft(getCsiParam(0, 1, 1, currentState.cursorX + 1), true);
3631 }
3632
3633 /**
3634 * CUU - Cursor up.
3635 */
3636 private void cuu() {
3637 cursorUp(getCsiParam(0, 1, 1, currentState.cursorY + 1), true);
3638 }
3639
3640 /**
3641 * CUP - Cursor position.
3642 */
3643 private void cup() {
3644 cursorPosition(getCsiParam(0, 1, 1, height) - 1,
3645 getCsiParam(1, 1, 1, rightMargin + 1) - 1);
3646 }
3647
3648 /**
3649 * CNL - Cursor down and to column 1.
3650 */
3651 private void cnl() {
3652 cursorDown(getCsiParam(0, 1, 1, height), true);
3653 // To column 0
3654 cursorLeft(currentState.cursorX, true);
3655 }
3656
3657 /**
3658 * CPL - Cursor up and to column 1.
3659 */
3660 private void cpl() {
3661 cursorUp(getCsiParam(0, 1, 1, currentState.cursorY + 1), true);
3662 // To column 0
3663 cursorLeft(currentState.cursorX, true);
3664 }
3665
3666 /**
3667 * CHA - Cursor to column # in current row.
3668 */
3669 private void cha() {
3670 cursorPosition(currentState.cursorY,
3671 getCsiParam(0, 1, 1, rightMargin + 1) - 1);
3672 }
3673
3674 /**
3675 * VPA - Cursor to row #, same column.
3676 */
3677 private void vpa() {
3678 cursorPosition(getCsiParam(0, 1, 1, height) - 1,
3679 currentState.cursorX);
3680 }
3681
3682 /**
3683 * ED - Erase in display.
3684 */
3685 private void ed() {
3686 boolean honorProtected = false;
3687 boolean decPrivateModeFlag = false;
3688
3689 for (int i = 0; i < collectBuffer.length(); i++) {
3690 if (collectBuffer.charAt(i) == '?') {
3691 decPrivateModeFlag = true;
3692 break;
3693 }
3694 }
3695
3696 if (((type == DeviceType.VT220) || (type == DeviceType.XTERM))
3697 && (decPrivateModeFlag == true)
3698 ) {
3699 honorProtected = true;
3700 }
3701
3702 int i = getCsiParam(0, 0);
3703
3704 if (i == 0) {
3705 // Erase from here to end of screen
3706 if (currentState.cursorY < height - 1) {
3707 eraseScreen(currentState.cursorY + 1, 0, height - 1, width - 1,
3708 honorProtected);
3709 }
3710 eraseLine(currentState.cursorX, width - 1, honorProtected);
3711 } else if (i == 1) {
3712 // Erase from beginning of screen to here
3713 eraseScreen(0, 0, currentState.cursorY - 1, width - 1,
3714 honorProtected);
3715 eraseLine(0, currentState.cursorX, honorProtected);
3716 } else if (i == 2) {
3717 // Erase entire screen
3718 eraseScreen(0, 0, height - 1, width - 1, honorProtected);
3719 }
3720 }
3721
3722 /**
3723 * EL - Erase in line.
3724 */
3725 private void el() {
3726 boolean honorProtected = false;
3727 boolean decPrivateModeFlag = false;
3728
3729 for (int i = 0; i < collectBuffer.length(); i++) {
3730 if (collectBuffer.charAt(i) == '?') {
3731 decPrivateModeFlag = true;
3732 break;
3733 }
3734 }
3735
3736 if (((type == DeviceType.VT220) || (type == DeviceType.XTERM))
3737 && (decPrivateModeFlag == true)
3738 ) {
3739 honorProtected = true;
3740 }
3741
3742 int i = getCsiParam(0, 0);
3743
3744 if (i == 0) {
3745 // Erase from here to end of line
3746 eraseLine(currentState.cursorX, width - 1, honorProtected);
3747 } else if (i == 1) {
3748 // Erase from beginning of line to here
3749 eraseLine(0, currentState.cursorX, honorProtected);
3750 } else if (i == 2) {
3751 // Erase entire line
3752 eraseLine(0, width - 1, honorProtected);
3753 }
3754 }
3755
3756 /**
3757 * ECH - Erase # of characters in current row.
3758 */
3759 private void ech() {
3760 int i = getCsiParam(0, 1, 1, width);
3761
3762 // Erase from here to i characters
3763 eraseLine(currentState.cursorX, currentState.cursorX + i - 1, false);
3764 }
3765
3766 /**
3767 * IL - Insert line.
3768 */
3769 private void il() {
3770 int i = getCsiParam(0, 1);
3771
3772 if ((currentState.cursorY >= scrollRegionTop)
3773 && (currentState.cursorY <= scrollRegionBottom)
3774 ) {
3775
3776 // I can get the same effect with a scroll-down
3777 scrollingRegionScrollDown(currentState.cursorY,
3778 scrollRegionBottom, i);
3779 }
3780 }
3781
3782 /**
3783 * DCH - Delete char.
3784 */
3785 private void dch() {
3786 int n = getCsiParam(0, 1);
3787 DisplayLine line = display.get(currentState.cursorY);
3788 Cell blank = new Cell();
3789 for (int i = 0; i < n; i++) {
3790 line.delete(currentState.cursorX, blank);
3791 }
3792 }
3793
3794 /**
3795 * ICH - Insert blank char at cursor.
3796 */
3797 private void ich() {
3798 int n = getCsiParam(0, 1);
3799 DisplayLine line = display.get(currentState.cursorY);
3800 Cell blank = new Cell();
3801 for (int i = 0; i < n; i++) {
3802 line.insert(currentState.cursorX, blank);
3803 }
3804 }
3805
3806 /**
3807 * DL - Delete line.
3808 */
3809 private void dl() {
3810 int i = getCsiParam(0, 1);
3811
3812 if ((currentState.cursorY >= scrollRegionTop)
3813 && (currentState.cursorY <= scrollRegionBottom)) {
3814
3815 // I can get the same effect with a scroll-down
3816 scrollingRegionScrollUp(currentState.cursorY,
3817 scrollRegionBottom, i);
3818 }
3819 }
3820
3821 /**
3822 * HVP - Horizontal and vertical position.
3823 */
3824 private void hvp() {
3825 cup();
3826 }
3827
3828 /**
3829 * REP - Repeat character.
3830 */
3831 private void rep() {
3832 int n = getCsiParam(0, 1);
3833 for (int i = 0; i < n; i++) {
3834 printCharacter(repCh);
3835 }
3836 }
3837
3838 /**
3839 * SU - Scroll up.
3840 */
3841 private void su() {
3842 scrollingRegionScrollUp(scrollRegionTop, scrollRegionBottom,
3843 getCsiParam(0, 1, 1, height));
3844 }
3845
3846 /**
3847 * SD - Scroll down.
3848 */
3849 private void sd() {
3850 scrollingRegionScrollDown(scrollRegionTop, scrollRegionBottom,
3851 getCsiParam(0, 1, 1, height));
3852 }
3853
3854 /**
3855 * CBT - Go back X tab stops.
3856 */
3857 private void cbt() {
3858 int tabsToMove = getCsiParam(0, 1);
3859 int tabI;
3860
3861 for (int i = 0; i < tabsToMove; i++) {
3862 int j = currentState.cursorX;
3863 for (tabI = 0; tabI < tabStops.size(); tabI++) {
3864 if (tabStops.get(tabI) >= currentState.cursorX) {
3865 break;
3866 }
3867 }
3868 tabI--;
3869 if (tabI <= 0) {
3870 j = 0;
3871 } else {
3872 j = tabStops.get(tabI);
3873 }
3874 cursorPosition(currentState.cursorY, j);
3875 }
3876 }
3877
3878 /**
3879 * CHT - Advance X tab stops.
3880 */
3881 private void cht() {
3882 int n = getCsiParam(0, 1);
3883 for (int i = 0; i < n; i++) {
3884 advanceToNextTabStop();
3885 }
3886 }
3887
3888 /**
3889 * SGR - Select graphics rendition.
3890 */
3891 private void sgr() {
3892
3893 if (csiParams.size() == 0) {
3894 currentState.attr.reset();
3895 return;
3896 }
3897
3898 int sgrColorMode = -1;
3899 boolean idx88Color = false;
3900 boolean rgbColor = false;
3901 int rgbRed = -1;
3902 int rgbGreen = -1;
3903
3904 for (Integer i: csiParams) {
3905
3906 if ((sgrColorMode == 38) || (sgrColorMode == 48)) {
3907
3908 assert (type == DeviceType.XTERM);
3909
3910 if (idx88Color) {
3911 /*
3912 * Indexed color mode, we now have the index number.
3913 */
3914 if (sgrColorMode == 38) {
3915 currentState.attr.setForeColorRGB(get88Color(i));
3916 } else {
3917 assert (sgrColorMode == 48);
3918 currentState.attr.setBackColorRGB(get88Color(i));
3919 }
3920 sgrColorMode = -1;
3921 idx88Color = false;
3922 continue;
3923 }
3924
3925 if (rgbColor) {
3926 /*
3927 * RGB color mode, we are collecting tokens.
3928 */
3929 if (rgbRed == -1) {
3930 rgbRed = i & 0xFF;
3931 } else if (rgbGreen == -1) {
3932 rgbGreen = i & 0xFF;
3933 } else {
3934 int rgb = rgbRed << 16;
3935 rgb |= rgbGreen << 8;
3936 rgb |= i & 0xFF;
3937
3938 // System.err.printf("RGB: %08x\n", rgb);
3939
3940 if (sgrColorMode == 38) {
3941 currentState.attr.setForeColorRGB(rgb);
3942 } else {
3943 assert (sgrColorMode == 48);
3944 currentState.attr.setBackColorRGB(rgb);
3945 }
3946 rgbRed = -1;
3947 rgbGreen = -1;
3948 sgrColorMode = -1;
3949 rgbColor = false;
3950 }
3951 continue;
3952 }
3953
3954 switch (i) {
3955
3956 case 2:
3957 /*
3958 * RGB color mode.
3959 */
3960 rgbColor = true;
3961 break;
3962
3963 case 5:
3964 /*
3965 * Indexed color mode.
3966 */
3967 idx88Color = true;
3968 break;
3969
3970 default:
3971 /*
3972 * This is neither indexed nor RGB color. Bail out.
3973 */
3974 return;
3975 }
3976
3977 } // if ((sgrColorMode == 38) || (sgrColorMode == 48))
3978
3979 switch (i) {
3980
3981 case 0:
3982 // Normal
3983 currentState.attr.reset();
3984 break;
3985
3986 case 1:
3987 // Bold
3988 currentState.attr.setBold(true);
3989 break;
3990
3991 case 4:
3992 // Underline
3993 currentState.attr.setUnderline(true);
3994 break;
3995
3996 case 5:
3997 // Blink
3998 currentState.attr.setBlink(true);
3999 break;
4000
4001 case 7:
4002 // Reverse
4003 currentState.attr.setReverse(true);
4004 break;
4005
4006 default:
4007 break;
4008 }
4009
4010 if (type == DeviceType.XTERM) {
4011
4012 switch (i) {
4013
4014 case 8:
4015 // Invisible
4016 // TODO
4017 break;
4018
4019 case 90:
4020 // Set black foreground
4021 currentState.attr.setForeColorRGB(get88Color(8));
4022 break;
4023 case 91:
4024 // Set red foreground
4025 currentState.attr.setForeColorRGB(get88Color(9));
4026 break;
4027 case 92:
4028 // Set green foreground
4029 currentState.attr.setForeColorRGB(get88Color(10));
4030 break;
4031 case 93:
4032 // Set yellow foreground
4033 currentState.attr.setForeColorRGB(get88Color(11));
4034 break;
4035 case 94:
4036 // Set blue foreground
4037 currentState.attr.setForeColorRGB(get88Color(12));
4038 break;
4039 case 95:
4040 // Set magenta foreground
4041 currentState.attr.setForeColorRGB(get88Color(13));
4042 break;
4043 case 96:
4044 // Set cyan foreground
4045 currentState.attr.setForeColorRGB(get88Color(14));
4046 break;
4047 case 97:
4048 // Set white foreground
4049 currentState.attr.setForeColorRGB(get88Color(15));
4050 break;
4051
4052 case 100:
4053 // Set black background
4054 currentState.attr.setBackColorRGB(get88Color(8));
4055 break;
4056 case 101:
4057 // Set red background
4058 currentState.attr.setBackColorRGB(get88Color(9));
4059 break;
4060 case 102:
4061 // Set green background
4062 currentState.attr.setBackColorRGB(get88Color(10));
4063 break;
4064 case 103:
4065 // Set yellow background
4066 currentState.attr.setBackColorRGB(get88Color(11));
4067 break;
4068 case 104:
4069 // Set blue background
4070 currentState.attr.setBackColorRGB(get88Color(12));
4071 break;
4072 case 105:
4073 // Set magenta background
4074 currentState.attr.setBackColorRGB(get88Color(13));
4075 break;
4076 case 106:
4077 // Set cyan background
4078 currentState.attr.setBackColorRGB(get88Color(14));
4079 break;
4080 case 107:
4081 // Set white background
4082 currentState.attr.setBackColorRGB(get88Color(15));
4083 break;
4084
4085 default:
4086 break;
4087 }
4088 }
4089
4090 if ((type == DeviceType.VT220)
4091 || (type == DeviceType.XTERM)) {
4092
4093 switch (i) {
4094
4095 case 22:
4096 // Normal intensity
4097 currentState.attr.setBold(false);
4098 break;
4099
4100 case 24:
4101 // No underline
4102 currentState.attr.setUnderline(false);
4103 break;
4104
4105 case 25:
4106 // No blink
4107 currentState.attr.setBlink(false);
4108 break;
4109
4110 case 27:
4111 // Un-reverse
4112 currentState.attr.setReverse(false);
4113 break;
4114
4115 default:
4116 break;
4117 }
4118 }
4119
4120 // A true VT100/102/220 does not support color, however everyone
4121 // is used to their terminal emulator supporting color so we will
4122 // unconditionally support color for all DeviceType's.
4123
4124 switch (i) {
4125
4126 case 30:
4127 // Set black foreground
4128 currentState.attr.setForeColor(Color.BLACK);
4129 currentState.attr.setForeColorRGB(-1);
4130 break;
4131 case 31:
4132 // Set red foreground
4133 currentState.attr.setForeColor(Color.RED);
4134 currentState.attr.setForeColorRGB(-1);
4135 break;
4136 case 32:
4137 // Set green foreground
4138 currentState.attr.setForeColor(Color.GREEN);
4139 currentState.attr.setForeColorRGB(-1);
4140 break;
4141 case 33:
4142 // Set yellow foreground
4143 currentState.attr.setForeColor(Color.YELLOW);
4144 currentState.attr.setForeColorRGB(-1);
4145 break;
4146 case 34:
4147 // Set blue foreground
4148 currentState.attr.setForeColor(Color.BLUE);
4149 currentState.attr.setForeColorRGB(-1);
4150 break;
4151 case 35:
4152 // Set magenta foreground
4153 currentState.attr.setForeColor(Color.MAGENTA);
4154 currentState.attr.setForeColorRGB(-1);
4155 break;
4156 case 36:
4157 // Set cyan foreground
4158 currentState.attr.setForeColor(Color.CYAN);
4159 currentState.attr.setForeColorRGB(-1);
4160 break;
4161 case 37:
4162 // Set white foreground
4163 currentState.attr.setForeColor(Color.WHITE);
4164 currentState.attr.setForeColorRGB(-1);
4165 break;
4166 case 38:
4167 if (type == DeviceType.XTERM) {
4168 /*
4169 * Xterm supports T.416 / ISO-8613-3 codes to select
4170 * either an indexed color or an RGB value. (It also
4171 * permits these ISO-8613-3 SGR sequences to be separated
4172 * by colons rather than semicolons.)
4173 *
4174 * We will support only the following:
4175 *
4176 * 1. Indexed color mode (88- or 256-color modes).
4177 *
4178 * 2. Direct RGB.
4179 *
4180 * These cover most of the use cases in the real world.
4181 *
4182 * HOWEVER, note that this is an awful broken "standard",
4183 * with no way to do it "right". See
4184 * http://invisible-island.net/ncurses/ncurses.faq.html#xterm_16MegaColors
4185 * for a detailed discussion of the current state of RGB
4186 * in various terminals, the point of which is that none
4187 * of them really do the same thing despite all appearing
4188 * to be "xterm".
4189 *
4190 * Also see
4191 * https://bugs.kde.org/show_bug.cgi?id=107487#c3 .
4192 * where it is assumed that supporting just the "indexed
4193 * mode" of these sequences (which could align easily
4194 * with existing SGR colors) is assumed to mean full
4195 * support of 24-bit RGB. So it is all or nothing.
4196 *
4197 * Finally, these sequences break the assumptions of
4198 * standard ECMA-48 style parsers as pointed out at
4199 * https://bugs.kde.org/show_bug.cgi?id=107487#c11 .
4200 * Therefore in order to keep a clean display, we cannot
4201 * parse anything else in this sequence.
4202 */
4203 sgrColorMode = 38;
4204 continue;
4205 } else {
4206 // Underscore on, default foreground color
4207 currentState.attr.setUnderline(true);
4208 currentState.attr.setForeColor(Color.WHITE);
4209 }
4210 break;
4211 case 39:
4212 // Underscore off, default foreground color
4213 currentState.attr.setUnderline(false);
4214 currentState.attr.setForeColor(Color.WHITE);
4215 currentState.attr.setForeColorRGB(-1);
4216 break;
4217 case 40:
4218 // Set black background
4219 currentState.attr.setBackColor(Color.BLACK);
4220 currentState.attr.setBackColorRGB(-1);
4221 break;
4222 case 41:
4223 // Set red background
4224 currentState.attr.setBackColor(Color.RED);
4225 currentState.attr.setBackColorRGB(-1);
4226 break;
4227 case 42:
4228 // Set green background
4229 currentState.attr.setBackColor(Color.GREEN);
4230 currentState.attr.setBackColorRGB(-1);
4231 break;
4232 case 43:
4233 // Set yellow background
4234 currentState.attr.setBackColor(Color.YELLOW);
4235 currentState.attr.setBackColorRGB(-1);
4236 break;
4237 case 44:
4238 // Set blue background
4239 currentState.attr.setBackColor(Color.BLUE);
4240 currentState.attr.setBackColorRGB(-1);
4241 break;
4242 case 45:
4243 // Set magenta background
4244 currentState.attr.setBackColor(Color.MAGENTA);
4245 currentState.attr.setBackColorRGB(-1);
4246 break;
4247 case 46:
4248 // Set cyan background
4249 currentState.attr.setBackColor(Color.CYAN);
4250 currentState.attr.setBackColorRGB(-1);
4251 break;
4252 case 47:
4253 // Set white background
4254 currentState.attr.setBackColor(Color.WHITE);
4255 currentState.attr.setBackColorRGB(-1);
4256 break;
4257 case 48:
4258 if (type == DeviceType.XTERM) {
4259 /*
4260 * Xterm supports T.416 / ISO-8613-3 codes to select
4261 * either an indexed color or an RGB value. (It also
4262 * permits these ISO-8613-3 SGR sequences to be separated
4263 * by colons rather than semicolons.)
4264 *
4265 * We will support only the following:
4266 *
4267 * 1. Indexed color mode (88- or 256-color modes).
4268 *
4269 * 2. Direct RGB.
4270 *
4271 * These cover most of the use cases in the real world.
4272 *
4273 * HOWEVER, note that this is an awful broken "standard",
4274 * with no way to do it "right". See
4275 * http://invisible-island.net/ncurses/ncurses.faq.html#xterm_16MegaColors
4276 * for a detailed discussion of the current state of RGB
4277 * in various terminals, the point of which is that none
4278 * of them really do the same thing despite all appearing
4279 * to be "xterm".
4280 *
4281 * Also see
4282 * https://bugs.kde.org/show_bug.cgi?id=107487#c3 .
4283 * where it is assumed that supporting just the "indexed
4284 * mode" of these sequences (which could align easily
4285 * with existing SGR colors) is assumed to mean full
4286 * support of 24-bit RGB. So it is all or nothing.
4287 *
4288 * Finally, these sequences break the assumptions of
4289 * standard ECMA-48 style parsers as pointed out at
4290 * https://bugs.kde.org/show_bug.cgi?id=107487#c11 .
4291 * Therefore in order to keep a clean display, we cannot
4292 * parse anything else in this sequence.
4293 */
4294 sgrColorMode = 48;
4295 continue;
4296 }
4297 break;
4298 case 49:
4299 // Default background
4300 currentState.attr.setBackColor(Color.BLACK);
4301 currentState.attr.setBackColorRGB(-1);
4302 break;
4303
4304 default:
4305 break;
4306 }
4307 }
4308 }
4309
4310 /**
4311 * DA - Device attributes.
4312 */
4313 private void da() {
4314 int extendedFlag = 0;
4315 int i = 0;
4316 if (collectBuffer.length() > 0) {
4317 String args = collectBuffer.substring(1);
4318 if (collectBuffer.charAt(0) == '>') {
4319 extendedFlag = 1;
4320 if (collectBuffer.length() >= 2) {
4321 i = Integer.parseInt(args);
4322 }
4323 } else if (collectBuffer.charAt(0) == '=') {
4324 extendedFlag = 2;
4325 if (collectBuffer.length() >= 2) {
4326 i = Integer.parseInt(args);
4327 }
4328 } else {
4329 // Unknown code, bail out
4330 return;
4331 }
4332 }
4333
4334 if ((i != 0) && (i != 1)) {
4335 return;
4336 }
4337
4338 if ((extendedFlag == 0) && (i == 0)) {
4339 // Send string directly to remote side
4340 writeRemote(deviceTypeResponse());
4341 return;
4342 }
4343
4344 if ((type == DeviceType.VT220) || (type == DeviceType.XTERM)) {
4345
4346 if ((extendedFlag == 1) && (i == 0)) {
4347 /*
4348 * Request "What type of terminal are you, what is your
4349 * firmware version, and what hardware options do you have
4350 * installed?"
4351 *
4352 * Respond: "I am a VT220 (identification code of 1), my
4353 * firmware version is _____ (Pv), and I have _____ Po
4354 * options installed."
4355 *
4356 * (Same as xterm)
4357 *
4358 */
4359
4360 if (s8c1t == true) {
4361 writeRemote("\u009b>1;10;0c");
4362 } else {
4363 writeRemote("\033[>1;10;0c");
4364 }
4365 }
4366 }
4367
4368 // VT420 and up
4369 if ((extendedFlag == 2) && (i == 0)) {
4370
4371 /*
4372 * Request "What is your unit ID?"
4373 *
4374 * Respond: "I was manufactured at site 00 and have a unique ID
4375 * number of 123."
4376 *
4377 */
4378 writeRemote("\033P!|00010203\033\\");
4379 }
4380 }
4381
4382 /**
4383 * DECSTBM - Set top and bottom margins.
4384 */
4385 private void decstbm() {
4386 boolean decPrivateModeFlag = false;
4387
4388 for (int i = 0; i < collectBuffer.length(); i++) {
4389 if (collectBuffer.charAt(i) == '?') {
4390 decPrivateModeFlag = true;
4391 break;
4392 }
4393 }
4394 if (decPrivateModeFlag) {
4395 // This could be restore DEC private mode values.
4396 // Ignore it.
4397 } else {
4398 // DECSTBM
4399 int top = getCsiParam(0, 1, 1, height) - 1;
4400 int bottom = getCsiParam(1, height, 1, height) - 1;
4401
4402 if (top > bottom) {
4403 top = bottom;
4404 }
4405 scrollRegionTop = top;
4406 scrollRegionBottom = bottom;
4407
4408 // Home cursor
4409 cursorPosition(0, 0);
4410 }
4411 }
4412
4413 /**
4414 * DECREQTPARM - Request terminal parameters.
4415 */
4416 private void decreqtparm() {
4417 int i = getCsiParam(0, 0);
4418
4419 if ((i != 0) && (i != 1)) {
4420 return;
4421 }
4422
4423 String str = "";
4424
4425 /*
4426 * Request terminal parameters.
4427 *
4428 * Respond with:
4429 *
4430 * Parity NONE, 8 bits, xmitspeed 38400, recvspeed 38400.
4431 * (CLoCk MULtiplier = 1, STP option flags = 0)
4432 *
4433 * (Same as xterm)
4434 */
4435 if (((type == DeviceType.VT220) || (type == DeviceType.XTERM))
4436 && (s8c1t == true)
4437 ) {
4438 str = String.format("\u009b%d;1;1;128;128;1;0x", i + 2);
4439 } else {
4440 str = String.format("\033[%d;1;1;128;128;1;0x", i + 2);
4441 }
4442 writeRemote(str);
4443 }
4444
4445 /**
4446 * DECSCA - Select Character Attributes.
4447 */
4448 private void decsca() {
4449 int i = getCsiParam(0, 0);
4450
4451 if ((i == 0) || (i == 2)) {
4452 // Protect mode OFF
4453 currentState.attr.setProtect(false);
4454 }
4455 if (i == 1) {
4456 // Protect mode ON
4457 currentState.attr.setProtect(true);
4458 }
4459 }
4460
4461 /**
4462 * DECSTR - Soft Terminal Reset.
4463 */
4464 private void decstr() {
4465 // Do exactly like RIS - Reset to initial state
4466 reset();
4467 // Do I clear screen too? I think so...
4468 eraseScreen(0, 0, height - 1, width - 1, false);
4469 cursorPosition(0, 0);
4470 }
4471
4472 /**
4473 * DSR - Device status report.
4474 */
4475 private void dsr() {
4476 boolean decPrivateModeFlag = false;
4477 int row = currentState.cursorY;
4478
4479 for (int i = 0; i < collectBuffer.length(); i++) {
4480 if (collectBuffer.charAt(i) == '?') {
4481 decPrivateModeFlag = true;
4482 break;
4483 }
4484 }
4485
4486 int i = getCsiParam(0, 0);
4487
4488 switch (i) {
4489
4490 case 5:
4491 // Request status report. Respond with "OK, no malfunction."
4492
4493 // Send string directly to remote side
4494 if (((type == DeviceType.VT220) || (type == DeviceType.XTERM))
4495 && (s8c1t == true)
4496 ) {
4497 writeRemote("\u009b0n");
4498 } else {
4499 writeRemote("\033[0n");
4500 }
4501 break;
4502
4503 case 6:
4504 // Request cursor position. Respond with current position.
4505 if (currentState.originMode == true) {
4506 row -= scrollRegionTop;
4507 }
4508 String str = "";
4509 if (((type == DeviceType.VT220) || (type == DeviceType.XTERM))
4510 && (s8c1t == true)
4511 ) {
4512 str = String.format("\u009b%d;%dR", row + 1,
4513 currentState.cursorX + 1);
4514 } else {
4515 str = String.format("\033[%d;%dR", row + 1,
4516 currentState.cursorX + 1);
4517 }
4518
4519 // Send string directly to remote side
4520 writeRemote(str);
4521 break;
4522
4523 case 15:
4524 if (decPrivateModeFlag == true) {
4525
4526 // Request printer status report. Respond with "Printer not
4527 // connected."
4528
4529 if (((type == DeviceType.VT220) || (type == DeviceType.XTERM))
4530 && (s8c1t == true)) {
4531 writeRemote("\u009b?13n");
4532 } else {
4533 writeRemote("\033[?13n");
4534 }
4535 }
4536 break;
4537
4538 case 25:
4539 if (((type == DeviceType.VT220) || (type == DeviceType.XTERM))
4540 && (decPrivateModeFlag == true)
4541 ) {
4542
4543 // Request user-defined keys are locked or unlocked. Respond
4544 // with "User-defined keys are locked."
4545
4546 if (s8c1t == true) {
4547 writeRemote("\u009b?21n");
4548 } else {
4549 writeRemote("\033[?21n");
4550 }
4551 }
4552 break;
4553
4554 case 26:
4555 if (((type == DeviceType.VT220) || (type == DeviceType.XTERM))
4556 && (decPrivateModeFlag == true)
4557 ) {
4558
4559 // Request keyboard language. Respond with "Keyboard
4560 // language is North American."
4561
4562 if (s8c1t == true) {
4563 writeRemote("\u009b?27;1n");
4564 } else {
4565 writeRemote("\033[?27;1n");
4566 }
4567
4568 }
4569 break;
4570
4571 default:
4572 // Some other option, ignore
4573 break;
4574 }
4575 }
4576
4577 /**
4578 * TBC - Tabulation clear.
4579 */
4580 private void tbc() {
4581 int i = getCsiParam(0, 0);
4582 if (i == 0) {
4583 List<Integer> newStops = new ArrayList<Integer>();
4584 for (Integer stop: tabStops) {
4585 if (stop == currentState.cursorX) {
4586 continue;
4587 }
4588 newStops.add(stop);
4589 }
4590 tabStops = newStops;
4591 }
4592 if (i == 3) {
4593 tabStops.clear();
4594 }
4595 }
4596
4597 /**
4598 * Erase the characters in the current line from the start column to the
4599 * end column, inclusive.
4600 *
4601 * @param start starting column to erase (between 0 and width - 1)
4602 * @param end ending column to erase (between 0 and width - 1)
4603 * @param honorProtected if true, do not erase characters with the
4604 * protected attribute set
4605 */
4606 private void eraseLine(int start, int end, final boolean honorProtected) {
4607
4608 if (start > end) {
4609 return;
4610 }
4611 if (end > width - 1) {
4612 end = width - 1;
4613 }
4614 if (start < 0) {
4615 start = 0;
4616 }
4617
4618 for (int i = start; i <= end; i++) {
4619 DisplayLine line = display.get(currentState.cursorY);
4620 if ((!honorProtected)
4621 || ((honorProtected) && (!line.charAt(i).isProtect()))) {
4622
4623 switch (type) {
4624 case VT100:
4625 case VT102:
4626 case VT220:
4627 /*
4628 * From the VT102 manual:
4629 *
4630 * Erasing a character also erases any character
4631 * attribute of the character.
4632 */
4633 line.setBlank(i);
4634 break;
4635 case XTERM:
4636 /*
4637 * Erase with the current color a.k.a. back-color erase
4638 * (bce).
4639 */
4640 line.setChar(i, ' ');
4641 line.setAttr(i, currentState.attr);
4642 break;
4643 }
4644 }
4645 }
4646 }
4647
4648 /**
4649 * Erase a rectangular section of the screen, inclusive. end column,
4650 * inclusive.
4651 *
4652 * @param startRow starting row to erase (between 0 and height - 1)
4653 * @param startCol starting column to erase (between 0 and width - 1)
4654 * @param endRow ending row to erase (between 0 and height - 1)
4655 * @param endCol ending column to erase (between 0 and width - 1)
4656 * @param honorProtected if true, do not erase characters with the
4657 * protected attribute set
4658 */
4659 private void eraseScreen(final int startRow, final int startCol,
4660 final int endRow, final int endCol, final boolean honorProtected) {
4661
4662 int oldCursorY;
4663
4664 if ((startRow < 0)
4665 || (startCol < 0)
4666 || (endRow < 0)
4667 || (endCol < 0)
4668 || (endRow < startRow)
4669 || (endCol < startCol)
4670 ) {
4671 return;
4672 }
4673
4674 oldCursorY = currentState.cursorY;
4675 for (int i = startRow; i <= endRow; i++) {
4676 currentState.cursorY = i;
4677 eraseLine(startCol, endCol, honorProtected);
4678
4679 // Erase display clears the double attributes
4680 display.get(i).setDoubleWidth(false);
4681 display.get(i).setDoubleHeight(0);
4682 }
4683 currentState.cursorY = oldCursorY;
4684 }
4685
4686 /**
4687 * VT220 printer functions. All of these are parsed, but won't do
4688 * anything.
4689 */
4690 private void printerFunctions() {
4691 boolean decPrivateModeFlag = false;
4692 for (int i = 0; i < collectBuffer.length(); i++) {
4693 if (collectBuffer.charAt(i) == '?') {
4694 decPrivateModeFlag = true;
4695 break;
4696 }
4697 }
4698
4699 int i = getCsiParam(0, 0);
4700
4701 switch (i) {
4702
4703 case 0:
4704 if (decPrivateModeFlag == false) {
4705 // Print screen
4706 }
4707 break;
4708
4709 case 1:
4710 if (decPrivateModeFlag == true) {
4711 // Print cursor line
4712 }
4713 break;
4714
4715 case 4:
4716 if (decPrivateModeFlag == true) {
4717 // Auto print mode OFF
4718 } else {
4719 // Printer controller OFF
4720
4721 // Characters re-appear on the screen
4722 printerControllerMode = false;
4723 }
4724 break;
4725
4726 case 5:
4727 if (decPrivateModeFlag == true) {
4728 // Auto print mode
4729
4730 } else {
4731 // Printer controller
4732
4733 // Characters get sucked into oblivion
4734 printerControllerMode = true;
4735 }
4736 break;
4737
4738 default:
4739 break;
4740
4741 }
4742 }
4743
4744 /**
4745 * Handle the SCAN_OSC_STRING state. Handle this in VT100 because lots
4746 * of remote systems will send an XTerm title sequence even if TERM isn't
4747 * xterm.
4748 *
4749 * @param xtermChar the character received from the remote side
4750 */
4751 private void oscPut(final char xtermChar) {
4752 // System.err.println("oscPut: " + xtermChar);
4753
4754 // Collect first
4755 collectBuffer.append(xtermChar);
4756
4757 // Xterm cases...
4758 if ((xtermChar == 0x07)
4759 || (collectBuffer.toString().endsWith("\033\\"))
4760 ) {
4761 String args = null;
4762 if (xtermChar == 0x07) {
4763 args = collectBuffer.substring(0, collectBuffer.length() - 1);
4764 } else {
4765 args = collectBuffer.substring(0, collectBuffer.length() - 2);
4766 }
4767
4768 String [] p = args.split(";");
4769 if (p.length > 0) {
4770 if ((p[0].equals("0")) || (p[0].equals("2"))) {
4771 if (p.length > 1) {
4772 // Screen title
4773 screenTitle = p[1];
4774 }
4775 }
4776
4777 if (p[0].equals("4")) {
4778 for (int i = 1; i + 1 < p.length; i += 2) {
4779 // Set a color index value
4780 try {
4781 set88Color(Integer.parseInt(p[i]), p[i + 1]);
4782 } catch (NumberFormatException e) {
4783 // SQUASH
4784 }
4785 }
4786 }
4787
4788 if (p[0].equals("10")) {
4789 if (p[1].equals("?")) {
4790 // Respond with foreground color.
4791 java.awt.Color color = jexer.backend.SwingTerminal.attrToForegroundColor(currentState.attr);
4792
4793 writeRemote(String.format(
4794 "\033]10;rgb:%04x/%04x/%04x\033\\",
4795 color.getRed() << 8,
4796 color.getGreen() << 8,
4797 color.getBlue() << 8));
4798 }
4799 }
4800
4801 if (p[0].equals("11")) {
4802 if (p[1].equals("?")) {
4803 // Respond with background color.
4804 java.awt.Color color = jexer.backend.SwingTerminal.attrToBackgroundColor(currentState.attr);
4805
4806 writeRemote(String.format(
4807 "\033]11;rgb:%04x/%04x/%04x\033\\",
4808 color.getRed() << 8,
4809 color.getGreen() << 8,
4810 color.getBlue() << 8));
4811 }
4812 }
4813
4814 if (p[0].equals("444") && (p.length == 5)) {
4815 // Jexer image
4816 parseJexerImage(p[1], p[2], p[3], p[4]);
4817 }
4818
4819 }
4820
4821 // Go to SCAN_GROUND state
4822 toGround();
4823 return;
4824 }
4825 }
4826
4827 /**
4828 * Handle the SCAN_SOSPMAPC_STRING state. This is currently only used by
4829 * Jexer ECMA48Terminal to talk to ECMA48.
4830 *
4831 * @param pmChar the character received from the remote side
4832 */
4833 private void pmPut(final char pmChar) {
4834 // System.err.println("pmPut: " + pmChar);
4835
4836 // Collect first
4837 collectBuffer.append(pmChar);
4838
4839 // Xterm cases...
4840 if (collectBuffer.toString().endsWith("\033\\")) {
4841 String arg = null;
4842 arg = collectBuffer.substring(0, collectBuffer.length() - 2);
4843
4844 // System.err.println("arg: '" + arg + "'");
4845
4846 if (arg.equals("hideMousePointer")) {
4847 hideMousePointer = true;
4848 }
4849 if (arg.equals("showMousePointer")) {
4850 hideMousePointer = false;
4851 }
4852
4853 // Go to SCAN_GROUND state
4854 toGround();
4855 return;
4856 }
4857 }
4858
4859 /**
4860 * Perform xterm window operations.
4861 */
4862 private void xtermWindowOps() {
4863 boolean xtermPrivateModeFlag = false;
4864
4865 for (int i = 0; i < collectBuffer.length(); i++) {
4866 if (collectBuffer.charAt(i) == '?') {
4867 xtermPrivateModeFlag = true;
4868 break;
4869 }
4870 }
4871
4872 int i = getCsiParam(0, 0);
4873
4874 if (!xtermPrivateModeFlag) {
4875 switch (i) {
4876 case 14:
4877 // Report xterm text area size in pixels as CSI 4 ; height ;
4878 // width t
4879 writeRemote(String.format("\033[4;%d;%dt", textHeight * height,
4880 textWidth * width));
4881 break;
4882 case 16:
4883 // Report character size in pixels as CSI 6 ; height ; width
4884 // t
4885 writeRemote(String.format("\033[6;%d;%dt", textHeight,
4886 textWidth));
4887 break;
4888 case 18:
4889 // Report the text are size in characters as CSI 8 ; height ;
4890 // width t
4891 writeRemote(String.format("\033[8;%d;%dt", height, width));
4892 break;
4893 default:
4894 break;
4895 }
4896 }
4897 }
4898
4899 /**
4900 * Respond to xterm sixel query.
4901 */
4902 private void xtermSixelQuery() {
4903 int item = getCsiParam(0, 0);
4904 int action = getCsiParam(1, 0);
4905 int value = getCsiParam(2, 0);
4906
4907 switch (item) {
4908 case 1:
4909 if (action == 1) {
4910 // Report number of color registers.
4911 writeRemote(String.format("\033[?%d;%d;%dS", item, 0, 1024));
4912 return;
4913 }
4914 break;
4915 default:
4916 break;
4917 }
4918 // We will not support this option.
4919 writeRemote(String.format("\033[?%d;%dS", item, action));
4920 }
4921
4922 /**
4923 * Run this input character through the ECMA48 state machine.
4924 *
4925 * @param ch character from the remote side
4926 */
4927 private void consume(final int ch) {
4928
4929 // DEBUG
4930 // System.err.printf("%c STATE = %s\n", ch, scanState);
4931
4932 // Special "anywhere" states
4933
4934 // 18, 1A --> execute, then switch to SCAN_GROUND
4935 if ((ch == 0x18) || (ch == 0x1A)) {
4936 // CAN and SUB abort escape sequences
4937 toGround();
4938 return;
4939 }
4940
4941 // 80-8F, 91-97, 99, 9A, 9C --> execute, then switch to SCAN_GROUND
4942
4943 // 0x1B == ESCAPE
4944 if (ch == 0x1B) {
4945 if ((type == DeviceType.XTERM)
4946 && ((scanState == ScanState.OSC_STRING)
4947 || (scanState == ScanState.DCS_SIXEL)
4948 || (scanState == ScanState.SOSPMAPC_STRING))
4949 ) {
4950 // Xterm can pass ESCAPE to its OSC sequence.
4951 // Xterm can pass ESCAPE to its DCS sequence.
4952 // Jexer can pass ESCAPE to its PM sequence.
4953 } else if ((scanState != ScanState.DCS_ENTRY)
4954 && (scanState != ScanState.DCS_INTERMEDIATE)
4955 && (scanState != ScanState.DCS_IGNORE)
4956 && (scanState != ScanState.DCS_PARAM)
4957 && (scanState != ScanState.DCS_PASSTHROUGH)
4958 ) {
4959 scanState = ScanState.ESCAPE;
4960 return;
4961 }
4962 }
4963
4964 // 0x9B == CSI 8-bit sequence
4965 if (ch == 0x9B) {
4966 scanState = ScanState.CSI_ENTRY;
4967 return;
4968 }
4969
4970 // 0x9D goes to ScanState.OSC_STRING
4971 if (ch == 0x9D) {
4972 scanState = ScanState.OSC_STRING;
4973 return;
4974 }
4975
4976 // 0x90 goes to DCS_ENTRY
4977 if (ch == 0x90) {
4978 scanState = ScanState.DCS_ENTRY;
4979 return;
4980 }
4981
4982 // 0x98, 0x9E, and 0x9F go to SOSPMAPC_STRING
4983 if ((ch == 0x98) || (ch == 0x9E) || (ch == 0x9F)) {
4984 scanState = ScanState.SOSPMAPC_STRING;
4985 return;
4986 }
4987
4988 // 0x7F (DEL) is always discarded
4989 if (ch == 0x7F) {
4990 return;
4991 }
4992
4993 switch (scanState) {
4994
4995 case GROUND:
4996 // 00-17, 19, 1C-1F --> execute
4997 // 80-8F, 91-9A, 9C --> execute
4998 if ((ch <= 0x1F) || ((ch >= 0x80) && (ch <= 0x9F))) {
4999 handleControlChar((char) ch);
5000 }
5001
5002 // 20-7F --> print
5003 if (((ch >= 0x20) && (ch <= 0x7F))
5004 || (ch >= 0xA0)
5005 ) {
5006
5007 // VT220 printer --> trash bin
5008 if (((type == DeviceType.VT220)
5009 || (type == DeviceType.XTERM))
5010 && (printerControllerMode == true)
5011 ) {
5012 return;
5013 }
5014
5015 // Hang onto this character
5016 repCh = mapCharacter(ch);
5017
5018 // Print this character
5019 printCharacter(repCh);
5020 }
5021 return;
5022
5023 case ESCAPE:
5024 // 00-17, 19, 1C-1F --> execute
5025 if (ch <= 0x1F) {
5026 handleControlChar((char) ch);
5027 return;
5028 }
5029
5030 // 20-2F --> collect, then switch to ESCAPE_INTERMEDIATE
5031 if ((ch >= 0x20) && (ch <= 0x2F)) {
5032 collect((char) ch);
5033 scanState = ScanState.ESCAPE_INTERMEDIATE;
5034 return;
5035 }
5036
5037 // 30-4F, 51-57, 59, 5A, 5C, 60-7E --> dispatch, then switch to GROUND
5038 if ((ch >= 0x30) && (ch <= 0x4F)) {
5039 switch (ch) {
5040 case '0':
5041 case '1':
5042 case '2':
5043 case '3':
5044 case '4':
5045 case '5':
5046 case '6':
5047 break;
5048 case '7':
5049 // DECSC - Save cursor
5050 // Note this code overlaps both ANSI and VT52 mode
5051 decsc();
5052 break;
5053
5054 case '8':
5055 // DECRC - Restore cursor
5056 // Note this code overlaps both ANSI and VT52 mode
5057 decrc();
5058 break;
5059
5060 case '9':
5061 case ':':
5062 case ';':
5063 break;
5064 case '<':
5065 if (vt52Mode == true) {
5066 // DECANM - Enter ANSI mode
5067 vt52Mode = false;
5068 arrowKeyMode = ArrowKeyMode.VT100;
5069
5070 /*
5071 * From the VT102 docs: "You use ANSI mode to select
5072 * most terminal features; the terminal uses the same
5073 * features when it switches to VT52 mode. You
5074 * cannot, however, change most of these features in
5075 * VT52 mode."
5076 *
5077 * In other words, do not reset any other attributes
5078 * when switching between VT52 submode and ANSI.
5079 */
5080
5081 // Reset fonts
5082 currentState.g0Charset = CharacterSet.US;
5083 currentState.g1Charset = CharacterSet.DRAWING;
5084 s8c1t = false;
5085 singleshift = Singleshift.NONE;
5086 currentState.glLockshift = LockshiftMode.NONE;
5087 currentState.grLockshift = LockshiftMode.NONE;
5088 }
5089 break;
5090 case '=':
5091 // DECKPAM - Keypad application mode
5092 // Note this code overlaps both ANSI and VT52 mode
5093 deckpam();
5094 break;
5095 case '>':
5096 // DECKPNM - Keypad numeric mode
5097 // Note this code overlaps both ANSI and VT52 mode
5098 deckpnm();
5099 break;
5100 case '?':
5101 case '@':
5102 break;
5103 case 'A':
5104 if (vt52Mode == true) {
5105 // Cursor up, and stop at the top without scrolling
5106 cursorUp(1, false);
5107 }
5108 break;
5109 case 'B':
5110 if (vt52Mode == true) {
5111 // Cursor down, and stop at the bottom without scrolling
5112 cursorDown(1, false);
5113 }
5114 break;
5115 case 'C':
5116 if (vt52Mode == true) {
5117 // Cursor right, and stop at the right without scrolling
5118 cursorRight(1, false);
5119 }
5120 break;
5121 case 'D':
5122 if (vt52Mode == true) {
5123 // Cursor left, and stop at the left without scrolling
5124 cursorLeft(1, false);
5125 } else {
5126 // IND - Index
5127 ind();
5128 }
5129 break;
5130 case 'E':
5131 if (vt52Mode == true) {
5132 // Nothing
5133 } else {
5134 // NEL - Next line
5135 nel();
5136 }
5137 break;
5138 case 'F':
5139 if (vt52Mode == true) {
5140 // G0 --> Special graphics
5141 currentState.g0Charset = CharacterSet.VT52_GRAPHICS;
5142 }
5143 break;
5144 case 'G':
5145 if (vt52Mode == true) {
5146 // G0 --> ASCII set
5147 currentState.g0Charset = CharacterSet.US;
5148 }
5149 break;
5150 case 'H':
5151 if (vt52Mode == true) {
5152 // Cursor to home
5153 cursorPosition(0, 0);
5154 } else {
5155 // HTS - Horizontal tabulation set
5156 hts();
5157 }
5158 break;
5159 case 'I':
5160 if (vt52Mode == true) {
5161 // Reverse line feed. Same as RI.
5162 ri();
5163 }
5164 break;
5165 case 'J':
5166 if (vt52Mode == true) {
5167 // Erase to end of screen
5168 eraseLine(currentState.cursorX, width - 1, false);
5169 eraseScreen(currentState.cursorY + 1, 0, height - 1,
5170 width - 1, false);
5171 }
5172 break;
5173 case 'K':
5174 if (vt52Mode == true) {
5175 // Erase to end of line
5176 eraseLine(currentState.cursorX, width - 1, false);
5177 }
5178 break;
5179 case 'L':
5180 break;
5181 case 'M':
5182 if (vt52Mode == true) {
5183 // Nothing
5184 } else {
5185 // RI - Reverse index
5186 ri();
5187 }
5188 break;
5189 case 'N':
5190 if (vt52Mode == false) {
5191 // SS2
5192 singleshift = Singleshift.SS2;
5193 }
5194 break;
5195 case 'O':
5196 if (vt52Mode == false) {
5197 // SS3
5198 singleshift = Singleshift.SS3;
5199 }
5200 break;
5201 }
5202 toGround();
5203 return;
5204 }
5205 if ((ch >= 0x51) && (ch <= 0x57)) {
5206 switch (ch) {
5207 case 'Q':
5208 case 'R':
5209 case 'S':
5210 case 'T':
5211 case 'U':
5212 case 'V':
5213 case 'W':
5214 break;
5215 }
5216 toGround();
5217 return;
5218 }
5219 if (ch == 0x59) {
5220 // 'Y'
5221 if (vt52Mode == true) {
5222 scanState = ScanState.VT52_DIRECT_CURSOR_ADDRESS;
5223 } else {
5224 toGround();
5225 }
5226 return;
5227 }
5228 if (ch == 0x5A) {
5229 // 'Z'
5230 if (vt52Mode == true) {
5231 // Identify
5232 // Send string directly to remote side
5233 writeRemote("\033/Z");
5234 } else {
5235 // DECID
5236 // Send string directly to remote side
5237 writeRemote(deviceTypeResponse());
5238 }
5239 toGround();
5240 return;
5241 }
5242 if (ch == 0x5C) {
5243 // '\'
5244 toGround();
5245 return;
5246 }
5247
5248 // VT52 cannot get to any of these other states
5249 if (vt52Mode == true) {
5250 toGround();
5251 return;
5252 }
5253
5254 if ((ch >= 0x60) && (ch <= 0x7E)) {
5255 switch (ch) {
5256 case '`':
5257 case 'a':
5258 case 'b':
5259 break;
5260 case 'c':
5261 // RIS - Reset to initial state
5262 reset();
5263 // Do I clear screen too? I think so...
5264 eraseScreen(0, 0, height - 1, width - 1, false);
5265 cursorPosition(0, 0);
5266 break;
5267 case 'd':
5268 case 'e':
5269 case 'f':
5270 case 'g':
5271 case 'h':
5272 case 'i':
5273 case 'j':
5274 case 'k':
5275 case 'l':
5276 case 'm':
5277 break;
5278 case 'n':
5279 if ((type == DeviceType.VT220)
5280 || (type == DeviceType.XTERM)) {
5281
5282 // VT220 lockshift G2 into GL
5283 currentState.glLockshift = LockshiftMode.G2_GL;
5284 shiftOut = false;
5285 }
5286 break;
5287 case 'o':
5288 if ((type == DeviceType.VT220)
5289 || (type == DeviceType.XTERM)) {
5290
5291 // VT220 lockshift G3 into GL
5292 currentState.glLockshift = LockshiftMode.G3_GL;
5293 shiftOut = false;
5294 }
5295 break;
5296 case 'p':
5297 case 'q':
5298 case 'r':
5299 case 's':
5300 case 't':
5301 case 'u':
5302 case 'v':
5303 case 'w':
5304 case 'x':
5305 case 'y':
5306 case 'z':
5307 case '{':
5308 break;
5309 case '|':
5310 if ((type == DeviceType.VT220)
5311 || (type == DeviceType.XTERM)) {
5312
5313 // VT220 lockshift G3 into GR
5314 currentState.grLockshift = LockshiftMode.G3_GR;
5315 shiftOut = false;
5316 }
5317 break;
5318 case '}':
5319 if ((type == DeviceType.VT220)
5320 || (type == DeviceType.XTERM)) {
5321
5322 // VT220 lockshift G2 into GR
5323 currentState.grLockshift = LockshiftMode.G2_GR;
5324 shiftOut = false;
5325 }
5326 break;
5327
5328 case '~':
5329 if ((type == DeviceType.VT220)
5330 || (type == DeviceType.XTERM)) {
5331
5332 // VT220 lockshift G1 into GR
5333 currentState.grLockshift = LockshiftMode.G1_GR;
5334 shiftOut = false;
5335 }
5336 break;
5337 }
5338 toGround();
5339 }
5340
5341 // 7F --> ignore
5342
5343 // 0x5B goes to CSI_ENTRY
5344 if (ch == 0x5B) {
5345 scanState = ScanState.CSI_ENTRY;
5346 }
5347
5348 // 0x5D goes to OSC_STRING
5349 if (ch == 0x5D) {
5350 scanState = ScanState.OSC_STRING;
5351 }
5352
5353 // 0x50 goes to DCS_ENTRY
5354 if (ch == 0x50) {
5355 scanState = ScanState.DCS_ENTRY;
5356 }
5357
5358 // 0x58, 0x5E, and 0x5F go to SOSPMAPC_STRING
5359 if ((ch == 0x58) || (ch == 0x5E) || (ch == 0x5F)) {
5360 scanState = ScanState.SOSPMAPC_STRING;
5361 }
5362
5363 return;
5364
5365 case ESCAPE_INTERMEDIATE:
5366 // 00-17, 19, 1C-1F --> execute
5367 if (ch <= 0x1F) {
5368 handleControlChar((char) ch);
5369 }
5370
5371 // 20-2F --> collect
5372 if ((ch >= 0x20) && (ch <= 0x2F)) {
5373 collect((char) ch);
5374 }
5375
5376 // 30-7E --> dispatch, then switch to GROUND
5377 if ((ch >= 0x30) && (ch <= 0x7E)) {
5378 switch (ch) {
5379 case '0':
5380 if ((collectBuffer.length() == 1)
5381 && (collectBuffer.charAt(0) == '(')) {
5382 // G0 --> Special graphics
5383 currentState.g0Charset = CharacterSet.DRAWING;
5384 }
5385 if ((collectBuffer.length() == 1)
5386 && (collectBuffer.charAt(0) == ')')) {
5387 // G1 --> Special graphics
5388 currentState.g1Charset = CharacterSet.DRAWING;
5389 }
5390 if ((type == DeviceType.VT220)
5391 || (type == DeviceType.XTERM)) {
5392
5393 if ((collectBuffer.length() == 1)
5394 && (collectBuffer.charAt(0) == '*')) {
5395 // G2 --> Special graphics
5396 currentState.g2Charset = CharacterSet.DRAWING;
5397 }
5398 if ((collectBuffer.length() == 1)
5399 && (collectBuffer.charAt(0) == '+')) {
5400 // G3 --> Special graphics
5401 currentState.g3Charset = CharacterSet.DRAWING;
5402 }
5403 }
5404 break;
5405 case '1':
5406 if ((collectBuffer.length() == 1)
5407 && (collectBuffer.charAt(0) == '(')) {
5408 // G0 --> Alternate character ROM standard character set
5409 currentState.g0Charset = CharacterSet.ROM;
5410 }
5411 if ((collectBuffer.length() == 1)
5412 && (collectBuffer.charAt(0) == ')')) {
5413 // G1 --> Alternate character ROM standard character set
5414 currentState.g1Charset = CharacterSet.ROM;
5415 }
5416 break;
5417 case '2':
5418 if ((collectBuffer.length() == 1)
5419 && (collectBuffer.charAt(0) == '(')) {
5420 // G0 --> Alternate character ROM special graphics
5421 currentState.g0Charset = CharacterSet.ROM_SPECIAL;
5422 }
5423 if ((collectBuffer.length() == 1)
5424 && (collectBuffer.charAt(0) == ')')) {
5425 // G1 --> Alternate character ROM special graphics
5426 currentState.g1Charset = CharacterSet.ROM_SPECIAL;
5427 }
5428 break;
5429 case '3':
5430 if ((collectBuffer.length() == 1)
5431 && (collectBuffer.charAt(0) == '#')) {
5432 // DECDHL - Double-height line (top half)
5433 dechdl(true);
5434 }
5435 break;
5436 case '4':
5437 if ((collectBuffer.length() == 1)
5438 && (collectBuffer.charAt(0) == '#')) {
5439 // DECDHL - Double-height line (bottom half)
5440 dechdl(false);
5441 }
5442 if ((type == DeviceType.VT220)
5443 || (type == DeviceType.XTERM)) {
5444
5445 if ((collectBuffer.length() == 1)
5446 && (collectBuffer.charAt(0) == '(')) {
5447 // G0 --> DUTCH
5448 currentState.g0Charset = CharacterSet.NRC_DUTCH;
5449 }
5450 if ((collectBuffer.length() == 1)
5451 && (collectBuffer.charAt(0) == ')')) {
5452 // G1 --> DUTCH
5453 currentState.g1Charset = CharacterSet.NRC_DUTCH;
5454 }
5455 if ((collectBuffer.length() == 1)
5456 && (collectBuffer.charAt(0) == '*')) {
5457 // G2 --> DUTCH
5458 currentState.g2Charset = CharacterSet.NRC_DUTCH;
5459 }
5460 if ((collectBuffer.length() == 1)
5461 && (collectBuffer.charAt(0) == '+')) {
5462 // G3 --> DUTCH
5463 currentState.g3Charset = CharacterSet.NRC_DUTCH;
5464 }
5465 }
5466 break;
5467 case '5':
5468 if ((collectBuffer.length() == 1)
5469 && (collectBuffer.charAt(0) == '#')) {
5470 // DECSWL - Single-width line
5471 decswl();
5472 }
5473 if ((type == DeviceType.VT220)
5474 || (type == DeviceType.XTERM)) {
5475
5476 if ((collectBuffer.length() == 1)
5477 && (collectBuffer.charAt(0) == '(')) {
5478 // G0 --> FINNISH
5479 currentState.g0Charset = CharacterSet.NRC_FINNISH;
5480 }
5481 if ((collectBuffer.length() == 1)
5482 && (collectBuffer.charAt(0) == ')')) {
5483 // G1 --> FINNISH
5484 currentState.g1Charset = CharacterSet.NRC_FINNISH;
5485 }
5486 if ((collectBuffer.length() == 1)
5487 && (collectBuffer.charAt(0) == '*')) {
5488 // G2 --> FINNISH
5489 currentState.g2Charset = CharacterSet.NRC_FINNISH;
5490 }
5491 if ((collectBuffer.length() == 1)
5492 && (collectBuffer.charAt(0) == '+')) {
5493 // G3 --> FINNISH
5494 currentState.g3Charset = CharacterSet.NRC_FINNISH;
5495 }
5496 }
5497 break;
5498 case '6':
5499 if ((collectBuffer.length() == 1)
5500 && (collectBuffer.charAt(0) == '#')) {
5501 // DECDWL - Double-width line
5502 decdwl();
5503 }
5504 if ((type == DeviceType.VT220)
5505 || (type == DeviceType.XTERM)) {
5506
5507 if ((collectBuffer.length() == 1)
5508 && (collectBuffer.charAt(0) == '(')) {
5509 // G0 --> NORWEGIAN
5510 currentState.g0Charset = CharacterSet.NRC_NORWEGIAN;
5511 }
5512 if ((collectBuffer.length() == 1)
5513 && (collectBuffer.charAt(0) == ')')) {
5514 // G1 --> NORWEGIAN
5515 currentState.g1Charset = CharacterSet.NRC_NORWEGIAN;
5516 }
5517 if ((collectBuffer.length() == 1)
5518 && (collectBuffer.charAt(0) == '*')) {
5519 // G2 --> NORWEGIAN
5520 currentState.g2Charset = CharacterSet.NRC_NORWEGIAN;
5521 }
5522 if ((collectBuffer.length() == 1)
5523 && (collectBuffer.charAt(0) == '+')) {
5524 // G3 --> NORWEGIAN
5525 currentState.g3Charset = CharacterSet.NRC_NORWEGIAN;
5526 }
5527 }
5528 break;
5529 case '7':
5530 if ((type == DeviceType.VT220)
5531 || (type == DeviceType.XTERM)) {
5532
5533 if ((collectBuffer.length() == 1)
5534 && (collectBuffer.charAt(0) == '(')) {
5535 // G0 --> SWEDISH
5536 currentState.g0Charset = CharacterSet.NRC_SWEDISH;
5537 }
5538 if ((collectBuffer.length() == 1)
5539 && (collectBuffer.charAt(0) == ')')) {
5540 // G1 --> SWEDISH
5541 currentState.g1Charset = CharacterSet.NRC_SWEDISH;
5542 }
5543 if ((collectBuffer.length() == 1)
5544 && (collectBuffer.charAt(0) == '*')) {
5545 // G2 --> SWEDISH
5546 currentState.g2Charset = CharacterSet.NRC_SWEDISH;
5547 }
5548 if ((collectBuffer.length() == 1)
5549 && (collectBuffer.charAt(0) == '+')) {
5550 // G3 --> SWEDISH
5551 currentState.g3Charset = CharacterSet.NRC_SWEDISH;
5552 }
5553 }
5554 break;
5555 case '8':
5556 if ((collectBuffer.length() == 1)
5557 && (collectBuffer.charAt(0) == '#')) {
5558 // DECALN - Screen alignment display
5559 decaln();
5560 }
5561 break;
5562 case '9':
5563 case ':':
5564 case ';':
5565 break;
5566 case '<':
5567 if ((type == DeviceType.VT220)
5568 || (type == DeviceType.XTERM)) {
5569
5570 if ((collectBuffer.length() == 1)
5571 && (collectBuffer.charAt(0) == '(')) {
5572 // G0 --> DEC_SUPPLEMENTAL
5573 currentState.g0Charset = CharacterSet.DEC_SUPPLEMENTAL;
5574 }
5575 if ((collectBuffer.length() == 1)
5576 && (collectBuffer.charAt(0) == ')')) {
5577 // G1 --> DEC_SUPPLEMENTAL
5578 currentState.g1Charset = CharacterSet.DEC_SUPPLEMENTAL;
5579 }
5580 if ((collectBuffer.length() == 1)
5581 && (collectBuffer.charAt(0) == '*')) {
5582 // G2 --> DEC_SUPPLEMENTAL
5583 currentState.g2Charset = CharacterSet.DEC_SUPPLEMENTAL;
5584 }
5585 if ((collectBuffer.length() == 1)
5586 && (collectBuffer.charAt(0) == '+')) {
5587 // G3 --> DEC_SUPPLEMENTAL
5588 currentState.g3Charset = CharacterSet.DEC_SUPPLEMENTAL;
5589 }
5590 }
5591 break;
5592 case '=':
5593 if ((type == DeviceType.VT220)
5594 || (type == DeviceType.XTERM)) {
5595
5596 if ((collectBuffer.length() == 1)
5597 && (collectBuffer.charAt(0) == '(')) {
5598 // G0 --> SWISS
5599 currentState.g0Charset = CharacterSet.NRC_SWISS;
5600 }
5601 if ((collectBuffer.length() == 1)
5602 && (collectBuffer.charAt(0) == ')')) {
5603 // G1 --> SWISS
5604 currentState.g1Charset = CharacterSet.NRC_SWISS;
5605 }
5606 if ((collectBuffer.length() == 1)
5607 && (collectBuffer.charAt(0) == '*')) {
5608 // G2 --> SWISS
5609 currentState.g2Charset = CharacterSet.NRC_SWISS;
5610 }
5611 if ((collectBuffer.length() == 1)
5612 && (collectBuffer.charAt(0) == '+')) {
5613 // G3 --> SWISS
5614 currentState.g3Charset = CharacterSet.NRC_SWISS;
5615 }
5616 }
5617 break;
5618 case '>':
5619 case '?':
5620 case '@':
5621 break;
5622 case 'A':
5623 if ((collectBuffer.length() == 1)
5624 && (collectBuffer.charAt(0) == '(')) {
5625 // G0 --> United Kingdom set
5626 currentState.g0Charset = CharacterSet.UK;
5627 }
5628 if ((collectBuffer.length() == 1)
5629 && (collectBuffer.charAt(0) == ')')) {
5630 // G1 --> United Kingdom set
5631 currentState.g1Charset = CharacterSet.UK;
5632 }
5633 if ((type == DeviceType.VT220)
5634 || (type == DeviceType.XTERM)) {
5635
5636 if ((collectBuffer.length() == 1)
5637 && (collectBuffer.charAt(0) == '*')) {
5638 // G2 --> United Kingdom set
5639 currentState.g2Charset = CharacterSet.UK;
5640 }
5641 if ((collectBuffer.length() == 1)
5642 && (collectBuffer.charAt(0) == '+')) {
5643 // G3 --> United Kingdom set
5644 currentState.g3Charset = CharacterSet.UK;
5645 }
5646 }
5647 break;
5648 case 'B':
5649 if ((collectBuffer.length() == 1)
5650 && (collectBuffer.charAt(0) == '(')) {
5651 // G0 --> ASCII set
5652 currentState.g0Charset = CharacterSet.US;
5653 }
5654 if ((collectBuffer.length() == 1)
5655 && (collectBuffer.charAt(0) == ')')) {
5656 // G1 --> ASCII set
5657 currentState.g1Charset = CharacterSet.US;
5658 }
5659 if ((type == DeviceType.VT220)
5660 || (type == DeviceType.XTERM)) {
5661
5662 if ((collectBuffer.length() == 1)
5663 && (collectBuffer.charAt(0) == '*')) {
5664 // G2 --> ASCII
5665 currentState.g2Charset = CharacterSet.US;
5666 }
5667 if ((collectBuffer.length() == 1)
5668 && (collectBuffer.charAt(0) == '+')) {
5669 // G3 --> ASCII
5670 currentState.g3Charset = CharacterSet.US;
5671 }
5672 }
5673 break;
5674 case 'C':
5675 if ((type == DeviceType.VT220)
5676 || (type == DeviceType.XTERM)) {
5677
5678 if ((collectBuffer.length() == 1)
5679 && (collectBuffer.charAt(0) == '(')) {
5680 // G0 --> FINNISH
5681 currentState.g0Charset = CharacterSet.NRC_FINNISH;
5682 }
5683 if ((collectBuffer.length() == 1)
5684 && (collectBuffer.charAt(0) == ')')) {
5685 // G1 --> FINNISH
5686 currentState.g1Charset = CharacterSet.NRC_FINNISH;
5687 }
5688 if ((collectBuffer.length() == 1)
5689 && (collectBuffer.charAt(0) == '*')) {
5690 // G2 --> FINNISH
5691 currentState.g2Charset = CharacterSet.NRC_FINNISH;
5692 }
5693 if ((collectBuffer.length() == 1)
5694 && (collectBuffer.charAt(0) == '+')) {
5695 // G3 --> FINNISH
5696 currentState.g3Charset = CharacterSet.NRC_FINNISH;
5697 }
5698 }
5699 break;
5700 case 'D':
5701 break;
5702 case 'E':
5703 if ((type == DeviceType.VT220)
5704 || (type == DeviceType.XTERM)) {
5705
5706 if ((collectBuffer.length() == 1)
5707 && (collectBuffer.charAt(0) == '(')) {
5708 // G0 --> NORWEGIAN
5709 currentState.g0Charset = CharacterSet.NRC_NORWEGIAN;
5710 }
5711 if ((collectBuffer.length() == 1)
5712 && (collectBuffer.charAt(0) == ')')) {
5713 // G1 --> NORWEGIAN
5714 currentState.g1Charset = CharacterSet.NRC_NORWEGIAN;
5715 }
5716 if ((collectBuffer.length() == 1)
5717 && (collectBuffer.charAt(0) == '*')) {
5718 // G2 --> NORWEGIAN
5719 currentState.g2Charset = CharacterSet.NRC_NORWEGIAN;
5720 }
5721 if ((collectBuffer.length() == 1)
5722 && (collectBuffer.charAt(0) == '+')) {
5723 // G3 --> NORWEGIAN
5724 currentState.g3Charset = CharacterSet.NRC_NORWEGIAN;
5725 }
5726 }
5727 break;
5728 case 'F':
5729 if ((type == DeviceType.VT220)
5730 || (type == DeviceType.XTERM)) {
5731
5732 if ((collectBuffer.length() == 1)
5733 && (collectBuffer.charAt(0) == ' ')) {
5734 // S7C1T
5735 s8c1t = false;
5736 }
5737 }
5738 break;
5739 case 'G':
5740 if ((type == DeviceType.VT220)
5741 || (type == DeviceType.XTERM)) {
5742
5743 if ((collectBuffer.length() == 1)
5744 && (collectBuffer.charAt(0) == ' ')) {
5745 // S8C1T
5746 s8c1t = true;
5747 }
5748 }
5749 break;
5750 case 'H':
5751 if ((type == DeviceType.VT220)
5752 || (type == DeviceType.XTERM)) {
5753
5754 if ((collectBuffer.length() == 1)
5755 && (collectBuffer.charAt(0) == '(')) {
5756 // G0 --> SWEDISH
5757 currentState.g0Charset = CharacterSet.NRC_SWEDISH;
5758 }
5759 if ((collectBuffer.length() == 1)
5760 && (collectBuffer.charAt(0) == ')')) {
5761 // G1 --> SWEDISH
5762 currentState.g1Charset = CharacterSet.NRC_SWEDISH;
5763 }
5764 if ((collectBuffer.length() == 1)
5765 && (collectBuffer.charAt(0) == '*')) {
5766 // G2 --> SWEDISH
5767 currentState.g2Charset = CharacterSet.NRC_SWEDISH;
5768 }
5769 if ((collectBuffer.length() == 1)
5770 && (collectBuffer.charAt(0) == '+')) {
5771 // G3 --> SWEDISH
5772 currentState.g3Charset = CharacterSet.NRC_SWEDISH;
5773 }
5774 }
5775 break;
5776 case 'I':
5777 case 'J':
5778 break;
5779 case 'K':
5780 if ((type == DeviceType.VT220)
5781 || (type == DeviceType.XTERM)) {
5782
5783 if ((collectBuffer.length() == 1)
5784 && (collectBuffer.charAt(0) == '(')) {
5785 // G0 --> GERMAN
5786 currentState.g0Charset = CharacterSet.NRC_GERMAN;
5787 }
5788 if ((collectBuffer.length() == 1)
5789 && (collectBuffer.charAt(0) == ')')) {
5790 // G1 --> GERMAN
5791 currentState.g1Charset = CharacterSet.NRC_GERMAN;
5792 }
5793 if ((collectBuffer.length() == 1)
5794 && (collectBuffer.charAt(0) == '*')) {
5795 // G2 --> GERMAN
5796 currentState.g2Charset = CharacterSet.NRC_GERMAN;
5797 }
5798 if ((collectBuffer.length() == 1)
5799 && (collectBuffer.charAt(0) == '+')) {
5800 // G3 --> GERMAN
5801 currentState.g3Charset = CharacterSet.NRC_GERMAN;
5802 }
5803 }
5804 break;
5805 case 'L':
5806 case 'M':
5807 case 'N':
5808 case 'O':
5809 case 'P':
5810 break;
5811 case 'Q':
5812 if ((type == DeviceType.VT220)
5813 || (type == DeviceType.XTERM)) {
5814
5815 if ((collectBuffer.length() == 1)
5816 && (collectBuffer.charAt(0) == '(')) {
5817 // G0 --> FRENCH_CA
5818 currentState.g0Charset = CharacterSet.NRC_FRENCH_CA;
5819 }
5820 if ((collectBuffer.length() == 1)
5821 && (collectBuffer.charAt(0) == ')')) {
5822 // G1 --> FRENCH_CA
5823 currentState.g1Charset = CharacterSet.NRC_FRENCH_CA;
5824 }
5825 if ((collectBuffer.length() == 1)
5826 && (collectBuffer.charAt(0) == '*')) {
5827 // G2 --> FRENCH_CA
5828 currentState.g2Charset = CharacterSet.NRC_FRENCH_CA;
5829 }
5830 if ((collectBuffer.length() == 1)
5831 && (collectBuffer.charAt(0) == '+')) {
5832 // G3 --> FRENCH_CA
5833 currentState.g3Charset = CharacterSet.NRC_FRENCH_CA;
5834 }
5835 }
5836 break;
5837 case 'R':
5838 if ((type == DeviceType.VT220)
5839 || (type == DeviceType.XTERM)) {
5840
5841 if ((collectBuffer.length() == 1)
5842 && (collectBuffer.charAt(0) == '(')) {
5843 // G0 --> FRENCH
5844 currentState.g0Charset = CharacterSet.NRC_FRENCH;
5845 }
5846 if ((collectBuffer.length() == 1)
5847 && (collectBuffer.charAt(0) == ')')) {
5848 // G1 --> FRENCH
5849 currentState.g1Charset = CharacterSet.NRC_FRENCH;
5850 }
5851 if ((collectBuffer.length() == 1)
5852 && (collectBuffer.charAt(0) == '*')) {
5853 // G2 --> FRENCH
5854 currentState.g2Charset = CharacterSet.NRC_FRENCH;
5855 }
5856 if ((collectBuffer.length() == 1)
5857 && (collectBuffer.charAt(0) == '+')) {
5858 // G3 --> FRENCH
5859 currentState.g3Charset = CharacterSet.NRC_FRENCH;
5860 }
5861 }
5862 break;
5863 case 'S':
5864 case 'T':
5865 case 'U':
5866 case 'V':
5867 case 'W':
5868 case 'X':
5869 break;
5870 case 'Y':
5871 if ((type == DeviceType.VT220)
5872 || (type == DeviceType.XTERM)) {
5873
5874 if ((collectBuffer.length() == 1)
5875 && (collectBuffer.charAt(0) == '(')) {
5876 // G0 --> ITALIAN
5877 currentState.g0Charset = CharacterSet.NRC_ITALIAN;
5878 }
5879 if ((collectBuffer.length() == 1)
5880 && (collectBuffer.charAt(0) == ')')) {
5881 // G1 --> ITALIAN
5882 currentState.g1Charset = CharacterSet.NRC_ITALIAN;
5883 }
5884 if ((collectBuffer.length() == 1)
5885 && (collectBuffer.charAt(0) == '*')) {
5886 // G2 --> ITALIAN
5887 currentState.g2Charset = CharacterSet.NRC_ITALIAN;
5888 }
5889 if ((collectBuffer.length() == 1)
5890 && (collectBuffer.charAt(0) == '+')) {
5891 // G3 --> ITALIAN
5892 currentState.g3Charset = CharacterSet.NRC_ITALIAN;
5893 }
5894 }
5895 break;
5896 case 'Z':
5897 if ((type == DeviceType.VT220)
5898 || (type == DeviceType.XTERM)) {
5899
5900 if ((collectBuffer.length() == 1)
5901 && (collectBuffer.charAt(0) == '(')) {
5902 // G0 --> SPANISH
5903 currentState.g0Charset = CharacterSet.NRC_SPANISH;
5904 }
5905 if ((collectBuffer.length() == 1)
5906 && (collectBuffer.charAt(0) == ')')) {
5907 // G1 --> SPANISH
5908 currentState.g1Charset = CharacterSet.NRC_SPANISH;
5909 }
5910 if ((collectBuffer.length() == 1)
5911 && (collectBuffer.charAt(0) == '*')) {
5912 // G2 --> SPANISH
5913 currentState.g2Charset = CharacterSet.NRC_SPANISH;
5914 }
5915 if ((collectBuffer.length() == 1)
5916 && (collectBuffer.charAt(0) == '+')) {
5917 // G3 --> SPANISH
5918 currentState.g3Charset = CharacterSet.NRC_SPANISH;
5919 }
5920 }
5921 break;
5922 case '[':
5923 case '\\':
5924 case ']':
5925 case '^':
5926 case '_':
5927 case '`':
5928 case 'a':
5929 case 'b':
5930 case 'c':
5931 case 'd':
5932 case 'e':
5933 case 'f':
5934 case 'g':
5935 case 'h':
5936 case 'i':
5937 case 'j':
5938 case 'k':
5939 case 'l':
5940 case 'm':
5941 case 'n':
5942 case 'o':
5943 case 'p':
5944 case 'q':
5945 case 'r':
5946 case 's':
5947 case 't':
5948 case 'u':
5949 case 'v':
5950 case 'w':
5951 case 'x':
5952 case 'y':
5953 case 'z':
5954 case '{':
5955 case '|':
5956 case '}':
5957 case '~':
5958 break;
5959 }
5960 toGround();
5961 }
5962
5963 // 7F --> ignore
5964
5965 // 0x9C goes to GROUND
5966 if (ch == 0x9C) {
5967 toGround();
5968 }
5969
5970 return;
5971
5972 case CSI_ENTRY:
5973 // 00-17, 19, 1C-1F --> execute
5974 if (ch <= 0x1F) {
5975 handleControlChar((char) ch);
5976 }
5977
5978 // 20-2F --> collect, then switch to CSI_INTERMEDIATE
5979 if ((ch >= 0x20) && (ch <= 0x2F)) {
5980 collect((char) ch);
5981 scanState = ScanState.CSI_INTERMEDIATE;
5982 }
5983
5984 // 30-39, 3B --> param, then switch to CSI_PARAM
5985 if ((ch >= '0') && (ch <= '9')) {
5986 param((byte) ch);
5987 scanState = ScanState.CSI_PARAM;
5988 }
5989 if (ch == ';') {
5990 param((byte) ch);
5991 scanState = ScanState.CSI_PARAM;
5992 }
5993
5994 // 3C-3F --> collect, then switch to CSI_PARAM
5995 if ((ch >= 0x3C) && (ch <= 0x3F)) {
5996 collect((char) ch);
5997 scanState = ScanState.CSI_PARAM;
5998 }
5999
6000 // 40-7E --> dispatch, then switch to GROUND
6001 if ((ch >= 0x40) && (ch <= 0x7E)) {
6002 switch (ch) {
6003 case '@':
6004 // ICH - Insert character
6005 ich();
6006 break;
6007 case 'A':
6008 // CUU - Cursor up
6009 cuu();
6010 break;
6011 case 'B':
6012 // CUD - Cursor down
6013 cud();
6014 break;
6015 case 'C':
6016 // CUF - Cursor forward
6017 cuf();
6018 break;
6019 case 'D':
6020 // CUB - Cursor backward
6021 cub();
6022 break;
6023 case 'E':
6024 // CNL - Cursor down and to column 1
6025 if (type == DeviceType.XTERM) {
6026 cnl();
6027 }
6028 break;
6029 case 'F':
6030 // CPL - Cursor up and to column 1
6031 if (type == DeviceType.XTERM) {
6032 cpl();
6033 }
6034 break;
6035 case 'G':
6036 // CHA - Cursor to column # in current row
6037 if (type == DeviceType.XTERM) {
6038 cha();
6039 }
6040 break;
6041 case 'H':
6042 // CUP - Cursor position
6043 cup();
6044 break;
6045 case 'I':
6046 // CHT - Cursor forward X tab stops (default 1)
6047 if (type == DeviceType.XTERM) {
6048 cht();
6049 }
6050 break;
6051 case 'J':
6052 // ED - Erase in display
6053 ed();
6054 break;
6055 case 'K':
6056 // EL - Erase in line
6057 el();
6058 break;
6059 case 'L':
6060 // IL - Insert line
6061 il();
6062 break;
6063 case 'M':
6064 // DL - Delete line
6065 dl();
6066 break;
6067 case 'N':
6068 case 'O':
6069 break;
6070 case 'P':
6071 // DCH - Delete character
6072 dch();
6073 break;
6074 case 'Q':
6075 case 'R':
6076 break;
6077 case 'S':
6078 // Scroll up X lines (default 1)
6079 if (type == DeviceType.XTERM) {
6080 boolean xtermPrivateModeFlag = false;
6081 for (int i = 0; i < collectBuffer.length(); i++) {
6082 if (collectBuffer.charAt(i) == '?') {
6083 xtermPrivateModeFlag = true;
6084 break;
6085 }
6086 }
6087 if (xtermPrivateModeFlag) {
6088 xtermSixelQuery();
6089 } else {
6090 su();
6091 }
6092 }
6093 break;
6094 case 'T':
6095 // Scroll down X lines (default 1)
6096 if (type == DeviceType.XTERM) {
6097 sd();
6098 }
6099 break;
6100 case 'U':
6101 case 'V':
6102 case 'W':
6103 break;
6104 case 'X':
6105 if ((type == DeviceType.VT220)
6106 || (type == DeviceType.XTERM)) {
6107
6108 // ECH - Erase character
6109 ech();
6110 }
6111 break;
6112 case 'Y':
6113 break;
6114 case 'Z':
6115 // CBT - Cursor backward X tab stops (default 1)
6116 if (type == DeviceType.XTERM) {
6117 cbt();
6118 }
6119 break;
6120 case '[':
6121 case '\\':
6122 case ']':
6123 case '^':
6124 case '_':
6125 break;
6126 case '`':
6127 // HPA - Cursor to column # in current row. Same as CHA
6128 if (type == DeviceType.XTERM) {
6129 cha();
6130 }
6131 break;
6132 case 'a':
6133 // HPR - Cursor right. Same as CUF
6134 if (type == DeviceType.XTERM) {
6135 cuf();
6136 }
6137 break;
6138 case 'b':
6139 // REP - Repeat last char X times
6140 if (type == DeviceType.XTERM) {
6141 rep();
6142 }
6143 break;
6144 case 'c':
6145 // DA - Device attributes
6146 da();
6147 break;
6148 case 'd':
6149 // VPA - Cursor to row, current column.
6150 if (type == DeviceType.XTERM) {
6151 vpa();
6152 }
6153 break;
6154 case 'e':
6155 // VPR - Cursor down. Same as CUD
6156 if (type == DeviceType.XTERM) {
6157 cud();
6158 }
6159 break;
6160 case 'f':
6161 // HVP - Horizontal and vertical position
6162 hvp();
6163 break;
6164 case 'g':
6165 // TBC - Tabulation clear
6166 tbc();
6167 break;
6168 case 'h':
6169 // Sets an ANSI or DEC private toggle
6170 setToggle(true);
6171 break;
6172 case 'i':
6173 if ((type == DeviceType.VT220)
6174 || (type == DeviceType.XTERM)) {
6175
6176 // Printer functions
6177 printerFunctions();
6178 }
6179 break;
6180 case 'j':
6181 case 'k':
6182 break;
6183 case 'l':
6184 // Sets an ANSI or DEC private toggle
6185 setToggle(false);
6186 break;
6187 case 'm':
6188 // SGR - Select graphics rendition
6189 sgr();
6190 break;
6191 case 'n':
6192 // DSR - Device status report
6193 dsr();
6194 break;
6195 case 'o':
6196 case 'p':
6197 break;
6198 case 'q':
6199 // DECLL - Load leds
6200 // Not supported
6201 break;
6202 case 'r':
6203 // DECSTBM - Set top and bottom margins
6204 decstbm();
6205 break;
6206 case 's':
6207 // Save cursor (ANSI.SYS)
6208 if (type == DeviceType.XTERM) {
6209 savedState.cursorX = currentState.cursorX;
6210 savedState.cursorY = currentState.cursorY;
6211 }
6212 break;
6213 case 't':
6214 if (type == DeviceType.XTERM) {
6215 // Window operations
6216 xtermWindowOps();
6217 }
6218 break;
6219 case 'u':
6220 // Restore cursor (ANSI.SYS)
6221 if (type == DeviceType.XTERM) {
6222 cursorPosition(savedState.cursorY, savedState.cursorX);
6223 }
6224 break;
6225 case 'v':
6226 case 'w':
6227 break;
6228 case 'x':
6229 // DECREQTPARM - Request terminal parameters
6230 decreqtparm();
6231 break;
6232 case 'y':
6233 case 'z':
6234 case '{':
6235 case '|':
6236 case '}':
6237 case '~':
6238 break;
6239 }
6240 toGround();
6241 }
6242
6243 // 7F --> ignore
6244
6245 // 0x9C goes to GROUND
6246 if (ch == 0x9C) {
6247 toGround();
6248 }
6249
6250 // 0x3A goes to CSI_IGNORE
6251 if (ch == 0x3A) {
6252 scanState = ScanState.CSI_IGNORE;
6253 }
6254 return;
6255
6256 case CSI_PARAM:
6257 // 00-17, 19, 1C-1F --> execute
6258 if (ch <= 0x1F) {
6259 handleControlChar((char) ch);
6260 }
6261
6262 // 20-2F --> collect, then switch to CSI_INTERMEDIATE
6263 if ((ch >= 0x20) && (ch <= 0x2F)) {
6264 collect((char) ch);
6265 scanState = ScanState.CSI_INTERMEDIATE;
6266 }
6267
6268 // 30-39, 3B --> param
6269 if ((ch >= '0') && (ch <= '9')) {
6270 param((byte) ch);
6271 }
6272 if (ch == ';') {
6273 param((byte) ch);
6274 }
6275
6276 // 0x3A goes to CSI_IGNORE
6277 if (ch == 0x3A) {
6278 scanState = ScanState.CSI_IGNORE;
6279 }
6280 // 0x3C-3F goes to CSI_IGNORE
6281 if ((ch >= 0x3C) && (ch <= 0x3F)) {
6282 scanState = ScanState.CSI_IGNORE;
6283 }
6284
6285 // 40-7E --> dispatch, then switch to GROUND
6286 if ((ch >= 0x40) && (ch <= 0x7E)) {
6287 switch (ch) {
6288 case '@':
6289 // ICH - Insert character
6290 ich();
6291 break;
6292 case 'A':
6293 // CUU - Cursor up
6294 cuu();
6295 break;
6296 case 'B':
6297 // CUD - Cursor down
6298 cud();
6299 break;
6300 case 'C':
6301 // CUF - Cursor forward
6302 cuf();
6303 break;
6304 case 'D':
6305 // CUB - Cursor backward
6306 cub();
6307 break;
6308 case 'E':
6309 // CNL - Cursor down and to column 1
6310 if (type == DeviceType.XTERM) {
6311 cnl();
6312 }
6313 break;
6314 case 'F':
6315 // CPL - Cursor up and to column 1
6316 if (type == DeviceType.XTERM) {
6317 cpl();
6318 }
6319 break;
6320 case 'G':
6321 // CHA - Cursor to column # in current row
6322 if (type == DeviceType.XTERM) {
6323 cha();
6324 }
6325 break;
6326 case 'H':
6327 // CUP - Cursor position
6328 cup();
6329 break;
6330 case 'I':
6331 // CHT - Cursor forward X tab stops (default 1)
6332 if (type == DeviceType.XTERM) {
6333 cht();
6334 }
6335 break;
6336 case 'J':
6337 // ED - Erase in display
6338 ed();
6339 break;
6340 case 'K':
6341 // EL - Erase in line
6342 el();
6343 break;
6344 case 'L':
6345 // IL - Insert line
6346 il();
6347 break;
6348 case 'M':
6349 // DL - Delete line
6350 dl();
6351 break;
6352 case 'N':
6353 case 'O':
6354 break;
6355 case 'P':
6356 // DCH - Delete character
6357 dch();
6358 break;
6359 case 'Q':
6360 case 'R':
6361 break;
6362 case 'S':
6363 // Scroll up X lines (default 1)
6364 if (type == DeviceType.XTERM) {
6365 boolean xtermPrivateModeFlag = false;
6366 for (int i = 0; i < collectBuffer.length(); i++) {
6367 if (collectBuffer.charAt(i) == '?') {
6368 xtermPrivateModeFlag = true;
6369 break;
6370 }
6371 }
6372 if (xtermPrivateModeFlag) {
6373 xtermSixelQuery();
6374 } else {
6375 su();
6376 }
6377 }
6378 break;
6379 case 'T':
6380 // Scroll down X lines (default 1)
6381 if (type == DeviceType.XTERM) {
6382 sd();
6383 }
6384 break;
6385 case 'U':
6386 case 'V':
6387 case 'W':
6388 break;
6389 case 'X':
6390 if ((type == DeviceType.VT220)
6391 || (type == DeviceType.XTERM)) {
6392
6393 // ECH - Erase character
6394 ech();
6395 }
6396 break;
6397 case 'Y':
6398 break;
6399 case 'Z':
6400 // CBT - Cursor backward X tab stops (default 1)
6401 if (type == DeviceType.XTERM) {
6402 cbt();
6403 }
6404 break;
6405 case '[':
6406 case '\\':
6407 case ']':
6408 case '^':
6409 case '_':
6410 break;
6411 case '`':
6412 // HPA - Cursor to column # in current row. Same as CHA
6413 if (type == DeviceType.XTERM) {
6414 cha();
6415 }
6416 break;
6417 case 'a':
6418 // HPR - Cursor right. Same as CUF
6419 if (type == DeviceType.XTERM) {
6420 cuf();
6421 }
6422 break;
6423 case 'b':
6424 // REP - Repeat last char X times
6425 if (type == DeviceType.XTERM) {
6426 rep();
6427 }
6428 break;
6429 case 'c':
6430 // DA - Device attributes
6431 da();
6432 break;
6433 case 'd':
6434 // VPA - Cursor to row, current column.
6435 if (type == DeviceType.XTERM) {
6436 vpa();
6437 }
6438 break;
6439 case 'e':
6440 // VPR - Cursor down. Same as CUD
6441 if (type == DeviceType.XTERM) {
6442 cud();
6443 }
6444 break;
6445 case 'f':
6446 // HVP - Horizontal and vertical position
6447 hvp();
6448 break;
6449 case 'g':
6450 // TBC - Tabulation clear
6451 tbc();
6452 break;
6453 case 'h':
6454 // Sets an ANSI or DEC private toggle
6455 setToggle(true);
6456 break;
6457 case 'i':
6458 if ((type == DeviceType.VT220)
6459 || (type == DeviceType.XTERM)) {
6460
6461 // Printer functions
6462 printerFunctions();
6463 }
6464 break;
6465 case 'j':
6466 case 'k':
6467 break;
6468 case 'l':
6469 // Sets an ANSI or DEC private toggle
6470 setToggle(false);
6471 break;
6472 case 'm':
6473 // SGR - Select graphics rendition
6474 sgr();
6475 break;
6476 case 'n':
6477 // DSR - Device status report
6478 dsr();
6479 break;
6480 case 'o':
6481 case 'p':
6482 break;
6483 case 'q':
6484 // DECLL - Load leds
6485 // Not supported
6486 break;
6487 case 'r':
6488 // DECSTBM - Set top and bottom margins
6489 decstbm();
6490 break;
6491 case 's':
6492 break;
6493 case 't':
6494 if (type == DeviceType.XTERM) {
6495 // Window operations
6496 xtermWindowOps();
6497 }
6498 break;
6499 case 'u':
6500 case 'v':
6501 case 'w':
6502 break;
6503 case 'x':
6504 // DECREQTPARM - Request terminal parameters
6505 decreqtparm();
6506 break;
6507 case 'y':
6508 case 'z':
6509 case '{':
6510 case '|':
6511 case '}':
6512 case '~':
6513 break;
6514 }
6515 toGround();
6516 }
6517
6518 // 7F --> ignore
6519 return;
6520
6521 case CSI_INTERMEDIATE:
6522 // 00-17, 19, 1C-1F --> execute
6523 if (ch <= 0x1F) {
6524 handleControlChar((char) ch);
6525 }
6526
6527 // 20-2F --> collect
6528 if ((ch >= 0x20) && (ch <= 0x2F)) {
6529 collect((char) ch);
6530 }
6531
6532 // 0x30-3F goes to CSI_IGNORE
6533 if ((ch >= 0x30) && (ch <= 0x3F)) {
6534 scanState = ScanState.CSI_IGNORE;
6535 }
6536
6537 // 40-7E --> dispatch, then switch to GROUND
6538 if ((ch >= 0x40) && (ch <= 0x7E)) {
6539 switch (ch) {
6540 case '@':
6541 case 'A':
6542 case 'B':
6543 case 'C':
6544 case 'D':
6545 case 'E':
6546 case 'F':
6547 case 'G':
6548 case 'H':
6549 case 'I':
6550 case 'J':
6551 case 'K':
6552 case 'L':
6553 case 'M':
6554 case 'N':
6555 case 'O':
6556 case 'P':
6557 case 'Q':
6558 case 'R':
6559 case 'S':
6560 case 'T':
6561 case 'U':
6562 case 'V':
6563 case 'W':
6564 case 'X':
6565 case 'Y':
6566 case 'Z':
6567 case '[':
6568 case '\\':
6569 case ']':
6570 case '^':
6571 case '_':
6572 case '`':
6573 case 'a':
6574 case 'b':
6575 case 'c':
6576 case 'd':
6577 case 'e':
6578 case 'f':
6579 case 'g':
6580 case 'h':
6581 case 'i':
6582 case 'j':
6583 case 'k':
6584 case 'l':
6585 case 'm':
6586 case 'n':
6587 case 'o':
6588 break;
6589 case 'p':
6590 if (((type == DeviceType.VT220)
6591 || (type == DeviceType.XTERM))
6592 && (collectBuffer.charAt(collectBuffer.length() - 1) == '\"')
6593 ) {
6594 // DECSCL - compatibility level
6595 decscl();
6596 }
6597 if ((type == DeviceType.XTERM)
6598 && (collectBuffer.charAt(collectBuffer.length() - 1) == '!')
6599 ) {
6600 // DECSTR - Soft terminal reset
6601 decstr();
6602 }
6603 break;
6604 case 'q':
6605 if (((type == DeviceType.VT220)
6606 || (type == DeviceType.XTERM))
6607 && (collectBuffer.charAt(collectBuffer.length() - 1) == '\"')
6608 ) {
6609 // DECSCA
6610 decsca();
6611 }
6612 break;
6613 case 'r':
6614 case 's':
6615 case 't':
6616 case 'u':
6617 case 'v':
6618 case 'w':
6619 case 'x':
6620 case 'y':
6621 case 'z':
6622 case '{':
6623 case '|':
6624 case '}':
6625 case '~':
6626 break;
6627 }
6628 toGround();
6629 }
6630
6631 // 7F --> ignore
6632 return;
6633
6634 case CSI_IGNORE:
6635 // 00-17, 19, 1C-1F --> execute
6636 if (ch <= 0x1F) {
6637 handleControlChar((char) ch);
6638 }
6639
6640 // 20-2F --> collect
6641 if ((ch >= 0x20) && (ch <= 0x2F)) {
6642 collect((char) ch);
6643 }
6644
6645 // 40-7E --> ignore, then switch to GROUND
6646 if ((ch >= 0x40) && (ch <= 0x7E)) {
6647 toGround();
6648 }
6649
6650 // 20-3F, 7F --> ignore
6651
6652 return;
6653
6654 case DCS_ENTRY:
6655
6656 // 0x9C goes to GROUND
6657 if (ch == 0x9C) {
6658 toGround();
6659 }
6660
6661 // 0x1B 0x5C goes to GROUND
6662 if (ch == 0x1B) {
6663 collect((char) ch);
6664 }
6665 if (ch == 0x5C) {
6666 if ((collectBuffer.length() > 0)
6667 && (collectBuffer.charAt(collectBuffer.length() - 1) == 0x1B)
6668 ) {
6669 toGround();
6670 }
6671 }
6672
6673 // 20-2F --> collect, then switch to DCS_INTERMEDIATE
6674 if ((ch >= 0x20) && (ch <= 0x2F)) {
6675 collect((char) ch);
6676 scanState = ScanState.DCS_INTERMEDIATE;
6677 }
6678
6679 // 30-39, 3B --> param, then switch to DCS_PARAM
6680 if ((ch >= '0') && (ch <= '9')) {
6681 param((byte) ch);
6682 scanState = ScanState.DCS_PARAM;
6683 }
6684 if (ch == ';') {
6685 param((byte) ch);
6686 scanState = ScanState.DCS_PARAM;
6687 }
6688
6689 // 3C-3F --> collect, then switch to DCS_PARAM
6690 if ((ch >= 0x3C) && (ch <= 0x3F)) {
6691 collect((char) ch);
6692 scanState = ScanState.DCS_PARAM;
6693 }
6694
6695 // 00-17, 19, 1C-1F, 7F --> ignore
6696
6697 // 0x3A goes to DCS_IGNORE
6698 if (ch == 0x3F) {
6699 scanState = ScanState.DCS_IGNORE;
6700 }
6701
6702 // 0x71 goes to DCS_SIXEL
6703 if (ch == 0x71) {
6704 sixelParseBuffer = new StringBuilder();
6705 scanState = ScanState.DCS_SIXEL;
6706 } else if ((ch >= 0x40) && (ch <= 0x7E)) {
6707 // 0x40-7E goes to DCS_PASSTHROUGH
6708 scanState = ScanState.DCS_PASSTHROUGH;
6709 }
6710 return;
6711
6712 case DCS_INTERMEDIATE:
6713
6714 // 0x9C goes to GROUND
6715 if (ch == 0x9C) {
6716 toGround();
6717 }
6718
6719 // 0x1B 0x5C goes to GROUND
6720 if (ch == 0x1B) {
6721 collect((char) ch);
6722 }
6723 if (ch == 0x5C) {
6724 if ((collectBuffer.length() > 0)
6725 && (collectBuffer.charAt(collectBuffer.length() - 1) == 0x1B)
6726 ) {
6727 toGround();
6728 }
6729 }
6730
6731 // 0x30-3F goes to DCS_IGNORE
6732 if ((ch >= 0x30) && (ch <= 0x3F)) {
6733 scanState = ScanState.DCS_IGNORE;
6734 }
6735
6736 // 0x40-7E goes to DCS_PASSTHROUGH
6737 if ((ch >= 0x40) && (ch <= 0x7E)) {
6738 scanState = ScanState.DCS_PASSTHROUGH;
6739 }
6740
6741 // 00-17, 19, 1C-1F, 7F --> ignore
6742 return;
6743
6744 case DCS_PARAM:
6745
6746 // 0x9C goes to GROUND
6747 if (ch == 0x9C) {
6748 toGround();
6749 }
6750
6751 // 0x1B 0x5C goes to GROUND
6752 if (ch == 0x1B) {
6753 collect((char) ch);
6754 }
6755 if (ch == 0x5C) {
6756 if ((collectBuffer.length() > 0)
6757 && (collectBuffer.charAt(collectBuffer.length() - 1) == 0x1B)
6758 ) {
6759 toGround();
6760 }
6761 }
6762
6763 // 20-2F --> collect, then switch to DCS_INTERMEDIATE
6764 if ((ch >= 0x20) && (ch <= 0x2F)) {
6765 collect((char) ch);
6766 scanState = ScanState.DCS_INTERMEDIATE;
6767 }
6768
6769 // 30-39, 3B --> param
6770 if ((ch >= '0') && (ch <= '9')) {
6771 param((byte) ch);
6772 }
6773 if (ch == ';') {
6774 param((byte) ch);
6775 }
6776
6777 // 00-17, 19, 1C-1F, 7F --> ignore
6778
6779 // 0x3A, 3C-3F goes to DCS_IGNORE
6780 if (ch == 0x3F) {
6781 scanState = ScanState.DCS_IGNORE;
6782 }
6783 if ((ch >= 0x3C) && (ch <= 0x3F)) {
6784 scanState = ScanState.DCS_IGNORE;
6785 }
6786
6787 // 0x71 goes to DCS_SIXEL
6788 if (ch == 0x71) {
6789 sixelParseBuffer = new StringBuilder();
6790 scanState = ScanState.DCS_SIXEL;
6791 } else if ((ch >= 0x40) && (ch <= 0x7E)) {
6792 // 0x40-7E goes to DCS_PASSTHROUGH
6793 scanState = ScanState.DCS_PASSTHROUGH;
6794 }
6795 return;
6796
6797 case DCS_PASSTHROUGH:
6798 // 0x9C goes to GROUND
6799 if (ch == 0x9C) {
6800 toGround();
6801 }
6802
6803 // 0x1B 0x5C goes to GROUND
6804 if (ch == 0x1B) {
6805 collect((char) ch);
6806 }
6807 if (ch == 0x5C) {
6808 if ((collectBuffer.length() > 0)
6809 && (collectBuffer.charAt(collectBuffer.length() - 1) == 0x1B)
6810 ) {
6811 toGround();
6812 }
6813 }
6814
6815 // 00-17, 19, 1C-1F, 20-7E --> put
6816 if (ch <= 0x17) {
6817 // We ignore all DCS except sixel.
6818 return;
6819 }
6820 if (ch == 0x19) {
6821 // We ignore all DCS except sixel.
6822 return;
6823 }
6824 if ((ch >= 0x1C) && (ch <= 0x1F)) {
6825 // We ignore all DCS except sixel.
6826 return;
6827 }
6828 if ((ch >= 0x20) && (ch <= 0x7E)) {
6829 // We ignore all DCS except sixel.
6830 return;
6831 }
6832
6833 // 7F --> ignore
6834
6835 return;
6836
6837 case DCS_IGNORE:
6838 // 00-17, 19, 1C-1F, 20-7F --> ignore
6839
6840 // 0x9C goes to GROUND
6841 if (ch == 0x9C) {
6842 toGround();
6843 }
6844
6845 return;
6846
6847 case DCS_SIXEL:
6848 // 0x9C goes to GROUND
6849 if (ch == 0x9C) {
6850 parseSixel();
6851 toGround();
6852 return;
6853 }
6854
6855 // 0x1B 0x5C goes to GROUND
6856 if (ch == 0x1B) {
6857 collect((char) ch);
6858 return;
6859 }
6860 if (ch == 0x5C) {
6861 if ((collectBuffer.length() > 0)
6862 && (collectBuffer.charAt(collectBuffer.length() - 1) == 0x1B)
6863 ) {
6864 parseSixel();
6865 toGround();
6866 return;
6867 }
6868 }
6869
6870 // 00-17, 19, 1C-1F, 20-7E --> put
6871 if ((ch <= 0x17)
6872 || (ch == 0x19)
6873 || ((ch >= 0x1C) && (ch <= 0x1F))
6874 || ((ch >= 0x20) && (ch <= 0x7E))
6875 ) {
6876 sixelParseBuffer.append((char) ch);
6877 }
6878
6879 // 7F --> ignore
6880 return;
6881
6882 case SOSPMAPC_STRING:
6883 // 00-17, 19, 1C-1F, 20-7F --> ignore
6884
6885 // Special case for Jexer: PM can pass one control character
6886 if (ch == 0x1B) {
6887 pmPut((char) ch);
6888 }
6889
6890 if ((ch >= 0x20) && (ch <= 0x7F)) {
6891 pmPut((char) ch);
6892 }
6893
6894 // 0x9C goes to GROUND
6895 if (ch == 0x9C) {
6896 toGround();
6897 }
6898
6899 return;
6900
6901 case OSC_STRING:
6902 // Special case for Xterm: OSC can pass control characters
6903 if ((ch == 0x9C) || (ch == 0x07) || (ch == 0x1B)) {
6904 oscPut((char) ch);
6905 }
6906
6907 // 00-17, 19, 1C-1F --> ignore
6908
6909 // 20-7F --> osc_put
6910 if ((ch >= 0x20) && (ch <= 0x7F)) {
6911 oscPut((char) ch);
6912 }
6913
6914 // 0x9C goes to GROUND
6915 if (ch == 0x9C) {
6916 toGround();
6917 }
6918
6919 return;
6920
6921 case VT52_DIRECT_CURSOR_ADDRESS:
6922 // This is a special case for the VT52 sequence "ESC Y l c"
6923 if (collectBuffer.length() == 0) {
6924 collect((char) ch);
6925 } else if (collectBuffer.length() == 1) {
6926 // We've got the two characters, one in the buffer and the
6927 // other in ch.
6928 cursorPosition(collectBuffer.charAt(0) - '\040', ch - '\040');
6929 toGround();
6930 }
6931 return;
6932 }
6933
6934 }
6935
6936 /**
6937 * Expose current cursor X to outside world.
6938 *
6939 * @return current cursor X
6940 */
6941 public final int getCursorX() {
6942 if (display.get(currentState.cursorY).isDoubleWidth()) {
6943 return currentState.cursorX * 2;
6944 }
6945 return currentState.cursorX;
6946 }
6947
6948 /**
6949 * Expose current cursor Y to outside world.
6950 *
6951 * @return current cursor Y
6952 */
6953 public final int getCursorY() {
6954 return currentState.cursorY;
6955 }
6956
6957 /**
6958 * Returns true if this terminal has requested the mouse pointer be
6959 * hidden.
6960 *
6961 * @return true if this terminal has requested the mouse pointer be
6962 * hidden
6963 */
6964 public final boolean hasHiddenMousePointer() {
6965 return hideMousePointer;
6966 }
6967
6968 /**
6969 * Get the mouse protocol.
6970 *
6971 * @return MouseProtocol.OFF, MouseProtocol.X10, etc.
6972 */
6973 public MouseProtocol getMouseProtocol() {
6974 return mouseProtocol;
6975 }
6976
6977 /**
6978 * Draw the left and right cells of a two-cell-wide (full-width) glyph.
6979 *
6980 * @param leftX the x position to draw the left half to
6981 * @param leftY the y position to draw the left half to
6982 * @param rightX the x position to draw the right half to
6983 * @param rightY the y position to draw the right half to
6984 * @param ch the character to draw
6985 */
6986 private void drawHalves(final int leftX, final int leftY,
6987 final int rightX, final int rightY, final int ch) {
6988
6989 // System.err.println("drawHalves(): " + Integer.toHexString(ch));
6990
6991 if (lastTextHeight != textHeight) {
6992 glyphMaker = GlyphMaker.getInstance(textHeight);
6993 lastTextHeight = textHeight;
6994 }
6995
6996 Cell cell = new Cell(ch, currentState.attr);
6997 BufferedImage image = glyphMaker.getImage(cell, textWidth * 2,
6998 textHeight);
6999 BufferedImage leftImage = image.getSubimage(0, 0, textWidth,
7000 textHeight);
7001 BufferedImage rightImage = image.getSubimage(textWidth, 0, textWidth,
7002 textHeight);
7003
7004 Cell left = new Cell(cell);
7005 left.setImage(leftImage);
7006 left.setWidth(Cell.Width.LEFT);
7007 display.get(leftY).replace(leftX, left);
7008
7009 Cell right = new Cell(cell);
7010 right.setImage(rightImage);
7011 right.setWidth(Cell.Width.RIGHT);
7012 display.get(rightY).replace(rightX, right);
7013 }
7014
7015 /**
7016 * Set the width of a character cell in pixels.
7017 *
7018 * @param textWidth the width in pixels of a character cell
7019 */
7020 public void setTextWidth(final int textWidth) {
7021 this.textWidth = textWidth;
7022 }
7023
7024 /**
7025 * Set the height of a character cell in pixels.
7026 *
7027 * @param textHeight the height in pixels of a character cell
7028 */
7029 public void setTextHeight(final int textHeight) {
7030 this.textHeight = textHeight;
7031 }
7032
7033 /**
7034 * Parse a sixel string into a bitmap image, and overlay that image onto
7035 * the text cells.
7036 */
7037 private void parseSixel() {
7038
7039 /*
7040 System.err.println("parseSixel(): '" + sixelParseBuffer.toString()
7041 + "'");
7042 */
7043
7044 Sixel sixel = new Sixel(sixelParseBuffer.toString(), sixelPalette);
7045 BufferedImage image = sixel.getImage();
7046
7047 // System.err.println("parseSixel(): image " + image);
7048
7049 if (image == null) {
7050 // Sixel data was malformed in some way, bail out.
7051 return;
7052 }
7053
7054 /*
7055 * Procedure:
7056 *
7057 * Break up the image into text cell sized pieces as a new array of
7058 * Cells.
7059 *
7060 * Note original column position x0.
7061 *
7062 * For each cell:
7063 *
7064 * 1. Advance (printCharacter(' ')) for horizontal increment, or
7065 * index (linefeed() + cursorPosition(y, x0)) for vertical
7066 * increment.
7067 *
7068 * 2. Set (x, y) cell image data.
7069 *
7070 * 3. For the right and bottom edges:
7071 *
7072 * a. Render the text to pixels using Terminus font.
7073 *
7074 * b. Blit the image on top of the text, using alpha channel.
7075 */
7076 int cellColumns = image.getWidth() / textWidth;
7077 if (cellColumns * textWidth < image.getWidth()) {
7078 cellColumns++;
7079 }
7080 int cellRows = image.getHeight() / textHeight;
7081 if (cellRows * textHeight < image.getHeight()) {
7082 cellRows++;
7083 }
7084
7085 // Break the image up into an array of cells.
7086 Cell [][] cells = new Cell[cellColumns][cellRows];
7087
7088 for (int x = 0; x < cellColumns; x++) {
7089 for (int y = 0; y < cellRows; y++) {
7090
7091 int width = textWidth;
7092 if ((x + 1) * textWidth > image.getWidth()) {
7093 width = image.getWidth() - (x * textWidth);
7094 }
7095 int height = textHeight;
7096 if ((y + 1) * textHeight > image.getHeight()) {
7097 height = image.getHeight() - (y * textHeight);
7098 }
7099
7100 Cell cell = new Cell();
7101 cell.setImage(image.getSubimage(x * textWidth,
7102 y * textHeight, width, height));
7103
7104 cells[x][y] = cell;
7105 }
7106 }
7107
7108 int x0 = currentState.cursorX;
7109 for (int y = 0; y < cellRows; y++) {
7110 for (int x = 0; x < cellColumns; x++) {
7111 assert (currentState.cursorX <= rightMargin);
7112
7113 // TODO: Render text of current cell first, then image over
7114 // it (accounting for blank pixels). For now, just copy the
7115 // cell.
7116 DisplayLine line = display.get(currentState.cursorY);
7117 line.replace(currentState.cursorX, cells[x][y]);
7118
7119 // If at the end of the visible screen, stop.
7120 if (currentState.cursorX == rightMargin) {
7121 break;
7122 }
7123 // Room for more image on the visible screen.
7124 currentState.cursorX++;
7125 }
7126 linefeed();
7127 cursorPosition(currentState.cursorY, x0);
7128 }
7129
7130 }
7131
7132 /**
7133 * Parse a "Jexer" image string into a bitmap image, and overlay that
7134 * image onto the text cells.
7135 *
7136 * @param pw width token
7137 * @param ph height token
7138 * @param ps scroll token
7139 * @param data pixel data
7140 */
7141 private void parseJexerImage(final String pw, final String ph,
7142 final String ps, final String data) {
7143
7144 int imageWidth = 0;
7145 int imageHeight = 0;
7146 boolean scroll = false;
7147 try {
7148 imageWidth = Integer.parseInt(pw);
7149 imageHeight = Integer.parseInt(ph);
7150 } catch (NumberFormatException e) {
7151 // SQUASH
7152 return;
7153 }
7154 if ((imageWidth < 1)
7155 || (imageWidth > 10000)
7156 || (imageHeight < 1)
7157 || (imageHeight > 10000)
7158 ) {
7159 return;
7160 }
7161 if (ps.equals("1")) {
7162 scroll = true;
7163 } else if (ps.equals("0")) {
7164 scroll = false;
7165 } else {
7166 return;
7167 }
7168
7169 java.util.Base64.Decoder base64 = java.util.Base64.getDecoder();
7170 byte [] bytes = base64.decode(data);
7171 if (bytes.length != (imageWidth * imageHeight * 3)) {
7172 return;
7173 }
7174
7175 BufferedImage image = new BufferedImage(imageWidth, imageHeight,
7176 BufferedImage.TYPE_INT_ARGB);
7177
7178 for (int x = 0; x < imageWidth; x++) {
7179 for (int y = 0; y < imageHeight; y++) {
7180 int red = bytes[(y * imageWidth * 3) + (x * 3) ];
7181 if (red < 0) {
7182 red += 256;
7183 }
7184 int green = bytes[(y * imageWidth * 3) + (x * 3) + 1];
7185 if (green < 0) {
7186 green += 256;
7187 }
7188 int blue = bytes[(y * imageWidth * 3) + (x * 3) + 2];
7189 if (blue < 0) {
7190 blue += 256;
7191 }
7192 int rgb = 0xFF000000 | (red << 16) | (green << 8) | blue;
7193 image.setRGB(x, y, rgb);
7194 }
7195 }
7196
7197 /*
7198 * Procedure:
7199 *
7200 * Break up the image into text cell sized pieces as a new array of
7201 * Cells.
7202 *
7203 * Note original column position x0.
7204 *
7205 * For each cell:
7206 *
7207 * 1. Advance (printCharacter(' ')) for horizontal increment, or
7208 * index (linefeed() + cursorPosition(y, x0)) for vertical
7209 * increment.
7210 *
7211 * 2. Set (x, y) cell image data.
7212 *
7213 * 3. For the right and bottom edges:
7214 *
7215 * a. Render the text to pixels using Terminus font.
7216 *
7217 * b. Blit the image on top of the text, using alpha channel.
7218 */
7219 int cellColumns = image.getWidth() / textWidth;
7220 if (cellColumns * textWidth < image.getWidth()) {
7221 cellColumns++;
7222 }
7223 int cellRows = image.getHeight() / textHeight;
7224 if (cellRows * textHeight < image.getHeight()) {
7225 cellRows++;
7226 }
7227
7228 // Break the image up into an array of cells.
7229 Cell [][] cells = new Cell[cellColumns][cellRows];
7230
7231 for (int x = 0; x < cellColumns; x++) {
7232 for (int y = 0; y < cellRows; y++) {
7233
7234 int width = textWidth;
7235 if ((x + 1) * textWidth > image.getWidth()) {
7236 width = image.getWidth() - (x * textWidth);
7237 }
7238 int height = textHeight;
7239 if ((y + 1) * textHeight > image.getHeight()) {
7240 height = image.getHeight() - (y * textHeight);
7241 }
7242
7243 Cell cell = new Cell();
7244 cell.setImage(image.getSubimage(x * textWidth,
7245 y * textHeight, width, height));
7246
7247 cells[x][y] = cell;
7248 }
7249 }
7250
7251 int x0 = currentState.cursorX;
7252 for (int y = 0; y < cellRows; y++) {
7253 for (int x = 0; x < cellColumns; x++) {
7254 assert (currentState.cursorX <= rightMargin);
7255 DisplayLine line = display.get(currentState.cursorY);
7256 line.replace(currentState.cursorX, cells[x][y]);
7257 // If at the end of the visible screen, stop.
7258 if (currentState.cursorX == rightMargin) {
7259 break;
7260 }
7261 // Room for more image on the visible screen.
7262 currentState.cursorX++;
7263 }
7264 if ((scroll == true)
7265 || ((scroll == false)
7266 && (currentState.cursorY < scrollRegionBottom))
7267 ) {
7268 linefeed();
7269 }
7270 cursorPosition(currentState.cursorY, x0);
7271 }
7272
7273 }
7274
7275 }