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
.IOException
;
32 import java
.lang
.reflect
.Field
;
33 import java
.util
.LinkedList
;
34 import java
.util
.List
;
37 import jexer
.bits
.Cell
;
38 import jexer
.bits
.CellAttributes
;
39 import jexer
.event
.TKeypressEvent
;
40 import jexer
.event
.TMouseEvent
;
41 import jexer
.event
.TResizeEvent
;
42 import jexer
.tterminal
.DisplayLine
;
43 import jexer
.tterminal
.ECMA48
;
44 import static jexer
.TKeypress
.*;
47 * TTerminalWindow exposes a ECMA-48 / ANSI X3.64 style terminal in a window.
49 public class TTerminalWindow
extends TScrollableWindow
{
54 private ECMA48 emulator
;
57 * The Process created by the shell spawning constructor.
59 private Process shell
;
62 * Claim the keystrokes the emulator will need.
64 private void addShortcutKeys() {
65 addShortcutKeypress(kbCtrlA
);
66 addShortcutKeypress(kbCtrlB
);
67 addShortcutKeypress(kbCtrlC
);
68 addShortcutKeypress(kbCtrlD
);
69 addShortcutKeypress(kbCtrlE
);
70 addShortcutKeypress(kbCtrlF
);
71 addShortcutKeypress(kbCtrlG
);
72 addShortcutKeypress(kbCtrlH
);
73 addShortcutKeypress(kbCtrlU
);
74 addShortcutKeypress(kbCtrlJ
);
75 addShortcutKeypress(kbCtrlK
);
76 addShortcutKeypress(kbCtrlL
);
77 addShortcutKeypress(kbCtrlM
);
78 addShortcutKeypress(kbCtrlN
);
79 addShortcutKeypress(kbCtrlO
);
80 addShortcutKeypress(kbCtrlP
);
81 addShortcutKeypress(kbCtrlQ
);
82 addShortcutKeypress(kbCtrlR
);
83 addShortcutKeypress(kbCtrlS
);
84 addShortcutKeypress(kbCtrlT
);
85 addShortcutKeypress(kbCtrlU
);
86 addShortcutKeypress(kbCtrlV
);
87 addShortcutKeypress(kbCtrlW
);
88 addShortcutKeypress(kbCtrlX
);
89 addShortcutKeypress(kbCtrlY
);
90 addShortcutKeypress(kbCtrlZ
);
91 addShortcutKeypress(kbF1
);
92 addShortcutKeypress(kbF2
);
93 addShortcutKeypress(kbF3
);
94 addShortcutKeypress(kbF4
);
95 addShortcutKeypress(kbF5
);
96 addShortcutKeypress(kbF6
);
97 addShortcutKeypress(kbF7
);
98 addShortcutKeypress(kbF8
);
99 addShortcutKeypress(kbF9
);
100 addShortcutKeypress(kbF10
);
101 addShortcutKeypress(kbF11
);
102 addShortcutKeypress(kbF12
);
103 addShortcutKeypress(kbAltA
);
104 addShortcutKeypress(kbAltB
);
105 addShortcutKeypress(kbAltC
);
106 addShortcutKeypress(kbAltD
);
107 addShortcutKeypress(kbAltE
);
108 addShortcutKeypress(kbAltF
);
109 addShortcutKeypress(kbAltG
);
110 addShortcutKeypress(kbAltH
);
111 addShortcutKeypress(kbAltU
);
112 addShortcutKeypress(kbAltJ
);
113 addShortcutKeypress(kbAltK
);
114 addShortcutKeypress(kbAltL
);
115 addShortcutKeypress(kbAltM
);
116 addShortcutKeypress(kbAltN
);
117 addShortcutKeypress(kbAltO
);
118 addShortcutKeypress(kbAltP
);
119 addShortcutKeypress(kbAltQ
);
120 addShortcutKeypress(kbAltR
);
121 addShortcutKeypress(kbAltS
);
122 addShortcutKeypress(kbAltT
);
123 addShortcutKeypress(kbAltU
);
124 addShortcutKeypress(kbAltV
);
125 addShortcutKeypress(kbAltW
);
126 addShortcutKeypress(kbAltX
);
127 addShortcutKeypress(kbAltY
);
128 addShortcutKeypress(kbAltZ
);
132 * Public constructor spawns a shell.
134 * @param application TApplication that manages this window
135 * @param x column relative to parent
136 * @param y row relative to parent
137 * @param flags mask of CENTERED, MODAL, or RESIZABLE
139 public TTerminalWindow(final TApplication application
, final int x
,
140 final int y
, final int flags
) {
142 super(application
, "Terminal", x
, y
, 80 + 2, 24 + 2, flags
);
144 vScroller
= new TVScroller(this, getWidth() - 2, 0, getHeight() - 2);
148 ECMA48
.DeviceType deviceType
= ECMA48
.DeviceType
.XTERM
;
151 String
[] cmdShellWindows
= {
155 // You cannot run a login shell in a bare Process interactively,
156 // due to libc's behavior of buffering when stdin/stdout aren't a
157 // tty. Use 'script' instead to run a shell in a pty. And
158 // because BSD and GNU differ on the '-f' vs '-F' flags, we need
159 // two different commands. Lovely.
160 String
[] cmdShellGNU
= {
161 "script", "-fqe", "/dev/null"
163 String
[] cmdShellBSD
= {
164 "script", "-q", "-F", "/dev/null"
166 // Spawn a shell and pass its I/O to the other constructor.
169 if (System
.getProperty("os.name").startsWith("Windows")) {
170 pb
= new ProcessBuilder(cmdShellWindows
);
171 } else if (System
.getProperty("os.name").startsWith("Mac")) {
172 pb
= new ProcessBuilder(cmdShellBSD
);
173 } else if (System
.getProperty("os.name").startsWith("Linux")) {
174 pb
= new ProcessBuilder(cmdShellGNU
);
176 // When all else fails, assume GNU.
177 pb
= new ProcessBuilder(cmdShellGNU
);
179 Map
<String
, String
> env
= pb
.environment();
180 env
.put("TERM", ECMA48
.deviceTypeTerm(deviceType
));
181 env
.put("LANG", ECMA48
.deviceTypeLang(deviceType
, "en"));
182 env
.put("COLUMNS", "80");
183 env
.put("LINES", "24");
184 pb
.redirectErrorStream(true);
186 emulator
= new ECMA48(deviceType
, shell
.getInputStream(),
187 shell
.getOutputStream());
188 } catch (IOException e
) {
189 messageBox("Error", "Error launching shell: " + e
.getMessage());
192 // Setup the scroll bars
193 onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
, getWidth(),
196 // Claim the keystrokes the emulator will need.
200 newStatusBar("Terminal session executing...");
204 * Terminate the child of the 'script' process used on POSIX. This may
207 private void terminateShellChildProcess() {
209 if (shell
.getClass().getName().equals("java.lang.UNIXProcess")) {
210 /* get the PID on unix/linux systems */
212 Field field
= shell
.getClass().getDeclaredField("pid");
213 field
.setAccessible(true);
214 pid
= field
.getInt(shell
);
215 } catch (Throwable e
) {
216 // SQUASH, this didn't work. Just bail out quietly.
221 // shell.destroy() works successfully at killing this side of
222 // 'script'. But we need to make sure the other side (child
223 // process) is also killed.
224 String
[] cmdKillIt
= {
225 "pkill", "-P", Integer
.toString(pid
)
228 Runtime
.getRuntime().exec(cmdKillIt
);
229 } catch (Throwable e
) {
230 // SQUASH, this didn't work. Just bail out quietly.
237 * Draw the display buffer.
241 // Synchronize against the emulator so we don't stomp on its reader
243 synchronized (emulator
) {
245 // Update the scroll bars
248 // Draw the box using my superclass
251 List
<DisplayLine
> scrollback
= emulator
.getScrollbackBuffer();
252 List
<DisplayLine
> display
= emulator
.getDisplayBuffer();
254 // Put together the visible rows
255 int visibleHeight
= getHeight() - 2;
256 int visibleBottom
= scrollback
.size() + display
.size()
257 + getVerticalValue();
258 assert (visibleBottom
>= 0);
260 List
<DisplayLine
> preceedingBlankLines
= new LinkedList
<DisplayLine
>();
261 int visibleTop
= visibleBottom
- visibleHeight
;
262 if (visibleTop
< 0) {
263 for (int i
= visibleTop
; i
< 0; i
++) {
264 preceedingBlankLines
.add(emulator
.getBlankDisplayLine());
268 assert (visibleTop
>= 0);
270 List
<DisplayLine
> displayLines
= new LinkedList
<DisplayLine
>();
271 displayLines
.addAll(scrollback
);
272 displayLines
.addAll(display
);
274 List
<DisplayLine
> visibleLines
= new LinkedList
<DisplayLine
>();
275 visibleLines
.addAll(preceedingBlankLines
);
276 visibleLines
.addAll(displayLines
.subList(visibleTop
,
279 visibleHeight
-= visibleLines
.size();
280 assert (visibleHeight
>= 0);
282 // Now draw the emulator screen
284 for (DisplayLine line
: visibleLines
) {
285 int widthMax
= emulator
.getWidth();
286 if (line
.isDoubleWidth()) {
289 if (widthMax
> getWidth() - 2) {
290 widthMax
= getWidth() - 2;
292 for (int i
= 0; i
< widthMax
; i
++) {
293 Cell ch
= line
.charAt(i
);
294 Cell newCell
= new Cell();
296 boolean reverse
= line
.isReverseColor() ^ ch
.isReverse();
297 newCell
.setReverse(false);
299 newCell
.setBackColor(ch
.getForeColor());
300 newCell
.setForeColor(ch
.getBackColor());
302 if (line
.isDoubleWidth()) {
303 getScreen().putCharXY((i
* 2) + 1, row
, newCell
);
304 getScreen().putCharXY((i
* 2) + 2, row
, ' ', newCell
);
306 getScreen().putCharXY(i
+ 1, row
, newCell
);
310 if (row
== getHeight() - 1) {
311 // Don't overwrite the box edge
315 CellAttributes background
= new CellAttributes();
316 // Fill in the blank lines on bottom
317 for (int i
= 0; i
< visibleHeight
; i
++) {
318 getScreen().hLineXY(1, i
+ row
, getWidth() - 2, ' ',
322 } // synchronized (emulator)
327 * Handle window close.
330 public void onClose() {
333 terminateShellChildProcess();
340 * Copy out variables from the emulator that TTerminal has to expose on
343 private void readEmulatorState() {
344 // Synchronize against the emulator so we don't stomp on its reader
346 synchronized (emulator
) {
348 setCursorX(emulator
.getCursorX() + 1);
349 setCursorY(emulator
.getCursorY() + 1
350 + (getHeight() - 2 - emulator
.getHeight())
351 - getVerticalValue());
352 setCursorVisible(emulator
.isCursorVisible());
353 if (getCursorX() > getWidth() - 2) {
354 setCursorVisible(false);
356 if ((getCursorY() > getHeight() - 2) || (getCursorY() < 0)) {
357 setCursorVisible(false);
359 if (emulator
.getScreenTitle().length() > 0) {
360 // Only update the title if the shell is still alive
362 setTitle(emulator
.getScreenTitle());
366 // Check to see if the shell has died.
367 if (!emulator
.isReading() && (shell
!= null)) {
369 int rc
= shell
.exitValue();
370 // The emulator exited on its own, all is fine
371 setTitle(String
.format("%s [Completed - %d]",
375 clearShortcutKeypresses();
376 statusBar
.setText("Terminal session completed, exit " +
378 } catch (IllegalThreadStateException e
) {
379 // The emulator thread has exited, but the shell Process
380 // hasn't figured that out yet. Do nothing, we will see
381 // this in a future tick.
383 } else if (emulator
.isReading() && (shell
!= null)) {
384 // The shell might be dead, let's check
386 int rc
= shell
.exitValue();
387 // If we got here, the shell died.
388 setTitle(String
.format("%s [Completed - %d]",
392 clearShortcutKeypresses();
393 statusBar
.setText("Terminal session completed, exit " +
395 } catch (IllegalThreadStateException e
) {
396 // The shell is still running, do nothing.
400 } // synchronized (emulator)
404 * Handle window/screen resize events.
406 * @param resize resize event
409 public void onResize(final TResizeEvent resize
) {
411 // Synchronize against the emulator so we don't stomp on its reader
413 synchronized (emulator
) {
415 if (resize
.getType() == TResizeEvent
.Type
.WIDGET
) {
416 // Resize the scroll bars
420 // Get out of scrollback
425 } // synchronized (emulator)
429 * Resize scrollbars for a new width/height.
432 public void reflowData() {
434 // Synchronize against the emulator so we don't stomp on its reader
436 synchronized (emulator
) {
438 // Pull cursor information
441 // Vertical scrollbar
442 setTopValue(getHeight() - 2
443 - (emulator
.getScrollbackBuffer().size()
444 + emulator
.getDisplayBuffer().size()));
445 setVerticalBigChange(getHeight() - 2);
447 } // synchronized (emulator)
451 * Check if a mouse press/release/motion event coordinate is over the
454 * @param mouse a mouse-based event
455 * @return whether or not the mouse is on the emulator
457 private final boolean mouseOnEmulator(final TMouseEvent mouse
) {
459 synchronized (emulator
) {
460 if (!emulator
.isReading()) {
465 if ((mouse
.getAbsoluteX() >= getAbsoluteX() + 1)
466 && (mouse
.getAbsoluteX() < getAbsoluteX() + getWidth() - 1)
467 && (mouse
.getAbsoluteY() >= getAbsoluteY() + 1)
468 && (mouse
.getAbsoluteY() < getAbsoluteY() + getHeight() - 1)
478 * @param keypress keystroke event
481 public void onKeypress(final TKeypressEvent keypress
) {
483 // Scrollback up/down
484 if (keypress
.equals(kbShiftPgUp
)
485 || keypress
.equals(kbCtrlPgUp
)
486 || keypress
.equals(kbAltPgUp
)
488 bigVerticalDecrement();
491 if (keypress
.equals(kbShiftPgDn
)
492 || keypress
.equals(kbCtrlPgDn
)
493 || keypress
.equals(kbAltPgDn
)
495 bigVerticalIncrement();
499 // Synchronize against the emulator so we don't stomp on its reader
501 synchronized (emulator
) {
502 if (emulator
.isReading()) {
503 // Get out of scrollback
505 emulator
.keypress(keypress
.getKey());
507 // UGLY HACK TIME! cmd.exe needs CRLF, not just CR, so if
508 // this is kBEnter then also send kbCtrlJ.
509 if (System
.getProperty("os.name").startsWith("Windows")) {
510 if (keypress
.equals(kbEnter
)) {
511 emulator
.keypress(kbCtrlJ
);
520 // Process is closed, honor "normal" TUI keystrokes
521 super.onKeypress(keypress
);
525 * Handle mouse press events.
527 * @param mouse mouse button press event
530 public void onMouseDown(final TMouseEvent mouse
) {
531 if (inWindowMove
|| inWindowResize
) {
532 // TWindow needs to deal with this.
533 super.onMouseDown(mouse
);
537 if (mouse
.isMouseWheelUp()) {
541 if (mouse
.isMouseWheelDown()) {
545 if (mouseOnEmulator(mouse
)) {
546 synchronized (emulator
) {
547 mouse
.setX(mouse
.getX() - 1);
548 mouse
.setY(mouse
.getY() - 1);
549 emulator
.mouse(mouse
);
555 // Emulator didn't consume it, pass it on
556 super.onMouseDown(mouse
);
560 * Handle mouse release events.
562 * @param mouse mouse button release event
565 public void onMouseUp(final TMouseEvent mouse
) {
566 if (inWindowMove
|| inWindowResize
) {
567 // TWindow needs to deal with this.
568 super.onMouseUp(mouse
);
572 if (mouseOnEmulator(mouse
)) {
573 synchronized (emulator
) {
574 mouse
.setX(mouse
.getX() - 1);
575 mouse
.setY(mouse
.getY() - 1);
576 emulator
.mouse(mouse
);
582 // Emulator didn't consume it, pass it on
583 super.onMouseUp(mouse
);
587 * Handle mouse motion events.
589 * @param mouse mouse motion event
592 public void onMouseMotion(final TMouseEvent mouse
) {
593 if (inWindowMove
|| inWindowResize
) {
594 // TWindow needs to deal with this.
595 super.onMouseMotion(mouse
);
599 if (mouseOnEmulator(mouse
)) {
600 synchronized (emulator
) {
601 mouse
.setX(mouse
.getX() - 1);
602 mouse
.setY(mouse
.getY() - 1);
603 emulator
.mouse(mouse
);
609 // Emulator didn't consume it, pass it on
610 super.onMouseMotion(mouse
);