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