2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2016 Kevin Lamonte
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
31 import java
.io
.InputStream
;
32 import java
.io
.IOException
;
33 import java
.io
.OutputStream
;
34 import java
.io
.UnsupportedEncodingException
;
35 import java
.lang
.reflect
.Field
;
36 import java
.util
.LinkedList
;
37 import java
.util
.List
;
40 import jexer
.bits
.Cell
;
41 import jexer
.bits
.CellAttributes
;
42 import jexer
.event
.TKeypressEvent
;
43 import jexer
.event
.TMouseEvent
;
44 import jexer
.event
.TResizeEvent
;
45 import jexer
.tterminal
.DisplayLine
;
46 import jexer
.tterminal
.ECMA48
;
47 import static jexer
.TKeypress
.*;
50 * TTerminalWindow exposes a ECMA-48 / ANSI X3.64 style terminal in a window.
52 public class TTerminalWindow
extends TWindow
{
57 private ECMA48 emulator
;
60 * The Process created by the shell spawning constructor.
62 private Process shell
;
67 private TVScroller vScroller
;
70 * Claim the keystrokes the emulator will need.
72 private void addShortcutKeys() {
73 addShortcutKeypress(kbCtrlA
);
74 addShortcutKeypress(kbCtrlB
);
75 addShortcutKeypress(kbCtrlC
);
76 addShortcutKeypress(kbCtrlD
);
77 addShortcutKeypress(kbCtrlE
);
78 addShortcutKeypress(kbCtrlF
);
79 addShortcutKeypress(kbCtrlG
);
80 addShortcutKeypress(kbCtrlH
);
81 addShortcutKeypress(kbCtrlU
);
82 addShortcutKeypress(kbCtrlJ
);
83 addShortcutKeypress(kbCtrlK
);
84 addShortcutKeypress(kbCtrlL
);
85 addShortcutKeypress(kbCtrlM
);
86 addShortcutKeypress(kbCtrlN
);
87 addShortcutKeypress(kbCtrlO
);
88 addShortcutKeypress(kbCtrlP
);
89 addShortcutKeypress(kbCtrlQ
);
90 addShortcutKeypress(kbCtrlR
);
91 addShortcutKeypress(kbCtrlS
);
92 addShortcutKeypress(kbCtrlT
);
93 addShortcutKeypress(kbCtrlU
);
94 addShortcutKeypress(kbCtrlV
);
95 addShortcutKeypress(kbCtrlW
);
96 addShortcutKeypress(kbCtrlX
);
97 addShortcutKeypress(kbCtrlY
);
98 addShortcutKeypress(kbCtrlZ
);
99 addShortcutKeypress(kbF1
);
100 addShortcutKeypress(kbF2
);
101 addShortcutKeypress(kbF3
);
102 addShortcutKeypress(kbF4
);
103 addShortcutKeypress(kbF5
);
104 addShortcutKeypress(kbF6
);
105 addShortcutKeypress(kbF7
);
106 addShortcutKeypress(kbF8
);
107 addShortcutKeypress(kbF9
);
108 addShortcutKeypress(kbF10
);
109 addShortcutKeypress(kbF11
);
110 addShortcutKeypress(kbF12
);
111 addShortcutKeypress(kbAltA
);
112 addShortcutKeypress(kbAltB
);
113 addShortcutKeypress(kbAltC
);
114 addShortcutKeypress(kbAltD
);
115 addShortcutKeypress(kbAltE
);
116 addShortcutKeypress(kbAltF
);
117 addShortcutKeypress(kbAltG
);
118 addShortcutKeypress(kbAltH
);
119 addShortcutKeypress(kbAltU
);
120 addShortcutKeypress(kbAltJ
);
121 addShortcutKeypress(kbAltK
);
122 addShortcutKeypress(kbAltL
);
123 addShortcutKeypress(kbAltM
);
124 addShortcutKeypress(kbAltN
);
125 addShortcutKeypress(kbAltO
);
126 addShortcutKeypress(kbAltP
);
127 addShortcutKeypress(kbAltQ
);
128 addShortcutKeypress(kbAltR
);
129 addShortcutKeypress(kbAltS
);
130 addShortcutKeypress(kbAltT
);
131 addShortcutKeypress(kbAltU
);
132 addShortcutKeypress(kbAltV
);
133 addShortcutKeypress(kbAltW
);
134 addShortcutKeypress(kbAltX
);
135 addShortcutKeypress(kbAltY
);
136 addShortcutKeypress(kbAltZ
);
140 * Public constructor spawns a shell.
142 * @param application TApplication that manages this window
143 * @param x column relative to parent
144 * @param y row relative to parent
145 * @param flags mask of CENTERED, MODAL, or RESIZABLE
147 public TTerminalWindow(final TApplication application
, final int x
,
148 final int y
, final int flags
) {
150 super(application
, "Terminal", x
, y
, 80 + 2, 24 + 2, flags
);
153 ECMA48
.DeviceType deviceType
= ECMA48
.DeviceType
.XTERM
;
156 String
[] cmdShellWindows
= {
160 // You cannot run a login shell in a bare Process interactively,
161 // due to libc's behavior of buffering when stdin/stdout aren't a
162 // tty. Use 'script' instead to run a shell in a pty. And
163 // because BSD and GNU differ on the '-f' vs '-F' flags, we need
164 // two different commands. Lovely.
165 String
[] cmdShellGNU
= {
166 "script", "-fqe", "/dev/null"
168 String
[] cmdShellBSD
= {
169 "script", "-qe", "-F", "/dev/null"
171 // Spawn a shell and pass its I/O to the other constructor.
174 if (System
.getProperty("os.name").startsWith("Windows")) {
175 pb
= new ProcessBuilder(cmdShellWindows
);
176 } else if (System
.getProperty("os.name").startsWith("Mac")) {
177 pb
= new ProcessBuilder(cmdShellBSD
);
178 } else if (System
.getProperty("os.name").startsWith("Linux")) {
179 pb
= new ProcessBuilder(cmdShellGNU
);
181 // When all else fails, assume GNU.
182 pb
= new ProcessBuilder(cmdShellGNU
);
184 Map
<String
, String
> env
= pb
.environment();
185 env
.put("TERM", ECMA48
.deviceTypeTerm(deviceType
));
186 env
.put("LANG", ECMA48
.deviceTypeLang(deviceType
, "en"));
187 env
.put("COLUMNS", "80");
188 env
.put("LINES", "24");
189 pb
.redirectErrorStream(true);
191 emulator
= new ECMA48(deviceType
, shell
.getInputStream(),
192 shell
.getOutputStream());
193 } catch (IOException e
) {
197 // Setup the scroll bars
198 onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
, getWidth(),
201 // Claim the keystrokes the emulator will need.
206 * Terminate the child of the 'script' process used on POSIX. This may
209 private void terminateShellChildProcess() {
211 if (shell
.getClass().getName().equals("java.lang.UNIXProcess")) {
212 /* get the PID on unix/linux systems */
214 Field field
= shell
.getClass().getDeclaredField("pid");
215 field
.setAccessible(true);
216 pid
= field
.getInt(shell
);
217 } catch (Throwable e
) {
218 // SQUASH, this didn't work. Just bail out quietly.
223 // shell.destroy() works successfully at killing this side of
224 // 'script'. But we need to make sure the other side (child
225 // process) is also killed.
226 String
[] cmdKillIt
= {
227 "pkill", "-P", Integer
.toString(pid
)
230 Runtime
.getRuntime().exec(cmdKillIt
);
231 } catch (Throwable e
) {
232 // SQUASH, this didn't work. Just bail out quietly.
239 * Public constructor.
241 * @param application TApplication that manages this window
242 * @param x column relative to parent
243 * @param y row relative to parent
244 * @param flags mask of CENTERED, MODAL, or RESIZABLE
245 * @param input an InputStream connected to the remote side. For type ==
246 * XTERM, input is converted to a Reader with UTF-8 encoding.
247 * @param output an OutputStream connected to the remote user. For type
248 * == XTERM, output is converted to a Writer with UTF-8 encoding.
249 * @throws UnsupportedEncodingException if an exception is thrown when
250 * creating the InputStreamReader
252 public TTerminalWindow(final TApplication application
, final int x
,
253 final int y
, final int flags
, final InputStream input
,
254 final OutputStream output
) throws UnsupportedEncodingException
{
256 super(application
, "Terminal", x
, y
, 80 + 2, 24 + 2, flags
);
258 emulator
= new ECMA48(ECMA48
.DeviceType
.XTERM
, input
, output
);
260 // Setup the scroll bars
261 onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
, getWidth(),
264 // Claim the keystrokes the emulator will need.
269 * Draw the display buffer.
273 // Synchronize against the emulator so we don't stomp on its reader
275 synchronized (emulator
) {
277 // Update the scroll bars
280 // Draw the box using my superclass
283 List
<DisplayLine
> scrollback
= emulator
.getScrollbackBuffer();
284 List
<DisplayLine
> display
= emulator
.getDisplayBuffer();
286 // Put together the visible rows
287 int visibleHeight
= getHeight() - 2;
288 int visibleBottom
= scrollback
.size() + display
.size()
289 + vScroller
.getValue();
290 assert (visibleBottom
>= 0);
292 List
<DisplayLine
> preceedingBlankLines
= new LinkedList
<DisplayLine
>();
293 int visibleTop
= visibleBottom
- visibleHeight
;
294 if (visibleTop
< 0) {
295 for (int i
= visibleTop
; i
< 0; i
++) {
296 preceedingBlankLines
.add(emulator
.getBlankDisplayLine());
300 assert (visibleTop
>= 0);
302 List
<DisplayLine
> displayLines
= new LinkedList
<DisplayLine
>();
303 displayLines
.addAll(scrollback
);
304 displayLines
.addAll(display
);
306 List
<DisplayLine
> visibleLines
= new LinkedList
<DisplayLine
>();
307 visibleLines
.addAll(preceedingBlankLines
);
308 visibleLines
.addAll(displayLines
.subList(visibleTop
,
311 visibleHeight
-= visibleLines
.size();
312 assert (visibleHeight
>= 0);
314 // Now draw the emulator screen
316 for (DisplayLine line
: visibleLines
) {
317 int widthMax
= emulator
.getWidth();
318 if (line
.isDoubleWidth()) {
321 if (widthMax
> getWidth() - 2) {
322 widthMax
= getWidth() - 2;
324 for (int i
= 0; i
< widthMax
; i
++) {
325 Cell ch
= line
.charAt(i
);
326 Cell newCell
= new Cell();
328 boolean reverse
= line
.isReverseColor() ^ ch
.isReverse();
329 newCell
.setReverse(false);
331 newCell
.setBackColor(ch
.getForeColor());
332 newCell
.setForeColor(ch
.getBackColor());
334 if (line
.isDoubleWidth()) {
335 getScreen().putCharXY((i
* 2) + 1, row
, newCell
);
336 getScreen().putCharXY((i
* 2) + 2, row
, ' ', newCell
);
338 getScreen().putCharXY(i
+ 1, row
, newCell
);
342 if (row
== getHeight() - 1) {
343 // Don't overwrite the box edge
347 CellAttributes background
= new CellAttributes();
348 // Fill in the blank lines on bottom
349 for (int i
= 0; i
< visibleHeight
; i
++) {
350 getScreen().hLineXY(1, i
+ row
, getWidth() - 2, ' ',
354 } // synchronized (emulator)
359 * Handle window close.
361 @Override public void onClose() {
364 terminateShellChildProcess();
371 * Copy out variables from the emulator that TTerminal has to expose on
374 private void readEmulatorState() {
375 // Synchronize against the emulator so we don't stomp on its reader
377 synchronized (emulator
) {
379 setCursorX(emulator
.getCursorX() + 1);
380 setCursorY(emulator
.getCursorY() + 1
381 + (getHeight() - 2 - emulator
.getHeight()));
382 if (vScroller
!= null) {
383 setCursorY(getCursorY() - vScroller
.getValue());
385 setCursorVisible(emulator
.isCursorVisible());
386 if (getCursorX() > getWidth() - 2) {
387 setCursorVisible(false);
389 if ((getCursorY() > getHeight() - 2) || (getCursorY() < 0)) {
390 setCursorVisible(false);
392 if (emulator
.getScreenTitle().length() > 0) {
393 // Only update the title if the shell is still alive
395 setTitle(emulator
.getScreenTitle());
399 // Check to see if the shell has died.
400 if (!emulator
.isReading() && (shell
!= null)) {
402 int rc
= shell
.exitValue();
403 // The emulator exited on its own, all is fine
404 setTitle(String
.format("%s [Completed - %d]",
408 clearShortcutKeypresses();
409 } catch (IllegalThreadStateException e
) {
410 // The emulator thread has exited, but the shell Process
411 // hasn't figured that out yet. Do nothing, we will see
412 // this in a future tick.
414 } else if (emulator
.isReading() && (shell
!= null)) {
415 // The shell might be dead, let's check
417 int rc
= shell
.exitValue();
418 // If we got here, the shell died.
419 setTitle(String
.format("%s [Completed - %d]",
423 clearShortcutKeypresses();
424 } catch (IllegalThreadStateException e
) {
425 // The shell is still running, do nothing.
429 } // synchronized (emulator)
433 * Handle window/screen resize events.
435 * @param resize resize event
438 public void onResize(final TResizeEvent resize
) {
440 // Synchronize against the emulator so we don't stomp on its reader
442 synchronized (emulator
) {
444 if (resize
.getType() == TResizeEvent
.Type
.WIDGET
) {
445 // Resize the scroll bars
448 // Get out of scrollback
449 vScroller
.setValue(0);
453 } // synchronized (emulator)
457 * Resize scrollbars for a new width/height.
459 private void reflow() {
461 // Synchronize against the emulator so we don't stomp on its reader
463 synchronized (emulator
) {
465 // Pull cursor information
468 // Vertical scrollbar
469 if (vScroller
== null) {
470 vScroller
= new TVScroller(this, getWidth() - 2, 0,
472 vScroller
.setBottomValue(0);
473 vScroller
.setValue(0);
475 vScroller
.setX(getWidth() - 2);
476 vScroller
.setHeight(getHeight() - 2);
478 vScroller
.setTopValue(getHeight() - 2
479 - (emulator
.getScrollbackBuffer().size()
480 + emulator
.getDisplayBuffer().size()));
481 vScroller
.setBigChange(getHeight() - 2);
483 } // synchronized (emulator)
487 * Check if a mouse press/release/motion event coordinate is over the
490 * @param mouse a mouse-based event
491 * @return whether or not the mouse is on the emulator
493 private final boolean mouseOnEmulator(final TMouseEvent mouse
) {
495 synchronized (emulator
) {
496 if (!emulator
.isReading()) {
501 if ((mouse
.getAbsoluteX() >= getAbsoluteX() + 1)
502 && (mouse
.getAbsoluteX() < getAbsoluteX() + getWidth() - 1)
503 && (mouse
.getAbsoluteY() >= getAbsoluteY() + 1)
504 && (mouse
.getAbsoluteY() < getAbsoluteY() + getHeight() - 1)
514 * @param keypress keystroke event
517 public void onKeypress(final TKeypressEvent keypress
) {
519 // Scrollback up/down
520 if (keypress
.equals(kbShiftPgUp
)
521 || keypress
.equals(kbCtrlPgUp
)
522 || keypress
.equals(kbAltPgUp
)
524 vScroller
.bigDecrement();
527 if (keypress
.equals(kbShiftPgDn
)
528 || keypress
.equals(kbCtrlPgDn
)
529 || keypress
.equals(kbAltPgDn
)
531 vScroller
.bigIncrement();
535 // Synchronize against the emulator so we don't stomp on its reader
537 synchronized (emulator
) {
538 if (emulator
.isReading()) {
539 // Get out of scrollback
540 vScroller
.setValue(0);
541 emulator
.keypress(keypress
.getKey());
543 // UGLY HACK TIME! cmd.exe needs CRLF, not just CR, so if
544 // this is kBEnter then also send kbCtrlJ.
545 if (System
.getProperty("os.name").startsWith("Windows")) {
546 if (keypress
.equals(kbEnter
)) {
547 emulator
.keypress(kbCtrlJ
);
556 // Process is closed, honor "normal" TUI keystrokes
557 super.onKeypress(keypress
);
561 * Handle mouse press events.
563 * @param mouse mouse button press event
566 public void onMouseDown(final TMouseEvent mouse
) {
567 if (inWindowMove
|| inWindowResize
) {
568 // TWindow needs to deal with this.
569 super.onMouseDown(mouse
);
573 if (mouse
.isMouseWheelUp()) {
574 vScroller
.decrement();
577 if (mouse
.isMouseWheelDown()) {
578 vScroller
.increment();
581 if (mouseOnEmulator(mouse
)) {
582 synchronized (emulator
) {
583 mouse
.setX(mouse
.getX() - 1);
584 mouse
.setY(mouse
.getY() - 1);
585 emulator
.mouse(mouse
);
591 // Emulator didn't consume it, pass it on
592 super.onMouseDown(mouse
);
596 * Handle mouse release events.
598 * @param mouse mouse button release event
601 public void onMouseUp(final TMouseEvent mouse
) {
602 if (inWindowMove
|| inWindowResize
) {
603 // TWindow needs to deal with this.
604 super.onMouseUp(mouse
);
608 if (mouseOnEmulator(mouse
)) {
609 synchronized (emulator
) {
610 mouse
.setX(mouse
.getX() - 1);
611 mouse
.setY(mouse
.getY() - 1);
612 emulator
.mouse(mouse
);
618 // Emulator didn't consume it, pass it on
619 super.onMouseUp(mouse
);
623 * Handle mouse motion events.
625 * @param mouse mouse motion event
628 public void onMouseMotion(final TMouseEvent mouse
) {
629 if (inWindowMove
|| inWindowResize
) {
630 // TWindow needs to deal with this.
631 super.onMouseMotion(mouse
);
635 if (mouseOnEmulator(mouse
)) {
636 synchronized (emulator
) {
637 mouse
.setX(mouse
.getX() - 1);
638 mouse
.setY(mouse
.getY() - 1);
639 emulator
.mouse(mouse
);
645 // Emulator didn't consume it, pass it on
646 super.onMouseMotion(mouse
);