immutable TMouseEvent
[nikiroo-utils.git] / src / jexer / io / ECMA48Terminal.java
1 /**
2 * Jexer - Java Text User Interface
3 *
4 * License: LGPLv3 or later
5 *
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.
9 *
10 * Copyright (C) 2015 Kevin Lamonte
11 *
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.
16 *
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.
21 *
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
26 * 02110-1301 USA
27 *
28 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
29 * @version 1
30 */
31 package jexer.io;
32
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;
48
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.*;
59
60 /**
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.
63 */
64 public class ECMA48Terminal implements Runnable {
65
66 /**
67 * The session information.
68 */
69 private SessionInfo sessionInfo;
70
71 /**
72 * Getter for sessionInfo.
73 *
74 * @return the SessionInfo
75 */
76 public final SessionInfo getSessionInfo() {
77 return sessionInfo;
78 }
79
80 /**
81 * The event queue, filled up by a thread reading on input.
82 */
83 private List<TInputEvent> eventQueue;
84
85 /**
86 * If true, we want the reader thread to exit gracefully.
87 */
88 private boolean stopReaderThread;
89
90 /**
91 * The reader thread.
92 */
93 private Thread readerThread;
94
95 /**
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.
98 */
99 private ArrayList<String> params;
100
101 /**
102 * params[paramI] is being appended to.
103 */
104 private int paramI;
105
106 /**
107 * States in the input parser.
108 */
109 private enum ParseState {
110 GROUND,
111 ESCAPE,
112 ESCAPE_INTERMEDIATE,
113 CSI_ENTRY,
114 CSI_PARAM,
115 // CSI_INTERMEDIATE,
116 MOUSE
117 }
118
119 /**
120 * Current parsing state.
121 */
122 private ParseState state;
123
124 /**
125 * The time we entered ESCAPE. If we get a bare escape without a code
126 * following it, this is used to return that bare escape.
127 */
128 private long escapeTime;
129
130 /**
131 * true if mouse1 was down. Used to report mouse1 on the release event.
132 */
133 private boolean mouse1;
134
135 /**
136 * true if mouse2 was down. Used to report mouse2 on the release event.
137 */
138 private boolean mouse2;
139
140 /**
141 * true if mouse3 was down. Used to report mouse3 on the release event.
142 */
143 private boolean mouse3;
144
145 /**
146 * Cache the cursor visibility value so we only emit the sequence when we
147 * need to.
148 */
149 private boolean cursorOn = true;
150
151 /**
152 * Cache the last window size to figure out if a TResizeEvent needs to be
153 * generated.
154 */
155 private TResizeEvent windowResize = null;
156
157 /**
158 * If true, then we changed System.in and need to change it back.
159 */
160 private boolean setRawMode;
161
162 /**
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.
166 */
167 private Reader input;
168
169 /**
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().
174 */
175 private InputStream inputStream;
176
177 /**
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
180 * UTF-8 encoding.
181 */
182 private PrintWriter output;
183
184 /**
185 * When true, the terminal is sending non-UTF8 bytes when reporting mouse
186 * events.
187 *
188 * TODO: Add broken mouse detection back into the reader.
189 */
190 private boolean brokenTerminalUTFMouse = false;
191
192 /**
193 * Get the output writer.
194 *
195 * @return the Writer
196 */
197 public PrintWriter getOutput() {
198 return output;
199 }
200
201 /**
202 * Check if there are events in the queue.
203 *
204 * @return if true, getEvents() has something to return to the backend
205 */
206 public boolean hasEvents() {
207 synchronized (eventQueue) {
208 return (eventQueue.size() > 0);
209 }
210 }
211
212 /**
213 * Call 'stty' to set cooked mode.
214 *
215 * <p>Actually executes '/bin/sh -c stty sane cooked &lt; /dev/tty'
216 */
217 private void sttyCooked() {
218 doStty(false);
219 }
220
221 /**
222 * Call 'stty' to set raw mode.
223 *
224 * <p>Actually executes '/bin/sh -c stty -ignbrk -brkint -parmrk -istrip
225 * -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten
226 * -parenb cs8 min 1 &lt; /dev/tty'
227 */
228 private void sttyRaw() {
229 doStty(true);
230 }
231
232 /**
233 * Call 'stty' to set raw or cooked mode.
234 *
235 * @param mode if true, set raw mode, otherwise set cooked mode
236 */
237 private void doStty(final boolean mode) {
238 String [] cmdRaw = {
239 "/bin/sh", "-c", "stty -ignbrk -brkint -parmrk -istrip -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten -parenb cs8 min 1 < /dev/tty"
240 };
241 String [] cmdCooked = {
242 "/bin/sh", "-c", "stty sane cooked < /dev/tty"
243 };
244 try {
245 Process process;
246 if (mode == true) {
247 process = Runtime.getRuntime().exec(cmdRaw);
248 } else {
249 process = Runtime.getRuntime().exec(cmdCooked);
250 }
251 BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
252 String line = in.readLine();
253 if ((line != null) && (line.length() > 0)) {
254 System.err.println("WEIRD?! Normal output from stty: " + line);
255 }
256 while (true) {
257 BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
258 line = err.readLine();
259 if ((line != null) && (line.length() > 0)) {
260 System.err.println("Error output from stty: " + line);
261 }
262 try {
263 process.waitFor();
264 break;
265 } catch (InterruptedException e) {
266 e.printStackTrace();
267 }
268 }
269 int rc = process.exitValue();
270 if (rc != 0) {
271 System.err.println("stty returned error code: " + rc);
272 }
273 } catch (IOException e) {
274 e.printStackTrace();
275 }
276 }
277
278 /**
279 * Constructor sets up state for getEvent().
280 *
281 * @param input an InputStream connected to the remote user, or null for
282 * System.in. If System.in is used, then on non-Windows systems it will
283 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
284 * mode. input is always converted to a Reader with UTF-8 encoding.
285 * @param output an OutputStream connected to the remote user, or null
286 * for System.out. output is always converted to a Writer with UTF-8
287 * encoding.
288 * @throws UnsupportedEncodingException if an exception is thrown when
289 * creating the InputStreamReader
290 */
291 public ECMA48Terminal(final InputStream input,
292 final OutputStream output) throws UnsupportedEncodingException {
293
294 reset();
295 mouse1 = false;
296 mouse2 = false;
297 mouse3 = false;
298 stopReaderThread = false;
299
300 if (input == null) {
301 // inputStream = System.in;
302 inputStream = new FileInputStream(FileDescriptor.in);
303 sttyRaw();
304 setRawMode = true;
305 } else {
306 inputStream = input;
307 }
308 this.input = new InputStreamReader(inputStream, "UTF-8");
309
310 // TODO: include TelnetSocket from NIB and have it implement
311 // SessionInfo
312 if (input instanceof SessionInfo) {
313 sessionInfo = (SessionInfo) input;
314 }
315 if (sessionInfo == null) {
316 if (input == null) {
317 // Reading right off the tty
318 sessionInfo = new TTYSessionInfo();
319 } else {
320 sessionInfo = new TSessionInfo();
321 }
322 }
323
324 if (output == null) {
325 this.output = new PrintWriter(new OutputStreamWriter(System.out,
326 "UTF-8"));
327 } else {
328 this.output = new PrintWriter(new OutputStreamWriter(output,
329 "UTF-8"));
330 }
331
332 // Enable mouse reporting and metaSendsEscape
333 this.output.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
334
335 // Hang onto the window size
336 windowResize = new TResizeEvent(TResizeEvent.Type.SCREEN,
337 sessionInfo.getWindowWidth(), sessionInfo.getWindowHeight());
338
339 // Spin up the input reader
340 eventQueue = new LinkedList<TInputEvent>();
341 readerThread = new Thread(this);
342 readerThread.start();
343 }
344
345 /**
346 * Restore terminal to normal state.
347 */
348 public void shutdown() {
349
350 // System.err.println("=== shutdown() ==="); System.err.flush();
351
352 // Tell the reader thread to stop looking at input
353 stopReaderThread = true;
354 try {
355 readerThread.join();
356 } catch (InterruptedException e) {
357 e.printStackTrace();
358 }
359
360 // Disable mouse reporting and show cursor
361 output.printf("%s%s%s", mouse(false), cursor(true), normal());
362 output.flush();
363
364 if (setRawMode) {
365 sttyCooked();
366 setRawMode = false;
367 // We don't close System.in/out
368 } else {
369 // Shut down the streams, this should wake up the reader thread
370 // and make it exit.
371 try {
372 if (input != null) {
373 input.close();
374 input = null;
375 }
376 if (output != null) {
377 output.close();
378 output = null;
379 }
380 } catch (IOException e) {
381 e.printStackTrace();
382 }
383 }
384 }
385
386 /**
387 * Flush output.
388 */
389 public void flush() {
390 output.flush();
391 }
392
393 /**
394 * Reset keyboard/mouse input parser.
395 */
396 private void reset() {
397 state = ParseState.GROUND;
398 params = new ArrayList<String>();
399 paramI = 0;
400 params.clear();
401 params.add("");
402 }
403
404 /**
405 * Produce a control character or one of the special ones (ENTER, TAB,
406 * etc.).
407 *
408 * @param ch Unicode code point
409 * @param alt if true, set alt on the TKeypress
410 * @return one TKeypress event, either a control character (e.g. isKey ==
411 * false, ch == 'A', ctrl == true), or a special key (e.g. isKey == true,
412 * fnKey == ESC)
413 */
414 private TKeypressEvent controlChar(final char ch, final boolean alt) {
415 // System.err.printf("controlChar: %02x\n", ch);
416
417 switch (ch) {
418 case 0x0D:
419 // Carriage return --> ENTER
420 return new TKeypressEvent(kbEnter, alt, false, false);
421 case 0x0A:
422 // Linefeed --> ENTER
423 return new TKeypressEvent(kbEnter, alt, false, false);
424 case 0x1B:
425 // ESC
426 return new TKeypressEvent(kbEsc, alt, false, false);
427 case '\t':
428 // TAB
429 return new TKeypressEvent(kbTab, alt, false, false);
430 default:
431 // Make all other control characters come back as the alphabetic
432 // character with the ctrl field set. So SOH would be 'A' +
433 // ctrl.
434 return new TKeypressEvent(false, 0, (char)(ch + 0x40),
435 alt, true, false);
436 }
437 }
438
439 /**
440 * Produce special key from CSI Pn ; Pm ; ... ~
441 *
442 * @return one KEYPRESS event representing a special key
443 */
444 private TInputEvent csiFnKey() {
445 int key = 0;
446 int modifier = 0;
447 if (params.size() > 0) {
448 key = Integer.parseInt(params.get(0));
449 }
450 if (params.size() > 1) {
451 modifier = Integer.parseInt(params.get(1));
452 }
453 boolean alt = false;
454 boolean ctrl = false;
455 boolean shift = false;
456
457 switch (modifier) {
458 case 0:
459 // No modifier
460 break;
461 case 2:
462 // Shift
463 shift = true;
464 break;
465 case 3:
466 // Alt
467 alt = true;
468 break;
469 case 5:
470 // Ctrl
471 ctrl = true;
472 break;
473 default:
474 // Unknown modifier, bail out
475 return null;
476 }
477
478 switch (key) {
479 case 1:
480 return new TKeypressEvent(kbHome, alt, ctrl, shift);
481 case 2:
482 return new TKeypressEvent(kbIns, alt, ctrl, shift);
483 case 3:
484 return new TKeypressEvent(kbDel, alt, ctrl, shift);
485 case 4:
486 return new TKeypressEvent(kbEnd, alt, ctrl, shift);
487 case 5:
488 return new TKeypressEvent(kbPgUp, alt, ctrl, shift);
489 case 6:
490 return new TKeypressEvent(kbPgDn, alt, ctrl, shift);
491 case 15:
492 return new TKeypressEvent(kbF5, alt, ctrl, shift);
493 case 17:
494 return new TKeypressEvent(kbF6, alt, ctrl, shift);
495 case 18:
496 return new TKeypressEvent(kbF7, alt, ctrl, shift);
497 case 19:
498 return new TKeypressEvent(kbF8, alt, ctrl, shift);
499 case 20:
500 return new TKeypressEvent(kbF9, alt, ctrl, shift);
501 case 21:
502 return new TKeypressEvent(kbF10, alt, ctrl, shift);
503 case 23:
504 return new TKeypressEvent(kbF11, alt, ctrl, shift);
505 case 24:
506 return new TKeypressEvent(kbF12, alt, ctrl, shift);
507 default:
508 // Unknown
509 return null;
510 }
511 }
512
513 /**
514 * Produce mouse events based on "Any event tracking" and UTF-8
515 * coordinates. See
516 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
517 *
518 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
519 */
520 private TInputEvent parseMouse() {
521 int buttons = params.get(0).charAt(0) - 32;
522 int x = params.get(0).charAt(1) - 32 - 1;
523 int y = params.get(0).charAt(2) - 32 - 1;
524
525 // Clamp X and Y to the physical screen coordinates.
526 if (x >= windowResize.getWidth()) {
527 x = windowResize.getWidth() - 1;
528 }
529 if (y >= windowResize.getHeight()) {
530 y = windowResize.getHeight() - 1;
531 }
532
533 TMouseEvent.Type eventType = TMouseEvent.Type.MOUSE_DOWN;
534 boolean eventMouse1 = false;
535 boolean eventMouse2 = false;
536 boolean eventMouse3 = false;
537 boolean eventMouseWheelUp = false;
538 boolean eventMouseWheelDown = false;
539
540 // System.err.printf("buttons: %04x\r\n", buttons);
541
542 switch (buttons) {
543 case 0:
544 eventMouse1 = true;
545 mouse1 = true;
546 break;
547 case 1:
548 eventMouse2 = true;
549 mouse2 = true;
550 break;
551 case 2:
552 eventMouse3 = true;
553 mouse3 = true;
554 break;
555 case 3:
556 // Release or Move
557 if (!mouse1 && !mouse2 && !mouse3) {
558 eventType = TMouseEvent.Type.MOUSE_MOTION;
559 } else {
560 eventType = TMouseEvent.Type.MOUSE_UP;
561 }
562 if (mouse1) {
563 mouse1 = false;
564 eventMouse1 = true;
565 }
566 if (mouse2) {
567 mouse2 = false;
568 eventMouse2 = true;
569 }
570 if (mouse3) {
571 mouse3 = false;
572 eventMouse3 = true;
573 }
574 break;
575
576 case 32:
577 // Dragging with mouse1 down
578 eventMouse1 = true;
579 mouse1 = true;
580 eventType = TMouseEvent.Type.MOUSE_MOTION;
581 break;
582
583 case 33:
584 // Dragging with mouse2 down
585 eventMouse2 = true;
586 mouse2 = true;
587 eventType = TMouseEvent.Type.MOUSE_MOTION;
588 break;
589
590 case 34:
591 // Dragging with mouse3 down
592 eventMouse3 = true;
593 mouse3 = true;
594 eventType = TMouseEvent.Type.MOUSE_MOTION;
595 break;
596
597 case 96:
598 // Dragging with mouse2 down after wheelUp
599 eventMouse2 = true;
600 mouse2 = true;
601 eventType = TMouseEvent.Type.MOUSE_MOTION;
602 break;
603
604 case 97:
605 // Dragging with mouse2 down after wheelDown
606 eventMouse2 = true;
607 mouse2 = true;
608 eventType = TMouseEvent.Type.MOUSE_MOTION;
609 break;
610
611 case 64:
612 eventMouseWheelUp = true;
613 break;
614
615 case 65:
616 eventMouseWheelDown = true;
617 break;
618
619 default:
620 // Unknown, just make it motion
621 eventType = TMouseEvent.Type.MOUSE_MOTION;
622 break;
623 }
624 return new TMouseEvent(eventType, x, y, x, y,
625 eventMouse1, eventMouse2, eventMouse3,
626 eventMouseWheelUp, eventMouseWheelDown);
627 }
628
629 /**
630 * Return any events in the IO queue.
631 *
632 * @param queue list to append new events to
633 */
634 public void getEvents(final List<TInputEvent> queue) {
635 synchronized (eventQueue) {
636 if (eventQueue.size() > 0) {
637 queue.addAll(eventQueue);
638 eventQueue.clear();
639 }
640 }
641 }
642
643 /**
644 * Return any events in the IO queue due to timeout.
645 *
646 * @param queue list to append new events to
647 */
648 public void getIdleEvents(final List<TInputEvent> queue) {
649
650 // Check for new window size
651 sessionInfo.queryWindowSize();
652 int newWidth = sessionInfo.getWindowWidth();
653 int newHeight = sessionInfo.getWindowHeight();
654 if ((newWidth != windowResize.getWidth())
655 || (newHeight != windowResize.getHeight())
656 ) {
657 TResizeEvent event = new TResizeEvent(TResizeEvent.Type.SCREEN,
658 newWidth, newHeight);
659 windowResize = new TResizeEvent(TResizeEvent.Type.SCREEN,
660 newWidth, newHeight);
661 synchronized (eventQueue) {
662 eventQueue.add(event);
663 }
664 }
665
666 synchronized (eventQueue) {
667 if (eventQueue.size() > 0) {
668 queue.addAll(eventQueue);
669 eventQueue.clear();
670 }
671 }
672 }
673
674 /**
675 * Parses the next character of input to see if an InputEvent is
676 * fully here.
677 *
678 * @param events list to append new events to
679 * @param ch Unicode code point
680 */
681 private void processChar(final List<TInputEvent> events, final char ch) {
682
683 // ESCDELAY type timeout
684 Date now = new Date();
685 if (state == ParseState.ESCAPE) {
686 long escDelay = now.getTime() - escapeTime;
687 if (escDelay > 250) {
688 // After 0.25 seconds, assume a true escape character
689 events.add(controlChar((char)0x1B, false));
690 reset();
691 }
692 }
693
694 // TKeypress fields
695 boolean ctrl = false;
696 boolean alt = false;
697 boolean shift = false;
698 char keyCh = ch;
699 TKeypress key;
700
701 // System.err.printf("state: %s ch %c\r\n", state, ch);
702
703 switch (state) {
704 case GROUND:
705
706 if (ch == 0x1B) {
707 state = ParseState.ESCAPE;
708 escapeTime = now.getTime();
709 return;
710 }
711
712 if (ch <= 0x1F) {
713 // Control character
714 events.add(controlChar(ch, false));
715 reset();
716 return;
717 }
718
719 if (ch >= 0x20) {
720 // Normal character
721 events.add(new TKeypressEvent(false, 0, ch,
722 false, false, false));
723 reset();
724 return;
725 }
726
727 break;
728
729 case ESCAPE:
730 if (ch <= 0x1F) {
731 // ALT-Control character
732 events.add(controlChar(ch, true));
733 reset();
734 return;
735 }
736
737 if (ch == 'O') {
738 // This will be one of the function keys
739 state = ParseState.ESCAPE_INTERMEDIATE;
740 return;
741 }
742
743 // '[' goes to CSI_ENTRY
744 if (ch == '[') {
745 state = ParseState.CSI_ENTRY;
746 return;
747 }
748
749 // Everything else is assumed to be Alt-keystroke
750 if ((ch >= 'A') && (ch <= 'Z')) {
751 shift = true;
752 }
753 alt = true;
754 events.add(new TKeypressEvent(false, 0, ch, alt, ctrl, shift));
755 reset();
756 return;
757
758 case ESCAPE_INTERMEDIATE:
759 if ((ch >= 'P') && (ch <= 'S')) {
760 // Function key
761 switch (ch) {
762 case 'P':
763 events.add(new TKeypressEvent(kbF1));
764 break;
765 case 'Q':
766 events.add(new TKeypressEvent(kbF2));
767 break;
768 case 'R':
769 events.add(new TKeypressEvent(kbF3));
770 break;
771 case 'S':
772 events.add(new TKeypressEvent(kbF4));
773 break;
774 default:
775 break;
776 }
777 reset();
778 return;
779 }
780
781 // Unknown keystroke, ignore
782 reset();
783 return;
784
785 case CSI_ENTRY:
786 // Numbers - parameter values
787 if ((ch >= '0') && (ch <= '9')) {
788 params.set(paramI, params.get(paramI) + ch);
789 state = ParseState.CSI_PARAM;
790 return;
791 }
792 // Parameter separator
793 if (ch == ';') {
794 paramI++;
795 params.set(paramI, "");
796 return;
797 }
798
799 if ((ch >= 0x30) && (ch <= 0x7E)) {
800 switch (ch) {
801 case 'A':
802 // Up
803 if (params.size() > 1) {
804 if (params.get(1).equals("2")) {
805 shift = true;
806 }
807 if (params.get(1).equals("5")) {
808 ctrl = true;
809 }
810 if (params.get(1).equals("3")) {
811 alt = true;
812 }
813 }
814 events.add(new TKeypressEvent(kbUp, alt, ctrl, shift));
815 reset();
816 return;
817 case 'B':
818 // Down
819 if (params.size() > 1) {
820 if (params.get(1).equals("2")) {
821 shift = true;
822 }
823 if (params.get(1).equals("5")) {
824 ctrl = true;
825 }
826 if (params.get(1).equals("3")) {
827 alt = true;
828 }
829 }
830 events.add(new TKeypressEvent(kbDown, alt, ctrl, shift));
831 reset();
832 return;
833 case 'C':
834 // Right
835 if (params.size() > 1) {
836 if (params.get(1).equals("2")) {
837 shift = true;
838 }
839 if (params.get(1).equals("5")) {
840 ctrl = true;
841 }
842 if (params.get(1).equals("3")) {
843 alt = true;
844 }
845 }
846 events.add(new TKeypressEvent(kbRight, alt, ctrl, shift));
847 reset();
848 return;
849 case 'D':
850 // Left
851 if (params.size() > 1) {
852 if (params.get(1).equals("2")) {
853 shift = true;
854 }
855 if (params.get(1).equals("5")) {
856 ctrl = true;
857 }
858 if (params.get(1).equals("3")) {
859 alt = true;
860 }
861 }
862 events.add(new TKeypressEvent(kbLeft, alt, ctrl, shift));
863 reset();
864 return;
865 case 'H':
866 // Home
867 events.add(new TKeypressEvent(kbHome));
868 reset();
869 return;
870 case 'F':
871 // End
872 events.add(new TKeypressEvent(kbEnd));
873 reset();
874 return;
875 case 'Z':
876 // CBT - Cursor backward X tab stops (default 1)
877 events.add(new TKeypressEvent(kbBackTab));
878 reset();
879 return;
880 case 'M':
881 // Mouse position
882 state = ParseState.MOUSE;
883 return;
884 default:
885 break;
886 }
887 }
888
889 // Unknown keystroke, ignore
890 reset();
891 return;
892
893 case CSI_PARAM:
894 // Numbers - parameter values
895 if ((ch >= '0') && (ch <= '9')) {
896 params.set(paramI, params.get(paramI) + ch);
897 state = ParseState.CSI_PARAM;
898 return;
899 }
900 // Parameter separator
901 if (ch == ';') {
902 paramI++;
903 params.set(paramI, "");
904 return;
905 }
906
907 if (ch == '~') {
908 events.add(csiFnKey());
909 reset();
910 return;
911 }
912
913 if ((ch >= 0x30) && (ch <= 0x7E)) {
914 switch (ch) {
915 case 'A':
916 // Up
917 if (params.size() > 1) {
918 if (params.get(1).equals("2")) {
919 shift = true;
920 }
921 if (params.get(1).equals("5")) {
922 ctrl = true;
923 }
924 if (params.get(1).equals("3")) {
925 alt = true;
926 }
927 }
928 events.add(new TKeypressEvent(kbUp, alt, ctrl, shift));
929 reset();
930 return;
931 case 'B':
932 // Down
933 if (params.size() > 1) {
934 if (params.get(1).equals("2")) {
935 shift = true;
936 }
937 if (params.get(1).equals("5")) {
938 ctrl = true;
939 }
940 if (params.get(1).equals("3")) {
941 alt = true;
942 }
943 }
944 events.add(new TKeypressEvent(kbDown, alt, ctrl, shift));
945 reset();
946 return;
947 case 'C':
948 // Right
949 if (params.size() > 1) {
950 if (params.get(1).equals("2")) {
951 shift = true;
952 }
953 if (params.get(1).equals("5")) {
954 ctrl = true;
955 }
956 if (params.get(1).equals("3")) {
957 alt = true;
958 }
959 }
960 events.add(new TKeypressEvent(kbRight, alt, ctrl, shift));
961 reset();
962 return;
963 case 'D':
964 // Left
965 if (params.size() > 1) {
966 if (params.get(1).equals("2")) {
967 shift = true;
968 }
969 if (params.get(1).equals("5")) {
970 ctrl = true;
971 }
972 if (params.get(1).equals("3")) {
973 alt = true;
974 }
975 }
976 events.add(new TKeypressEvent(kbLeft, alt, ctrl, shift));
977 reset();
978 return;
979 default:
980 break;
981 }
982 }
983
984 // Unknown keystroke, ignore
985 reset();
986 return;
987
988 case MOUSE:
989 params.set(0, params.get(paramI) + ch);
990 if (params.get(0).length() == 3) {
991 // We have enough to generate a mouse event
992 events.add(parseMouse());
993 reset();
994 }
995 return;
996
997 default:
998 break;
999 }
1000
1001 // This "should" be impossible to reach
1002 return;
1003 }
1004
1005 /**
1006 * Tell (u)xterm that we want alt- keystrokes to send escape + character
1007 * rather than set the 8th bit. Anyone who wants UTF8 should want this
1008 * enabled.
1009 *
1010 * @param on if true, enable metaSendsEscape
1011 * @return the string to emit to xterm
1012 */
1013 public String xtermMetaSendsEscape(final boolean on) {
1014 if (on) {
1015 return "\033[?1036h\033[?1034l";
1016 }
1017 return "\033[?1036l";
1018 }
1019
1020 /**
1021 * Convert a list of SGR parameters into a full escape sequence. This
1022 * also eliminates a trailing ';' which would otherwise reset everything
1023 * to white-on-black not-bold.
1024 *
1025 * @param str string of parameters, e.g. "31;1;"
1026 * @return the string to emit to an ANSI / ECMA-style terminal,
1027 * e.g. "\033[31;1m"
1028 */
1029 public String addHeaderSGR(String str) {
1030 if (str.length() > 0) {
1031 // Nix any trailing ';' because that resets all attributes
1032 while (str.endsWith(":")) {
1033 str = str.substring(0, str.length() - 1);
1034 }
1035 }
1036 return "\033[" + str + "m";
1037 }
1038
1039 /**
1040 * Create a SGR parameter sequence for a single color change.
1041 *
1042 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
1043 * @param foreground if true, this is a foreground color
1044 * @return the string to emit to an ANSI / ECMA-style terminal,
1045 * e.g. "\033[42m"
1046 */
1047 public String color(final Color color, final boolean foreground) {
1048 return color(color, foreground, true);
1049 }
1050
1051 /**
1052 * Create a SGR parameter sequence for a single color change.
1053 *
1054 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
1055 * @param foreground if true, this is a foreground color
1056 * @param header if true, make the full header, otherwise just emit the
1057 * color parameter e.g. "42;"
1058 * @return the string to emit to an ANSI / ECMA-style terminal,
1059 * e.g. "\033[42m"
1060 */
1061 public String color(final Color color, final boolean foreground,
1062 final boolean header) {
1063
1064 int ecmaColor = color.getValue();
1065
1066 // Convert Color.* values to SGR numerics
1067 if (foreground) {
1068 ecmaColor += 30;
1069 } else {
1070 ecmaColor += 40;
1071 }
1072
1073 if (header) {
1074 return String.format("\033[%dm", ecmaColor);
1075 } else {
1076 return String.format("%d;", ecmaColor);
1077 }
1078 }
1079
1080 /**
1081 * Create a SGR parameter sequence for both foreground and
1082 * background color change.
1083 *
1084 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1085 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1086 * @return the string to emit to an ANSI / ECMA-style terminal,
1087 * e.g. "\033[31;42m"
1088 */
1089 public String color(final Color foreColor, final Color backColor) {
1090 return color(foreColor, backColor, true);
1091 }
1092
1093 /**
1094 * Create a SGR parameter sequence for both foreground and
1095 * background color change.
1096 *
1097 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1098 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1099 * @param header if true, make the full header, otherwise just emit the
1100 * color parameter e.g. "31;42;"
1101 * @return the string to emit to an ANSI / ECMA-style terminal,
1102 * e.g. "\033[31;42m"
1103 */
1104 public String color(final Color foreColor, final Color backColor,
1105 final boolean header) {
1106
1107 int ecmaForeColor = foreColor.getValue();
1108 int ecmaBackColor = backColor.getValue();
1109
1110 // Convert Color.* values to SGR numerics
1111 ecmaBackColor += 40;
1112 ecmaForeColor += 30;
1113
1114 if (header) {
1115 return String.format("\033[%d;%dm", ecmaForeColor, ecmaBackColor);
1116 } else {
1117 return String.format("%d;%d;", ecmaForeColor, ecmaBackColor);
1118 }
1119 }
1120
1121 /**
1122 * Create a SGR parameter sequence for foreground, background, and
1123 * several attributes. This sequence first resets all attributes to
1124 * default, then sets attributes as per the parameters.
1125 *
1126 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
1127 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
1128 * @param bold if true, set bold
1129 * @param reverse if true, set reverse
1130 * @param blink if true, set blink
1131 * @param underline if true, set underline
1132 * @return the string to emit to an ANSI / ECMA-style terminal,
1133 * e.g. "\033[0;1;31;42m"
1134 */
1135 public String color(final Color foreColor, final Color backColor,
1136 final boolean bold, final boolean reverse, final boolean blink,
1137 final boolean underline) {
1138
1139 int ecmaForeColor = foreColor.getValue();
1140 int ecmaBackColor = backColor.getValue();
1141
1142 // Convert Color.* values to SGR numerics
1143 ecmaBackColor += 40;
1144 ecmaForeColor += 30;
1145
1146 StringBuilder sb = new StringBuilder();
1147 if ( bold && reverse && blink && !underline ) {
1148 sb.append("\033[0;1;7;5;");
1149 } else if ( bold && reverse && !blink && !underline ) {
1150 sb.append("\033[0;1;7;");
1151 } else if ( !bold && reverse && blink && !underline ) {
1152 sb.append("\033[0;7;5;");
1153 } else if ( bold && !reverse && blink && !underline ) {
1154 sb.append("\033[0;1;5;");
1155 } else if ( bold && !reverse && !blink && !underline ) {
1156 sb.append("\033[0;1;");
1157 } else if ( !bold && reverse && !blink && !underline ) {
1158 sb.append("\033[0;7;");
1159 } else if ( !bold && !reverse && blink && !underline) {
1160 sb.append("\033[0;5;");
1161 } else if ( bold && reverse && blink && underline ) {
1162 sb.append("\033[0;1;7;5;4;");
1163 } else if ( bold && reverse && !blink && underline ) {
1164 sb.append("\033[0;1;7;4;");
1165 } else if ( !bold && reverse && blink && underline ) {
1166 sb.append("\033[0;7;5;4;");
1167 } else if ( bold && !reverse && blink && underline ) {
1168 sb.append("\033[0;1;5;4;");
1169 } else if ( bold && !reverse && !blink && underline ) {
1170 sb.append("\033[0;1;4;");
1171 } else if ( !bold && reverse && !blink && underline ) {
1172 sb.append("\033[0;7;4;");
1173 } else if ( !bold && !reverse && blink && underline) {
1174 sb.append("\033[0;5;4;");
1175 } else if ( !bold && !reverse && !blink && underline) {
1176 sb.append("\033[0;4;");
1177 } else {
1178 assert (!bold && !reverse && !blink && !underline);
1179 sb.append("\033[0;");
1180 }
1181 sb.append(String.format("%d;%dm", ecmaForeColor, ecmaBackColor));
1182 return sb.toString();
1183 }
1184
1185 /**
1186 * Create a SGR parameter sequence for enabling reverse color.
1187 *
1188 * @param on if true, turn on reverse
1189 * @return the string to emit to an ANSI / ECMA-style terminal,
1190 * e.g. "\033[7m"
1191 */
1192 public String reverse(final boolean on) {
1193 if (on) {
1194 return "\033[7m";
1195 }
1196 return "\033[27m";
1197 }
1198
1199 /**
1200 * Create a SGR parameter sequence to reset to defaults.
1201 *
1202 * @return the string to emit to an ANSI / ECMA-style terminal,
1203 * e.g. "\033[0m"
1204 */
1205 public String normal() {
1206 return normal(true);
1207 }
1208
1209 /**
1210 * Create a SGR parameter sequence to reset to defaults.
1211 *
1212 * @param header if true, make the full header, otherwise just emit the
1213 * bare parameter e.g. "0;"
1214 * @return the string to emit to an ANSI / ECMA-style terminal,
1215 * e.g. "\033[0m"
1216 */
1217 public String normal(final boolean header) {
1218 if (header) {
1219 return "\033[0;37;40m";
1220 }
1221 return "0;37;40";
1222 }
1223
1224 /**
1225 * Create a SGR parameter sequence for enabling boldface.
1226 *
1227 * @param on if true, turn on bold
1228 * @return the string to emit to an ANSI / ECMA-style terminal,
1229 * e.g. "\033[1m"
1230 */
1231 public String bold(final boolean on) {
1232 return bold(on, true);
1233 }
1234
1235 /**
1236 * Create a SGR parameter sequence for enabling boldface.
1237 *
1238 * @param on if true, turn on bold
1239 * @param header if true, make the full header, otherwise just emit the
1240 * bare parameter e.g. "1;"
1241 * @return the string to emit to an ANSI / ECMA-style terminal,
1242 * e.g. "\033[1m"
1243 */
1244 public String bold(final boolean on, final boolean header) {
1245 if (header) {
1246 if (on) {
1247 return "\033[1m";
1248 }
1249 return "\033[22m";
1250 }
1251 if (on) {
1252 return "1;";
1253 }
1254 return "22;";
1255 }
1256
1257 /**
1258 * Create a SGR parameter sequence for enabling blinking text.
1259 *
1260 * @param on if true, turn on blink
1261 * @return the string to emit to an ANSI / ECMA-style terminal,
1262 * e.g. "\033[5m"
1263 */
1264 public String blink(final boolean on) {
1265 return blink(on, true);
1266 }
1267
1268 /**
1269 * Create a SGR parameter sequence for enabling blinking text.
1270 *
1271 * @param on if true, turn on blink
1272 * @param header if true, make the full header, otherwise just emit the
1273 * bare parameter e.g. "5;"
1274 * @return the string to emit to an ANSI / ECMA-style terminal,
1275 * e.g. "\033[5m"
1276 */
1277 public String blink(final boolean on, final boolean header) {
1278 if (header) {
1279 if (on) {
1280 return "\033[5m";
1281 }
1282 return "\033[25m";
1283 }
1284 if (on) {
1285 return "5;";
1286 }
1287 return "25;";
1288 }
1289
1290 /**
1291 * Create a SGR parameter sequence for enabling underline / underscored
1292 * text.
1293 *
1294 * @param on if true, turn on underline
1295 * @return the string to emit to an ANSI / ECMA-style terminal,
1296 * e.g. "\033[4m"
1297 */
1298 public String underline(final boolean on) {
1299 if (on) {
1300 return "\033[4m";
1301 }
1302 return "\033[24m";
1303 }
1304
1305 /**
1306 * Create a SGR parameter sequence for enabling the visible cursor.
1307 *
1308 * @param on if true, turn on cursor
1309 * @return the string to emit to an ANSI / ECMA-style terminal
1310 */
1311 public String cursor(final boolean on) {
1312 if (on && !cursorOn) {
1313 cursorOn = true;
1314 return "\033[?25h";
1315 }
1316 if (!on && cursorOn) {
1317 cursorOn = false;
1318 return "\033[?25l";
1319 }
1320 return "";
1321 }
1322
1323 /**
1324 * Clear the entire screen. Because some terminals use back-color-erase,
1325 * set the color to white-on-black beforehand.
1326 *
1327 * @return the string to emit to an ANSI / ECMA-style terminal
1328 */
1329 public String clearAll() {
1330 return "\033[0;37;40m\033[2J";
1331 }
1332
1333 /**
1334 * Clear the line from the cursor (inclusive) to the end of the screen.
1335 * Because some terminals use back-color-erase, set the color to
1336 * white-on-black beforehand.
1337 *
1338 * @return the string to emit to an ANSI / ECMA-style terminal
1339 */
1340 public String clearRemainingLine() {
1341 return "\033[0;37;40m\033[K";
1342 }
1343
1344 /**
1345 * Clear the line up the cursor (inclusive). Because some terminals use
1346 * back-color-erase, set the color to white-on-black beforehand.
1347 *
1348 * @return the string to emit to an ANSI / ECMA-style terminal
1349 */
1350 public String clearPreceedingLine() {
1351 return "\033[0;37;40m\033[1K";
1352 }
1353
1354 /**
1355 * Clear the line. Because some terminals use back-color-erase, set the
1356 * color to white-on-black beforehand.
1357 *
1358 * @return the string to emit to an ANSI / ECMA-style terminal
1359 */
1360 public String clearLine() {
1361 return "\033[0;37;40m\033[2K";
1362 }
1363
1364 /**
1365 * Move the cursor to the top-left corner.
1366 *
1367 * @return the string to emit to an ANSI / ECMA-style terminal
1368 */
1369 public String home() {
1370 return "\033[H";
1371 }
1372
1373 /**
1374 * Move the cursor to (x, y).
1375 *
1376 * @param x column coordinate. 0 is the left-most column.
1377 * @param y row coordinate. 0 is the top-most row.
1378 * @return the string to emit to an ANSI / ECMA-style terminal
1379 */
1380 public String gotoXY(final int x, final int y) {
1381 return String.format("\033[%d;%dH", y + 1, x + 1);
1382 }
1383
1384 /**
1385 * Tell (u)xterm that we want to receive mouse events based on "Any event
1386 * tracking" and UTF-8 coordinates. See
1387 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
1388 *
1389 * Note that this also sets the alternate/primary screen buffer.
1390 *
1391 * @param on If true, enable mouse report and use the alternate screen
1392 * buffer. If false disable mouse reporting and use the primary screen
1393 * buffer.
1394 * @return the string to emit to xterm
1395 */
1396 public String mouse(final boolean on) {
1397 if (on) {
1398 return "\033[?1003;1005h\033[?1049h";
1399 }
1400 return "\033[?1003;1005l\033[?1049l";
1401 }
1402
1403 /**
1404 * Read function runs on a separate thread.
1405 */
1406 public void run() {
1407 boolean done = false;
1408 // available() will often return > 1, so we need to read in chunks to
1409 // stay caught up.
1410 char [] readBuffer = new char[128];
1411 List<TInputEvent> events = new LinkedList<TInputEvent>();
1412
1413 while (!done && !stopReaderThread) {
1414 try {
1415 // We assume that if inputStream has bytes available, then
1416 // input won't block on read().
1417 int n = inputStream.available();
1418 if (n > 0) {
1419 if (readBuffer.length < n) {
1420 // The buffer wasn't big enough, make it huger
1421 readBuffer = new char[readBuffer.length * 2];
1422 }
1423
1424 int rc = input.read(readBuffer, 0, n);
1425 // System.err.printf("read() %d", rc); System.err.flush();
1426 if (rc == -1) {
1427 // This is EOF
1428 done = true;
1429 } else {
1430 for (int i = 0; i < rc; i++) {
1431 int ch = readBuffer[i];
1432 processChar(events, (char)ch);
1433 if (events.size() > 0) {
1434 // Add to the queue for the backend thread to
1435 // be able to obtain.
1436 synchronized (eventQueue) {
1437 eventQueue.addAll(events);
1438 }
1439 // Now wake up the backend
1440 synchronized (this) {
1441 this.notifyAll();
1442 }
1443 events.clear();
1444 }
1445 }
1446 }
1447 } else {
1448 // Wait 5 millis for more data
1449 Thread.sleep(5);
1450 }
1451 // System.err.println("end while loop"); System.err.flush();
1452 } catch (InterruptedException e) {
1453 // SQUASH
1454 } catch (IOException e) {
1455 e.printStackTrace();
1456 done = true;
1457 }
1458 } // while ((done == false) && (stopReaderThread == false))
1459 // System.err.println("*** run() exiting..."); System.err.flush();
1460 }
1461
1462 }