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
.bits
.Color
;
50 import jexer
.event
.TInputEvent
;
51 import jexer
.event
.TKeypressEvent
;
52 import jexer
.event
.TMouseEvent
;
53 import jexer
.event
.TResizeEvent
;
54 import jexer
.session
.SessionInfo
;
55 import jexer
.session
.TSessionInfo
;
56 import jexer
.session
.TTYSessionInfo
;
57 import static jexer
.TKeypress
.*;
60 * This class reads keystrokes and mouse events and emits output to ANSI
61 * X3.64 / ECMA-48 type terminals e.g. xterm, linux, vt100, ansi.sys, etc.
63 public final class ECMA48Terminal
implements Runnable
{
66 * The session information.
68 private SessionInfo sessionInfo
;
71 * Getter for sessionInfo.
73 * @return the SessionInfo
75 public SessionInfo
getSessionInfo() {
80 * The event queue, filled up by a thread reading on input.
82 private List
<TInputEvent
> eventQueue
;
85 * If true, we want the reader thread to exit gracefully.
87 private boolean stopReaderThread
;
92 private Thread readerThread
;
95 * Parameters being collected. E.g. if the string is \033[1;3m, then
96 * params[0] will be 1 and params[1] will be 3.
98 private ArrayList
<String
> params
;
101 * States in the input parser.
103 private enum ParseState
{
114 * Current parsing state.
116 private ParseState state
;
119 * The time we entered ESCAPE. If we get a bare escape without a code
120 * following it, this is used to return that bare escape.
122 private long escapeTime
;
125 * The time we last checked the window size. We try not to spawn stty
126 * more than once per second.
128 private long windowSizeTime
;
131 * true if mouse1 was down. Used to report mouse1 on the release event.
133 private boolean mouse1
;
136 * true if mouse2 was down. Used to report mouse2 on the release event.
138 private boolean mouse2
;
141 * true if mouse3 was down. Used to report mouse3 on the release event.
143 private boolean mouse3
;
146 * Cache the cursor visibility value so we only emit the sequence when we
149 private boolean cursorOn
= true;
152 * Cache the last window size to figure out if a TResizeEvent needs to be
155 private TResizeEvent windowResize
= null;
158 * If true, then we changed System.in and need to change it back.
160 private boolean setRawMode
;
163 * The terminal's input. If an InputStream is not specified in the
164 * constructor, then this InputStreamReader will be bound to System.in
165 * with UTF-8 encoding.
167 private Reader input
;
170 * The terminal's raw InputStream. If an InputStream is not specified in
171 * the constructor, then this InputReader will be bound to System.in.
172 * This is used by run() to see if bytes are available() before calling
173 * (Reader)input.read().
175 private InputStream inputStream
;
178 * The terminal's output. If an OutputStream is not specified in the
179 * constructor, then this PrintWriter will be bound to System.out with
182 private PrintWriter output
;
185 * The listening object that run() wakes up on new input.
187 private Object listener
;
190 * Get the output writer.
194 public PrintWriter
getOutput() {
199 * Check if there are events in the queue.
201 * @return if true, getEvents() has something to return to the backend
203 public boolean hasEvents() {
204 synchronized (eventQueue
) {
205 return (eventQueue
.size() > 0);
210 * Call 'stty' to set cooked mode.
212 * <p>Actually executes '/bin/sh -c stty sane cooked < /dev/tty'
214 private void sttyCooked() {
219 * Call 'stty' to set raw mode.
221 * <p>Actually executes '/bin/sh -c stty -ignbrk -brkint -parmrk -istrip
222 * -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten
223 * -parenb cs8 min 1 < /dev/tty'
225 private void sttyRaw() {
230 * Call 'stty' to set raw or cooked mode.
232 * @param mode if true, set raw mode, otherwise set cooked mode
234 private void doStty(final boolean mode
) {
236 "/bin/sh", "-c", "stty -ignbrk -brkint -parmrk -istrip -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten -parenb cs8 min 1 < /dev/tty"
238 String
[] cmdCooked
= {
239 "/bin/sh", "-c", "stty sane cooked < /dev/tty"
244 process
= Runtime
.getRuntime().exec(cmdRaw
);
246 process
= Runtime
.getRuntime().exec(cmdCooked
);
248 BufferedReader in
= new BufferedReader(new InputStreamReader(process
.getInputStream(), "UTF-8"));
249 String line
= in
.readLine();
250 if ((line
!= null) && (line
.length() > 0)) {
251 System
.err
.println("WEIRD?! Normal output from stty: " + line
);
254 BufferedReader err
= new BufferedReader(new InputStreamReader(process
.getErrorStream(), "UTF-8"));
255 line
= err
.readLine();
256 if ((line
!= null) && (line
.length() > 0)) {
257 System
.err
.println("Error output from stty: " + line
);
262 } catch (InterruptedException e
) {
266 int rc
= process
.exitValue();
268 System
.err
.println("stty returned error code: " + rc
);
270 } catch (IOException e
) {
276 * Constructor sets up state for getEvent().
278 * @param listener the object this backend needs to wake up when new
280 * @param input an InputStream connected to the remote user, or null for
281 * System.in. If System.in is used, then on non-Windows systems it will
282 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
283 * mode. input is always converted to a Reader with UTF-8 encoding.
284 * @param output an OutputStream connected to the remote user, or null
285 * for System.out. output is always converted to a Writer with UTF-8
287 * @throws UnsupportedEncodingException if an exception is thrown when
288 * creating the InputStreamReader
290 public ECMA48Terminal(final Object listener
, final InputStream input
,
291 final OutputStream output
) throws UnsupportedEncodingException
{
297 stopReaderThread
= false;
298 this.listener
= listener
;
301 // inputStream = System.in;
302 inputStream
= new FileInputStream(FileDescriptor
.in
);
308 this.input
= new InputStreamReader(inputStream
, "UTF-8");
310 // TODO: include TelnetSocket from NIB and have it implement
312 if (input
instanceof SessionInfo
) {
313 sessionInfo
= (SessionInfo
) input
;
315 if (sessionInfo
== null) {
317 // Reading right off the tty
318 sessionInfo
= new TTYSessionInfo();
320 sessionInfo
= new TSessionInfo();
324 if (output
== null) {
325 this.output
= new PrintWriter(new OutputStreamWriter(System
.out
,
328 this.output
= new PrintWriter(new OutputStreamWriter(output
,
332 // Enable mouse reporting and metaSendsEscape
333 this.output
.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
335 // Hang onto the window size
336 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
337 sessionInfo
.getWindowWidth(), sessionInfo
.getWindowHeight());
339 // Spin up the input reader
340 eventQueue
= new LinkedList
<TInputEvent
>();
341 readerThread
= new Thread(this);
342 readerThread
.start();
346 * Restore terminal to normal state.
348 public void shutdown() {
350 // System.err.println("=== shutdown() ==="); System.err.flush();
352 // Tell the reader thread to stop looking at input
353 stopReaderThread
= true;
356 } catch (InterruptedException e
) {
360 // Disable mouse reporting and show cursor
361 output
.printf("%s%s%s", mouse(false), cursor(true), normal());
367 // We don't close System.in/out
369 // Shut down the streams, this should wake up the reader thread
376 if (output
!= null) {
380 } catch (IOException e
) {
389 public void flush() {
394 * Reset keyboard/mouse input parser.
396 private void reset() {
397 state
= ParseState
.GROUND
;
398 params
= new ArrayList
<String
>();
404 * Produce a control character or one of the special ones (ENTER, TAB,
407 * @param ch Unicode code point
408 * @param alt if true, set alt on the TKeypress
409 * @return one TKeypress event, either a control character (e.g. isKey ==
410 * false, ch == 'A', ctrl == true), or a special key (e.g. isKey == true,
413 private TKeypressEvent
controlChar(final char ch
, final boolean alt
) {
414 // System.err.printf("controlChar: %02x\n", ch);
418 // Carriage return --> ENTER
419 return new TKeypressEvent(kbEnter
, alt
, false, false);
421 // Linefeed --> ENTER
422 return new TKeypressEvent(kbEnter
, alt
, false, false);
425 return new TKeypressEvent(kbEsc
, alt
, false, false);
428 return new TKeypressEvent(kbTab
, alt
, false, false);
430 // Make all other control characters come back as the alphabetic
431 // character with the ctrl field set. So SOH would be 'A' +
433 return new TKeypressEvent(false, 0, (char)(ch
+ 0x40),
439 * Produce special key from CSI Pn ; Pm ; ... ~
441 * @return one KEYPRESS event representing a special key
443 private TInputEvent
csiFnKey() {
446 if (params
.size() > 0) {
447 key
= Integer
.parseInt(params
.get(0));
449 if (params
.size() > 1) {
450 modifier
= Integer
.parseInt(params
.get(1));
453 boolean ctrl
= false;
454 boolean shift
= false;
473 // Unknown modifier, bail out
479 return new TKeypressEvent(kbHome
, alt
, ctrl
, shift
);
481 return new TKeypressEvent(kbIns
, alt
, ctrl
, shift
);
483 return new TKeypressEvent(kbDel
, alt
, ctrl
, shift
);
485 return new TKeypressEvent(kbEnd
, alt
, ctrl
, shift
);
487 return new TKeypressEvent(kbPgUp
, alt
, ctrl
, shift
);
489 return new TKeypressEvent(kbPgDn
, alt
, ctrl
, shift
);
491 return new TKeypressEvent(kbF5
, alt
, ctrl
, shift
);
493 return new TKeypressEvent(kbF6
, alt
, ctrl
, shift
);
495 return new TKeypressEvent(kbF7
, alt
, ctrl
, shift
);
497 return new TKeypressEvent(kbF8
, alt
, ctrl
, shift
);
499 return new TKeypressEvent(kbF9
, alt
, ctrl
, shift
);
501 return new TKeypressEvent(kbF10
, alt
, ctrl
, shift
);
503 return new TKeypressEvent(kbF11
, alt
, ctrl
, shift
);
505 return new TKeypressEvent(kbF12
, alt
, ctrl
, shift
);
513 * Produce mouse events based on "Any event tracking" and UTF-8
515 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
517 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
519 private TInputEvent
parseMouse() {
520 int buttons
= params
.get(0).charAt(0) - 32;
521 int x
= params
.get(0).charAt(1) - 32 - 1;
522 int y
= params
.get(0).charAt(2) - 32 - 1;
524 // Clamp X and Y to the physical screen coordinates.
525 if (x
>= windowResize
.getWidth()) {
526 x
= windowResize
.getWidth() - 1;
528 if (y
>= windowResize
.getHeight()) {
529 y
= windowResize
.getHeight() - 1;
532 TMouseEvent
.Type eventType
= TMouseEvent
.Type
.MOUSE_DOWN
;
533 boolean eventMouse1
= false;
534 boolean eventMouse2
= false;
535 boolean eventMouse3
= false;
536 boolean eventMouseWheelUp
= false;
537 boolean eventMouseWheelDown
= false;
539 // System.err.printf("buttons: %04x\r\n", buttons);
556 if (!mouse1
&& !mouse2
&& !mouse3
) {
557 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
559 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
576 // Dragging with mouse1 down
579 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
583 // Dragging with mouse2 down
586 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
590 // Dragging with mouse3 down
593 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
597 // Dragging with mouse2 down after wheelUp
600 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
604 // Dragging with mouse2 down after wheelDown
607 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
611 eventMouseWheelUp
= true;
615 eventMouseWheelDown
= true;
619 // Unknown, just make it motion
620 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
623 return new TMouseEvent(eventType
, x
, y
, x
, y
,
624 eventMouse1
, eventMouse2
, eventMouse3
,
625 eventMouseWheelUp
, eventMouseWheelDown
);
629 * Return any events in the IO queue.
631 * @param queue list to append new events to
633 public void getEvents(final List
<TInputEvent
> queue
) {
634 synchronized (eventQueue
) {
635 if (eventQueue
.size() > 0) {
636 synchronized (queue
) {
637 queue
.addAll(eventQueue
);
645 * Return any events in the IO queue due to timeout.
647 * @param queue list to append new events to
649 private void getIdleEvents(final List
<TInputEvent
> queue
) {
650 Date now
= new Date();
652 // Check for new window size
653 long windowSizeDelay
= now
.getTime() - windowSizeTime
;
654 if (windowSizeDelay
> 1000) {
655 sessionInfo
.queryWindowSize();
656 int newWidth
= sessionInfo
.getWindowWidth();
657 int newHeight
= sessionInfo
.getWindowHeight();
658 if ((newWidth
!= windowResize
.getWidth())
659 || (newHeight
!= windowResize
.getHeight())
661 TResizeEvent event
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
662 newWidth
, newHeight
);
663 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
664 newWidth
, newHeight
);
667 windowSizeTime
= now
.getTime();
670 // ESCDELAY type timeout
671 if (state
== ParseState
.ESCAPE
) {
672 long escDelay
= now
.getTime() - escapeTime
;
673 if (escDelay
> 100) {
674 // After 0.1 seconds, assume a true escape character
675 queue
.add(controlChar((char)0x1B, false));
682 * Parses the next character of input to see if an InputEvent is
685 * @param events list to append new events to
686 * @param ch Unicode code point
688 private void processChar(final List
<TInputEvent
> events
, final char ch
) {
690 // ESCDELAY type timeout
691 Date now
= new Date();
692 if (state
== ParseState
.ESCAPE
) {
693 long escDelay
= now
.getTime() - escapeTime
;
694 if (escDelay
> 250) {
695 // After 0.25 seconds, assume a true escape character
696 events
.add(controlChar((char)0x1B, false));
702 boolean ctrl
= false;
704 boolean shift
= false;
706 // System.err.printf("state: %s ch %c\r\n", state, ch);
712 state
= ParseState
.ESCAPE
;
713 escapeTime
= now
.getTime();
719 events
.add(controlChar(ch
, false));
726 events
.add(new TKeypressEvent(false, 0, ch
,
727 false, false, false));
736 // ALT-Control character
737 events
.add(controlChar(ch
, true));
743 // This will be one of the function keys
744 state
= ParseState
.ESCAPE_INTERMEDIATE
;
748 // '[' goes to CSI_ENTRY
750 state
= ParseState
.CSI_ENTRY
;
754 // Everything else is assumed to be Alt-keystroke
755 if ((ch
>= 'A') && (ch
<= 'Z')) {
759 events
.add(new TKeypressEvent(false, 0, ch
, alt
, ctrl
, shift
));
763 case ESCAPE_INTERMEDIATE
:
764 if ((ch
>= 'P') && (ch
<= 'S')) {
768 events
.add(new TKeypressEvent(kbF1
));
771 events
.add(new TKeypressEvent(kbF2
));
774 events
.add(new TKeypressEvent(kbF3
));
777 events
.add(new TKeypressEvent(kbF4
));
786 // Unknown keystroke, ignore
791 // Numbers - parameter values
792 if ((ch
>= '0') && (ch
<= '9')) {
793 params
.set(params
.size() - 1,
794 params
.get(params
.size() - 1) + ch
);
795 state
= ParseState
.CSI_PARAM
;
798 // Parameter separator
804 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
808 if (params
.size() > 1) {
809 if (params
.get(1).equals("2")) {
812 if (params
.get(1).equals("5")) {
815 if (params
.get(1).equals("3")) {
819 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
824 if (params
.size() > 1) {
825 if (params
.get(1).equals("2")) {
828 if (params
.get(1).equals("5")) {
831 if (params
.get(1).equals("3")) {
835 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
840 if (params
.size() > 1) {
841 if (params
.get(1).equals("2")) {
844 if (params
.get(1).equals("5")) {
847 if (params
.get(1).equals("3")) {
851 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
856 if (params
.size() > 1) {
857 if (params
.get(1).equals("2")) {
860 if (params
.get(1).equals("5")) {
863 if (params
.get(1).equals("3")) {
867 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
872 events
.add(new TKeypressEvent(kbHome
));
877 events
.add(new TKeypressEvent(kbEnd
));
881 // CBT - Cursor backward X tab stops (default 1)
882 events
.add(new TKeypressEvent(kbBackTab
));
887 state
= ParseState
.MOUSE
;
894 // Unknown keystroke, ignore
899 // Numbers - parameter values
900 if ((ch
>= '0') && (ch
<= '9')) {
901 params
.set(params
.size() - 1,
902 params
.get(params
.size() - 1) + ch
);
903 state
= ParseState
.CSI_PARAM
;
906 // Parameter separator
913 events
.add(csiFnKey());
918 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
922 if (params
.size() > 1) {
923 if (params
.get(1).equals("2")) {
926 if (params
.get(1).equals("5")) {
929 if (params
.get(1).equals("3")) {
933 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
938 if (params
.size() > 1) {
939 if (params
.get(1).equals("2")) {
942 if (params
.get(1).equals("5")) {
945 if (params
.get(1).equals("3")) {
949 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
954 if (params
.size() > 1) {
955 if (params
.get(1).equals("2")) {
958 if (params
.get(1).equals("5")) {
961 if (params
.get(1).equals("3")) {
965 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
970 if (params
.size() > 1) {
971 if (params
.get(1).equals("2")) {
974 if (params
.get(1).equals("5")) {
977 if (params
.get(1).equals("3")) {
981 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
989 // Unknown keystroke, ignore
994 params
.set(0, params
.get(params
.size() - 1) + ch
);
995 if (params
.get(0).length() == 3) {
996 // We have enough to generate a mouse event
997 events
.add(parseMouse());
1006 // This "should" be impossible to reach
1011 * Tell (u)xterm that we want alt- keystrokes to send escape + character
1012 * rather than set the 8th bit. Anyone who wants UTF8 should want this
1015 * @param on if true, enable metaSendsEscape
1016 * @return the string to emit to xterm
1018 public String
xtermMetaSendsEscape(final boolean on
) {
1020 return "\033[?1036h\033[?1034l";
1022 return "\033[?1036l";
1026 * Convert a list of SGR parameters into a full escape sequence. This
1027 * also eliminates a trailing ';' which would otherwise reset everything
1028 * to white-on-black not-bold.
1030 * @param str string of parameters, e.g. "31;1;"
1031 * @return the string to emit to an ANSI / ECMA-style terminal,
1034 public String
addHeaderSGR(String str
) {
1035 if (str
.length() > 0) {
1036 // Nix any trailing ';' because that resets all attributes
1037 while (str
.endsWith(":")) {
1038 str
= str
.substring(0, str
.length() - 1);
1041 return "\033[" + str
+ "m";
1045 * Create a SGR parameter sequence for a single color change.
1047 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
1048 * @param foreground if true, this is a foreground color
1049 * @return the string to emit to an ANSI / ECMA-style terminal,
1052 public String
color(final Color color
, final boolean foreground
) {
1053 return color(color
, foreground
, true);
1057 * Create a SGR parameter sequence for a single color change.
1059 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
1060 * @param foreground if true, this is a foreground color
1061 * @param header if true, make the full header, otherwise just emit the
1062 * color parameter e.g. "42;"
1063 * @return the string to emit to an ANSI / ECMA-style terminal,
1066 public String
color(final Color color
, final boolean foreground
,
1067 final boolean header
) {
1069 int ecmaColor
= color
.getValue();
1071 // Convert Color.* values to SGR numerics
1079 return String
.format("\033[%dm", ecmaColor
);
1081 return String
.format("%d;", ecmaColor
);
1086 * Create a SGR parameter sequence for both foreground and
1087 * background color change.
1089 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1090 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1091 * @return the string to emit to an ANSI / ECMA-style terminal,
1092 * e.g. "\033[31;42m"
1094 public String
color(final Color foreColor
, final Color backColor
) {
1095 return color(foreColor
, backColor
, true);
1099 * Create a SGR parameter sequence for both foreground and
1100 * background color change.
1102 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1103 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1104 * @param header if true, make the full header, otherwise just emit the
1105 * color parameter e.g. "31;42;"
1106 * @return the string to emit to an ANSI / ECMA-style terminal,
1107 * e.g. "\033[31;42m"
1109 public String
color(final Color foreColor
, final Color backColor
,
1110 final boolean header
) {
1112 int ecmaForeColor
= foreColor
.getValue();
1113 int ecmaBackColor
= backColor
.getValue();
1115 // Convert Color.* values to SGR numerics
1116 ecmaBackColor
+= 40;
1117 ecmaForeColor
+= 30;
1120 return String
.format("\033[%d;%dm", ecmaForeColor
, ecmaBackColor
);
1122 return String
.format("%d;%d;", ecmaForeColor
, ecmaBackColor
);
1127 * Create a SGR parameter sequence for foreground, background, and
1128 * several attributes. This sequence first resets all attributes to
1129 * default, then sets attributes as per the parameters.
1131 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1132 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1133 * @param bold if true, set bold
1134 * @param reverse if true, set reverse
1135 * @param blink if true, set blink
1136 * @param underline if true, set underline
1137 * @return the string to emit to an ANSI / ECMA-style terminal,
1138 * e.g. "\033[0;1;31;42m"
1140 public String
color(final Color foreColor
, final Color backColor
,
1141 final boolean bold
, final boolean reverse
, final boolean blink
,
1142 final boolean underline
) {
1144 int ecmaForeColor
= foreColor
.getValue();
1145 int ecmaBackColor
= backColor
.getValue();
1147 // Convert Color.* values to SGR numerics
1148 ecmaBackColor
+= 40;
1149 ecmaForeColor
+= 30;
1151 StringBuilder sb
= new StringBuilder();
1152 if ( bold
&& reverse
&& blink
&& !underline
) {
1153 sb
.append("\033[0;1;7;5;");
1154 } else if ( bold
&& reverse
&& !blink
&& !underline
) {
1155 sb
.append("\033[0;1;7;");
1156 } else if ( !bold
&& reverse
&& blink
&& !underline
) {
1157 sb
.append("\033[0;7;5;");
1158 } else if ( bold
&& !reverse
&& blink
&& !underline
) {
1159 sb
.append("\033[0;1;5;");
1160 } else if ( bold
&& !reverse
&& !blink
&& !underline
) {
1161 sb
.append("\033[0;1;");
1162 } else if ( !bold
&& reverse
&& !blink
&& !underline
) {
1163 sb
.append("\033[0;7;");
1164 } else if ( !bold
&& !reverse
&& blink
&& !underline
) {
1165 sb
.append("\033[0;5;");
1166 } else if ( bold
&& reverse
&& blink
&& underline
) {
1167 sb
.append("\033[0;1;7;5;4;");
1168 } else if ( bold
&& reverse
&& !blink
&& underline
) {
1169 sb
.append("\033[0;1;7;4;");
1170 } else if ( !bold
&& reverse
&& blink
&& underline
) {
1171 sb
.append("\033[0;7;5;4;");
1172 } else if ( bold
&& !reverse
&& blink
&& underline
) {
1173 sb
.append("\033[0;1;5;4;");
1174 } else if ( bold
&& !reverse
&& !blink
&& underline
) {
1175 sb
.append("\033[0;1;4;");
1176 } else if ( !bold
&& reverse
&& !blink
&& underline
) {
1177 sb
.append("\033[0;7;4;");
1178 } else if ( !bold
&& !reverse
&& blink
&& underline
) {
1179 sb
.append("\033[0;5;4;");
1180 } else if ( !bold
&& !reverse
&& !blink
&& underline
) {
1181 sb
.append("\033[0;4;");
1183 assert (!bold
&& !reverse
&& !blink
&& !underline
);
1184 sb
.append("\033[0;");
1186 sb
.append(String
.format("%d;%dm", ecmaForeColor
, ecmaBackColor
));
1187 return sb
.toString();
1191 * Create a SGR parameter sequence for enabling reverse color.
1193 * @param on if true, turn on reverse
1194 * @return the string to emit to an ANSI / ECMA-style terminal,
1197 public String
reverse(final boolean on
) {
1205 * Create a SGR parameter sequence to reset to defaults.
1207 * @return the string to emit to an ANSI / ECMA-style terminal,
1210 public String
normal() {
1211 return normal(true);
1215 * Create a SGR parameter sequence to reset to defaults.
1217 * @param header if true, make the full header, otherwise just emit the
1218 * bare parameter e.g. "0;"
1219 * @return the string to emit to an ANSI / ECMA-style terminal,
1222 public String
normal(final boolean header
) {
1224 return "\033[0;37;40m";
1230 * Create a SGR parameter sequence for enabling boldface.
1232 * @param on if true, turn on bold
1233 * @return the string to emit to an ANSI / ECMA-style terminal,
1236 public String
bold(final boolean on
) {
1237 return bold(on
, true);
1241 * Create a SGR parameter sequence for enabling boldface.
1243 * @param on if true, turn on bold
1244 * @param header if true, make the full header, otherwise just emit the
1245 * bare parameter e.g. "1;"
1246 * @return the string to emit to an ANSI / ECMA-style terminal,
1249 public String
bold(final boolean on
, final boolean header
) {
1263 * Create a SGR parameter sequence for enabling blinking text.
1265 * @param on if true, turn on blink
1266 * @return the string to emit to an ANSI / ECMA-style terminal,
1269 public String
blink(final boolean on
) {
1270 return blink(on
, true);
1274 * Create a SGR parameter sequence for enabling blinking text.
1276 * @param on if true, turn on blink
1277 * @param header if true, make the full header, otherwise just emit the
1278 * bare parameter e.g. "5;"
1279 * @return the string to emit to an ANSI / ECMA-style terminal,
1282 public String
blink(final boolean on
, final boolean header
) {
1296 * Create a SGR parameter sequence for enabling underline / underscored
1299 * @param on if true, turn on underline
1300 * @return the string to emit to an ANSI / ECMA-style terminal,
1303 public String
underline(final boolean on
) {
1311 * Create a SGR parameter sequence for enabling the visible cursor.
1313 * @param on if true, turn on cursor
1314 * @return the string to emit to an ANSI / ECMA-style terminal
1316 public String
cursor(final boolean on
) {
1317 if (on
&& !cursorOn
) {
1321 if (!on
&& cursorOn
) {
1329 * Clear the entire screen. Because some terminals use back-color-erase,
1330 * set the color to white-on-black beforehand.
1332 * @return the string to emit to an ANSI / ECMA-style terminal
1334 public String
clearAll() {
1335 return "\033[0;37;40m\033[2J";
1339 * Clear the line from the cursor (inclusive) to the end of the screen.
1340 * Because some terminals use back-color-erase, set the color to
1341 * white-on-black beforehand.
1343 * @return the string to emit to an ANSI / ECMA-style terminal
1345 public String
clearRemainingLine() {
1346 return "\033[0;37;40m\033[K";
1350 * Clear the line up the cursor (inclusive). Because some terminals use
1351 * back-color-erase, set the color to white-on-black beforehand.
1353 * @return the string to emit to an ANSI / ECMA-style terminal
1355 public String
clearPreceedingLine() {
1356 return "\033[0;37;40m\033[1K";
1360 * Clear the line. Because some terminals use back-color-erase, set the
1361 * color to white-on-black beforehand.
1363 * @return the string to emit to an ANSI / ECMA-style terminal
1365 public String
clearLine() {
1366 return "\033[0;37;40m\033[2K";
1370 * Move the cursor to the top-left corner.
1372 * @return the string to emit to an ANSI / ECMA-style terminal
1374 public String
home() {
1379 * Move the cursor to (x, y).
1381 * @param x column coordinate. 0 is the left-most column.
1382 * @param y row coordinate. 0 is the top-most row.
1383 * @return the string to emit to an ANSI / ECMA-style terminal
1385 public String
gotoXY(final int x
, final int y
) {
1386 return String
.format("\033[%d;%dH", y
+ 1, x
+ 1);
1390 * Tell (u)xterm that we want to receive mouse events based on "Any event
1391 * tracking" and UTF-8 coordinates. See
1392 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
1394 * Note that this also sets the alternate/primary screen buffer.
1396 * @param on If true, enable mouse report and use the alternate screen
1397 * buffer. If false disable mouse reporting and use the primary screen
1399 * @return the string to emit to xterm
1401 public String
mouse(final boolean on
) {
1403 return "\033[?1003;1005h\033[?1049h";
1405 return "\033[?1003;1005l\033[?1049l";
1409 * Read function runs on a separate thread.
1412 boolean done
= false;
1413 // available() will often return > 1, so we need to read in chunks to
1415 char [] readBuffer
= new char[128];
1416 List
<TInputEvent
> events
= new LinkedList
<TInputEvent
>();
1418 while (!done
&& !stopReaderThread
) {
1420 // We assume that if inputStream has bytes available, then
1421 // input won't block on read().
1422 int n
= inputStream
.available();
1424 if (readBuffer
.length
< n
) {
1425 // The buffer wasn't big enough, make it huger
1426 readBuffer
= new char[readBuffer
.length
* 2];
1429 int rc
= input
.read(readBuffer
, 0, readBuffer
.length
);
1430 // System.err.printf("read() %d", rc); System.err.flush();
1435 for (int i
= 0; i
< rc
; i
++) {
1436 int ch
= readBuffer
[i
];
1437 processChar(events
, (char)ch
);
1438 if (events
.size() > 0) {
1439 // Add to the queue for the backend thread to
1440 // be able to obtain.
1441 synchronized (eventQueue
) {
1442 eventQueue
.addAll(events
);
1444 synchronized (listener
) {
1445 listener
.notifyAll();
1452 getIdleEvents(events
);
1453 if (events
.size() > 0) {
1454 synchronized (eventQueue
) {
1455 eventQueue
.addAll(events
);
1458 synchronized (listener
) {
1459 listener
.notifyAll();
1463 // Wait 10 millis for more data
1466 // System.err.println("end while loop"); System.err.flush();
1467 } catch (InterruptedException e
) {
1469 } catch (IOException e
) {
1470 e
.printStackTrace();
1473 } // while ((done == false) && (stopReaderThread == false))
1474 // System.err.println("*** run() exiting..."); System.err.flush();