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());
206 emulator
.setListener(this);
207 } catch (IOException e
) {
208 messageBox("Error", "Error launching shell: " + e
.getMessage());
211 // Setup the scroll bars
212 onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
, getWidth(),
215 // Claim the keystrokes the emulator will need.
219 newStatusBar("Terminal session executing...");
223 * Terminate the child of the 'script' process used on POSIX. This may
226 private void terminateShellChildProcess() {
228 if (shell
.getClass().getName().equals("java.lang.UNIXProcess")) {
229 /* get the PID on unix/linux systems */
231 Field field
= shell
.getClass().getDeclaredField("pid");
232 field
.setAccessible(true);
233 pid
= field
.getInt(shell
);
234 } catch (Throwable e
) {
235 // SQUASH, this didn't work. Just bail out quietly.
240 // shell.destroy() works successfully at killing this side of
241 // 'script'. But we need to make sure the other side (child
242 // process) is also killed.
243 String
[] cmdKillIt
= {
244 "pkill", "-P", Integer
.toString(pid
)
247 Runtime
.getRuntime().exec(cmdKillIt
);
248 } catch (Throwable e
) {
249 // SQUASH, this didn't work. Just bail out quietly.
256 * Draw the display buffer.
260 // Synchronize against the emulator so we don't stomp on its reader
262 synchronized (emulator
) {
264 // Update the scroll bars
267 // Draw the box using my superclass
270 List
<DisplayLine
> scrollback
= emulator
.getScrollbackBuffer();
271 List
<DisplayLine
> display
= emulator
.getDisplayBuffer();
273 // Put together the visible rows
274 int visibleHeight
= getHeight() - 2;
275 int visibleBottom
= scrollback
.size() + display
.size()
276 + getVerticalValue();
277 assert (visibleBottom
>= 0);
279 List
<DisplayLine
> preceedingBlankLines
= new LinkedList
<DisplayLine
>();
280 int visibleTop
= visibleBottom
- visibleHeight
;
281 if (visibleTop
< 0) {
282 for (int i
= visibleTop
; i
< 0; i
++) {
283 preceedingBlankLines
.add(emulator
.getBlankDisplayLine());
287 assert (visibleTop
>= 0);
289 List
<DisplayLine
> displayLines
= new LinkedList
<DisplayLine
>();
290 displayLines
.addAll(scrollback
);
291 displayLines
.addAll(display
);
293 List
<DisplayLine
> visibleLines
= new LinkedList
<DisplayLine
>();
294 visibleLines
.addAll(preceedingBlankLines
);
295 visibleLines
.addAll(displayLines
.subList(visibleTop
,
298 visibleHeight
-= visibleLines
.size();
299 assert (visibleHeight
>= 0);
301 // Now draw the emulator screen
303 for (DisplayLine line
: visibleLines
) {
304 int widthMax
= emulator
.getWidth();
305 if (line
.isDoubleWidth()) {
308 if (widthMax
> getWidth() - 2) {
309 widthMax
= getWidth() - 2;
311 for (int i
= 0; i
< widthMax
; i
++) {
312 Cell ch
= line
.charAt(i
);
313 Cell newCell
= new Cell();
315 boolean reverse
= line
.isReverseColor() ^ ch
.isReverse();
316 newCell
.setReverse(false);
318 newCell
.setBackColor(ch
.getForeColor());
319 newCell
.setForeColor(ch
.getBackColor());
321 if (line
.isDoubleWidth()) {
322 getScreen().putCharXY((i
* 2) + 1, row
, newCell
);
323 getScreen().putCharXY((i
* 2) + 2, row
, ' ', newCell
);
325 getScreen().putCharXY(i
+ 1, row
, newCell
);
329 if (row
== getHeight() - 1) {
330 // Don't overwrite the box edge
334 CellAttributes background
= new CellAttributes();
335 // Fill in the blank lines on bottom
336 for (int i
= 0; i
< visibleHeight
; i
++) {
337 getScreen().hLineXY(1, i
+ row
, getWidth() - 2, ' ',
341 } // synchronized (emulator)
346 * Called by emulator when fresh data has come in.
348 public void displayChanged() {
353 * Handle window close.
356 public void onClose() {
359 terminateShellChildProcess();
366 * Copy out variables from the emulator that TTerminal has to expose on
369 private void readEmulatorState() {
370 // Synchronize against the emulator so we don't stomp on its reader
372 synchronized (emulator
) {
374 setCursorX(emulator
.getCursorX() + 1);
375 setCursorY(emulator
.getCursorY() + 1
376 + (getHeight() - 2 - emulator
.getHeight())
377 - getVerticalValue());
378 setCursorVisible(emulator
.isCursorVisible());
379 if (getCursorX() > getWidth() - 2) {
380 setCursorVisible(false);
382 if ((getCursorY() > getHeight() - 2) || (getCursorY() < 0)) {
383 setCursorVisible(false);
385 if (emulator
.getScreenTitle().length() > 0) {
386 // Only update the title if the shell is still alive
388 setTitle(emulator
.getScreenTitle());
392 // Check to see if the shell has died.
393 if (!emulator
.isReading() && (shell
!= null)) {
395 int rc
= shell
.exitValue();
396 // The emulator exited on its own, all is fine
397 setTitle(String
.format("%s [Completed - %d]",
401 clearShortcutKeypresses();
402 statusBar
.setText("Terminal session completed, exit " +
404 } catch (IllegalThreadStateException e
) {
405 // The emulator thread has exited, but the shell Process
406 // hasn't figured that out yet. Do nothing, we will see
407 // this in a future tick.
409 } else if (emulator
.isReading() && (shell
!= null)) {
410 // The shell might be dead, let's check
412 int rc
= shell
.exitValue();
413 // If we got here, the shell died.
414 setTitle(String
.format("%s [Completed - %d]",
418 clearShortcutKeypresses();
419 statusBar
.setText("Terminal session completed, exit " +
421 } catch (IllegalThreadStateException e
) {
422 // The shell is still running, do nothing.
426 } // synchronized (emulator)
430 * Handle window/screen resize events.
432 * @param resize resize event
435 public void onResize(final TResizeEvent resize
) {
437 // Synchronize against the emulator so we don't stomp on its reader
439 synchronized (emulator
) {
441 if (resize
.getType() == TResizeEvent
.Type
.WIDGET
) {
442 // Resize the scroll bars
446 // Get out of scrollback
450 emulator
.setWidth(getWidth() - 2);
451 emulator
.setHeight(getHeight() - 2);
453 emulator
.writeRemote("\033[8;" + (getHeight() - 2) + ";" +
454 (getWidth() - 2) + "t");
459 } // synchronized (emulator)
463 * Resize scrollbars for a new width/height.
466 public void reflowData() {
468 // Synchronize against the emulator so we don't stomp on its reader
470 synchronized (emulator
) {
472 // Pull cursor information
475 // Vertical scrollbar
476 setTopValue(getHeight() - 2
477 - (emulator
.getScrollbackBuffer().size()
478 + emulator
.getDisplayBuffer().size()));
479 setVerticalBigChange(getHeight() - 2);
481 } // synchronized (emulator)
485 * Check if a mouse press/release/motion event coordinate is over the
488 * @param mouse a mouse-based event
489 * @return whether or not the mouse is on the emulator
491 private final boolean mouseOnEmulator(final TMouseEvent mouse
) {
493 synchronized (emulator
) {
494 if (!emulator
.isReading()) {
499 if ((mouse
.getAbsoluteX() >= getAbsoluteX() + 1)
500 && (mouse
.getAbsoluteX() < getAbsoluteX() + getWidth() - 1)
501 && (mouse
.getAbsoluteY() >= getAbsoluteY() + 1)
502 && (mouse
.getAbsoluteY() < getAbsoluteY() + getHeight() - 1)
512 * @param keypress keystroke event
515 public void onKeypress(final TKeypressEvent keypress
) {
517 // Scrollback up/down
518 if (keypress
.equals(kbShiftPgUp
)
519 || keypress
.equals(kbCtrlPgUp
)
520 || keypress
.equals(kbAltPgUp
)
522 bigVerticalDecrement();
525 if (keypress
.equals(kbShiftPgDn
)
526 || keypress
.equals(kbCtrlPgDn
)
527 || keypress
.equals(kbAltPgDn
)
529 bigVerticalIncrement();
533 // Synchronize against the emulator so we don't stomp on its reader
535 synchronized (emulator
) {
536 if (emulator
.isReading()) {
537 // Get out of scrollback
539 emulator
.keypress(keypress
.getKey());
541 // UGLY HACK TIME! cmd.exe needs CRLF, not just CR, so if
542 // this is kBEnter then also send kbCtrlJ.
543 if (System
.getProperty("os.name").startsWith("Windows")) {
544 if (keypress
.equals(kbEnter
)) {
545 emulator
.keypress(kbCtrlJ
);
554 // Process is closed, honor "normal" TUI keystrokes
555 super.onKeypress(keypress
);
559 * Handle mouse press events.
561 * @param mouse mouse button press event
564 public void onMouseDown(final TMouseEvent mouse
) {
565 if (inWindowMove
|| inWindowResize
) {
566 // TWindow needs to deal with this.
567 super.onMouseDown(mouse
);
571 if (mouse
.isMouseWheelUp()) {
575 if (mouse
.isMouseWheelDown()) {
579 if (mouseOnEmulator(mouse
)) {
580 synchronized (emulator
) {
581 mouse
.setX(mouse
.getX() - 1);
582 mouse
.setY(mouse
.getY() - 1);
583 emulator
.mouse(mouse
);
589 // Emulator didn't consume it, pass it on
590 super.onMouseDown(mouse
);
594 * Handle mouse release events.
596 * @param mouse mouse button release event
599 public void onMouseUp(final TMouseEvent mouse
) {
600 if (inWindowMove
|| inWindowResize
) {
601 // TWindow needs to deal with this.
602 super.onMouseUp(mouse
);
606 if (mouseOnEmulator(mouse
)) {
607 synchronized (emulator
) {
608 mouse
.setX(mouse
.getX() - 1);
609 mouse
.setY(mouse
.getY() - 1);
610 emulator
.mouse(mouse
);
616 // Emulator didn't consume it, pass it on
617 super.onMouseUp(mouse
);
621 * Handle mouse motion events.
623 * @param mouse mouse motion event
626 public void onMouseMotion(final TMouseEvent mouse
) {
627 if (inWindowMove
|| inWindowResize
) {
628 // TWindow needs to deal with this.
629 super.onMouseMotion(mouse
);
633 if (mouseOnEmulator(mouse
)) {
634 synchronized (emulator
) {
635 mouse
.setX(mouse
.getX() - 1);
636 mouse
.setY(mouse
.getY() - 1);
637 emulator
.mouse(mouse
);
643 // Emulator didn't consume it, pass it on
644 super.onMouseMotion(mouse
);