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