2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2017 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]
29 package jexer
.backend
;
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
.Cell
;
48 import jexer
.bits
.CellAttributes
;
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 static jexer
.TKeypress
.*;
57 * This class reads keystrokes and mouse events and emits output to ANSI
58 * X3.64 / ECMA-48 type terminals e.g. xterm, linux, vt100, ansi.sys, etc.
60 public final class ECMA48Terminal
extends LogicalScreen
61 implements TerminalReader
, Runnable
{
64 * Emit debugging to stderr.
66 private boolean debugToStderr
= false;
69 * If true, emit T.416-style RGB colors. This is a) expensive in
70 * bandwidth, and b) potentially terrible looking for non-xterms.
72 private static boolean doRgbColor
= false;
75 * The session information.
77 private SessionInfo sessionInfo
;
80 * Getter for sessionInfo.
82 * @return the SessionInfo
84 public SessionInfo
getSessionInfo() {
89 * The event queue, filled up by a thread reading on input.
91 private List
<TInputEvent
> eventQueue
;
94 * If true, we want the reader thread to exit gracefully.
96 private boolean stopReaderThread
;
101 private Thread readerThread
;
104 * Parameters being collected. E.g. if the string is \033[1;3m, then
105 * params[0] will be 1 and params[1] will be 3.
107 private ArrayList
<String
> params
;
110 * States in the input parser.
112 private enum ParseState
{
123 * Current parsing state.
125 private ParseState state
;
128 * The time we entered ESCAPE. If we get a bare escape without a code
129 * following it, this is used to return that bare escape.
131 private long escapeTime
;
134 * The time we last checked the window size. We try not to spawn stty
135 * more than once per second.
137 private long windowSizeTime
;
140 * true if mouse1 was down. Used to report mouse1 on the release event.
142 private boolean mouse1
;
145 * true if mouse2 was down. Used to report mouse2 on the release event.
147 private boolean mouse2
;
150 * true if mouse3 was down. Used to report mouse3 on the release event.
152 private boolean mouse3
;
155 * Cache the cursor visibility value so we only emit the sequence when we
158 private boolean cursorOn
= true;
161 * Cache the last window size to figure out if a TResizeEvent needs to be
164 private TResizeEvent windowResize
= null;
167 * If true, then we changed System.in and need to change it back.
169 private boolean setRawMode
;
172 * The terminal's input. If an InputStream is not specified in the
173 * constructor, then this InputStreamReader will be bound to System.in
174 * with UTF-8 encoding.
176 private Reader input
;
179 * The terminal's raw InputStream. If an InputStream is not specified in
180 * the constructor, then this InputReader will be bound to System.in.
181 * This is used by run() to see if bytes are available() before calling
182 * (Reader)input.read().
184 private InputStream inputStream
;
187 * The terminal's output. If an OutputStream is not specified in the
188 * constructor, then this PrintWriter will be bound to System.out with
191 private PrintWriter output
;
194 * The listening object that run() wakes up on new input.
196 private Object listener
;
199 * Set listener to a different Object.
201 * @param listener the new listening object that run() wakes up on new
204 public void setListener(final Object listener
) {
205 this.listener
= listener
;
209 * Get the output writer.
213 public PrintWriter
getOutput() {
218 * Check if there are events in the queue.
220 * @return if true, getEvents() has something to return to the backend
222 public boolean hasEvents() {
223 synchronized (eventQueue
) {
224 return (eventQueue
.size() > 0);
229 * Call 'stty' to set cooked mode.
231 * <p>Actually executes '/bin/sh -c stty sane cooked < /dev/tty'
233 private void sttyCooked() {
238 * Call 'stty' to set raw mode.
240 * <p>Actually executes '/bin/sh -c stty -ignbrk -brkint -parmrk -istrip
241 * -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten
242 * -parenb cs8 min 1 < /dev/tty'
244 private void sttyRaw() {
249 * Call 'stty' to set raw or cooked mode.
251 * @param mode if true, set raw mode, otherwise set cooked mode
253 private void doStty(final boolean mode
) {
255 "/bin/sh", "-c", "stty -ignbrk -brkint -parmrk -istrip -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten -parenb cs8 min 1 < /dev/tty"
257 String
[] cmdCooked
= {
258 "/bin/sh", "-c", "stty sane cooked < /dev/tty"
263 process
= Runtime
.getRuntime().exec(cmdRaw
);
265 process
= Runtime
.getRuntime().exec(cmdCooked
);
267 BufferedReader in
= new BufferedReader(new InputStreamReader(process
.getInputStream(), "UTF-8"));
268 String line
= in
.readLine();
269 if ((line
!= null) && (line
.length() > 0)) {
270 System
.err
.println("WEIRD?! Normal output from stty: " + line
);
273 BufferedReader err
= new BufferedReader(new InputStreamReader(process
.getErrorStream(), "UTF-8"));
274 line
= err
.readLine();
275 if ((line
!= null) && (line
.length() > 0)) {
276 System
.err
.println("Error output from stty: " + line
);
281 } catch (InterruptedException e
) {
285 int rc
= process
.exitValue();
287 System
.err
.println("stty returned error code: " + rc
);
289 } catch (IOException e
) {
295 * Constructor sets up state for getEvent().
297 * @param listener the object this backend needs to wake up when new
299 * @param input an InputStream connected to the remote user, or null for
300 * System.in. If System.in is used, then on non-Windows systems it will
301 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
302 * mode. input is always converted to a Reader with UTF-8 encoding.
303 * @param output an OutputStream connected to the remote user, or null
304 * for System.out. output is always converted to a Writer with UTF-8
306 * @throws UnsupportedEncodingException if an exception is thrown when
307 * creating the InputStreamReader
309 public ECMA48Terminal(final Object listener
, final InputStream input
,
310 final OutputStream output
) throws UnsupportedEncodingException
{
316 stopReaderThread
= false;
317 this.listener
= listener
;
320 // inputStream = System.in;
321 inputStream
= new FileInputStream(FileDescriptor
.in
);
327 this.input
= new InputStreamReader(inputStream
, "UTF-8");
329 if (input
instanceof SessionInfo
) {
330 // This is a TelnetInputStream that exposes window size and
331 // environment variables from the telnet layer.
332 sessionInfo
= (SessionInfo
) input
;
334 if (sessionInfo
== null) {
336 // Reading right off the tty
337 sessionInfo
= new TTYSessionInfo();
339 sessionInfo
= new TSessionInfo();
343 if (output
== null) {
344 this.output
= new PrintWriter(new OutputStreamWriter(System
.out
,
347 this.output
= new PrintWriter(new OutputStreamWriter(output
,
351 // Enable mouse reporting and metaSendsEscape
352 this.output
.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
355 // Query the screen size
356 sessionInfo
.queryWindowSize();
357 setDimensions(sessionInfo
.getWindowWidth(),
358 sessionInfo
.getWindowHeight());
360 // Hang onto the window size
361 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
362 sessionInfo
.getWindowWidth(), sessionInfo
.getWindowHeight());
364 // Permit RGB colors only if externally requested
365 if (System
.getProperty("jexer.ECMA48.rgbColor") != null) {
366 if (System
.getProperty("jexer.ECMA48.rgbColor").equals("true")) {
373 // Spin up the input reader
374 eventQueue
= new LinkedList
<TInputEvent
>();
375 readerThread
= new Thread(this);
376 readerThread
.start();
379 this.output
.write(clearAll());
384 * Constructor sets up state for getEvent().
386 * @param listener the object this backend needs to wake up when new
388 * @param input the InputStream underlying 'reader'. Its available()
389 * method is used to determine if reader.read() will block or not.
390 * @param reader a Reader connected to the remote user.
391 * @param writer a PrintWriter connected to the remote user.
392 * @param setRawMode if true, set System.in into raw mode with stty.
393 * This should in general not be used. It is here solely for Demo3,
394 * which uses System.in.
395 * @throws IllegalArgumentException if input, reader, or writer are null.
397 public ECMA48Terminal(final Object listener
, final InputStream input
,
398 final Reader reader
, final PrintWriter writer
,
399 final boolean setRawMode
) {
402 throw new IllegalArgumentException("InputStream must be specified");
404 if (reader
== null) {
405 throw new IllegalArgumentException("Reader must be specified");
407 if (writer
== null) {
408 throw new IllegalArgumentException("Writer must be specified");
414 stopReaderThread
= false;
415 this.listener
= listener
;
420 if (setRawMode
== true) {
423 this.setRawMode
= setRawMode
;
425 if (input
instanceof SessionInfo
) {
426 // This is a TelnetInputStream that exposes window size and
427 // environment variables from the telnet layer.
428 sessionInfo
= (SessionInfo
) input
;
430 if (sessionInfo
== null) {
431 if (setRawMode
== true) {
432 // Reading right off the tty
433 sessionInfo
= new TTYSessionInfo();
435 sessionInfo
= new TSessionInfo();
439 this.output
= writer
;
441 // Enable mouse reporting and metaSendsEscape
442 this.output
.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
445 // Query the screen size
446 sessionInfo
.queryWindowSize();
447 setDimensions(sessionInfo
.getWindowWidth(),
448 sessionInfo
.getWindowHeight());
450 // Hang onto the window size
451 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
452 sessionInfo
.getWindowWidth(), sessionInfo
.getWindowHeight());
454 // Permit RGB colors only if externally requested
455 if (System
.getProperty("jexer.ECMA48.rgbColor") != null) {
456 if (System
.getProperty("jexer.ECMA48.rgbColor").equals("true")) {
463 // Spin up the input reader
464 eventQueue
= new LinkedList
<TInputEvent
>();
465 readerThread
= new Thread(this);
466 readerThread
.start();
469 this.output
.write(clearAll());
474 * Constructor sets up state for getEvent().
476 * @param listener the object this backend needs to wake up when new
478 * @param input the InputStream underlying 'reader'. Its available()
479 * method is used to determine if reader.read() will block or not.
480 * @param reader a Reader connected to the remote user.
481 * @param writer a PrintWriter connected to the remote user.
482 * @throws IllegalArgumentException if input, reader, or writer are null.
484 public ECMA48Terminal(final Object listener
, final InputStream input
,
485 final Reader reader
, final PrintWriter writer
) {
487 this(listener
, input
, reader
, writer
, false);
491 * Restore terminal to normal state.
493 public void closeTerminal() {
495 // System.err.println("=== shutdown() ==="); System.err.flush();
497 // Tell the reader thread to stop looking at input
498 stopReaderThread
= true;
501 } catch (InterruptedException e
) {
505 // Disable mouse reporting and show cursor
506 output
.printf("%s%s%s", mouse(false), cursor(true), normal());
512 // We don't close System.in/out
514 // Shut down the streams, this should wake up the reader thread
521 if (output
!= null) {
525 } catch (IOException e
) {
534 public void flush() {
539 * Perform a somewhat-optimal rendering of a line.
541 * @param y row coordinate. 0 is the top-most row.
542 * @param sb StringBuilder to write escape sequences to
543 * @param lastAttr cell attributes from the last call to flushLine
545 private void flushLine(final int y
, final StringBuilder sb
,
546 CellAttributes lastAttr
) {
550 for (int x
= 0; x
< width
; x
++) {
551 Cell lCell
= logical
[x
][y
];
552 if (!lCell
.isBlank()) {
556 // Push textEnd to first column beyond the text area
560 // reallyCleared = true;
562 for (int x
= 0; x
< width
; x
++) {
563 Cell lCell
= logical
[x
][y
];
564 Cell pCell
= physical
[x
][y
];
566 if (!lCell
.equals(pCell
) || reallyCleared
) {
569 System
.err
.printf("\n--\n");
570 System
.err
.printf(" Y: %d X: %d\n", y
, x
);
571 System
.err
.printf(" lCell: %s\n", lCell
);
572 System
.err
.printf(" pCell: %s\n", pCell
);
573 System
.err
.printf(" ==== \n");
576 if (lastAttr
== null) {
577 lastAttr
= new CellAttributes();
582 if ((lastX
!= (x
- 1)) || (lastX
== -1)) {
583 // Advancing at least one cell, or the first gotoXY
584 sb
.append(gotoXY(x
, y
));
587 assert (lastAttr
!= null);
589 if ((x
== textEnd
) && (textEnd
< width
- 1)) {
590 assert (lCell
.isBlank());
592 for (int i
= x
; i
< width
; i
++) {
593 assert (logical
[i
][y
].isBlank());
594 // Physical is always updated
595 physical
[i
][y
].reset();
598 // Clear remaining line
599 sb
.append(clearRemainingLine());
604 // Now emit only the modified attributes
605 if ((lCell
.getForeColor() != lastAttr
.getForeColor())
606 && (lCell
.getBackColor() != lastAttr
.getBackColor())
607 && (lCell
.isBold() == lastAttr
.isBold())
608 && (lCell
.isReverse() == lastAttr
.isReverse())
609 && (lCell
.isUnderline() == lastAttr
.isUnderline())
610 && (lCell
.isBlink() == lastAttr
.isBlink())
612 // Both colors changed, attributes the same
613 sb
.append(color(lCell
.isBold(),
614 lCell
.getForeColor(), lCell
.getBackColor()));
617 System
.err
.printf("1 Change only fore/back colors\n");
619 } else if ((lCell
.getForeColor() != lastAttr
.getForeColor())
620 && (lCell
.getBackColor() != lastAttr
.getBackColor())
621 && (lCell
.isBold() != lastAttr
.isBold())
622 && (lCell
.isReverse() != lastAttr
.isReverse())
623 && (lCell
.isUnderline() != lastAttr
.isUnderline())
624 && (lCell
.isBlink() != lastAttr
.isBlink())
626 // Everything is different
627 sb
.append(color(lCell
.getForeColor(),
628 lCell
.getBackColor(),
629 lCell
.isBold(), lCell
.isReverse(),
631 lCell
.isUnderline()));
634 System
.err
.printf("2 Set all attributes\n");
636 } else if ((lCell
.getForeColor() != lastAttr
.getForeColor())
637 && (lCell
.getBackColor() == lastAttr
.getBackColor())
638 && (lCell
.isBold() == lastAttr
.isBold())
639 && (lCell
.isReverse() == lastAttr
.isReverse())
640 && (lCell
.isUnderline() == lastAttr
.isUnderline())
641 && (lCell
.isBlink() == lastAttr
.isBlink())
644 // Attributes same, foreColor different
645 sb
.append(color(lCell
.isBold(),
646 lCell
.getForeColor(), true));
649 System
.err
.printf("3 Change foreColor\n");
651 } else if ((lCell
.getForeColor() == lastAttr
.getForeColor())
652 && (lCell
.getBackColor() != lastAttr
.getBackColor())
653 && (lCell
.isBold() == lastAttr
.isBold())
654 && (lCell
.isReverse() == lastAttr
.isReverse())
655 && (lCell
.isUnderline() == lastAttr
.isUnderline())
656 && (lCell
.isBlink() == lastAttr
.isBlink())
658 // Attributes same, backColor different
659 sb
.append(color(lCell
.isBold(),
660 lCell
.getBackColor(), false));
663 System
.err
.printf("4 Change backColor\n");
665 } else if ((lCell
.getForeColor() == lastAttr
.getForeColor())
666 && (lCell
.getBackColor() == lastAttr
.getBackColor())
667 && (lCell
.isBold() == lastAttr
.isBold())
668 && (lCell
.isReverse() == lastAttr
.isReverse())
669 && (lCell
.isUnderline() == lastAttr
.isUnderline())
670 && (lCell
.isBlink() == lastAttr
.isBlink())
673 // All attributes the same, just print the char
677 System
.err
.printf("5 Only emit character\n");
680 // Just reset everything again
681 sb
.append(color(lCell
.getForeColor(),
682 lCell
.getBackColor(),
686 lCell
.isUnderline()));
689 System
.err
.printf("6 Change all attributes\n");
692 // Emit the character
693 sb
.append(lCell
.getChar());
695 // Save the last rendered cell
697 lastAttr
.setTo(lCell
);
699 // Physical is always updated
700 physical
[x
][y
].setTo(lCell
);
702 } // if (!lCell.equals(pCell) || (reallyCleared == true))
704 } // for (int x = 0; x < width; x++)
708 * Render the screen to a string that can be emitted to something that
709 * knows how to process ECMA-48/ANSI X3.64 escape sequences.
711 * @return escape sequences string that provides the updates to the
714 private String
flushString() {
716 assert (!reallyCleared
);
720 CellAttributes attr
= null;
722 StringBuilder sb
= new StringBuilder();
724 attr
= new CellAttributes();
725 sb
.append(clearAll());
728 for (int y
= 0; y
< height
; y
++) {
729 flushLine(y
, sb
, attr
);
733 reallyCleared
= false;
735 String result
= sb
.toString();
737 System
.err
.printf("flushString(): %s\n", result
);
743 * Push the logical screen to the physical device.
746 public void flushPhysical() {
747 String result
= flushString();
749 && (cursorY
<= height
- 1)
750 && (cursorX
<= width
- 1)
752 result
+= cursor(true);
753 result
+= gotoXY(cursorX
, cursorY
);
755 result
+= cursor(false);
757 output
.write(result
);
762 * Set the window title.
764 * @param title the new title
766 public void setTitle(final String title
) {
767 output
.write(getSetTitleString(title
));
772 * Reset keyboard/mouse input parser.
774 private void resetParser() {
775 state
= ParseState
.GROUND
;
776 params
= new ArrayList
<String
>();
782 * Produce a control character or one of the special ones (ENTER, TAB,
785 * @param ch Unicode code point
786 * @param alt if true, set alt on the TKeypress
787 * @return one TKeypress event, either a control character (e.g. isKey ==
788 * false, ch == 'A', ctrl == true), or a special key (e.g. isKey == true,
791 private TKeypressEvent
controlChar(final char ch
, final boolean alt
) {
792 // System.err.printf("controlChar: %02x\n", ch);
796 // Carriage return --> ENTER
797 return new TKeypressEvent(kbEnter
, alt
, false, false);
799 // Linefeed --> ENTER
800 return new TKeypressEvent(kbEnter
, alt
, false, false);
803 return new TKeypressEvent(kbEsc
, alt
, false, false);
806 return new TKeypressEvent(kbTab
, alt
, false, false);
808 // Make all other control characters come back as the alphabetic
809 // character with the ctrl field set. So SOH would be 'A' +
811 return new TKeypressEvent(false, 0, (char)(ch
+ 0x40),
817 * Produce special key from CSI Pn ; Pm ; ... ~
819 * @return one KEYPRESS event representing a special key
821 private TInputEvent
csiFnKey() {
823 if (params
.size() > 0) {
824 key
= Integer
.parseInt(params
.get(0));
827 boolean ctrl
= false;
828 boolean shift
= false;
829 if (params
.size() > 1) {
830 shift
= csiIsShift(params
.get(1));
831 alt
= csiIsAlt(params
.get(1));
832 ctrl
= csiIsCtrl(params
.get(1));
837 return new TKeypressEvent(kbHome
, alt
, ctrl
, shift
);
839 return new TKeypressEvent(kbIns
, alt
, ctrl
, shift
);
841 return new TKeypressEvent(kbDel
, alt
, ctrl
, shift
);
843 return new TKeypressEvent(kbEnd
, alt
, ctrl
, shift
);
845 return new TKeypressEvent(kbPgUp
, alt
, ctrl
, shift
);
847 return new TKeypressEvent(kbPgDn
, alt
, ctrl
, shift
);
849 return new TKeypressEvent(kbF5
, alt
, ctrl
, shift
);
851 return new TKeypressEvent(kbF6
, alt
, ctrl
, shift
);
853 return new TKeypressEvent(kbF7
, alt
, ctrl
, shift
);
855 return new TKeypressEvent(kbF8
, alt
, ctrl
, shift
);
857 return new TKeypressEvent(kbF9
, alt
, ctrl
, shift
);
859 return new TKeypressEvent(kbF10
, alt
, ctrl
, shift
);
861 return new TKeypressEvent(kbF11
, alt
, ctrl
, shift
);
863 return new TKeypressEvent(kbF12
, alt
, ctrl
, shift
);
871 * Produce mouse events based on "Any event tracking" and UTF-8
873 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
875 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
877 private TInputEvent
parseMouse() {
878 int buttons
= params
.get(0).charAt(0) - 32;
879 int x
= params
.get(0).charAt(1) - 32 - 1;
880 int y
= params
.get(0).charAt(2) - 32 - 1;
882 // Clamp X and Y to the physical screen coordinates.
883 if (x
>= windowResize
.getWidth()) {
884 x
= windowResize
.getWidth() - 1;
886 if (y
>= windowResize
.getHeight()) {
887 y
= windowResize
.getHeight() - 1;
890 TMouseEvent
.Type eventType
= TMouseEvent
.Type
.MOUSE_DOWN
;
891 boolean eventMouse1
= false;
892 boolean eventMouse2
= false;
893 boolean eventMouse3
= false;
894 boolean eventMouseWheelUp
= false;
895 boolean eventMouseWheelDown
= false;
897 // System.err.printf("buttons: %04x\r\n", buttons);
914 if (!mouse1
&& !mouse2
&& !mouse3
) {
915 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
917 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
934 // Dragging with mouse1 down
937 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
941 // Dragging with mouse2 down
944 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
948 // Dragging with mouse3 down
951 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
955 // Dragging with mouse2 down after wheelUp
958 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
962 // Dragging with mouse2 down after wheelDown
965 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
969 eventMouseWheelUp
= true;
973 eventMouseWheelDown
= true;
977 // Unknown, just make it motion
978 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
981 return new TMouseEvent(eventType
, x
, y
, x
, y
,
982 eventMouse1
, eventMouse2
, eventMouse3
,
983 eventMouseWheelUp
, eventMouseWheelDown
);
987 * Produce mouse events based on "Any event tracking" and SGR
989 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
991 * @param release if true, this was a release ('m')
992 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
994 private TInputEvent
parseMouseSGR(final boolean release
) {
995 // SGR extended coordinates - mode 1006
996 if (params
.size() < 3) {
997 // Invalid position, bail out.
1000 int buttons
= Integer
.parseInt(params
.get(0));
1001 int x
= Integer
.parseInt(params
.get(1)) - 1;
1002 int y
= Integer
.parseInt(params
.get(2)) - 1;
1004 // Clamp X and Y to the physical screen coordinates.
1005 if (x
>= windowResize
.getWidth()) {
1006 x
= windowResize
.getWidth() - 1;
1008 if (y
>= windowResize
.getHeight()) {
1009 y
= windowResize
.getHeight() - 1;
1012 TMouseEvent
.Type eventType
= TMouseEvent
.Type
.MOUSE_DOWN
;
1013 boolean eventMouse1
= false;
1014 boolean eventMouse2
= false;
1015 boolean eventMouse3
= false;
1016 boolean eventMouseWheelUp
= false;
1017 boolean eventMouseWheelDown
= false;
1020 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
1034 // Motion only, no buttons down
1035 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
1039 // Dragging with mouse1 down
1041 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
1045 // Dragging with mouse2 down
1047 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
1051 // Dragging with mouse3 down
1053 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
1057 // Dragging with mouse2 down after wheelUp
1059 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
1063 // Dragging with mouse2 down after wheelDown
1065 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
1069 eventMouseWheelUp
= true;
1073 eventMouseWheelDown
= true;
1077 // Unknown, bail out
1080 return new TMouseEvent(eventType
, x
, y
, x
, y
,
1081 eventMouse1
, eventMouse2
, eventMouse3
,
1082 eventMouseWheelUp
, eventMouseWheelDown
);
1086 * Return any events in the IO queue.
1088 * @param queue list to append new events to
1090 public void getEvents(final List
<TInputEvent
> queue
) {
1091 synchronized (eventQueue
) {
1092 if (eventQueue
.size() > 0) {
1093 synchronized (queue
) {
1094 queue
.addAll(eventQueue
);
1102 * Return any events in the IO queue due to timeout.
1104 * @param queue list to append new events to
1106 private void getIdleEvents(final List
<TInputEvent
> queue
) {
1107 Date now
= new Date();
1109 // Check for new window size
1110 long windowSizeDelay
= now
.getTime() - windowSizeTime
;
1111 if (windowSizeDelay
> 1000) {
1112 sessionInfo
.queryWindowSize();
1113 int newWidth
= sessionInfo
.getWindowWidth();
1114 int newHeight
= sessionInfo
.getWindowHeight();
1115 if ((newWidth
!= windowResize
.getWidth())
1116 || (newHeight
!= windowResize
.getHeight())
1118 TResizeEvent event
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
1119 newWidth
, newHeight
);
1120 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
1121 newWidth
, newHeight
);
1124 windowSizeTime
= now
.getTime();
1127 // ESCDELAY type timeout
1128 if (state
== ParseState
.ESCAPE
) {
1129 long escDelay
= now
.getTime() - escapeTime
;
1130 if (escDelay
> 100) {
1131 // After 0.1 seconds, assume a true escape character
1132 queue
.add(controlChar((char)0x1B, false));
1139 * Returns true if the CSI parameter for a keyboard command means that
1142 private boolean csiIsShift(final String x
) {
1154 * Returns true if the CSI parameter for a keyboard command means that
1157 private boolean csiIsAlt(final String x
) {
1169 * Returns true if the CSI parameter for a keyboard command means that
1172 private boolean csiIsCtrl(final String x
) {
1184 * Parses the next character of input to see if an InputEvent is
1187 * @param events list to append new events to
1188 * @param ch Unicode code point
1190 private void processChar(final List
<TInputEvent
> events
, final char ch
) {
1192 // ESCDELAY type timeout
1193 Date now
= new Date();
1194 if (state
== ParseState
.ESCAPE
) {
1195 long escDelay
= now
.getTime() - escapeTime
;
1196 if (escDelay
> 250) {
1197 // After 0.25 seconds, assume a true escape character
1198 events
.add(controlChar((char)0x1B, false));
1204 boolean ctrl
= false;
1205 boolean alt
= false;
1206 boolean shift
= false;
1208 // System.err.printf("state: %s ch %c\r\n", state, ch);
1214 state
= ParseState
.ESCAPE
;
1215 escapeTime
= now
.getTime();
1220 // Control character
1221 events
.add(controlChar(ch
, false));
1228 events
.add(new TKeypressEvent(false, 0, ch
,
1229 false, false, false));
1238 // ALT-Control character
1239 events
.add(controlChar(ch
, true));
1245 // This will be one of the function keys
1246 state
= ParseState
.ESCAPE_INTERMEDIATE
;
1250 // '[' goes to CSI_ENTRY
1252 state
= ParseState
.CSI_ENTRY
;
1256 // Everything else is assumed to be Alt-keystroke
1257 if ((ch
>= 'A') && (ch
<= 'Z')) {
1261 events
.add(new TKeypressEvent(false, 0, ch
, alt
, ctrl
, shift
));
1265 case ESCAPE_INTERMEDIATE
:
1266 if ((ch
>= 'P') && (ch
<= 'S')) {
1270 events
.add(new TKeypressEvent(kbF1
));
1273 events
.add(new TKeypressEvent(kbF2
));
1276 events
.add(new TKeypressEvent(kbF3
));
1279 events
.add(new TKeypressEvent(kbF4
));
1288 // Unknown keystroke, ignore
1293 // Numbers - parameter values
1294 if ((ch
>= '0') && (ch
<= '9')) {
1295 params
.set(params
.size() - 1,
1296 params
.get(params
.size() - 1) + ch
);
1297 state
= ParseState
.CSI_PARAM
;
1300 // Parameter separator
1306 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
1310 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
1315 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
1320 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
1325 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
1330 events
.add(new TKeypressEvent(kbHome
));
1335 events
.add(new TKeypressEvent(kbEnd
));
1339 // CBT - Cursor backward X tab stops (default 1)
1340 events
.add(new TKeypressEvent(kbBackTab
));
1345 state
= ParseState
.MOUSE
;
1348 // Mouse position, SGR (1006) coordinates
1349 state
= ParseState
.MOUSE_SGR
;
1356 // Unknown keystroke, ignore
1361 // Numbers - parameter values
1362 if ((ch
>= '0') && (ch
<= '9')) {
1363 params
.set(params
.size() - 1,
1364 params
.get(params
.size() - 1) + ch
);
1367 // Parameter separator
1375 // Generate a mouse press event
1376 TInputEvent event
= parseMouseSGR(false);
1377 if (event
!= null) {
1383 // Generate a mouse release event
1384 event
= parseMouseSGR(true);
1385 if (event
!= null) {
1394 // Unknown keystroke, ignore
1399 // Numbers - parameter values
1400 if ((ch
>= '0') && (ch
<= '9')) {
1401 params
.set(params
.size() - 1,
1402 params
.get(params
.size() - 1) + ch
);
1403 state
= ParseState
.CSI_PARAM
;
1406 // Parameter separator
1413 events
.add(csiFnKey());
1418 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
1422 if (params
.size() > 1) {
1423 shift
= csiIsShift(params
.get(1));
1424 alt
= csiIsAlt(params
.get(1));
1425 ctrl
= csiIsCtrl(params
.get(1));
1427 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
1432 if (params
.size() > 1) {
1433 shift
= csiIsShift(params
.get(1));
1434 alt
= csiIsAlt(params
.get(1));
1435 ctrl
= csiIsCtrl(params
.get(1));
1437 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
1442 if (params
.size() > 1) {
1443 shift
= csiIsShift(params
.get(1));
1444 alt
= csiIsAlt(params
.get(1));
1445 ctrl
= csiIsCtrl(params
.get(1));
1447 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
1452 if (params
.size() > 1) {
1453 shift
= csiIsShift(params
.get(1));
1454 alt
= csiIsAlt(params
.get(1));
1455 ctrl
= csiIsCtrl(params
.get(1));
1457 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
1462 if (params
.size() > 1) {
1463 shift
= csiIsShift(params
.get(1));
1464 alt
= csiIsAlt(params
.get(1));
1465 ctrl
= csiIsCtrl(params
.get(1));
1467 events
.add(new TKeypressEvent(kbHome
, alt
, ctrl
, shift
));
1472 if (params
.size() > 1) {
1473 shift
= csiIsShift(params
.get(1));
1474 alt
= csiIsAlt(params
.get(1));
1475 ctrl
= csiIsCtrl(params
.get(1));
1477 events
.add(new TKeypressEvent(kbEnd
, alt
, ctrl
, shift
));
1485 // Unknown keystroke, ignore
1490 params
.set(0, params
.get(params
.size() - 1) + ch
);
1491 if (params
.get(0).length() == 3) {
1492 // We have enough to generate a mouse event
1493 events
.add(parseMouse());
1502 // This "should" be impossible to reach
1507 * Tell (u)xterm that we want alt- keystrokes to send escape + character
1508 * rather than set the 8th bit. Anyone who wants UTF8 should want this
1511 * @param on if true, enable metaSendsEscape
1512 * @return the string to emit to xterm
1514 private String
xtermMetaSendsEscape(final boolean on
) {
1516 return "\033[?1036h\033[?1034l";
1518 return "\033[?1036l";
1522 * Create an xterm OSC sequence to change the window title.
1524 * @param title the new title
1525 * @return the string to emit to xterm
1527 private String
getSetTitleString(final String title
) {
1528 return "\033]2;" + title
+ "\007";
1532 * Create a SGR parameter sequence for a single color change.
1534 * @param bold if true, set bold
1535 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
1536 * @param foreground if true, this is a foreground color
1537 * @return the string to emit to an ANSI / ECMA-style terminal,
1540 private String
color(final boolean bold
, final Color color
,
1541 final boolean foreground
) {
1542 return color(color
, foreground
, true) +
1543 rgbColor(bold
, color
, foreground
);
1547 * Create a T.416 RGB parameter sequence for a single color change.
1549 * @param bold if true, set bold
1550 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
1551 * @param foreground if true, this is a foreground color
1552 * @return the string to emit to an xterm terminal with RGB support,
1553 * e.g. "\033[38;2;RR;GG;BBm"
1555 private String
rgbColor(final boolean bold
, final Color color
,
1556 final boolean foreground
) {
1557 if (doRgbColor
== false) {
1560 StringBuilder sb
= new StringBuilder("\033[");
1562 // Bold implies foreground only
1564 if (color
.equals(Color
.BLACK
)) {
1565 sb
.append("84;84;84");
1566 } else if (color
.equals(Color
.RED
)) {
1567 sb
.append("252;84;84");
1568 } else if (color
.equals(Color
.GREEN
)) {
1569 sb
.append("84;252;84");
1570 } else if (color
.equals(Color
.YELLOW
)) {
1571 sb
.append("252;252;84");
1572 } else if (color
.equals(Color
.BLUE
)) {
1573 sb
.append("84;84;252");
1574 } else if (color
.equals(Color
.MAGENTA
)) {
1575 sb
.append("252;84;252");
1576 } else if (color
.equals(Color
.CYAN
)) {
1577 sb
.append("84;252;252");
1578 } else if (color
.equals(Color
.WHITE
)) {
1579 sb
.append("252;252;252");
1587 if (color
.equals(Color
.BLACK
)) {
1589 } else if (color
.equals(Color
.RED
)) {
1590 sb
.append("168;0;0");
1591 } else if (color
.equals(Color
.GREEN
)) {
1592 sb
.append("0;168;0");
1593 } else if (color
.equals(Color
.YELLOW
)) {
1594 sb
.append("168;84;0");
1595 } else if (color
.equals(Color
.BLUE
)) {
1596 sb
.append("0;0;168");
1597 } else if (color
.equals(Color
.MAGENTA
)) {
1598 sb
.append("168;0;168");
1599 } else if (color
.equals(Color
.CYAN
)) {
1600 sb
.append("0;168;168");
1601 } else if (color
.equals(Color
.WHITE
)) {
1602 sb
.append("168;168;168");
1606 return sb
.toString();
1610 * Create a T.416 RGB parameter sequence for both foreground and
1611 * background color change.
1613 * @param bold if true, set bold
1614 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1615 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1616 * @return the string to emit to an xterm terminal with RGB support,
1617 * e.g. "\033[38;2;RR;GG;BB;48;2;RR;GG;BBm"
1619 private String
rgbColor(final boolean bold
, final Color foreColor
,
1620 final Color backColor
) {
1621 if (doRgbColor
== false) {
1625 return rgbColor(bold
, foreColor
, true) +
1626 rgbColor(false, backColor
, false);
1630 * Create a SGR parameter sequence for a single color change.
1632 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
1633 * @param foreground if true, this is a foreground color
1634 * @param header if true, make the full header, otherwise just emit the
1635 * color parameter e.g. "42;"
1636 * @return the string to emit to an ANSI / ECMA-style terminal,
1639 private String
color(final Color color
, final boolean foreground
,
1640 final boolean header
) {
1642 int ecmaColor
= color
.getValue();
1644 // Convert Color.* values to SGR numerics
1652 return String
.format("\033[%dm", ecmaColor
);
1654 return String
.format("%d;", ecmaColor
);
1659 * Create a SGR parameter sequence for both foreground and background
1662 * @param bold if true, set bold
1663 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1664 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1665 * @return the string to emit to an ANSI / ECMA-style terminal,
1666 * e.g. "\033[31;42m"
1668 private String
color(final boolean bold
, final Color foreColor
,
1669 final Color backColor
) {
1670 return color(foreColor
, backColor
, true) +
1671 rgbColor(bold
, foreColor
, backColor
);
1675 * Create a SGR parameter sequence for both foreground and
1676 * background color change.
1678 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1679 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1680 * @param header if true, make the full header, otherwise just emit the
1681 * color parameter e.g. "31;42;"
1682 * @return the string to emit to an ANSI / ECMA-style terminal,
1683 * e.g. "\033[31;42m"
1685 private String
color(final Color foreColor
, final Color backColor
,
1686 final boolean header
) {
1688 int ecmaForeColor
= foreColor
.getValue();
1689 int ecmaBackColor
= backColor
.getValue();
1691 // Convert Color.* values to SGR numerics
1692 ecmaBackColor
+= 40;
1693 ecmaForeColor
+= 30;
1696 return String
.format("\033[%d;%dm", ecmaForeColor
, ecmaBackColor
);
1698 return String
.format("%d;%d;", ecmaForeColor
, ecmaBackColor
);
1703 * Create a SGR parameter sequence for foreground, background, and
1704 * several attributes. This sequence first resets all attributes to
1705 * default, then sets attributes as per the parameters.
1707 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1708 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1709 * @param bold if true, set bold
1710 * @param reverse if true, set reverse
1711 * @param blink if true, set blink
1712 * @param underline if true, set underline
1713 * @return the string to emit to an ANSI / ECMA-style terminal,
1714 * e.g. "\033[0;1;31;42m"
1716 private String
color(final Color foreColor
, final Color backColor
,
1717 final boolean bold
, final boolean reverse
, final boolean blink
,
1718 final boolean underline
) {
1720 int ecmaForeColor
= foreColor
.getValue();
1721 int ecmaBackColor
= backColor
.getValue();
1723 // Convert Color.* values to SGR numerics
1724 ecmaBackColor
+= 40;
1725 ecmaForeColor
+= 30;
1727 StringBuilder sb
= new StringBuilder();
1728 if ( bold
&& reverse
&& blink
&& !underline
) {
1729 sb
.append("\033[0;1;7;5;");
1730 } else if ( bold
&& reverse
&& !blink
&& !underline
) {
1731 sb
.append("\033[0;1;7;");
1732 } else if ( !bold
&& reverse
&& blink
&& !underline
) {
1733 sb
.append("\033[0;7;5;");
1734 } else if ( bold
&& !reverse
&& blink
&& !underline
) {
1735 sb
.append("\033[0;1;5;");
1736 } else if ( bold
&& !reverse
&& !blink
&& !underline
) {
1737 sb
.append("\033[0;1;");
1738 } else if ( !bold
&& reverse
&& !blink
&& !underline
) {
1739 sb
.append("\033[0;7;");
1740 } else if ( !bold
&& !reverse
&& blink
&& !underline
) {
1741 sb
.append("\033[0;5;");
1742 } else if ( bold
&& reverse
&& blink
&& underline
) {
1743 sb
.append("\033[0;1;7;5;4;");
1744 } else if ( bold
&& reverse
&& !blink
&& underline
) {
1745 sb
.append("\033[0;1;7;4;");
1746 } else if ( !bold
&& reverse
&& blink
&& underline
) {
1747 sb
.append("\033[0;7;5;4;");
1748 } else if ( bold
&& !reverse
&& blink
&& underline
) {
1749 sb
.append("\033[0;1;5;4;");
1750 } else if ( bold
&& !reverse
&& !blink
&& underline
) {
1751 sb
.append("\033[0;1;4;");
1752 } else if ( !bold
&& reverse
&& !blink
&& underline
) {
1753 sb
.append("\033[0;7;4;");
1754 } else if ( !bold
&& !reverse
&& blink
&& underline
) {
1755 sb
.append("\033[0;5;4;");
1756 } else if ( !bold
&& !reverse
&& !blink
&& underline
) {
1757 sb
.append("\033[0;4;");
1759 assert (!bold
&& !reverse
&& !blink
&& !underline
);
1760 sb
.append("\033[0;");
1762 sb
.append(String
.format("%d;%dm", ecmaForeColor
, ecmaBackColor
));
1763 sb
.append(rgbColor(bold
, foreColor
, backColor
));
1764 return sb
.toString();
1768 * Create a SGR parameter sequence to reset to defaults.
1770 * @return the string to emit to an ANSI / ECMA-style terminal,
1773 private String
normal() {
1774 return normal(true) + rgbColor(false, Color
.WHITE
, Color
.BLACK
);
1778 * Create a SGR parameter sequence to reset to defaults.
1780 * @param header if true, make the full header, otherwise just emit the
1781 * bare parameter e.g. "0;"
1782 * @return the string to emit to an ANSI / ECMA-style terminal,
1785 private String
normal(final boolean header
) {
1787 return "\033[0;37;40m";
1793 * Create a SGR parameter sequence for enabling the visible cursor.
1795 * @param on if true, turn on cursor
1796 * @return the string to emit to an ANSI / ECMA-style terminal
1798 private String
cursor(final boolean on
) {
1799 if (on
&& !cursorOn
) {
1803 if (!on
&& cursorOn
) {
1811 * Clear the entire screen. Because some terminals use back-color-erase,
1812 * set the color to white-on-black beforehand.
1814 * @return the string to emit to an ANSI / ECMA-style terminal
1816 private String
clearAll() {
1817 return "\033[0;37;40m\033[2J";
1821 * Clear the line from the cursor (inclusive) to the end of the screen.
1822 * Because some terminals use back-color-erase, set the color to
1823 * white-on-black beforehand.
1825 * @return the string to emit to an ANSI / ECMA-style terminal
1827 private String
clearRemainingLine() {
1828 return "\033[0;37;40m\033[K";
1832 * Move the cursor to (x, y).
1834 * @param x column coordinate. 0 is the left-most column.
1835 * @param y row coordinate. 0 is the top-most row.
1836 * @return the string to emit to an ANSI / ECMA-style terminal
1838 private String
gotoXY(final int x
, final int y
) {
1839 return String
.format("\033[%d;%dH", y
+ 1, x
+ 1);
1843 * Tell (u)xterm that we want to receive mouse events based on "Any event
1844 * tracking", UTF-8 coordinates, and then SGR coordinates. Ideally we
1845 * will end up with SGR coordinates with UTF-8 coordinates as a fallback.
1847 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
1849 * Note that this also sets the alternate/primary screen buffer.
1851 * @param on If true, enable mouse report and use the alternate screen
1852 * buffer. If false disable mouse reporting and use the primary screen
1854 * @return the string to emit to xterm
1856 private String
mouse(final boolean on
) {
1858 return "\033[?1002;1003;1005;1006h\033[?1049h";
1860 return "\033[?1002;1003;1006;1005l\033[?1049l";
1864 * Read function runs on a separate thread.
1867 boolean done
= false;
1868 // available() will often return > 1, so we need to read in chunks to
1870 char [] readBuffer
= new char[128];
1871 List
<TInputEvent
> events
= new LinkedList
<TInputEvent
>();
1873 while (!done
&& !stopReaderThread
) {
1875 // We assume that if inputStream has bytes available, then
1876 // input won't block on read().
1877 int n
= inputStream
.available();
1879 if (readBuffer
.length
< n
) {
1880 // The buffer wasn't big enough, make it huger
1881 readBuffer
= new char[readBuffer
.length
* 2];
1884 int rc
= input
.read(readBuffer
, 0, readBuffer
.length
);
1885 // System.err.printf("read() %d", rc); System.err.flush();
1890 for (int i
= 0; i
< rc
; i
++) {
1891 int ch
= readBuffer
[i
];
1892 processChar(events
, (char)ch
);
1894 getIdleEvents(events
);
1895 if (events
.size() > 0) {
1896 // Add to the queue for the backend thread to
1897 // be able to obtain.
1898 synchronized (eventQueue
) {
1899 eventQueue
.addAll(events
);
1901 if (listener
!= null) {
1902 synchronized (listener
) {
1903 listener
.notifyAll();
1910 getIdleEvents(events
);
1911 if (events
.size() > 0) {
1912 synchronized (eventQueue
) {
1913 eventQueue
.addAll(events
);
1916 if (listener
!= null) {
1917 synchronized (listener
) {
1918 listener
.notifyAll();
1923 // Wait 10 millis for more data
1926 // System.err.println("end while loop"); System.err.flush();
1927 } catch (InterruptedException e
) {
1929 } catch (IOException e
) {
1930 e
.printStackTrace();
1933 } // while ((done == false) && (stopReaderThread == false))
1934 // System.err.println("*** run() exiting..."); System.err.flush();