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