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
.text
.MessageFormat
;
34 import java
.util
.LinkedList
;
35 import java
.util
.List
;
37 import java
.util
.ResourceBundle
;
39 import jexer
.bits
.Cell
;
40 import jexer
.bits
.CellAttributes
;
41 import jexer
.event
.TKeypressEvent
;
42 import jexer
.event
.TMenuEvent
;
43 import jexer
.event
.TMouseEvent
;
44 import jexer
.event
.TResizeEvent
;
45 import jexer
.menu
.TMenu
;
46 import jexer
.tterminal
.DisplayLine
;
47 import jexer
.tterminal
.DisplayListener
;
48 import jexer
.tterminal
.ECMA48
;
49 import static jexer
.TKeypress
.*;
52 * TTerminalWindow exposes a ECMA-48 / ANSI X3.64 style terminal in a window.
54 public class TTerminalWindow
extends TScrollableWindow
55 implements DisplayListener
{
61 private static final ResourceBundle i18n
= ResourceBundle
.getBundle(TTerminalWindow
.class.getName());
66 private ECMA48 emulator
;
69 * The Process created by the shell spawning constructor.
71 private Process shell
;
74 * If true, we are using the ptypipe utility to support dynamic window
75 * resizing. ptypipe is available at
76 * https://github.com/klamonte/ptypipe .
78 private boolean ptypipe
= false;
81 * Claim the keystrokes the emulator will need.
83 private void addShortcutKeys() {
84 addShortcutKeypress(kbCtrlA
);
85 addShortcutKeypress(kbCtrlB
);
86 addShortcutKeypress(kbCtrlC
);
87 addShortcutKeypress(kbCtrlD
);
88 addShortcutKeypress(kbCtrlE
);
89 addShortcutKeypress(kbCtrlF
);
90 addShortcutKeypress(kbCtrlG
);
91 addShortcutKeypress(kbCtrlH
);
92 addShortcutKeypress(kbCtrlU
);
93 addShortcutKeypress(kbCtrlJ
);
94 addShortcutKeypress(kbCtrlK
);
95 addShortcutKeypress(kbCtrlL
);
96 addShortcutKeypress(kbCtrlM
);
97 addShortcutKeypress(kbCtrlN
);
98 addShortcutKeypress(kbCtrlO
);
99 addShortcutKeypress(kbCtrlP
);
100 addShortcutKeypress(kbCtrlQ
);
101 addShortcutKeypress(kbCtrlR
);
102 addShortcutKeypress(kbCtrlS
);
103 addShortcutKeypress(kbCtrlT
);
104 addShortcutKeypress(kbCtrlU
);
105 addShortcutKeypress(kbCtrlV
);
106 addShortcutKeypress(kbCtrlW
);
107 addShortcutKeypress(kbCtrlX
);
108 addShortcutKeypress(kbCtrlY
);
109 addShortcutKeypress(kbCtrlZ
);
110 addShortcutKeypress(kbF1
);
111 addShortcutKeypress(kbF2
);
112 addShortcutKeypress(kbF3
);
113 addShortcutKeypress(kbF4
);
114 addShortcutKeypress(kbF5
);
115 addShortcutKeypress(kbF6
);
116 addShortcutKeypress(kbF7
);
117 addShortcutKeypress(kbF8
);
118 addShortcutKeypress(kbF9
);
119 addShortcutKeypress(kbF10
);
120 addShortcutKeypress(kbF11
);
121 addShortcutKeypress(kbF12
);
122 addShortcutKeypress(kbAltA
);
123 addShortcutKeypress(kbAltB
);
124 addShortcutKeypress(kbAltC
);
125 addShortcutKeypress(kbAltD
);
126 addShortcutKeypress(kbAltE
);
127 addShortcutKeypress(kbAltF
);
128 addShortcutKeypress(kbAltG
);
129 addShortcutKeypress(kbAltH
);
130 addShortcutKeypress(kbAltU
);
131 addShortcutKeypress(kbAltJ
);
132 addShortcutKeypress(kbAltK
);
133 addShortcutKeypress(kbAltL
);
134 addShortcutKeypress(kbAltM
);
135 addShortcutKeypress(kbAltN
);
136 addShortcutKeypress(kbAltO
);
137 addShortcutKeypress(kbAltP
);
138 addShortcutKeypress(kbAltQ
);
139 addShortcutKeypress(kbAltR
);
140 addShortcutKeypress(kbAltS
);
141 addShortcutKeypress(kbAltT
);
142 addShortcutKeypress(kbAltU
);
143 addShortcutKeypress(kbAltV
);
144 addShortcutKeypress(kbAltW
);
145 addShortcutKeypress(kbAltX
);
146 addShortcutKeypress(kbAltY
);
147 addShortcutKeypress(kbAltZ
);
153 * @param commandLine the command line to execute
155 private void spawnShell(final String commandLine
) {
157 vScroller
= new TVScroller(this, getWidth() - 2, 0, getHeight() - 2);
161 ECMA48
.DeviceType deviceType
= ECMA48
.DeviceType
.XTERM
;
164 String
[] command
= commandLine
.split("\\s");
165 ProcessBuilder pb
= new ProcessBuilder(command
);
166 Map
<String
, String
> env
= pb
.environment();
167 env
.put("TERM", ECMA48
.deviceTypeTerm(deviceType
));
168 env
.put("LANG", ECMA48
.deviceTypeLang(deviceType
, "en"));
169 env
.put("COLUMNS", "80");
170 env
.put("LINES", "24");
171 pb
.redirectErrorStream(true);
173 emulator
= new ECMA48(deviceType
, shell
.getInputStream(),
174 shell
.getOutputStream(), this);
175 } catch (IOException e
) {
176 messageBox(i18n
.getString("errorLaunchingShellTitle"),
177 MessageFormat
.format(i18n
.getString("errorLaunchingShellText"),
181 // Setup the scroll bars
182 onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
, getWidth(),
185 // Claim the keystrokes the emulator will need.
189 newStatusBar(i18n
.getString("statusBarRunning"));
193 * Public constructor spawns a custom command line.
195 * @param application TApplication that manages this window
196 * @param x column relative to parent
197 * @param y row relative to parent
198 * @param commandLine the command line to execute
200 public TTerminalWindow(final TApplication application
, final int x
,
201 final int y
, final String commandLine
) {
203 this(application
, x
, y
, RESIZABLE
, commandLine
);
207 * Public constructor spawns a custom command line.
209 * @param application TApplication that manages this window
210 * @param x column relative to parent
211 * @param y row relative to parent
212 * @param flags mask of CENTERED, MODAL, or RESIZABLE
213 * @param commandLine the command line to execute
215 public TTerminalWindow(final TApplication application
, final int x
,
216 final int y
, final int flags
, final String commandLine
) {
218 super(application
, i18n
.getString("windowTitle"), x
, y
,
219 80 + 2, 24 + 2, flags
);
221 String cmdShellWindows
= "cmd.exe /c" + commandLine
;
222 String cmdShellGNU
= "script -fqe /dev/null -c " + commandLine
;
223 String cmdShellBSD
= "script -q -F /dev/null -c " + commandLine
;
224 String cmdShellPtypipe
= "ptypipe " + commandLine
;
226 // Spawn a shell and pass its I/O to the other constructor.
227 if ((System
.getProperty("jexer.TTerminal.ptypipe") != null)
228 && (System
.getProperty("jexer.TTerminal.ptypipe").
232 spawnShell(cmdShellPtypipe
);
233 } else if (System
.getProperty("os.name").startsWith("Windows")) {
234 spawnShell(cmdShellWindows
);
235 } else if (System
.getProperty("os.name").startsWith("Mac")) {
236 spawnShell(cmdShellBSD
);
237 } else if (System
.getProperty("os.name").startsWith("Linux")) {
238 spawnShell(cmdShellGNU
);
240 // When all else fails, assume GNU.
241 spawnShell(cmdShellGNU
);
246 * Public constructor spawns a shell.
248 * @param application TApplication that manages this window
249 * @param x column relative to parent
250 * @param y row relative to parent
251 * @param flags mask of CENTERED, MODAL, or RESIZABLE
253 public TTerminalWindow(final TApplication application
, final int x
,
254 final int y
, final int flags
) {
256 super(application
, i18n
.getString("windowTitle"), x
, y
,
257 80 + 2, 24 + 2, flags
);
259 String cmdShellWindows
= "cmd.exe";
261 // You cannot run a login shell in a bare Process interactively, due
262 // to libc's behavior of buffering when stdin/stdout aren't a tty.
263 // Use 'script' instead to run a shell in a pty. And because BSD and
264 // GNU differ on the '-f' vs '-F' flags, we need two different
266 String cmdShellGNU
= "script -fqe /dev/null";
267 String cmdShellBSD
= "script -q -F /dev/null";
269 // ptypipe is another solution that permits dynamic window resizing.
270 String cmdShellPtypipe
= "ptypipe /bin/bash --login";
272 // Spawn a shell and pass its I/O to the other constructor.
273 if ((System
.getProperty("jexer.TTerminal.ptypipe") != null)
274 && (System
.getProperty("jexer.TTerminal.ptypipe").
278 spawnShell(cmdShellPtypipe
);
279 } else if (System
.getProperty("os.name").startsWith("Windows")) {
280 spawnShell(cmdShellWindows
);
281 } else if (System
.getProperty("os.name").startsWith("Mac")) {
282 spawnShell(cmdShellBSD
);
283 } else if (System
.getProperty("os.name").startsWith("Linux")) {
284 spawnShell(cmdShellGNU
);
286 // When all else fails, assume GNU.
287 spawnShell(cmdShellGNU
);
292 * Terminate the child of the 'script' process used on POSIX. This may
295 private void terminateShellChildProcess() {
297 if (shell
.getClass().getName().equals("java.lang.UNIXProcess")) {
298 /* get the PID on unix/linux systems */
300 Field field
= shell
.getClass().getDeclaredField("pid");
301 field
.setAccessible(true);
302 pid
= field
.getInt(shell
);
303 } catch (Throwable e
) {
304 // SQUASH, this didn't work. Just bail out quietly.
309 // shell.destroy() works successfully at killing this side of
310 // 'script'. But we need to make sure the other side (child
311 // process) is also killed.
312 String
[] cmdKillIt
= {
313 "pkill", "-P", Integer
.toString(pid
)
316 Runtime
.getRuntime().exec(cmdKillIt
);
317 } catch (Throwable e
) {
318 // SQUASH, this didn't work. Just bail out quietly.
325 * Draw the display buffer.
329 // Synchronize against the emulator so we don't stomp on its reader
331 synchronized (emulator
) {
333 // Update the scroll bars
336 // Draw the box using my superclass
339 List
<DisplayLine
> scrollback
= emulator
.getScrollbackBuffer();
340 List
<DisplayLine
> display
= emulator
.getDisplayBuffer();
342 // Put together the visible rows
343 int visibleHeight
= getHeight() - 2;
344 int visibleBottom
= scrollback
.size() + display
.size()
345 + getVerticalValue();
346 assert (visibleBottom
>= 0);
348 List
<DisplayLine
> preceedingBlankLines
= new LinkedList
<DisplayLine
>();
349 int visibleTop
= visibleBottom
- visibleHeight
;
350 if (visibleTop
< 0) {
351 for (int i
= visibleTop
; i
< 0; i
++) {
352 preceedingBlankLines
.add(emulator
.getBlankDisplayLine());
356 assert (visibleTop
>= 0);
358 List
<DisplayLine
> displayLines
= new LinkedList
<DisplayLine
>();
359 displayLines
.addAll(scrollback
);
360 displayLines
.addAll(display
);
362 List
<DisplayLine
> visibleLines
= new LinkedList
<DisplayLine
>();
363 visibleLines
.addAll(preceedingBlankLines
);
364 visibleLines
.addAll(displayLines
.subList(visibleTop
,
367 visibleHeight
-= visibleLines
.size();
368 assert (visibleHeight
>= 0);
370 // Now draw the emulator screen
372 for (DisplayLine line
: visibleLines
) {
373 int widthMax
= emulator
.getWidth();
374 if (line
.isDoubleWidth()) {
377 if (widthMax
> getWidth() - 2) {
378 widthMax
= getWidth() - 2;
380 for (int i
= 0; i
< widthMax
; i
++) {
381 Cell ch
= line
.charAt(i
);
382 Cell newCell
= new Cell();
384 boolean reverse
= line
.isReverseColor() ^ ch
.isReverse();
385 newCell
.setReverse(false);
387 newCell
.setBackColor(ch
.getForeColor());
388 newCell
.setForeColor(ch
.getBackColor());
390 if (line
.isDoubleWidth()) {
391 getScreen().putCharXY((i
* 2) + 1, row
, newCell
);
392 getScreen().putCharXY((i
* 2) + 2, row
, ' ', newCell
);
394 getScreen().putCharXY(i
+ 1, row
, newCell
);
398 if (row
== getHeight() - 1) {
399 // Don't overwrite the box edge
403 CellAttributes background
= new CellAttributes();
404 // Fill in the blank lines on bottom
405 for (int i
= 0; i
< visibleHeight
; i
++) {
406 getScreen().hLineXY(1, i
+ row
, getWidth() - 2, ' ',
410 } // synchronized (emulator)
415 * Called by emulator when fresh data has come in.
417 public void displayChanged() {
418 getApplication().postEvent(new TMenuEvent(TMenu
.MID_REPAINT
));
422 * Function to call to obtain the display width.
424 * @return the number of columns in the display
426 public int getDisplayWidth() {
428 return getWidth() - 2;
434 * Function to call to obtain the display height.
436 * @return the number of rows in the display
438 public int getDisplayHeight() {
440 return getHeight() - 2;
446 * Handle window close.
449 public void onClose() {
452 terminateShellChildProcess();
459 * Hook for subclasses to be notified of the shell termination.
461 public void onShellExit() {
462 getApplication().postEvent(new TMenuEvent(TMenu
.MID_REPAINT
));
466 * Copy out variables from the emulator that TTerminal has to expose on
469 private void readEmulatorState() {
470 // Synchronize against the emulator so we don't stomp on its reader
472 synchronized (emulator
) {
474 setCursorX(emulator
.getCursorX() + 1);
475 setCursorY(emulator
.getCursorY() + 1
476 + (getHeight() - 2 - emulator
.getHeight())
477 - getVerticalValue());
478 setCursorVisible(emulator
.isCursorVisible());
479 if (getCursorX() > getWidth() - 2) {
480 setCursorVisible(false);
482 if ((getCursorY() > getHeight() - 2) || (getCursorY() < 0)) {
483 setCursorVisible(false);
485 if (emulator
.getScreenTitle().length() > 0) {
486 // Only update the title if the shell is still alive
488 setTitle(emulator
.getScreenTitle());
492 // Check to see if the shell has died.
493 if (!emulator
.isReading() && (shell
!= null)) {
495 int rc
= shell
.exitValue();
496 // The emulator exited on its own, all is fine
497 setTitle(MessageFormat
.format(i18n
.
498 getString("windowTitleCompleted"), getTitle(), rc
));
501 clearShortcutKeypresses();
502 statusBar
.setText(MessageFormat
.format(i18n
.
503 getString("statusBarCompleted"), rc
));
505 } catch (IllegalThreadStateException e
) {
506 // The emulator thread has exited, but the shell Process
507 // hasn't figured that out yet. Do nothing, we will see
508 // this in a future tick.
510 } else if (emulator
.isReading() && (shell
!= null)) {
511 // The shell might be dead, let's check
513 int rc
= shell
.exitValue();
514 // If we got here, the shell died.
515 setTitle(MessageFormat
.format(i18n
.
516 getString("windowTitleCompleted"), getTitle(), rc
));
519 clearShortcutKeypresses();
520 statusBar
.setText(MessageFormat
.format(i18n
.
521 getString("statusBarCompleted"), rc
));
523 } catch (IllegalThreadStateException e
) {
524 // The shell is still running, do nothing.
528 } // synchronized (emulator)
532 * Handle window/screen resize events.
534 * @param resize resize event
537 public void onResize(final TResizeEvent resize
) {
539 // Synchronize against the emulator so we don't stomp on its reader
541 synchronized (emulator
) {
543 if (resize
.getType() == TResizeEvent
.Type
.WIDGET
) {
544 // Resize the scroll bars
548 // Get out of scrollback
552 emulator
.setWidth(getWidth() - 2);
553 emulator
.setHeight(getHeight() - 2);
555 emulator
.writeRemote("\033[8;" + (getHeight() - 2) + ";" +
556 (getWidth() - 2) + "t");
561 } // synchronized (emulator)
565 * Resize scrollbars for a new width/height.
568 public void reflowData() {
570 // Synchronize against the emulator so we don't stomp on its reader
572 synchronized (emulator
) {
574 // Pull cursor information
577 // Vertical scrollbar
578 setTopValue(getHeight() - 2
579 - (emulator
.getScrollbackBuffer().size()
580 + emulator
.getDisplayBuffer().size()));
581 setVerticalBigChange(getHeight() - 2);
583 } // synchronized (emulator)
587 * Check if a mouse press/release/motion event coordinate is over the
590 * @param mouse a mouse-based event
591 * @return whether or not the mouse is on the emulator
593 private final boolean mouseOnEmulator(final TMouseEvent mouse
) {
595 synchronized (emulator
) {
596 if (!emulator
.isReading()) {
601 if ((mouse
.getAbsoluteX() >= getAbsoluteX() + 1)
602 && (mouse
.getAbsoluteX() < getAbsoluteX() + getWidth() - 1)
603 && (mouse
.getAbsoluteY() >= getAbsoluteY() + 1)
604 && (mouse
.getAbsoluteY() < getAbsoluteY() + getHeight() - 1)
614 * @param keypress keystroke event
617 public void onKeypress(final TKeypressEvent keypress
) {
619 // Scrollback up/down
620 if (keypress
.equals(kbShiftPgUp
)
621 || keypress
.equals(kbCtrlPgUp
)
622 || keypress
.equals(kbAltPgUp
)
624 bigVerticalDecrement();
627 if (keypress
.equals(kbShiftPgDn
)
628 || keypress
.equals(kbCtrlPgDn
)
629 || keypress
.equals(kbAltPgDn
)
631 bigVerticalIncrement();
635 // Synchronize against the emulator so we don't stomp on its reader
637 synchronized (emulator
) {
638 if (emulator
.isReading()) {
639 // Get out of scrollback
641 emulator
.keypress(keypress
.getKey());
643 // UGLY HACK TIME! cmd.exe needs CRLF, not just CR, so if
644 // this is kBEnter then also send kbCtrlJ.
645 if (System
.getProperty("os.name").startsWith("Windows")) {
646 if (keypress
.equals(kbEnter
)) {
647 emulator
.keypress(kbCtrlJ
);
656 // Process is closed, honor "normal" TUI keystrokes
657 super.onKeypress(keypress
);
661 * Handle mouse press events.
663 * @param mouse mouse button press event
666 public void onMouseDown(final TMouseEvent mouse
) {
667 if (inWindowMove
|| inWindowResize
) {
668 // TWindow needs to deal with this.
669 super.onMouseDown(mouse
);
673 if (mouse
.isMouseWheelUp()) {
677 if (mouse
.isMouseWheelDown()) {
681 if (mouseOnEmulator(mouse
)) {
682 synchronized (emulator
) {
683 mouse
.setX(mouse
.getX() - 1);
684 mouse
.setY(mouse
.getY() - 1);
685 emulator
.mouse(mouse
);
691 // Emulator didn't consume it, pass it on
692 super.onMouseDown(mouse
);
696 * Handle mouse release events.
698 * @param mouse mouse button release event
701 public void onMouseUp(final TMouseEvent mouse
) {
702 if (inWindowMove
|| inWindowResize
) {
703 // TWindow needs to deal with this.
704 super.onMouseUp(mouse
);
708 if (mouseOnEmulator(mouse
)) {
709 synchronized (emulator
) {
710 mouse
.setX(mouse
.getX() - 1);
711 mouse
.setY(mouse
.getY() - 1);
712 emulator
.mouse(mouse
);
718 // Emulator didn't consume it, pass it on
719 super.onMouseUp(mouse
);
723 * Handle mouse motion events.
725 * @param mouse mouse motion event
728 public void onMouseMotion(final TMouseEvent mouse
) {
729 if (inWindowMove
|| inWindowResize
) {
730 // TWindow needs to deal with this.
731 super.onMouseMotion(mouse
);
735 if (mouseOnEmulator(mouse
)) {
736 synchronized (emulator
) {
737 mouse
.setX(mouse
.getX() - 1);
738 mouse
.setY(mouse
.getY() - 1);
739 emulator
.mouse(mouse
);
745 // Emulator didn't consume it, pass it on
746 super.onMouseMotion(mouse
);