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 * If true, we are using the ptypipe utility to support dynamic window
65 * resizing. ptypipe is available at
66 * https://github.com/klamonte/ptypipe .
68 private boolean ptypipe
= false;
71 * Claim the keystrokes the emulator will need.
73 private void addShortcutKeys() {
74 addShortcutKeypress(kbCtrlA
);
75 addShortcutKeypress(kbCtrlB
);
76 addShortcutKeypress(kbCtrlC
);
77 addShortcutKeypress(kbCtrlD
);
78 addShortcutKeypress(kbCtrlE
);
79 addShortcutKeypress(kbCtrlF
);
80 addShortcutKeypress(kbCtrlG
);
81 addShortcutKeypress(kbCtrlH
);
82 addShortcutKeypress(kbCtrlU
);
83 addShortcutKeypress(kbCtrlJ
);
84 addShortcutKeypress(kbCtrlK
);
85 addShortcutKeypress(kbCtrlL
);
86 addShortcutKeypress(kbCtrlM
);
87 addShortcutKeypress(kbCtrlN
);
88 addShortcutKeypress(kbCtrlO
);
89 addShortcutKeypress(kbCtrlP
);
90 addShortcutKeypress(kbCtrlQ
);
91 addShortcutKeypress(kbCtrlR
);
92 addShortcutKeypress(kbCtrlS
);
93 addShortcutKeypress(kbCtrlT
);
94 addShortcutKeypress(kbCtrlU
);
95 addShortcutKeypress(kbCtrlV
);
96 addShortcutKeypress(kbCtrlW
);
97 addShortcutKeypress(kbCtrlX
);
98 addShortcutKeypress(kbCtrlY
);
99 addShortcutKeypress(kbCtrlZ
);
100 addShortcutKeypress(kbF1
);
101 addShortcutKeypress(kbF2
);
102 addShortcutKeypress(kbF3
);
103 addShortcutKeypress(kbF4
);
104 addShortcutKeypress(kbF5
);
105 addShortcutKeypress(kbF6
);
106 addShortcutKeypress(kbF7
);
107 addShortcutKeypress(kbF8
);
108 addShortcutKeypress(kbF9
);
109 addShortcutKeypress(kbF10
);
110 addShortcutKeypress(kbF11
);
111 addShortcutKeypress(kbF12
);
112 addShortcutKeypress(kbAltA
);
113 addShortcutKeypress(kbAltB
);
114 addShortcutKeypress(kbAltC
);
115 addShortcutKeypress(kbAltD
);
116 addShortcutKeypress(kbAltE
);
117 addShortcutKeypress(kbAltF
);
118 addShortcutKeypress(kbAltG
);
119 addShortcutKeypress(kbAltH
);
120 addShortcutKeypress(kbAltU
);
121 addShortcutKeypress(kbAltJ
);
122 addShortcutKeypress(kbAltK
);
123 addShortcutKeypress(kbAltL
);
124 addShortcutKeypress(kbAltM
);
125 addShortcutKeypress(kbAltN
);
126 addShortcutKeypress(kbAltO
);
127 addShortcutKeypress(kbAltP
);
128 addShortcutKeypress(kbAltQ
);
129 addShortcutKeypress(kbAltR
);
130 addShortcutKeypress(kbAltS
);
131 addShortcutKeypress(kbAltT
);
132 addShortcutKeypress(kbAltU
);
133 addShortcutKeypress(kbAltV
);
134 addShortcutKeypress(kbAltW
);
135 addShortcutKeypress(kbAltX
);
136 addShortcutKeypress(kbAltY
);
137 addShortcutKeypress(kbAltZ
);
141 * Public constructor spawns a shell.
143 * @param application TApplication that manages this window
144 * @param x column relative to parent
145 * @param y row relative to parent
146 * @param flags mask of CENTERED, MODAL, or RESIZABLE
148 public TTerminalWindow(final TApplication application
, final int x
,
149 final int y
, final int flags
) {
151 super(application
, "Terminal", x
, y
, 80 + 2, 24 + 2, flags
);
153 vScroller
= new TVScroller(this, getWidth() - 2, 0, getHeight() - 2);
157 ECMA48
.DeviceType deviceType
= ECMA48
.DeviceType
.XTERM
;
160 String
[] cmdShellWindows
= {
164 // You cannot run a login shell in a bare Process interactively,
165 // due to libc's behavior of buffering when stdin/stdout aren't a
166 // tty. Use 'script' instead to run a shell in a pty. And
167 // because BSD and GNU differ on the '-f' vs '-F' flags, we need
168 // two different commands. Lovely.
169 String
[] cmdShellGNU
= {
170 "script", "-fqe", "/dev/null"
172 String
[] cmdShellBSD
= {
173 "script", "-q", "-F", "/dev/null"
175 String
[] cmdShellPtypipe
= {
176 "ptypipe", "/bin/bash", "--login"
178 // Spawn a shell and pass its I/O to the other constructor.
181 if ((System
.getProperty("jexer.TTerminal.ptypipe") != null)
182 && (System
.getProperty("jexer.TTerminal.ptypipe").
185 pb
= new ProcessBuilder(cmdShellPtypipe
);
187 } else if (System
.getProperty("os.name").startsWith("Windows")) {
188 pb
= new ProcessBuilder(cmdShellWindows
);
189 } else if (System
.getProperty("os.name").startsWith("Mac")) {
190 pb
= new ProcessBuilder(cmdShellBSD
);
191 } else if (System
.getProperty("os.name").startsWith("Linux")) {
192 pb
= new ProcessBuilder(cmdShellGNU
);
194 // When all else fails, assume GNU.
195 pb
= new ProcessBuilder(cmdShellGNU
);
197 Map
<String
, String
> env
= pb
.environment();
198 env
.put("TERM", ECMA48
.deviceTypeTerm(deviceType
));
199 env
.put("LANG", ECMA48
.deviceTypeLang(deviceType
, "en"));
200 env
.put("COLUMNS", "80");
201 env
.put("LINES", "24");
202 pb
.redirectErrorStream(true);
204 emulator
= new ECMA48(deviceType
, shell
.getInputStream(),
205 shell
.getOutputStream(), this);
206 } catch (IOException e
) {
207 messageBox("Error", "Error launching shell: " + e
.getMessage());
210 // Setup the scroll bars
211 onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
, getWidth(),
214 // Claim the keystrokes the emulator will need.
218 newStatusBar("Terminal session executing...");
222 * Terminate the child of the 'script' process used on POSIX. This may
225 private void terminateShellChildProcess() {
227 if (shell
.getClass().getName().equals("java.lang.UNIXProcess")) {
228 /* get the PID on unix/linux systems */
230 Field field
= shell
.getClass().getDeclaredField("pid");
231 field
.setAccessible(true);
232 pid
= field
.getInt(shell
);
233 } catch (Throwable e
) {
234 // SQUASH, this didn't work. Just bail out quietly.
239 // shell.destroy() works successfully at killing this side of
240 // 'script'. But we need to make sure the other side (child
241 // process) is also killed.
242 String
[] cmdKillIt
= {
243 "pkill", "-P", Integer
.toString(pid
)
246 Runtime
.getRuntime().exec(cmdKillIt
);
247 } catch (Throwable e
) {
248 // SQUASH, this didn't work. Just bail out quietly.
255 * Draw the display buffer.
259 // Synchronize against the emulator so we don't stomp on its reader
261 synchronized (emulator
) {
263 // Update the scroll bars
266 // Draw the box using my superclass
269 List
<DisplayLine
> scrollback
= emulator
.getScrollbackBuffer();
270 List
<DisplayLine
> display
= emulator
.getDisplayBuffer();
272 // Put together the visible rows
273 int visibleHeight
= getHeight() - 2;
274 int visibleBottom
= scrollback
.size() + display
.size()
275 + getVerticalValue();
276 assert (visibleBottom
>= 0);
278 List
<DisplayLine
> preceedingBlankLines
= new LinkedList
<DisplayLine
>();
279 int visibleTop
= visibleBottom
- visibleHeight
;
280 if (visibleTop
< 0) {
281 for (int i
= visibleTop
; i
< 0; i
++) {
282 preceedingBlankLines
.add(emulator
.getBlankDisplayLine());
286 assert (visibleTop
>= 0);
288 List
<DisplayLine
> displayLines
= new LinkedList
<DisplayLine
>();
289 displayLines
.addAll(scrollback
);
290 displayLines
.addAll(display
);
292 List
<DisplayLine
> visibleLines
= new LinkedList
<DisplayLine
>();
293 visibleLines
.addAll(preceedingBlankLines
);
294 visibleLines
.addAll(displayLines
.subList(visibleTop
,
297 visibleHeight
-= visibleLines
.size();
298 assert (visibleHeight
>= 0);
300 // Now draw the emulator screen
302 for (DisplayLine line
: visibleLines
) {
303 int widthMax
= emulator
.getWidth();
304 if (line
.isDoubleWidth()) {
307 if (widthMax
> getWidth() - 2) {
308 widthMax
= getWidth() - 2;
310 for (int i
= 0; i
< widthMax
; i
++) {
311 Cell ch
= line
.charAt(i
);
312 Cell newCell
= new Cell();
314 boolean reverse
= line
.isReverseColor() ^ ch
.isReverse();
315 newCell
.setReverse(false);
317 newCell
.setBackColor(ch
.getForeColor());
318 newCell
.setForeColor(ch
.getBackColor());
320 if (line
.isDoubleWidth()) {
321 getScreen().putCharXY((i
* 2) + 1, row
, newCell
);
322 getScreen().putCharXY((i
* 2) + 2, row
, ' ', newCell
);
324 getScreen().putCharXY(i
+ 1, row
, newCell
);
328 if (row
== getHeight() - 1) {
329 // Don't overwrite the box edge
333 CellAttributes background
= new CellAttributes();
334 // Fill in the blank lines on bottom
335 for (int i
= 0; i
< visibleHeight
; i
++) {
336 getScreen().hLineXY(1, i
+ row
, getWidth() - 2, ' ',
340 } // synchronized (emulator)
345 * Called by emulator when fresh data has come in.
347 public void displayChanged() {
352 * Function to call to obtain the display width.
354 * @return the number of columns in the display
356 public int getDisplayWidth() {
357 return getWidth() - 2;
361 * Function to call to obtain the display height.
363 * @return the number of rows in the display
365 public int getDisplayHeight() {
366 return getHeight() - 2;
370 * Handle window close.
373 public void onClose() {
376 terminateShellChildProcess();
383 * Copy out variables from the emulator that TTerminal has to expose on
386 private void readEmulatorState() {
387 // Synchronize against the emulator so we don't stomp on its reader
389 synchronized (emulator
) {
391 setCursorX(emulator
.getCursorX() + 1);
392 setCursorY(emulator
.getCursorY() + 1
393 + (getHeight() - 2 - emulator
.getHeight())
394 - getVerticalValue());
395 setCursorVisible(emulator
.isCursorVisible());
396 if (getCursorX() > getWidth() - 2) {
397 setCursorVisible(false);
399 if ((getCursorY() > getHeight() - 2) || (getCursorY() < 0)) {
400 setCursorVisible(false);
402 if (emulator
.getScreenTitle().length() > 0) {
403 // Only update the title if the shell is still alive
405 setTitle(emulator
.getScreenTitle());
409 // Check to see if the shell has died.
410 if (!emulator
.isReading() && (shell
!= null)) {
412 int rc
= shell
.exitValue();
413 // The emulator exited on its own, all is fine
414 setTitle(String
.format("%s [Completed - %d]",
418 clearShortcutKeypresses();
419 statusBar
.setText("Terminal session completed, exit " +
421 } catch (IllegalThreadStateException e
) {
422 // The emulator thread has exited, but the shell Process
423 // hasn't figured that out yet. Do nothing, we will see
424 // this in a future tick.
426 } else if (emulator
.isReading() && (shell
!= null)) {
427 // The shell might be dead, let's check
429 int rc
= shell
.exitValue();
430 // If we got here, the shell died.
431 setTitle(String
.format("%s [Completed - %d]",
435 clearShortcutKeypresses();
436 statusBar
.setText("Terminal session completed, exit " +
438 } catch (IllegalThreadStateException e
) {
439 // The shell is still running, do nothing.
443 } // synchronized (emulator)
447 * Handle window/screen resize events.
449 * @param resize resize event
452 public void onResize(final TResizeEvent resize
) {
454 // Synchronize against the emulator so we don't stomp on its reader
456 synchronized (emulator
) {
458 if (resize
.getType() == TResizeEvent
.Type
.WIDGET
) {
459 // Resize the scroll bars
463 // Get out of scrollback
467 emulator
.setWidth(getWidth() - 2);
468 emulator
.setHeight(getHeight() - 2);
470 emulator
.writeRemote("\033[8;" + (getHeight() - 2) + ";" +
471 (getWidth() - 2) + "t");
476 } // synchronized (emulator)
480 * Resize scrollbars for a new width/height.
483 public void reflowData() {
485 // Synchronize against the emulator so we don't stomp on its reader
487 synchronized (emulator
) {
489 // Pull cursor information
492 // Vertical scrollbar
493 setTopValue(getHeight() - 2
494 - (emulator
.getScrollbackBuffer().size()
495 + emulator
.getDisplayBuffer().size()));
496 setVerticalBigChange(getHeight() - 2);
498 } // synchronized (emulator)
502 * Check if a mouse press/release/motion event coordinate is over the
505 * @param mouse a mouse-based event
506 * @return whether or not the mouse is on the emulator
508 private final boolean mouseOnEmulator(final TMouseEvent mouse
) {
510 synchronized (emulator
) {
511 if (!emulator
.isReading()) {
516 if ((mouse
.getAbsoluteX() >= getAbsoluteX() + 1)
517 && (mouse
.getAbsoluteX() < getAbsoluteX() + getWidth() - 1)
518 && (mouse
.getAbsoluteY() >= getAbsoluteY() + 1)
519 && (mouse
.getAbsoluteY() < getAbsoluteY() + getHeight() - 1)
529 * @param keypress keystroke event
532 public void onKeypress(final TKeypressEvent keypress
) {
534 // Scrollback up/down
535 if (keypress
.equals(kbShiftPgUp
)
536 || keypress
.equals(kbCtrlPgUp
)
537 || keypress
.equals(kbAltPgUp
)
539 bigVerticalDecrement();
542 if (keypress
.equals(kbShiftPgDn
)
543 || keypress
.equals(kbCtrlPgDn
)
544 || keypress
.equals(kbAltPgDn
)
546 bigVerticalIncrement();
550 // Synchronize against the emulator so we don't stomp on its reader
552 synchronized (emulator
) {
553 if (emulator
.isReading()) {
554 // Get out of scrollback
556 emulator
.keypress(keypress
.getKey());
558 // UGLY HACK TIME! cmd.exe needs CRLF, not just CR, so if
559 // this is kBEnter then also send kbCtrlJ.
560 if (System
.getProperty("os.name").startsWith("Windows")) {
561 if (keypress
.equals(kbEnter
)) {
562 emulator
.keypress(kbCtrlJ
);
571 // Process is closed, honor "normal" TUI keystrokes
572 super.onKeypress(keypress
);
576 * Handle mouse press events.
578 * @param mouse mouse button press event
581 public void onMouseDown(final TMouseEvent mouse
) {
582 if (inWindowMove
|| inWindowResize
) {
583 // TWindow needs to deal with this.
584 super.onMouseDown(mouse
);
588 if (mouse
.isMouseWheelUp()) {
592 if (mouse
.isMouseWheelDown()) {
596 if (mouseOnEmulator(mouse
)) {
597 synchronized (emulator
) {
598 mouse
.setX(mouse
.getX() - 1);
599 mouse
.setY(mouse
.getY() - 1);
600 emulator
.mouse(mouse
);
606 // Emulator didn't consume it, pass it on
607 super.onMouseDown(mouse
);
611 * Handle mouse release events.
613 * @param mouse mouse button release event
616 public void onMouseUp(final TMouseEvent mouse
) {
617 if (inWindowMove
|| inWindowResize
) {
618 // TWindow needs to deal with this.
619 super.onMouseUp(mouse
);
623 if (mouseOnEmulator(mouse
)) {
624 synchronized (emulator
) {
625 mouse
.setX(mouse
.getX() - 1);
626 mouse
.setY(mouse
.getY() - 1);
627 emulator
.mouse(mouse
);
633 // Emulator didn't consume it, pass it on
634 super.onMouseUp(mouse
);
638 * Handle mouse motion events.
640 * @param mouse mouse motion event
643 public void onMouseMotion(final TMouseEvent mouse
) {
644 if (inWindowMove
|| inWindowResize
) {
645 // TWindow needs to deal with this.
646 super.onMouseMotion(mouse
);
650 if (mouseOnEmulator(mouse
)) {
651 synchronized (emulator
) {
652 mouse
.setX(mouse
.getX() - 1);
653 mouse
.setY(mouse
.getY() - 1);
654 emulator
.mouse(mouse
);
660 // Emulator didn't consume it, pass it on
661 super.onMouseMotion(mouse
);