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
.DisplayListener
;
44 import jexer
.tterminal
.ECMA48
;
45 import static jexer
.TKeypress
.*;
48 * TTerminalWindow exposes a ECMA-48 / ANSI X3.64 style terminal in a window.
50 public class TTerminalWindow
extends TScrollableWindow
51 implements DisplayListener
{
56 private ECMA48 emulator
;
59 * The Process created by the shell spawning constructor.
61 private Process shell
;
64 * Claim the keystrokes the emulator will need.
66 private void addShortcutKeys() {
67 addShortcutKeypress(kbCtrlA
);
68 addShortcutKeypress(kbCtrlB
);
69 addShortcutKeypress(kbCtrlC
);
70 addShortcutKeypress(kbCtrlD
);
71 addShortcutKeypress(kbCtrlE
);
72 addShortcutKeypress(kbCtrlF
);
73 addShortcutKeypress(kbCtrlG
);
74 addShortcutKeypress(kbCtrlH
);
75 addShortcutKeypress(kbCtrlU
);
76 addShortcutKeypress(kbCtrlJ
);
77 addShortcutKeypress(kbCtrlK
);
78 addShortcutKeypress(kbCtrlL
);
79 addShortcutKeypress(kbCtrlM
);
80 addShortcutKeypress(kbCtrlN
);
81 addShortcutKeypress(kbCtrlO
);
82 addShortcutKeypress(kbCtrlP
);
83 addShortcutKeypress(kbCtrlQ
);
84 addShortcutKeypress(kbCtrlR
);
85 addShortcutKeypress(kbCtrlS
);
86 addShortcutKeypress(kbCtrlT
);
87 addShortcutKeypress(kbCtrlU
);
88 addShortcutKeypress(kbCtrlV
);
89 addShortcutKeypress(kbCtrlW
);
90 addShortcutKeypress(kbCtrlX
);
91 addShortcutKeypress(kbCtrlY
);
92 addShortcutKeypress(kbCtrlZ
);
93 addShortcutKeypress(kbF1
);
94 addShortcutKeypress(kbF2
);
95 addShortcutKeypress(kbF3
);
96 addShortcutKeypress(kbF4
);
97 addShortcutKeypress(kbF5
);
98 addShortcutKeypress(kbF6
);
99 addShortcutKeypress(kbF7
);
100 addShortcutKeypress(kbF8
);
101 addShortcutKeypress(kbF9
);
102 addShortcutKeypress(kbF10
);
103 addShortcutKeypress(kbF11
);
104 addShortcutKeypress(kbF12
);
105 addShortcutKeypress(kbAltA
);
106 addShortcutKeypress(kbAltB
);
107 addShortcutKeypress(kbAltC
);
108 addShortcutKeypress(kbAltD
);
109 addShortcutKeypress(kbAltE
);
110 addShortcutKeypress(kbAltF
);
111 addShortcutKeypress(kbAltG
);
112 addShortcutKeypress(kbAltH
);
113 addShortcutKeypress(kbAltU
);
114 addShortcutKeypress(kbAltJ
);
115 addShortcutKeypress(kbAltK
);
116 addShortcutKeypress(kbAltL
);
117 addShortcutKeypress(kbAltM
);
118 addShortcutKeypress(kbAltN
);
119 addShortcutKeypress(kbAltO
);
120 addShortcutKeypress(kbAltP
);
121 addShortcutKeypress(kbAltQ
);
122 addShortcutKeypress(kbAltR
);
123 addShortcutKeypress(kbAltS
);
124 addShortcutKeypress(kbAltT
);
125 addShortcutKeypress(kbAltU
);
126 addShortcutKeypress(kbAltV
);
127 addShortcutKeypress(kbAltW
);
128 addShortcutKeypress(kbAltX
);
129 addShortcutKeypress(kbAltY
);
130 addShortcutKeypress(kbAltZ
);
134 * Public constructor spawns a shell.
136 * @param application TApplication that manages this window
137 * @param x column relative to parent
138 * @param y row relative to parent
139 * @param flags mask of CENTERED, MODAL, or RESIZABLE
141 public TTerminalWindow(final TApplication application
, final int x
,
142 final int y
, final int flags
) {
144 super(application
, "Terminal", x
, y
, 80 + 2, 24 + 2, flags
);
146 vScroller
= new TVScroller(this, getWidth() - 2, 0, getHeight() - 2);
150 ECMA48
.DeviceType deviceType
= ECMA48
.DeviceType
.XTERM
;
153 String
[] cmdShellWindows
= {
157 // You cannot run a login shell in a bare Process interactively,
158 // due to libc's behavior of buffering when stdin/stdout aren't a
159 // tty. Use 'script' instead to run a shell in a pty. And
160 // because BSD and GNU differ on the '-f' vs '-F' flags, we need
161 // two different commands. Lovely.
162 String
[] cmdShellGNU
= {
163 "script", "-fqe", "/dev/null"
165 String
[] cmdShellBSD
= {
166 "script", "-q", "-F", "/dev/null"
168 // Spawn a shell and pass its I/O to the other constructor.
171 if (System
.getProperty("os.name").startsWith("Windows")) {
172 pb
= new ProcessBuilder(cmdShellWindows
);
173 } else if (System
.getProperty("os.name").startsWith("Mac")) {
174 pb
= new ProcessBuilder(cmdShellBSD
);
175 } else if (System
.getProperty("os.name").startsWith("Linux")) {
176 pb
= new ProcessBuilder(cmdShellGNU
);
178 // When all else fails, assume GNU.
179 pb
= new ProcessBuilder(cmdShellGNU
);
181 Map
<String
, String
> env
= pb
.environment();
182 env
.put("TERM", ECMA48
.deviceTypeTerm(deviceType
));
183 env
.put("LANG", ECMA48
.deviceTypeLang(deviceType
, "en"));
184 env
.put("COLUMNS", "80");
185 env
.put("LINES", "24");
186 pb
.redirectErrorStream(true);
188 emulator
= new ECMA48(deviceType
, shell
.getInputStream(),
189 shell
.getOutputStream());
190 emulator
.setListener(this);
191 } catch (IOException e
) {
192 messageBox("Error", "Error launching shell: " + e
.getMessage());
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 * Draw the display buffer.
244 // Synchronize against the emulator so we don't stomp on its reader
246 synchronized (emulator
) {
248 // Update the scroll bars
251 // Draw the box using my superclass
254 List
<DisplayLine
> scrollback
= emulator
.getScrollbackBuffer();
255 List
<DisplayLine
> display
= emulator
.getDisplayBuffer();
257 // Put together the visible rows
258 int visibleHeight
= getHeight() - 2;
259 int visibleBottom
= scrollback
.size() + display
.size()
260 + getVerticalValue();
261 assert (visibleBottom
>= 0);
263 List
<DisplayLine
> preceedingBlankLines
= new LinkedList
<DisplayLine
>();
264 int visibleTop
= visibleBottom
- visibleHeight
;
265 if (visibleTop
< 0) {
266 for (int i
= visibleTop
; i
< 0; i
++) {
267 preceedingBlankLines
.add(emulator
.getBlankDisplayLine());
271 assert (visibleTop
>= 0);
273 List
<DisplayLine
> displayLines
= new LinkedList
<DisplayLine
>();
274 displayLines
.addAll(scrollback
);
275 displayLines
.addAll(display
);
277 List
<DisplayLine
> visibleLines
= new LinkedList
<DisplayLine
>();
278 visibleLines
.addAll(preceedingBlankLines
);
279 visibleLines
.addAll(displayLines
.subList(visibleTop
,
282 visibleHeight
-= visibleLines
.size();
283 assert (visibleHeight
>= 0);
285 // Now draw the emulator screen
287 for (DisplayLine line
: visibleLines
) {
288 int widthMax
= emulator
.getWidth();
289 if (line
.isDoubleWidth()) {
292 if (widthMax
> getWidth() - 2) {
293 widthMax
= getWidth() - 2;
295 for (int i
= 0; i
< widthMax
; i
++) {
296 Cell ch
= line
.charAt(i
);
297 Cell newCell
= new Cell();
299 boolean reverse
= line
.isReverseColor() ^ ch
.isReverse();
300 newCell
.setReverse(false);
302 newCell
.setBackColor(ch
.getForeColor());
303 newCell
.setForeColor(ch
.getBackColor());
305 if (line
.isDoubleWidth()) {
306 getScreen().putCharXY((i
* 2) + 1, row
, newCell
);
307 getScreen().putCharXY((i
* 2) + 2, row
, ' ', newCell
);
309 getScreen().putCharXY(i
+ 1, row
, newCell
);
313 if (row
== getHeight() - 1) {
314 // Don't overwrite the box edge
318 CellAttributes background
= new CellAttributes();
319 // Fill in the blank lines on bottom
320 for (int i
= 0; i
< visibleHeight
; i
++) {
321 getScreen().hLineXY(1, i
+ row
, getWidth() - 2, ' ',
325 } // synchronized (emulator)
330 * Called by emulator when fresh data has come in.
332 public void displayChanged() {
337 * Handle window close.
340 public void onClose() {
343 terminateShellChildProcess();
350 * Copy out variables from the emulator that TTerminal has to expose on
353 private void readEmulatorState() {
354 // Synchronize against the emulator so we don't stomp on its reader
356 synchronized (emulator
) {
358 setCursorX(emulator
.getCursorX() + 1);
359 setCursorY(emulator
.getCursorY() + 1
360 + (getHeight() - 2 - emulator
.getHeight())
361 - getVerticalValue());
362 setCursorVisible(emulator
.isCursorVisible());
363 if (getCursorX() > getWidth() - 2) {
364 setCursorVisible(false);
366 if ((getCursorY() > getHeight() - 2) || (getCursorY() < 0)) {
367 setCursorVisible(false);
369 if (emulator
.getScreenTitle().length() > 0) {
370 // Only update the title if the shell is still alive
372 setTitle(emulator
.getScreenTitle());
376 // Check to see if the shell has died.
377 if (!emulator
.isReading() && (shell
!= null)) {
379 int rc
= shell
.exitValue();
380 // The emulator exited on its own, all is fine
381 setTitle(String
.format("%s [Completed - %d]",
385 clearShortcutKeypresses();
386 statusBar
.setText("Terminal session completed, exit " +
388 } catch (IllegalThreadStateException e
) {
389 // The emulator thread has exited, but the shell Process
390 // hasn't figured that out yet. Do nothing, we will see
391 // this in a future tick.
393 } else if (emulator
.isReading() && (shell
!= null)) {
394 // The shell might be dead, let's check
396 int rc
= shell
.exitValue();
397 // If we got here, the shell died.
398 setTitle(String
.format("%s [Completed - %d]",
402 clearShortcutKeypresses();
403 statusBar
.setText("Terminal session completed, exit " +
405 } catch (IllegalThreadStateException e
) {
406 // The shell is still running, do nothing.
410 } // synchronized (emulator)
414 * Handle window/screen resize events.
416 * @param resize resize event
419 public void onResize(final TResizeEvent resize
) {
421 // Synchronize against the emulator so we don't stomp on its reader
423 synchronized (emulator
) {
425 if (resize
.getType() == TResizeEvent
.Type
.WIDGET
) {
426 // Resize the scroll bars
430 // Get out of scrollback
435 } // synchronized (emulator)
439 * Resize scrollbars for a new width/height.
442 public void reflowData() {
444 // Synchronize against the emulator so we don't stomp on its reader
446 synchronized (emulator
) {
448 // Pull cursor information
451 // Vertical scrollbar
452 setTopValue(getHeight() - 2
453 - (emulator
.getScrollbackBuffer().size()
454 + emulator
.getDisplayBuffer().size()));
455 setVerticalBigChange(getHeight() - 2);
457 } // synchronized (emulator)
461 * Check if a mouse press/release/motion event coordinate is over the
464 * @param mouse a mouse-based event
465 * @return whether or not the mouse is on the emulator
467 private final boolean mouseOnEmulator(final TMouseEvent mouse
) {
469 synchronized (emulator
) {
470 if (!emulator
.isReading()) {
475 if ((mouse
.getAbsoluteX() >= getAbsoluteX() + 1)
476 && (mouse
.getAbsoluteX() < getAbsoluteX() + getWidth() - 1)
477 && (mouse
.getAbsoluteY() >= getAbsoluteY() + 1)
478 && (mouse
.getAbsoluteY() < getAbsoluteY() + getHeight() - 1)
488 * @param keypress keystroke event
491 public void onKeypress(final TKeypressEvent keypress
) {
493 // Scrollback up/down
494 if (keypress
.equals(kbShiftPgUp
)
495 || keypress
.equals(kbCtrlPgUp
)
496 || keypress
.equals(kbAltPgUp
)
498 bigVerticalDecrement();
501 if (keypress
.equals(kbShiftPgDn
)
502 || keypress
.equals(kbCtrlPgDn
)
503 || keypress
.equals(kbAltPgDn
)
505 bigVerticalIncrement();
509 // Synchronize against the emulator so we don't stomp on its reader
511 synchronized (emulator
) {
512 if (emulator
.isReading()) {
513 // Get out of scrollback
515 emulator
.keypress(keypress
.getKey());
517 // UGLY HACK TIME! cmd.exe needs CRLF, not just CR, so if
518 // this is kBEnter then also send kbCtrlJ.
519 if (System
.getProperty("os.name").startsWith("Windows")) {
520 if (keypress
.equals(kbEnter
)) {
521 emulator
.keypress(kbCtrlJ
);
530 // Process is closed, honor "normal" TUI keystrokes
531 super.onKeypress(keypress
);
535 * Handle mouse press events.
537 * @param mouse mouse button press event
540 public void onMouseDown(final TMouseEvent mouse
) {
541 if (inWindowMove
|| inWindowResize
) {
542 // TWindow needs to deal with this.
543 super.onMouseDown(mouse
);
547 if (mouse
.isMouseWheelUp()) {
551 if (mouse
.isMouseWheelDown()) {
555 if (mouseOnEmulator(mouse
)) {
556 synchronized (emulator
) {
557 mouse
.setX(mouse
.getX() - 1);
558 mouse
.setY(mouse
.getY() - 1);
559 emulator
.mouse(mouse
);
565 // Emulator didn't consume it, pass it on
566 super.onMouseDown(mouse
);
570 * Handle mouse release events.
572 * @param mouse mouse button release event
575 public void onMouseUp(final TMouseEvent mouse
) {
576 if (inWindowMove
|| inWindowResize
) {
577 // TWindow needs to deal with this.
578 super.onMouseUp(mouse
);
582 if (mouseOnEmulator(mouse
)) {
583 synchronized (emulator
) {
584 mouse
.setX(mouse
.getX() - 1);
585 mouse
.setY(mouse
.getY() - 1);
586 emulator
.mouse(mouse
);
592 // Emulator didn't consume it, pass it on
593 super.onMouseUp(mouse
);
597 * Handle mouse motion events.
599 * @param mouse mouse motion event
602 public void onMouseMotion(final TMouseEvent mouse
) {
603 if (inWindowMove
|| inWindowResize
) {
604 // TWindow needs to deal with this.
605 super.onMouseMotion(mouse
);
609 if (mouseOnEmulator(mouse
)) {
610 synchronized (emulator
) {
611 mouse
.setX(mouse
.getX() - 1);
612 mouse
.setY(mouse
.getY() - 1);
613 emulator
.mouse(mouse
);
619 // Emulator didn't consume it, pass it on
620 super.onMouseMotion(mouse
);