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