2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2016 Kevin Lamonte
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:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
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.
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
31 import java
.io
.BufferedReader
;
32 import java
.io
.FileDescriptor
;
33 import java
.io
.FileInputStream
;
34 import java
.io
.InputStream
;
35 import java
.io
.InputStreamReader
;
36 import java
.io
.IOException
;
37 import java
.io
.OutputStream
;
38 import java
.io
.OutputStreamWriter
;
39 import java
.io
.PrintWriter
;
40 import java
.io
.Reader
;
41 import java
.io
.UnsupportedEncodingException
;
42 import java
.util
.ArrayList
;
43 import java
.util
.Date
;
44 import java
.util
.List
;
45 import java
.util
.LinkedList
;
47 import jexer
.bits
.Color
;
48 import jexer
.event
.TInputEvent
;
49 import jexer
.event
.TKeypressEvent
;
50 import jexer
.event
.TMouseEvent
;
51 import jexer
.event
.TResizeEvent
;
52 import jexer
.session
.SessionInfo
;
53 import jexer
.session
.TSessionInfo
;
54 import jexer
.session
.TTYSessionInfo
;
55 import static jexer
.TKeypress
.*;
58 * This class reads keystrokes and mouse events and emits output to ANSI
59 * X3.64 / ECMA-48 type terminals e.g. xterm, linux, vt100, ansi.sys, etc.
61 public final class ECMA48Terminal
implements Runnable
{
64 * The session information.
66 private SessionInfo sessionInfo
;
69 * Getter for sessionInfo.
71 * @return the SessionInfo
73 public SessionInfo
getSessionInfo() {
78 * The event queue, filled up by a thread reading on input.
80 private List
<TInputEvent
> eventQueue
;
83 * If true, we want the reader thread to exit gracefully.
85 private boolean stopReaderThread
;
90 private Thread readerThread
;
93 * Parameters being collected. E.g. if the string is \033[1;3m, then
94 * params[0] will be 1 and params[1] will be 3.
96 private ArrayList
<String
> params
;
99 * States in the input parser.
101 private enum ParseState
{
112 * Current parsing state.
114 private ParseState state
;
117 * The time we entered ESCAPE. If we get a bare escape without a code
118 * following it, this is used to return that bare escape.
120 private long escapeTime
;
123 * The time we last checked the window size. We try not to spawn stty
124 * more than once per second.
126 private long windowSizeTime
;
129 * true if mouse1 was down. Used to report mouse1 on the release event.
131 private boolean mouse1
;
134 * true if mouse2 was down. Used to report mouse2 on the release event.
136 private boolean mouse2
;
139 * true if mouse3 was down. Used to report mouse3 on the release event.
141 private boolean mouse3
;
144 * Cache the cursor visibility value so we only emit the sequence when we
147 private boolean cursorOn
= true;
150 * Cache the last window size to figure out if a TResizeEvent needs to be
153 private TResizeEvent windowResize
= null;
156 * If true, then we changed System.in and need to change it back.
158 private boolean setRawMode
;
161 * The terminal's input. If an InputStream is not specified in the
162 * constructor, then this InputStreamReader will be bound to System.in
163 * with UTF-8 encoding.
165 private Reader input
;
168 * The terminal's raw InputStream. If an InputStream is not specified in
169 * the constructor, then this InputReader will be bound to System.in.
170 * This is used by run() to see if bytes are available() before calling
171 * (Reader)input.read().
173 private InputStream inputStream
;
176 * The terminal's output. If an OutputStream is not specified in the
177 * constructor, then this PrintWriter will be bound to System.out with
180 private PrintWriter output
;
183 * The listening object that run() wakes up on new input.
185 private Object listener
;
188 * Get the output writer.
192 public PrintWriter
getOutput() {
197 * Check if there are events in the queue.
199 * @return if true, getEvents() has something to return to the backend
201 public boolean hasEvents() {
202 synchronized (eventQueue
) {
203 return (eventQueue
.size() > 0);
208 * Call 'stty' to set cooked mode.
210 * <p>Actually executes '/bin/sh -c stty sane cooked < /dev/tty'
212 private void sttyCooked() {
217 * Call 'stty' to set raw mode.
219 * <p>Actually executes '/bin/sh -c stty -ignbrk -brkint -parmrk -istrip
220 * -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten
221 * -parenb cs8 min 1 < /dev/tty'
223 private void sttyRaw() {
228 * Call 'stty' to set raw or cooked mode.
230 * @param mode if true, set raw mode, otherwise set cooked mode
232 private void doStty(final boolean mode
) {
234 "/bin/sh", "-c", "stty -ignbrk -brkint -parmrk -istrip -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten -parenb cs8 min 1 < /dev/tty"
236 String
[] cmdCooked
= {
237 "/bin/sh", "-c", "stty sane cooked < /dev/tty"
242 process
= Runtime
.getRuntime().exec(cmdRaw
);
244 process
= Runtime
.getRuntime().exec(cmdCooked
);
246 BufferedReader in
= new BufferedReader(new InputStreamReader(process
.getInputStream(), "UTF-8"));
247 String line
= in
.readLine();
248 if ((line
!= null) && (line
.length() > 0)) {
249 System
.err
.println("WEIRD?! Normal output from stty: " + line
);
252 BufferedReader err
= new BufferedReader(new InputStreamReader(process
.getErrorStream(), "UTF-8"));
253 line
= err
.readLine();
254 if ((line
!= null) && (line
.length() > 0)) {
255 System
.err
.println("Error output from stty: " + line
);
260 } catch (InterruptedException e
) {
264 int rc
= process
.exitValue();
266 System
.err
.println("stty returned error code: " + rc
);
268 } catch (IOException e
) {
274 * Constructor sets up state for getEvent().
276 * @param listener the object this backend needs to wake up when new
278 * @param input an InputStream connected to the remote user, or null for
279 * System.in. If System.in is used, then on non-Windows systems it will
280 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
281 * mode. input is always converted to a Reader with UTF-8 encoding.
282 * @param output an OutputStream connected to the remote user, or null
283 * for System.out. output is always converted to a Writer with UTF-8
285 * @throws UnsupportedEncodingException if an exception is thrown when
286 * creating the InputStreamReader
288 public ECMA48Terminal(final Object listener
, final InputStream input
,
289 final OutputStream output
) throws UnsupportedEncodingException
{
295 stopReaderThread
= false;
296 this.listener
= listener
;
299 // inputStream = System.in;
300 inputStream
= new FileInputStream(FileDescriptor
.in
);
306 this.input
= new InputStreamReader(inputStream
, "UTF-8");
308 if (input
instanceof SessionInfo
) {
309 // This is a TelnetInputStream that exposes window size and
310 // environment variables from the telnet layer.
311 sessionInfo
= (SessionInfo
) input
;
313 if (sessionInfo
== null) {
315 // Reading right off the tty
316 sessionInfo
= new TTYSessionInfo();
318 sessionInfo
= new TSessionInfo();
322 if (output
== null) {
323 this.output
= new PrintWriter(new OutputStreamWriter(System
.out
,
326 this.output
= new PrintWriter(new OutputStreamWriter(output
,
330 // Enable mouse reporting and metaSendsEscape
331 this.output
.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
334 // Hang onto the window size
335 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
336 sessionInfo
.getWindowWidth(), sessionInfo
.getWindowHeight());
338 // Spin up the input reader
339 eventQueue
= new LinkedList
<TInputEvent
>();
340 readerThread
= new Thread(this);
341 readerThread
.start();
345 * Restore terminal to normal state.
347 public void shutdown() {
349 // System.err.println("=== shutdown() ==="); System.err.flush();
351 // Tell the reader thread to stop looking at input
352 stopReaderThread
= true;
355 } catch (InterruptedException e
) {
359 // Disable mouse reporting and show cursor
360 output
.printf("%s%s%s", mouse(false), cursor(true), normal());
366 // We don't close System.in/out
368 // Shut down the streams, this should wake up the reader thread
375 if (output
!= null) {
379 } catch (IOException e
) {
388 public void flush() {
393 * Reset keyboard/mouse input parser.
395 private void reset() {
396 state
= ParseState
.GROUND
;
397 params
= new ArrayList
<String
>();
403 * Produce a control character or one of the special ones (ENTER, TAB,
406 * @param ch Unicode code point
407 * @param alt if true, set alt on the TKeypress
408 * @return one TKeypress event, either a control character (e.g. isKey ==
409 * false, ch == 'A', ctrl == true), or a special key (e.g. isKey == true,
412 private TKeypressEvent
controlChar(final char ch
, final boolean alt
) {
413 // System.err.printf("controlChar: %02x\n", ch);
417 // Carriage return --> ENTER
418 return new TKeypressEvent(kbEnter
, alt
, false, false);
420 // Linefeed --> ENTER
421 return new TKeypressEvent(kbEnter
, alt
, false, false);
424 return new TKeypressEvent(kbEsc
, alt
, false, false);
427 return new TKeypressEvent(kbTab
, alt
, false, false);
429 // Make all other control characters come back as the alphabetic
430 // character with the ctrl field set. So SOH would be 'A' +
432 return new TKeypressEvent(false, 0, (char)(ch
+ 0x40),
438 * Produce special key from CSI Pn ; Pm ; ... ~
440 * @return one KEYPRESS event representing a special key
442 private TInputEvent
csiFnKey() {
444 if (params
.size() > 0) {
445 key
= Integer
.parseInt(params
.get(0));
448 boolean ctrl
= false;
449 boolean shift
= false;
450 if (params
.size() > 1) {
451 shift
= csiIsShift(params
.get(1));
452 alt
= csiIsAlt(params
.get(1));
453 ctrl
= csiIsCtrl(params
.get(1));
458 return new TKeypressEvent(kbHome
, alt
, ctrl
, shift
);
460 return new TKeypressEvent(kbIns
, alt
, ctrl
, shift
);
462 return new TKeypressEvent(kbDel
, alt
, ctrl
, shift
);
464 return new TKeypressEvent(kbEnd
, alt
, ctrl
, shift
);
466 return new TKeypressEvent(kbPgUp
, alt
, ctrl
, shift
);
468 return new TKeypressEvent(kbPgDn
, alt
, ctrl
, shift
);
470 return new TKeypressEvent(kbF5
, alt
, ctrl
, shift
);
472 return new TKeypressEvent(kbF6
, alt
, ctrl
, shift
);
474 return new TKeypressEvent(kbF7
, alt
, ctrl
, shift
);
476 return new TKeypressEvent(kbF8
, alt
, ctrl
, shift
);
478 return new TKeypressEvent(kbF9
, alt
, ctrl
, shift
);
480 return new TKeypressEvent(kbF10
, alt
, ctrl
, shift
);
482 return new TKeypressEvent(kbF11
, alt
, ctrl
, shift
);
484 return new TKeypressEvent(kbF12
, alt
, ctrl
, shift
);
492 * Produce mouse events based on "Any event tracking" and UTF-8
494 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
496 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
498 private TInputEvent
parseMouse() {
499 int buttons
= params
.get(0).charAt(0) - 32;
500 int x
= params
.get(0).charAt(1) - 32 - 1;
501 int y
= params
.get(0).charAt(2) - 32 - 1;
503 // Clamp X and Y to the physical screen coordinates.
504 if (x
>= windowResize
.getWidth()) {
505 x
= windowResize
.getWidth() - 1;
507 if (y
>= windowResize
.getHeight()) {
508 y
= windowResize
.getHeight() - 1;
511 TMouseEvent
.Type eventType
= TMouseEvent
.Type
.MOUSE_DOWN
;
512 boolean eventMouse1
= false;
513 boolean eventMouse2
= false;
514 boolean eventMouse3
= false;
515 boolean eventMouseWheelUp
= false;
516 boolean eventMouseWheelDown
= false;
518 // System.err.printf("buttons: %04x\r\n", buttons);
535 if (!mouse1
&& !mouse2
&& !mouse3
) {
536 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
538 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
555 // Dragging with mouse1 down
558 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
562 // Dragging with mouse2 down
565 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
569 // Dragging with mouse3 down
572 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
576 // Dragging with mouse2 down after wheelUp
579 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
583 // Dragging with mouse2 down after wheelDown
586 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
590 eventMouseWheelUp
= true;
594 eventMouseWheelDown
= true;
598 // Unknown, just make it motion
599 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
602 return new TMouseEvent(eventType
, x
, y
, x
, y
,
603 eventMouse1
, eventMouse2
, eventMouse3
,
604 eventMouseWheelUp
, eventMouseWheelDown
);
608 * Produce mouse events based on "Any event tracking" and SGR
610 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
612 * @param release if true, this was a release ('m')
613 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
615 private TInputEvent
parseMouseSGR(final boolean release
) {
616 // SGR extended coordinates - mode 1006
617 if (params
.size() < 3) {
618 // Invalid position, bail out.
621 int buttons
= Integer
.parseInt(params
.get(0));
622 int x
= Integer
.parseInt(params
.get(1)) - 1;
623 int y
= Integer
.parseInt(params
.get(2)) - 1;
625 // Clamp X and Y to the physical screen coordinates.
626 if (x
>= windowResize
.getWidth()) {
627 x
= windowResize
.getWidth() - 1;
629 if (y
>= windowResize
.getHeight()) {
630 y
= windowResize
.getHeight() - 1;
633 TMouseEvent
.Type eventType
= TMouseEvent
.Type
.MOUSE_DOWN
;
634 boolean eventMouse1
= false;
635 boolean eventMouse2
= false;
636 boolean eventMouse3
= false;
637 boolean eventMouseWheelUp
= false;
638 boolean eventMouseWheelDown
= false;
641 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
655 // Motion only, no buttons down
656 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
660 // Dragging with mouse1 down
662 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
666 // Dragging with mouse2 down
668 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
672 // Dragging with mouse3 down
674 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
678 // Dragging with mouse2 down after wheelUp
680 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
684 // Dragging with mouse2 down after wheelDown
686 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
690 eventMouseWheelUp
= true;
694 eventMouseWheelDown
= true;
701 return new TMouseEvent(eventType
, x
, y
, x
, y
,
702 eventMouse1
, eventMouse2
, eventMouse3
,
703 eventMouseWheelUp
, eventMouseWheelDown
);
707 * Return any events in the IO queue.
709 * @param queue list to append new events to
711 public void getEvents(final List
<TInputEvent
> queue
) {
712 synchronized (eventQueue
) {
713 if (eventQueue
.size() > 0) {
714 synchronized (queue
) {
715 queue
.addAll(eventQueue
);
723 * Return any events in the IO queue due to timeout.
725 * @param queue list to append new events to
727 private void getIdleEvents(final List
<TInputEvent
> queue
) {
728 Date now
= new Date();
730 // Check for new window size
731 long windowSizeDelay
= now
.getTime() - windowSizeTime
;
732 if (windowSizeDelay
> 1000) {
733 sessionInfo
.queryWindowSize();
734 int newWidth
= sessionInfo
.getWindowWidth();
735 int newHeight
= sessionInfo
.getWindowHeight();
736 if ((newWidth
!= windowResize
.getWidth())
737 || (newHeight
!= windowResize
.getHeight())
739 TResizeEvent event
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
740 newWidth
, newHeight
);
741 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
742 newWidth
, newHeight
);
745 windowSizeTime
= now
.getTime();
748 // ESCDELAY type timeout
749 if (state
== ParseState
.ESCAPE
) {
750 long escDelay
= now
.getTime() - escapeTime
;
751 if (escDelay
> 100) {
752 // After 0.1 seconds, assume a true escape character
753 queue
.add(controlChar((char)0x1B, false));
760 * Returns true if the CSI parameter for a keyboard command means that
763 private boolean csiIsShift(final String x
) {
775 * Returns true if the CSI parameter for a keyboard command means that
778 private boolean csiIsAlt(final String x
) {
790 * Returns true if the CSI parameter for a keyboard command means that
793 private boolean csiIsCtrl(final String x
) {
805 * Parses the next character of input to see if an InputEvent is
808 * @param events list to append new events to
809 * @param ch Unicode code point
811 private void processChar(final List
<TInputEvent
> events
, final char ch
) {
813 // ESCDELAY type timeout
814 Date now
= new Date();
815 if (state
== ParseState
.ESCAPE
) {
816 long escDelay
= now
.getTime() - escapeTime
;
817 if (escDelay
> 250) {
818 // After 0.25 seconds, assume a true escape character
819 events
.add(controlChar((char)0x1B, false));
825 boolean ctrl
= false;
827 boolean shift
= false;
829 // System.err.printf("state: %s ch %c\r\n", state, ch);
835 state
= ParseState
.ESCAPE
;
836 escapeTime
= now
.getTime();
842 events
.add(controlChar(ch
, false));
849 events
.add(new TKeypressEvent(false, 0, ch
,
850 false, false, false));
859 // ALT-Control character
860 events
.add(controlChar(ch
, true));
866 // This will be one of the function keys
867 state
= ParseState
.ESCAPE_INTERMEDIATE
;
871 // '[' goes to CSI_ENTRY
873 state
= ParseState
.CSI_ENTRY
;
877 // Everything else is assumed to be Alt-keystroke
878 if ((ch
>= 'A') && (ch
<= 'Z')) {
882 events
.add(new TKeypressEvent(false, 0, ch
, alt
, ctrl
, shift
));
886 case ESCAPE_INTERMEDIATE
:
887 if ((ch
>= 'P') && (ch
<= 'S')) {
891 events
.add(new TKeypressEvent(kbF1
));
894 events
.add(new TKeypressEvent(kbF2
));
897 events
.add(new TKeypressEvent(kbF3
));
900 events
.add(new TKeypressEvent(kbF4
));
909 // Unknown keystroke, ignore
914 // Numbers - parameter values
915 if ((ch
>= '0') && (ch
<= '9')) {
916 params
.set(params
.size() - 1,
917 params
.get(params
.size() - 1) + ch
);
918 state
= ParseState
.CSI_PARAM
;
921 // Parameter separator
927 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
931 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
936 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
941 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
946 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
951 events
.add(new TKeypressEvent(kbHome
));
956 events
.add(new TKeypressEvent(kbEnd
));
960 // CBT - Cursor backward X tab stops (default 1)
961 events
.add(new TKeypressEvent(kbBackTab
));
966 state
= ParseState
.MOUSE
;
969 // Mouse position, SGR (1006) coordinates
970 state
= ParseState
.MOUSE_SGR
;
977 // Unknown keystroke, ignore
982 // Numbers - parameter values
983 if ((ch
>= '0') && (ch
<= '9')) {
984 params
.set(params
.size() - 1,
985 params
.get(params
.size() - 1) + ch
);
988 // Parameter separator
996 // Generate a mouse press event
997 TInputEvent event
= parseMouseSGR(false);
1004 // Generate a mouse release event
1005 event
= parseMouseSGR(true);
1006 if (event
!= null) {
1015 // Unknown keystroke, ignore
1020 // Numbers - parameter values
1021 if ((ch
>= '0') && (ch
<= '9')) {
1022 params
.set(params
.size() - 1,
1023 params
.get(params
.size() - 1) + ch
);
1024 state
= ParseState
.CSI_PARAM
;
1027 // Parameter separator
1034 events
.add(csiFnKey());
1039 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
1043 if (params
.size() > 1) {
1044 shift
= csiIsShift(params
.get(1));
1045 alt
= csiIsAlt(params
.get(1));
1046 ctrl
= csiIsCtrl(params
.get(1));
1048 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
1053 if (params
.size() > 1) {
1054 shift
= csiIsShift(params
.get(1));
1055 alt
= csiIsAlt(params
.get(1));
1056 ctrl
= csiIsCtrl(params
.get(1));
1058 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
1063 if (params
.size() > 1) {
1064 shift
= csiIsShift(params
.get(1));
1065 alt
= csiIsAlt(params
.get(1));
1066 ctrl
= csiIsCtrl(params
.get(1));
1068 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
1073 if (params
.size() > 1) {
1074 shift
= csiIsShift(params
.get(1));
1075 alt
= csiIsAlt(params
.get(1));
1076 ctrl
= csiIsCtrl(params
.get(1));
1078 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
1083 if (params
.size() > 1) {
1084 shift
= csiIsShift(params
.get(1));
1085 alt
= csiIsAlt(params
.get(1));
1086 ctrl
= csiIsCtrl(params
.get(1));
1088 events
.add(new TKeypressEvent(kbHome
, alt
, ctrl
, shift
));
1093 if (params
.size() > 1) {
1094 shift
= csiIsShift(params
.get(1));
1095 alt
= csiIsAlt(params
.get(1));
1096 ctrl
= csiIsCtrl(params
.get(1));
1098 events
.add(new TKeypressEvent(kbEnd
, alt
, ctrl
, shift
));
1106 // Unknown keystroke, ignore
1111 params
.set(0, params
.get(params
.size() - 1) + ch
);
1112 if (params
.get(0).length() == 3) {
1113 // We have enough to generate a mouse event
1114 events
.add(parseMouse());
1123 // This "should" be impossible to reach
1128 * Tell (u)xterm that we want alt- keystrokes to send escape + character
1129 * rather than set the 8th bit. Anyone who wants UTF8 should want this
1132 * @param on if true, enable metaSendsEscape
1133 * @return the string to emit to xterm
1135 private String
xtermMetaSendsEscape(final boolean on
) {
1137 return "\033[?1036h\033[?1034l";
1139 return "\033[?1036l";
1143 * Create a SGR parameter sequence for a single color change. Note
1144 * package private access.
1146 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
1147 * @param foreground if true, this is a foreground color
1148 * @return the string to emit to an ANSI / ECMA-style terminal,
1151 String
color(final Color color
, final boolean foreground
) {
1152 return color(color
, foreground
, true);
1156 * Create a SGR parameter sequence for a single color change.
1158 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
1159 * @param foreground if true, this is a foreground color
1160 * @param header if true, make the full header, otherwise just emit the
1161 * color parameter e.g. "42;"
1162 * @return the string to emit to an ANSI / ECMA-style terminal,
1165 private String
color(final Color color
, final boolean foreground
,
1166 final boolean header
) {
1168 int ecmaColor
= color
.getValue();
1170 // Convert Color.* values to SGR numerics
1178 return String
.format("\033[%dm", ecmaColor
);
1180 return String
.format("%d;", ecmaColor
);
1185 * Create a SGR parameter sequence for both foreground and background
1186 * color change. Note package private access.
1188 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1189 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1190 * @return the string to emit to an ANSI / ECMA-style terminal,
1191 * e.g. "\033[31;42m"
1193 String
color(final Color foreColor
, final Color backColor
) {
1194 return color(foreColor
, backColor
, true);
1198 * Create a SGR parameter sequence for both foreground and
1199 * background color change.
1201 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1202 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1203 * @param header if true, make the full header, otherwise just emit the
1204 * color parameter e.g. "31;42;"
1205 * @return the string to emit to an ANSI / ECMA-style terminal,
1206 * e.g. "\033[31;42m"
1208 private String
color(final Color foreColor
, final Color backColor
,
1209 final boolean header
) {
1211 int ecmaForeColor
= foreColor
.getValue();
1212 int ecmaBackColor
= backColor
.getValue();
1214 // Convert Color.* values to SGR numerics
1215 ecmaBackColor
+= 40;
1216 ecmaForeColor
+= 30;
1219 return String
.format("\033[%d;%dm", ecmaForeColor
, ecmaBackColor
);
1221 return String
.format("%d;%d;", ecmaForeColor
, ecmaBackColor
);
1226 * Create a SGR parameter sequence for foreground, background, and
1227 * several attributes. This sequence first resets all attributes to
1228 * default, then sets attributes as per the parameters. Note package
1231 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1232 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1233 * @param bold if true, set bold
1234 * @param reverse if true, set reverse
1235 * @param blink if true, set blink
1236 * @param underline if true, set underline
1237 * @return the string to emit to an ANSI / ECMA-style terminal,
1238 * e.g. "\033[0;1;31;42m"
1240 String
color(final Color foreColor
, final Color backColor
,
1241 final boolean bold
, final boolean reverse
, final boolean blink
,
1242 final boolean underline
) {
1244 int ecmaForeColor
= foreColor
.getValue();
1245 int ecmaBackColor
= backColor
.getValue();
1247 // Convert Color.* values to SGR numerics
1248 ecmaBackColor
+= 40;
1249 ecmaForeColor
+= 30;
1251 StringBuilder sb
= new StringBuilder();
1252 if ( bold
&& reverse
&& blink
&& !underline
) {
1253 sb
.append("\033[0;1;7;5;");
1254 } else if ( bold
&& reverse
&& !blink
&& !underline
) {
1255 sb
.append("\033[0;1;7;");
1256 } else if ( !bold
&& reverse
&& blink
&& !underline
) {
1257 sb
.append("\033[0;7;5;");
1258 } else if ( bold
&& !reverse
&& blink
&& !underline
) {
1259 sb
.append("\033[0;1;5;");
1260 } else if ( bold
&& !reverse
&& !blink
&& !underline
) {
1261 sb
.append("\033[0;1;");
1262 } else if ( !bold
&& reverse
&& !blink
&& !underline
) {
1263 sb
.append("\033[0;7;");
1264 } else if ( !bold
&& !reverse
&& blink
&& !underline
) {
1265 sb
.append("\033[0;5;");
1266 } else if ( bold
&& reverse
&& blink
&& underline
) {
1267 sb
.append("\033[0;1;7;5;4;");
1268 } else if ( bold
&& reverse
&& !blink
&& underline
) {
1269 sb
.append("\033[0;1;7;4;");
1270 } else if ( !bold
&& reverse
&& blink
&& underline
) {
1271 sb
.append("\033[0;7;5;4;");
1272 } else if ( bold
&& !reverse
&& blink
&& underline
) {
1273 sb
.append("\033[0;1;5;4;");
1274 } else if ( bold
&& !reverse
&& !blink
&& underline
) {
1275 sb
.append("\033[0;1;4;");
1276 } else if ( !bold
&& reverse
&& !blink
&& underline
) {
1277 sb
.append("\033[0;7;4;");
1278 } else if ( !bold
&& !reverse
&& blink
&& underline
) {
1279 sb
.append("\033[0;5;4;");
1280 } else if ( !bold
&& !reverse
&& !blink
&& underline
) {
1281 sb
.append("\033[0;4;");
1283 assert (!bold
&& !reverse
&& !blink
&& !underline
);
1284 sb
.append("\033[0;");
1286 sb
.append(String
.format("%d;%dm", ecmaForeColor
, ecmaBackColor
));
1287 return sb
.toString();
1291 * Create a SGR parameter sequence to reset to defaults. Note package
1294 * @return the string to emit to an ANSI / ECMA-style terminal,
1298 return normal(true);
1302 * Create a SGR parameter sequence to reset to defaults.
1304 * @param header if true, make the full header, otherwise just emit the
1305 * bare parameter e.g. "0;"
1306 * @return the string to emit to an ANSI / ECMA-style terminal,
1309 private String
normal(final boolean header
) {
1311 return "\033[0;37;40m";
1317 * Create a SGR parameter sequence for enabling the visible cursor. Note
1318 * package private access.
1320 * @param on if true, turn on cursor
1321 * @return the string to emit to an ANSI / ECMA-style terminal
1323 String
cursor(final boolean on
) {
1324 if (on
&& !cursorOn
) {
1328 if (!on
&& cursorOn
) {
1336 * Clear the entire screen. Because some terminals use back-color-erase,
1337 * set the color to white-on-black beforehand.
1339 * @return the string to emit to an ANSI / ECMA-style terminal
1341 public String
clearAll() {
1342 return "\033[0;37;40m\033[2J";
1346 * Clear the line from the cursor (inclusive) to the end of the screen.
1347 * Because some terminals use back-color-erase, set the color to
1348 * white-on-black beforehand. Note package private access.
1350 * @return the string to emit to an ANSI / ECMA-style terminal
1352 String
clearRemainingLine() {
1353 return "\033[0;37;40m\033[K";
1357 * Move the cursor to (x, y). Note package private access.
1359 * @param x column coordinate. 0 is the left-most column.
1360 * @param y row coordinate. 0 is the top-most row.
1361 * @return the string to emit to an ANSI / ECMA-style terminal
1363 String
gotoXY(final int x
, final int y
) {
1364 return String
.format("\033[%d;%dH", y
+ 1, x
+ 1);
1368 * Tell (u)xterm that we want to receive mouse events based on "Any event
1369 * tracking", UTF-8 coordinates, and then SGR coordinates. Ideally we
1370 * will end up with SGR coordinates with UTF-8 coordinates as a fallback.
1372 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
1374 * Note that this also sets the alternate/primary screen buffer.
1376 * @param on If true, enable mouse report and use the alternate screen
1377 * buffer. If false disable mouse reporting and use the primary screen
1379 * @return the string to emit to xterm
1381 private String
mouse(final boolean on
) {
1383 return "\033[?1002;1003;1005;1006h\033[?1049h";
1385 return "\033[?1002;1003;1006;1005l\033[?1049l";
1389 * Read function runs on a separate thread.
1392 boolean done
= false;
1393 // available() will often return > 1, so we need to read in chunks to
1395 char [] readBuffer
= new char[128];
1396 List
<TInputEvent
> events
= new LinkedList
<TInputEvent
>();
1398 while (!done
&& !stopReaderThread
) {
1400 // We assume that if inputStream has bytes available, then
1401 // input won't block on read().
1402 int n
= inputStream
.available();
1404 if (readBuffer
.length
< n
) {
1405 // The buffer wasn't big enough, make it huger
1406 readBuffer
= new char[readBuffer
.length
* 2];
1409 int rc
= input
.read(readBuffer
, 0, readBuffer
.length
);
1410 // System.err.printf("read() %d", rc); System.err.flush();
1415 for (int i
= 0; i
< rc
; i
++) {
1416 int ch
= readBuffer
[i
];
1417 processChar(events
, (char)ch
);
1419 getIdleEvents(events
);
1420 if (events
.size() > 0) {
1421 // Add to the queue for the backend thread to
1422 // be able to obtain.
1423 synchronized (eventQueue
) {
1424 eventQueue
.addAll(events
);
1426 synchronized (listener
) {
1427 listener
.notifyAll();
1433 getIdleEvents(events
);
1434 if (events
.size() > 0) {
1435 synchronized (eventQueue
) {
1436 eventQueue
.addAll(events
);
1439 synchronized (listener
) {
1440 listener
.notifyAll();
1444 // Wait 10 millis for more data
1447 // System.err.println("end while loop"); System.err.flush();
1448 } catch (InterruptedException e
) {
1450 } catch (IOException e
) {
1451 e
.printStackTrace();
1454 } // while ((done == false) && (stopReaderThread == false))
1455 // System.err.println("*** run() exiting..."); System.err.flush();