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]
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 TScrollableWindow
{
57 private ECMA48 emulator
;
60 * The Process created by the shell spawning constructor.
62 private Process shell
;
65 * Claim the keystrokes the emulator will need.
67 private void addShortcutKeys() {
68 addShortcutKeypress(kbCtrlA
);
69 addShortcutKeypress(kbCtrlB
);
70 addShortcutKeypress(kbCtrlC
);
71 addShortcutKeypress(kbCtrlD
);
72 addShortcutKeypress(kbCtrlE
);
73 addShortcutKeypress(kbCtrlF
);
74 addShortcutKeypress(kbCtrlG
);
75 addShortcutKeypress(kbCtrlH
);
76 addShortcutKeypress(kbCtrlU
);
77 addShortcutKeypress(kbCtrlJ
);
78 addShortcutKeypress(kbCtrlK
);
79 addShortcutKeypress(kbCtrlL
);
80 addShortcutKeypress(kbCtrlM
);
81 addShortcutKeypress(kbCtrlN
);
82 addShortcutKeypress(kbCtrlO
);
83 addShortcutKeypress(kbCtrlP
);
84 addShortcutKeypress(kbCtrlQ
);
85 addShortcutKeypress(kbCtrlR
);
86 addShortcutKeypress(kbCtrlS
);
87 addShortcutKeypress(kbCtrlT
);
88 addShortcutKeypress(kbCtrlU
);
89 addShortcutKeypress(kbCtrlV
);
90 addShortcutKeypress(kbCtrlW
);
91 addShortcutKeypress(kbCtrlX
);
92 addShortcutKeypress(kbCtrlY
);
93 addShortcutKeypress(kbCtrlZ
);
94 addShortcutKeypress(kbF1
);
95 addShortcutKeypress(kbF2
);
96 addShortcutKeypress(kbF3
);
97 addShortcutKeypress(kbF4
);
98 addShortcutKeypress(kbF5
);
99 addShortcutKeypress(kbF6
);
100 addShortcutKeypress(kbF7
);
101 addShortcutKeypress(kbF8
);
102 addShortcutKeypress(kbF9
);
103 addShortcutKeypress(kbF10
);
104 addShortcutKeypress(kbF11
);
105 addShortcutKeypress(kbF12
);
106 addShortcutKeypress(kbAltA
);
107 addShortcutKeypress(kbAltB
);
108 addShortcutKeypress(kbAltC
);
109 addShortcutKeypress(kbAltD
);
110 addShortcutKeypress(kbAltE
);
111 addShortcutKeypress(kbAltF
);
112 addShortcutKeypress(kbAltG
);
113 addShortcutKeypress(kbAltH
);
114 addShortcutKeypress(kbAltU
);
115 addShortcutKeypress(kbAltJ
);
116 addShortcutKeypress(kbAltK
);
117 addShortcutKeypress(kbAltL
);
118 addShortcutKeypress(kbAltM
);
119 addShortcutKeypress(kbAltN
);
120 addShortcutKeypress(kbAltO
);
121 addShortcutKeypress(kbAltP
);
122 addShortcutKeypress(kbAltQ
);
123 addShortcutKeypress(kbAltR
);
124 addShortcutKeypress(kbAltS
);
125 addShortcutKeypress(kbAltT
);
126 addShortcutKeypress(kbAltU
);
127 addShortcutKeypress(kbAltV
);
128 addShortcutKeypress(kbAltW
);
129 addShortcutKeypress(kbAltX
);
130 addShortcutKeypress(kbAltY
);
131 addShortcutKeypress(kbAltZ
);
135 * Public constructor spawns a shell.
137 * @param application TApplication that manages this window
138 * @param x column relative to parent
139 * @param y row relative to parent
140 * @param flags mask of CENTERED, MODAL, or RESIZABLE
142 public TTerminalWindow(final TApplication application
, final int x
,
143 final int y
, final int flags
) {
145 super(application
, "Terminal", x
, y
, 80 + 2, 24 + 2, flags
);
147 vScroller
= new TVScroller(this, getWidth() - 2, 0, getHeight() - 2);
151 ECMA48
.DeviceType deviceType
= ECMA48
.DeviceType
.XTERM
;
154 String
[] cmdShellWindows
= {
158 // You cannot run a login shell in a bare Process interactively,
159 // due to libc's behavior of buffering when stdin/stdout aren't a
160 // tty. Use 'script' instead to run a shell in a pty. And
161 // because BSD and GNU differ on the '-f' vs '-F' flags, we need
162 // two different commands. Lovely.
163 String
[] cmdShellGNU
= {
164 "script", "-fqe", "/dev/null"
166 String
[] cmdShellBSD
= {
167 "script", "-q", "-F", "/dev/null"
169 // Spawn a shell and pass its I/O to the other constructor.
172 if (System
.getProperty("os.name").startsWith("Windows")) {
173 pb
= new ProcessBuilder(cmdShellWindows
);
174 } else if (System
.getProperty("os.name").startsWith("Mac")) {
175 pb
= new ProcessBuilder(cmdShellBSD
);
176 } else if (System
.getProperty("os.name").startsWith("Linux")) {
177 pb
= new ProcessBuilder(cmdShellGNU
);
179 // When all else fails, assume GNU.
180 pb
= new ProcessBuilder(cmdShellGNU
);
182 Map
<String
, String
> env
= pb
.environment();
183 env
.put("TERM", ECMA48
.deviceTypeTerm(deviceType
));
184 env
.put("LANG", ECMA48
.deviceTypeLang(deviceType
, "en"));
185 env
.put("COLUMNS", "80");
186 env
.put("LINES", "24");
187 pb
.redirectErrorStream(true);
189 emulator
= new ECMA48(deviceType
, shell
.getInputStream(),
190 shell
.getOutputStream());
191 } catch (IOException e
) {
195 // Setup the scroll bars
196 onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
, getWidth(),
199 // Claim the keystrokes the emulator will need.
203 newStatusBar("Terminal session executing...");
207 * Terminate the child of the 'script' process used on POSIX. This may
210 private void terminateShellChildProcess() {
212 if (shell
.getClass().getName().equals("java.lang.UNIXProcess")) {
213 /* get the PID on unix/linux systems */
215 Field field
= shell
.getClass().getDeclaredField("pid");
216 field
.setAccessible(true);
217 pid
= field
.getInt(shell
);
218 } catch (Throwable e
) {
219 // SQUASH, this didn't work. Just bail out quietly.
224 // shell.destroy() works successfully at killing this side of
225 // 'script'. But we need to make sure the other side (child
226 // process) is also killed.
227 String
[] cmdKillIt
= {
228 "pkill", "-P", Integer
.toString(pid
)
231 Runtime
.getRuntime().exec(cmdKillIt
);
232 } catch (Throwable e
) {
233 // SQUASH, this didn't work. Just bail out quietly.
240 * Public constructor.
242 * @param application TApplication that manages this window
243 * @param x column relative to parent
244 * @param y row relative to parent
245 * @param flags mask of CENTERED, MODAL, or RESIZABLE
246 * @param input an InputStream connected to the remote side. For type ==
247 * XTERM, input is converted to a Reader with UTF-8 encoding.
248 * @param output an OutputStream connected to the remote user. For type
249 * == XTERM, output is converted to a Writer with UTF-8 encoding.
250 * @throws UnsupportedEncodingException if an exception is thrown when
251 * creating the InputStreamReader
253 public TTerminalWindow(final TApplication application
, final int x
,
254 final int y
, final int flags
, final InputStream input
,
255 final OutputStream output
) throws UnsupportedEncodingException
{
257 super(application
, "Terminal", x
, y
, 80 + 2, 24 + 2, flags
);
259 emulator
= new ECMA48(ECMA48
.DeviceType
.XTERM
, input
, output
);
261 // Setup the scroll bars
262 onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
, getWidth(),
265 // Claim the keystrokes the emulator will need.
269 newStatusBar("Terminal session executing...");
273 * Draw the display buffer.
277 // Synchronize against the emulator so we don't stomp on its reader
279 synchronized (emulator
) {
281 // Update the scroll bars
284 // Draw the box using my superclass
287 List
<DisplayLine
> scrollback
= emulator
.getScrollbackBuffer();
288 List
<DisplayLine
> display
= emulator
.getDisplayBuffer();
290 // Put together the visible rows
291 int visibleHeight
= getHeight() - 2;
292 int visibleBottom
= scrollback
.size() + display
.size()
293 + getVerticalValue();
294 assert (visibleBottom
>= 0);
296 List
<DisplayLine
> preceedingBlankLines
= new LinkedList
<DisplayLine
>();
297 int visibleTop
= visibleBottom
- visibleHeight
;
298 if (visibleTop
< 0) {
299 for (int i
= visibleTop
; i
< 0; i
++) {
300 preceedingBlankLines
.add(emulator
.getBlankDisplayLine());
304 assert (visibleTop
>= 0);
306 List
<DisplayLine
> displayLines
= new LinkedList
<DisplayLine
>();
307 displayLines
.addAll(scrollback
);
308 displayLines
.addAll(display
);
310 List
<DisplayLine
> visibleLines
= new LinkedList
<DisplayLine
>();
311 visibleLines
.addAll(preceedingBlankLines
);
312 visibleLines
.addAll(displayLines
.subList(visibleTop
,
315 visibleHeight
-= visibleLines
.size();
316 assert (visibleHeight
>= 0);
318 // Now draw the emulator screen
320 for (DisplayLine line
: visibleLines
) {
321 int widthMax
= emulator
.getWidth();
322 if (line
.isDoubleWidth()) {
325 if (widthMax
> getWidth() - 2) {
326 widthMax
= getWidth() - 2;
328 for (int i
= 0; i
< widthMax
; i
++) {
329 Cell ch
= line
.charAt(i
);
330 Cell newCell
= new Cell();
332 boolean reverse
= line
.isReverseColor() ^ ch
.isReverse();
333 newCell
.setReverse(false);
335 newCell
.setBackColor(ch
.getForeColor());
336 newCell
.setForeColor(ch
.getBackColor());
338 if (line
.isDoubleWidth()) {
339 getScreen().putCharXY((i
* 2) + 1, row
, newCell
);
340 getScreen().putCharXY((i
* 2) + 2, row
, ' ', newCell
);
342 getScreen().putCharXY(i
+ 1, row
, newCell
);
346 if (row
== getHeight() - 1) {
347 // Don't overwrite the box edge
351 CellAttributes background
= new CellAttributes();
352 // Fill in the blank lines on bottom
353 for (int i
= 0; i
< visibleHeight
; i
++) {
354 getScreen().hLineXY(1, i
+ row
, getWidth() - 2, ' ',
358 } // synchronized (emulator)
363 * Handle window close.
366 public void onClose() {
369 terminateShellChildProcess();
376 * Copy out variables from the emulator that TTerminal has to expose on
379 private void readEmulatorState() {
380 // Synchronize against the emulator so we don't stomp on its reader
382 synchronized (emulator
) {
384 setCursorX(emulator
.getCursorX() + 1);
385 setCursorY(emulator
.getCursorY() + 1
386 + (getHeight() - 2 - emulator
.getHeight())
387 - getVerticalValue());
388 setCursorVisible(emulator
.isCursorVisible());
389 if (getCursorX() > getWidth() - 2) {
390 setCursorVisible(false);
392 if ((getCursorY() > getHeight() - 2) || (getCursorY() < 0)) {
393 setCursorVisible(false);
395 if (emulator
.getScreenTitle().length() > 0) {
396 // Only update the title if the shell is still alive
398 setTitle(emulator
.getScreenTitle());
402 // Check to see if the shell has died.
403 if (!emulator
.isReading() && (shell
!= null)) {
405 int rc
= shell
.exitValue();
406 // The emulator exited on its own, all is fine
407 setTitle(String
.format("%s [Completed - %d]",
411 clearShortcutKeypresses();
412 statusBar
.setText("Terminal session completed, exit " +
414 } catch (IllegalThreadStateException e
) {
415 // The emulator thread has exited, but the shell Process
416 // hasn't figured that out yet. Do nothing, we will see
417 // this in a future tick.
419 } else if (emulator
.isReading() && (shell
!= null)) {
420 // The shell might be dead, let's check
422 int rc
= shell
.exitValue();
423 // If we got here, the shell died.
424 setTitle(String
.format("%s [Completed - %d]",
428 clearShortcutKeypresses();
429 statusBar
.setText("Terminal session completed, exit " +
431 } catch (IllegalThreadStateException e
) {
432 // The shell is still running, do nothing.
436 } // synchronized (emulator)
440 * Handle window/screen resize events.
442 * @param resize resize event
445 public void onResize(final TResizeEvent resize
) {
447 // Synchronize against the emulator so we don't stomp on its reader
449 synchronized (emulator
) {
451 if (resize
.getType() == TResizeEvent
.Type
.WIDGET
) {
452 // Resize the scroll bars
456 // Get out of scrollback
461 } // synchronized (emulator)
465 * Resize scrollbars for a new width/height.
468 public void reflowData() {
470 // Synchronize against the emulator so we don't stomp on its reader
472 synchronized (emulator
) {
474 // Pull cursor information
477 // Vertical scrollbar
478 setTopValue(getHeight() - 2
479 - (emulator
.getScrollbackBuffer().size()
480 + emulator
.getDisplayBuffer().size()));
481 setVerticalBigChange(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 bigVerticalDecrement();
527 if (keypress
.equals(kbShiftPgDn
)
528 || keypress
.equals(kbCtrlPgDn
)
529 || keypress
.equals(kbAltPgDn
)
531 bigVerticalIncrement();
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
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()) {
577 if (mouse
.isMouseWheelDown()) {
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
);