2 * Jexer - Java Text User Interface
4 * License: LGPLv3 or later
6 * This module is licensed under the GNU Lesser General Public License
7 * Version 3. Please see the file "COPYING" in this directory for more
8 * information about the GNU Lesser General Public License Version 3.
10 * Copyright (C) 2015 Kevin Lamonte
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public License
14 * as published by the Free Software Foundation; either version 3 of
15 * the License, or (at your option) any later version.
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this program; if not, see
24 * http://www.gnu.org/licenses/, or write to the Free Software
25 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
28 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
33 import java
.io
.BufferedReader
;
34 import java
.io
.FileDescriptor
;
35 import java
.io
.FileInputStream
;
36 import java
.io
.InputStream
;
37 import java
.io
.InputStreamReader
;
38 import java
.io
.IOException
;
39 import java
.io
.OutputStream
;
40 import java
.io
.OutputStreamWriter
;
41 import java
.io
.PrintWriter
;
42 import java
.io
.Reader
;
43 import java
.io
.UnsupportedEncodingException
;
44 import java
.util
.ArrayList
;
45 import java
.util
.Date
;
46 import java
.util
.List
;
47 import java
.util
.LinkedList
;
49 import jexer
.TKeypress
;
50 import jexer
.bits
.Color
;
51 import jexer
.event
.TInputEvent
;
52 import jexer
.event
.TKeypressEvent
;
53 import jexer
.event
.TMouseEvent
;
54 import jexer
.event
.TResizeEvent
;
55 import jexer
.session
.SessionInfo
;
56 import jexer
.session
.TSessionInfo
;
57 import jexer
.session
.TTYSessionInfo
;
58 import static jexer
.TKeypress
.*;
61 * This class reads keystrokes and mouse events and emits output to ANSI
62 * X3.64 / ECMA-48 type terminals e.g. xterm, linux, vt100, ansi.sys, etc.
64 public final class ECMA48Terminal
implements Runnable
{
67 * The session information.
69 private SessionInfo sessionInfo
;
72 * Getter for sessionInfo.
74 * @return the SessionInfo
76 public SessionInfo
getSessionInfo() {
81 * The event queue, filled up by a thread reading on input.
83 private List
<TInputEvent
> eventQueue
;
86 * If true, we want the reader thread to exit gracefully.
88 private boolean stopReaderThread
;
93 private Thread readerThread
;
96 * Parameters being collected. E.g. if the string is \033[1;3m, then
97 * params[0] will be 1 and params[1] will be 3.
99 private ArrayList
<String
> params
;
102 * States in the input parser.
104 private enum ParseState
{
115 * Current parsing state.
117 private ParseState state
;
120 * The time we entered ESCAPE. If we get a bare escape without a code
121 * following it, this is used to return that bare escape.
123 private long escapeTime
;
126 * The time we last checked the window size. We try not to spawn stty
127 * more than once per second.
129 private long windowSizeTime
;
132 * true if mouse1 was down. Used to report mouse1 on the release event.
134 private boolean mouse1
;
137 * true if mouse2 was down. Used to report mouse2 on the release event.
139 private boolean mouse2
;
142 * true if mouse3 was down. Used to report mouse3 on the release event.
144 private boolean mouse3
;
147 * Cache the cursor visibility value so we only emit the sequence when we
150 private boolean cursorOn
= true;
153 * Cache the last window size to figure out if a TResizeEvent needs to be
156 private TResizeEvent windowResize
= null;
159 * If true, then we changed System.in and need to change it back.
161 private boolean setRawMode
;
164 * The terminal's input. If an InputStream is not specified in the
165 * constructor, then this InputStreamReader will be bound to System.in
166 * with UTF-8 encoding.
168 private Reader input
;
171 * The terminal's raw InputStream. If an InputStream is not specified in
172 * the constructor, then this InputReader will be bound to System.in.
173 * This is used by run() to see if bytes are available() before calling
174 * (Reader)input.read().
176 private InputStream inputStream
;
179 * The terminal's output. If an OutputStream is not specified in the
180 * constructor, then this PrintWriter will be bound to System.out with
183 private PrintWriter output
;
186 * The listening object that run() wakes up on new input.
188 private Object listener
;
191 * When true, the terminal is sending non-UTF8 bytes when reporting mouse
194 * TODO: Add broken mouse detection back into the reader.
196 private boolean brokenTerminalUTFMouse
= false;
199 * Get the output writer.
203 public PrintWriter
getOutput() {
208 * Check if there are events in the queue.
210 * @return if true, getEvents() has something to return to the backend
212 public boolean hasEvents() {
213 synchronized (eventQueue
) {
214 return (eventQueue
.size() > 0);
219 * Call 'stty' to set cooked mode.
221 * <p>Actually executes '/bin/sh -c stty sane cooked < /dev/tty'
223 private void sttyCooked() {
228 * Call 'stty' to set raw mode.
230 * <p>Actually executes '/bin/sh -c stty -ignbrk -brkint -parmrk -istrip
231 * -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten
232 * -parenb cs8 min 1 < /dev/tty'
234 private void sttyRaw() {
239 * Call 'stty' to set raw or cooked mode.
241 * @param mode if true, set raw mode, otherwise set cooked mode
243 private void doStty(final boolean mode
) {
245 "/bin/sh", "-c", "stty -ignbrk -brkint -parmrk -istrip -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten -parenb cs8 min 1 < /dev/tty"
247 String
[] cmdCooked
= {
248 "/bin/sh", "-c", "stty sane cooked < /dev/tty"
253 process
= Runtime
.getRuntime().exec(cmdRaw
);
255 process
= Runtime
.getRuntime().exec(cmdCooked
);
257 BufferedReader in
= new BufferedReader(new InputStreamReader(process
.getInputStream(), "UTF-8"));
258 String line
= in
.readLine();
259 if ((line
!= null) && (line
.length() > 0)) {
260 System
.err
.println("WEIRD?! Normal output from stty: " + line
);
263 BufferedReader err
= new BufferedReader(new InputStreamReader(process
.getErrorStream(), "UTF-8"));
264 line
= err
.readLine();
265 if ((line
!= null) && (line
.length() > 0)) {
266 System
.err
.println("Error output from stty: " + line
);
271 } catch (InterruptedException e
) {
275 int rc
= process
.exitValue();
277 System
.err
.println("stty returned error code: " + rc
);
279 } catch (IOException e
) {
285 * Constructor sets up state for getEvent().
287 * @param listener the object this backend needs to wake up when new
289 * @param input an InputStream connected to the remote user, or null for
290 * System.in. If System.in is used, then on non-Windows systems it will
291 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
292 * mode. input is always converted to a Reader with UTF-8 encoding.
293 * @param output an OutputStream connected to the remote user, or null
294 * for System.out. output is always converted to a Writer with UTF-8
296 * @throws UnsupportedEncodingException if an exception is thrown when
297 * creating the InputStreamReader
299 public ECMA48Terminal(final Object listener
, final InputStream input
,
300 final OutputStream output
) throws UnsupportedEncodingException
{
306 stopReaderThread
= false;
307 this.listener
= listener
;
310 // inputStream = System.in;
311 inputStream
= new FileInputStream(FileDescriptor
.in
);
317 this.input
= new InputStreamReader(inputStream
, "UTF-8");
319 // TODO: include TelnetSocket from NIB and have it implement
321 if (input
instanceof SessionInfo
) {
322 sessionInfo
= (SessionInfo
) input
;
324 if (sessionInfo
== null) {
326 // Reading right off the tty
327 sessionInfo
= new TTYSessionInfo();
329 sessionInfo
= new TSessionInfo();
333 if (output
== null) {
334 this.output
= new PrintWriter(new OutputStreamWriter(System
.out
,
337 this.output
= new PrintWriter(new OutputStreamWriter(output
,
341 // Enable mouse reporting and metaSendsEscape
342 this.output
.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
344 // Hang onto the window size
345 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
346 sessionInfo
.getWindowWidth(), sessionInfo
.getWindowHeight());
348 // Spin up the input reader
349 eventQueue
= new LinkedList
<TInputEvent
>();
350 readerThread
= new Thread(this);
351 readerThread
.start();
355 * Restore terminal to normal state.
357 public void shutdown() {
359 // System.err.println("=== shutdown() ==="); System.err.flush();
361 // Tell the reader thread to stop looking at input
362 stopReaderThread
= true;
365 } catch (InterruptedException e
) {
369 // Disable mouse reporting and show cursor
370 output
.printf("%s%s%s", mouse(false), cursor(true), normal());
376 // We don't close System.in/out
378 // Shut down the streams, this should wake up the reader thread
385 if (output
!= null) {
389 } catch (IOException e
) {
398 public void flush() {
403 * Reset keyboard/mouse input parser.
405 private void reset() {
406 state
= ParseState
.GROUND
;
407 params
= new ArrayList
<String
>();
413 * Produce a control character or one of the special ones (ENTER, TAB,
416 * @param ch Unicode code point
417 * @param alt if true, set alt on the TKeypress
418 * @return one TKeypress event, either a control character (e.g. isKey ==
419 * false, ch == 'A', ctrl == true), or a special key (e.g. isKey == true,
422 private TKeypressEvent
controlChar(final char ch
, final boolean alt
) {
423 // System.err.printf("controlChar: %02x\n", ch);
427 // Carriage return --> ENTER
428 return new TKeypressEvent(kbEnter
, alt
, false, false);
430 // Linefeed --> ENTER
431 return new TKeypressEvent(kbEnter
, alt
, false, false);
434 return new TKeypressEvent(kbEsc
, alt
, false, false);
437 return new TKeypressEvent(kbTab
, alt
, false, false);
439 // Make all other control characters come back as the alphabetic
440 // character with the ctrl field set. So SOH would be 'A' +
442 return new TKeypressEvent(false, 0, (char)(ch
+ 0x40),
448 * Produce special key from CSI Pn ; Pm ; ... ~
450 * @return one KEYPRESS event representing a special key
452 private TInputEvent
csiFnKey() {
455 if (params
.size() > 0) {
456 key
= Integer
.parseInt(params
.get(0));
458 if (params
.size() > 1) {
459 modifier
= Integer
.parseInt(params
.get(1));
462 boolean ctrl
= false;
463 boolean shift
= false;
482 // Unknown modifier, bail out
488 return new TKeypressEvent(kbHome
, alt
, ctrl
, shift
);
490 return new TKeypressEvent(kbIns
, alt
, ctrl
, shift
);
492 return new TKeypressEvent(kbDel
, alt
, ctrl
, shift
);
494 return new TKeypressEvent(kbEnd
, alt
, ctrl
, shift
);
496 return new TKeypressEvent(kbPgUp
, alt
, ctrl
, shift
);
498 return new TKeypressEvent(kbPgDn
, alt
, ctrl
, shift
);
500 return new TKeypressEvent(kbF5
, alt
, ctrl
, shift
);
502 return new TKeypressEvent(kbF6
, alt
, ctrl
, shift
);
504 return new TKeypressEvent(kbF7
, alt
, ctrl
, shift
);
506 return new TKeypressEvent(kbF8
, alt
, ctrl
, shift
);
508 return new TKeypressEvent(kbF9
, alt
, ctrl
, shift
);
510 return new TKeypressEvent(kbF10
, alt
, ctrl
, shift
);
512 return new TKeypressEvent(kbF11
, alt
, ctrl
, shift
);
514 return new TKeypressEvent(kbF12
, alt
, ctrl
, shift
);
522 * Produce mouse events based on "Any event tracking" and UTF-8
524 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
526 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
528 private TInputEvent
parseMouse() {
529 int buttons
= params
.get(0).charAt(0) - 32;
530 int x
= params
.get(0).charAt(1) - 32 - 1;
531 int y
= params
.get(0).charAt(2) - 32 - 1;
533 // Clamp X and Y to the physical screen coordinates.
534 if (x
>= windowResize
.getWidth()) {
535 x
= windowResize
.getWidth() - 1;
537 if (y
>= windowResize
.getHeight()) {
538 y
= windowResize
.getHeight() - 1;
541 TMouseEvent
.Type eventType
= TMouseEvent
.Type
.MOUSE_DOWN
;
542 boolean eventMouse1
= false;
543 boolean eventMouse2
= false;
544 boolean eventMouse3
= false;
545 boolean eventMouseWheelUp
= false;
546 boolean eventMouseWheelDown
= false;
548 // System.err.printf("buttons: %04x\r\n", buttons);
565 if (!mouse1
&& !mouse2
&& !mouse3
) {
566 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
568 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
585 // Dragging with mouse1 down
588 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
592 // Dragging with mouse2 down
595 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
599 // Dragging with mouse3 down
602 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
606 // Dragging with mouse2 down after wheelUp
609 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
613 // Dragging with mouse2 down after wheelDown
616 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
620 eventMouseWheelUp
= true;
624 eventMouseWheelDown
= true;
628 // Unknown, just make it motion
629 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
632 return new TMouseEvent(eventType
, x
, y
, x
, y
,
633 eventMouse1
, eventMouse2
, eventMouse3
,
634 eventMouseWheelUp
, eventMouseWheelDown
);
638 * Return any events in the IO queue.
640 * @param queue list to append new events to
642 public void getEvents(final List
<TInputEvent
> queue
) {
643 synchronized (eventQueue
) {
644 if (eventQueue
.size() > 0) {
645 synchronized (queue
) {
646 queue
.addAll(eventQueue
);
654 * Return any events in the IO queue due to timeout.
656 * @param queue list to append new events to
658 private void getIdleEvents(final List
<TInputEvent
> queue
) {
659 Date now
= new Date();
661 // Check for new window size
662 long windowSizeDelay
= now
.getTime() - windowSizeTime
;
663 if (windowSizeDelay
> 1000) {
664 sessionInfo
.queryWindowSize();
665 int newWidth
= sessionInfo
.getWindowWidth();
666 int newHeight
= sessionInfo
.getWindowHeight();
667 if ((newWidth
!= windowResize
.getWidth())
668 || (newHeight
!= windowResize
.getHeight())
670 TResizeEvent event
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
671 newWidth
, newHeight
);
672 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
673 newWidth
, newHeight
);
676 windowSizeTime
= now
.getTime();
679 // ESCDELAY type timeout
680 if (state
== ParseState
.ESCAPE
) {
681 long escDelay
= now
.getTime() - escapeTime
;
682 if (escDelay
> 100) {
683 // After 0.1 seconds, assume a true escape character
684 queue
.add(controlChar((char)0x1B, false));
691 * Parses the next character of input to see if an InputEvent is
694 * @param events list to append new events to
695 * @param ch Unicode code point
697 private void processChar(final List
<TInputEvent
> events
, final char ch
) {
699 // ESCDELAY type timeout
700 Date now
= new Date();
701 if (state
== ParseState
.ESCAPE
) {
702 long escDelay
= now
.getTime() - escapeTime
;
703 if (escDelay
> 250) {
704 // After 0.25 seconds, assume a true escape character
705 events
.add(controlChar((char)0x1B, false));
711 boolean ctrl
= false;
713 boolean shift
= false;
717 // System.err.printf("state: %s ch %c\r\n", state, ch);
723 state
= ParseState
.ESCAPE
;
724 escapeTime
= now
.getTime();
730 events
.add(controlChar(ch
, false));
737 events
.add(new TKeypressEvent(false, 0, ch
,
738 false, false, false));
747 // ALT-Control character
748 events
.add(controlChar(ch
, true));
754 // This will be one of the function keys
755 state
= ParseState
.ESCAPE_INTERMEDIATE
;
759 // '[' goes to CSI_ENTRY
761 state
= ParseState
.CSI_ENTRY
;
765 // Everything else is assumed to be Alt-keystroke
766 if ((ch
>= 'A') && (ch
<= 'Z')) {
770 events
.add(new TKeypressEvent(false, 0, ch
, alt
, ctrl
, shift
));
774 case ESCAPE_INTERMEDIATE
:
775 if ((ch
>= 'P') && (ch
<= 'S')) {
779 events
.add(new TKeypressEvent(kbF1
));
782 events
.add(new TKeypressEvent(kbF2
));
785 events
.add(new TKeypressEvent(kbF3
));
788 events
.add(new TKeypressEvent(kbF4
));
797 // Unknown keystroke, ignore
802 // Numbers - parameter values
803 if ((ch
>= '0') && (ch
<= '9')) {
804 params
.set(params
.size() - 1,
805 params
.get(params
.size() - 1) + ch
);
806 state
= ParseState
.CSI_PARAM
;
809 // Parameter separator
815 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
819 if (params
.size() > 1) {
820 if (params
.get(1).equals("2")) {
823 if (params
.get(1).equals("5")) {
826 if (params
.get(1).equals("3")) {
830 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
835 if (params
.size() > 1) {
836 if (params
.get(1).equals("2")) {
839 if (params
.get(1).equals("5")) {
842 if (params
.get(1).equals("3")) {
846 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
851 if (params
.size() > 1) {
852 if (params
.get(1).equals("2")) {
855 if (params
.get(1).equals("5")) {
858 if (params
.get(1).equals("3")) {
862 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
867 if (params
.size() > 1) {
868 if (params
.get(1).equals("2")) {
871 if (params
.get(1).equals("5")) {
874 if (params
.get(1).equals("3")) {
878 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
883 events
.add(new TKeypressEvent(kbHome
));
888 events
.add(new TKeypressEvent(kbEnd
));
892 // CBT - Cursor backward X tab stops (default 1)
893 events
.add(new TKeypressEvent(kbBackTab
));
898 state
= ParseState
.MOUSE
;
905 // Unknown keystroke, ignore
910 // Numbers - parameter values
911 if ((ch
>= '0') && (ch
<= '9')) {
912 params
.set(params
.size() - 1,
913 params
.get(params
.size() - 1) + ch
);
914 state
= ParseState
.CSI_PARAM
;
917 // Parameter separator
924 events
.add(csiFnKey());
929 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
933 if (params
.size() > 1) {
934 if (params
.get(1).equals("2")) {
937 if (params
.get(1).equals("5")) {
940 if (params
.get(1).equals("3")) {
944 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
949 if (params
.size() > 1) {
950 if (params
.get(1).equals("2")) {
953 if (params
.get(1).equals("5")) {
956 if (params
.get(1).equals("3")) {
960 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
965 if (params
.size() > 1) {
966 if (params
.get(1).equals("2")) {
969 if (params
.get(1).equals("5")) {
972 if (params
.get(1).equals("3")) {
976 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
981 if (params
.size() > 1) {
982 if (params
.get(1).equals("2")) {
985 if (params
.get(1).equals("5")) {
988 if (params
.get(1).equals("3")) {
992 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
1000 // Unknown keystroke, ignore
1005 params
.set(0, params
.get(params
.size() - 1) + ch
);
1006 if (params
.get(0).length() == 3) {
1007 // We have enough to generate a mouse event
1008 events
.add(parseMouse());
1017 // This "should" be impossible to reach
1022 * Tell (u)xterm that we want alt- keystrokes to send escape + character
1023 * rather than set the 8th bit. Anyone who wants UTF8 should want this
1026 * @param on if true, enable metaSendsEscape
1027 * @return the string to emit to xterm
1029 public String
xtermMetaSendsEscape(final boolean on
) {
1031 return "\033[?1036h\033[?1034l";
1033 return "\033[?1036l";
1037 * Convert a list of SGR parameters into a full escape sequence. This
1038 * also eliminates a trailing ';' which would otherwise reset everything
1039 * to white-on-black not-bold.
1041 * @param str string of parameters, e.g. "31;1;"
1042 * @return the string to emit to an ANSI / ECMA-style terminal,
1045 public String
addHeaderSGR(String str
) {
1046 if (str
.length() > 0) {
1047 // Nix any trailing ';' because that resets all attributes
1048 while (str
.endsWith(":")) {
1049 str
= str
.substring(0, str
.length() - 1);
1052 return "\033[" + str
+ "m";
1056 * Create a SGR parameter sequence for a single color change.
1058 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
1059 * @param foreground if true, this is a foreground color
1060 * @return the string to emit to an ANSI / ECMA-style terminal,
1063 public String
color(final Color color
, final boolean foreground
) {
1064 return color(color
, foreground
, true);
1068 * Create a SGR parameter sequence for a single color change.
1070 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
1071 * @param foreground if true, this is a foreground color
1072 * @param header if true, make the full header, otherwise just emit the
1073 * color parameter e.g. "42;"
1074 * @return the string to emit to an ANSI / ECMA-style terminal,
1077 public String
color(final Color color
, final boolean foreground
,
1078 final boolean header
) {
1080 int ecmaColor
= color
.getValue();
1082 // Convert Color.* values to SGR numerics
1090 return String
.format("\033[%dm", ecmaColor
);
1092 return String
.format("%d;", ecmaColor
);
1097 * Create a SGR parameter sequence for both foreground and
1098 * background color change.
1100 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1101 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1102 * @return the string to emit to an ANSI / ECMA-style terminal,
1103 * e.g. "\033[31;42m"
1105 public String
color(final Color foreColor
, final Color backColor
) {
1106 return color(foreColor
, backColor
, true);
1110 * Create a SGR parameter sequence for both foreground and
1111 * background color change.
1113 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1114 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1115 * @param header if true, make the full header, otherwise just emit the
1116 * color parameter e.g. "31;42;"
1117 * @return the string to emit to an ANSI / ECMA-style terminal,
1118 * e.g. "\033[31;42m"
1120 public String
color(final Color foreColor
, final Color backColor
,
1121 final boolean header
) {
1123 int ecmaForeColor
= foreColor
.getValue();
1124 int ecmaBackColor
= backColor
.getValue();
1126 // Convert Color.* values to SGR numerics
1127 ecmaBackColor
+= 40;
1128 ecmaForeColor
+= 30;
1131 return String
.format("\033[%d;%dm", ecmaForeColor
, ecmaBackColor
);
1133 return String
.format("%d;%d;", ecmaForeColor
, ecmaBackColor
);
1138 * Create a SGR parameter sequence for foreground, background, and
1139 * several attributes. This sequence first resets all attributes to
1140 * default, then sets attributes as per the parameters.
1142 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1143 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1144 * @param bold if true, set bold
1145 * @param reverse if true, set reverse
1146 * @param blink if true, set blink
1147 * @param underline if true, set underline
1148 * @return the string to emit to an ANSI / ECMA-style terminal,
1149 * e.g. "\033[0;1;31;42m"
1151 public String
color(final Color foreColor
, final Color backColor
,
1152 final boolean bold
, final boolean reverse
, final boolean blink
,
1153 final boolean underline
) {
1155 int ecmaForeColor
= foreColor
.getValue();
1156 int ecmaBackColor
= backColor
.getValue();
1158 // Convert Color.* values to SGR numerics
1159 ecmaBackColor
+= 40;
1160 ecmaForeColor
+= 30;
1162 StringBuilder sb
= new StringBuilder();
1163 if ( bold
&& reverse
&& blink
&& !underline
) {
1164 sb
.append("\033[0;1;7;5;");
1165 } else if ( bold
&& reverse
&& !blink
&& !underline
) {
1166 sb
.append("\033[0;1;7;");
1167 } else if ( !bold
&& reverse
&& blink
&& !underline
) {
1168 sb
.append("\033[0;7;5;");
1169 } else if ( bold
&& !reverse
&& blink
&& !underline
) {
1170 sb
.append("\033[0;1;5;");
1171 } else if ( bold
&& !reverse
&& !blink
&& !underline
) {
1172 sb
.append("\033[0;1;");
1173 } else if ( !bold
&& reverse
&& !blink
&& !underline
) {
1174 sb
.append("\033[0;7;");
1175 } else if ( !bold
&& !reverse
&& blink
&& !underline
) {
1176 sb
.append("\033[0;5;");
1177 } else if ( bold
&& reverse
&& blink
&& underline
) {
1178 sb
.append("\033[0;1;7;5;4;");
1179 } else if ( bold
&& reverse
&& !blink
&& underline
) {
1180 sb
.append("\033[0;1;7;4;");
1181 } else if ( !bold
&& reverse
&& blink
&& underline
) {
1182 sb
.append("\033[0;7;5;4;");
1183 } else if ( bold
&& !reverse
&& blink
&& underline
) {
1184 sb
.append("\033[0;1;5;4;");
1185 } else if ( bold
&& !reverse
&& !blink
&& underline
) {
1186 sb
.append("\033[0;1;4;");
1187 } else if ( !bold
&& reverse
&& !blink
&& underline
) {
1188 sb
.append("\033[0;7;4;");
1189 } else if ( !bold
&& !reverse
&& blink
&& underline
) {
1190 sb
.append("\033[0;5;4;");
1191 } else if ( !bold
&& !reverse
&& !blink
&& underline
) {
1192 sb
.append("\033[0;4;");
1194 assert (!bold
&& !reverse
&& !blink
&& !underline
);
1195 sb
.append("\033[0;");
1197 sb
.append(String
.format("%d;%dm", ecmaForeColor
, ecmaBackColor
));
1198 return sb
.toString();
1202 * Create a SGR parameter sequence for enabling reverse color.
1204 * @param on if true, turn on reverse
1205 * @return the string to emit to an ANSI / ECMA-style terminal,
1208 public String
reverse(final boolean on
) {
1216 * Create a SGR parameter sequence to reset to defaults.
1218 * @return the string to emit to an ANSI / ECMA-style terminal,
1221 public String
normal() {
1222 return normal(true);
1226 * Create a SGR parameter sequence to reset to defaults.
1228 * @param header if true, make the full header, otherwise just emit the
1229 * bare parameter e.g. "0;"
1230 * @return the string to emit to an ANSI / ECMA-style terminal,
1233 public String
normal(final boolean header
) {
1235 return "\033[0;37;40m";
1241 * Create a SGR parameter sequence for enabling boldface.
1243 * @param on if true, turn on bold
1244 * @return the string to emit to an ANSI / ECMA-style terminal,
1247 public String
bold(final boolean on
) {
1248 return bold(on
, true);
1252 * Create a SGR parameter sequence for enabling boldface.
1254 * @param on if true, turn on bold
1255 * @param header if true, make the full header, otherwise just emit the
1256 * bare parameter e.g. "1;"
1257 * @return the string to emit to an ANSI / ECMA-style terminal,
1260 public String
bold(final boolean on
, final boolean header
) {
1274 * Create a SGR parameter sequence for enabling blinking text.
1276 * @param on if true, turn on blink
1277 * @return the string to emit to an ANSI / ECMA-style terminal,
1280 public String
blink(final boolean on
) {
1281 return blink(on
, true);
1285 * Create a SGR parameter sequence for enabling blinking text.
1287 * @param on if true, turn on blink
1288 * @param header if true, make the full header, otherwise just emit the
1289 * bare parameter e.g. "5;"
1290 * @return the string to emit to an ANSI / ECMA-style terminal,
1293 public String
blink(final boolean on
, final boolean header
) {
1307 * Create a SGR parameter sequence for enabling underline / underscored
1310 * @param on if true, turn on underline
1311 * @return the string to emit to an ANSI / ECMA-style terminal,
1314 public String
underline(final boolean on
) {
1322 * Create a SGR parameter sequence for enabling the visible cursor.
1324 * @param on if true, turn on cursor
1325 * @return the string to emit to an ANSI / ECMA-style terminal
1327 public String
cursor(final boolean on
) {
1328 if (on
&& !cursorOn
) {
1332 if (!on
&& cursorOn
) {
1340 * Clear the entire screen. Because some terminals use back-color-erase,
1341 * set the color to white-on-black beforehand.
1343 * @return the string to emit to an ANSI / ECMA-style terminal
1345 public String
clearAll() {
1346 return "\033[0;37;40m\033[2J";
1350 * Clear the line from the cursor (inclusive) to the end of the screen.
1351 * Because some terminals use back-color-erase, set the color to
1352 * white-on-black beforehand.
1354 * @return the string to emit to an ANSI / ECMA-style terminal
1356 public String
clearRemainingLine() {
1357 return "\033[0;37;40m\033[K";
1361 * Clear the line up the cursor (inclusive). Because some terminals use
1362 * back-color-erase, set the color to white-on-black beforehand.
1364 * @return the string to emit to an ANSI / ECMA-style terminal
1366 public String
clearPreceedingLine() {
1367 return "\033[0;37;40m\033[1K";
1371 * Clear the line. Because some terminals use back-color-erase, set the
1372 * color to white-on-black beforehand.
1374 * @return the string to emit to an ANSI / ECMA-style terminal
1376 public String
clearLine() {
1377 return "\033[0;37;40m\033[2K";
1381 * Move the cursor to the top-left corner.
1383 * @return the string to emit to an ANSI / ECMA-style terminal
1385 public String
home() {
1390 * Move the cursor to (x, y).
1392 * @param x column coordinate. 0 is the left-most column.
1393 * @param y row coordinate. 0 is the top-most row.
1394 * @return the string to emit to an ANSI / ECMA-style terminal
1396 public String
gotoXY(final int x
, final int y
) {
1397 return String
.format("\033[%d;%dH", y
+ 1, x
+ 1);
1401 * Tell (u)xterm that we want to receive mouse events based on "Any event
1402 * tracking" and UTF-8 coordinates. See
1403 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
1405 * Note that this also sets the alternate/primary screen buffer.
1407 * @param on If true, enable mouse report and use the alternate screen
1408 * buffer. If false disable mouse reporting and use the primary screen
1410 * @return the string to emit to xterm
1412 public String
mouse(final boolean on
) {
1414 return "\033[?1003;1005h\033[?1049h";
1416 return "\033[?1003;1005l\033[?1049l";
1420 * Read function runs on a separate thread.
1423 boolean done
= false;
1424 // available() will often return > 1, so we need to read in chunks to
1426 char [] readBuffer
= new char[128];
1427 List
<TInputEvent
> events
= new LinkedList
<TInputEvent
>();
1429 while (!done
&& !stopReaderThread
) {
1431 // We assume that if inputStream has bytes available, then
1432 // input won't block on read().
1433 int n
= inputStream
.available();
1435 if (readBuffer
.length
< n
) {
1436 // The buffer wasn't big enough, make it huger
1437 readBuffer
= new char[readBuffer
.length
* 2];
1440 int rc
= input
.read(readBuffer
, 0, n
);
1441 // System.err.printf("read() %d", rc); System.err.flush();
1446 for (int i
= 0; i
< rc
; i
++) {
1447 int ch
= readBuffer
[i
];
1448 processChar(events
, (char)ch
);
1449 if (events
.size() > 0) {
1450 // Add to the queue for the backend thread to
1451 // be able to obtain.
1452 synchronized (eventQueue
) {
1453 eventQueue
.addAll(events
);
1455 synchronized (listener
) {
1456 listener
.notifyAll();
1463 getIdleEvents(events
);
1464 if (events
.size() > 0) {
1465 synchronized (eventQueue
) {
1466 eventQueue
.addAll(events
);
1469 synchronized (listener
) {
1470 listener
.notifyAll();
1474 // Wait 10 millis for more data
1477 // System.err.println("end while loop"); System.err.flush();
1478 } catch (InterruptedException e
) {
1480 } catch (IOException e
) {
1481 e
.printStackTrace();
1484 } // while ((done == false) && (stopReaderThread == false))
1485 // System.err.println("*** run() exiting..."); System.err.flush();