Common Scrollable interface
[fanfix.git] / src / jexer / TTerminalWindow.java
1 /*
2 * Jexer - Java Text User Interface
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (C) 2017 Kevin Lamonte
7 *
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:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
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.
25 *
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
27 * @version 1
28 */
29 package jexer;
30
31 import java.io.InputStream;
32 import java.io.IOException;
33 import java.io.OutputStream;
34 import java.io.UnsupportedEncodingException;
35 import java.lang.reflect.Field;
36 import java.util.LinkedList;
37 import java.util.List;
38 import java.util.Map;
39
40 import jexer.bits.Cell;
41 import jexer.bits.CellAttributes;
42 import jexer.event.TKeypressEvent;
43 import jexer.event.TMouseEvent;
44 import jexer.event.TResizeEvent;
45 import jexer.tterminal.DisplayLine;
46 import jexer.tterminal.ECMA48;
47 import static jexer.TKeypress.*;
48
49 /**
50 * TTerminalWindow exposes a ECMA-48 / ANSI X3.64 style terminal in a window.
51 */
52 public class TTerminalWindow extends TScrollableWindow {
53
54 /**
55 * The emulator.
56 */
57 private ECMA48 emulator;
58
59 /**
60 * The Process created by the shell spawning constructor.
61 */
62 private Process shell;
63
64 /**
65 * Claim the keystrokes the emulator will need.
66 */
67 private void addShortcutKeys() {
68 addShortcutKeypress(kbCtrlA);
69 addShortcutKeypress(kbCtrlB);
70 addShortcutKeypress(kbCtrlC);
71 addShortcutKeypress(kbCtrlD);
72 addShortcutKeypress(kbCtrlE);
73 addShortcutKeypress(kbCtrlF);
74 addShortcutKeypress(kbCtrlG);
75 addShortcutKeypress(kbCtrlH);
76 addShortcutKeypress(kbCtrlU);
77 addShortcutKeypress(kbCtrlJ);
78 addShortcutKeypress(kbCtrlK);
79 addShortcutKeypress(kbCtrlL);
80 addShortcutKeypress(kbCtrlM);
81 addShortcutKeypress(kbCtrlN);
82 addShortcutKeypress(kbCtrlO);
83 addShortcutKeypress(kbCtrlP);
84 addShortcutKeypress(kbCtrlQ);
85 addShortcutKeypress(kbCtrlR);
86 addShortcutKeypress(kbCtrlS);
87 addShortcutKeypress(kbCtrlT);
88 addShortcutKeypress(kbCtrlU);
89 addShortcutKeypress(kbCtrlV);
90 addShortcutKeypress(kbCtrlW);
91 addShortcutKeypress(kbCtrlX);
92 addShortcutKeypress(kbCtrlY);
93 addShortcutKeypress(kbCtrlZ);
94 addShortcutKeypress(kbF1);
95 addShortcutKeypress(kbF2);
96 addShortcutKeypress(kbF3);
97 addShortcutKeypress(kbF4);
98 addShortcutKeypress(kbF5);
99 addShortcutKeypress(kbF6);
100 addShortcutKeypress(kbF7);
101 addShortcutKeypress(kbF8);
102 addShortcutKeypress(kbF9);
103 addShortcutKeypress(kbF10);
104 addShortcutKeypress(kbF11);
105 addShortcutKeypress(kbF12);
106 addShortcutKeypress(kbAltA);
107 addShortcutKeypress(kbAltB);
108 addShortcutKeypress(kbAltC);
109 addShortcutKeypress(kbAltD);
110 addShortcutKeypress(kbAltE);
111 addShortcutKeypress(kbAltF);
112 addShortcutKeypress(kbAltG);
113 addShortcutKeypress(kbAltH);
114 addShortcutKeypress(kbAltU);
115 addShortcutKeypress(kbAltJ);
116 addShortcutKeypress(kbAltK);
117 addShortcutKeypress(kbAltL);
118 addShortcutKeypress(kbAltM);
119 addShortcutKeypress(kbAltN);
120 addShortcutKeypress(kbAltO);
121 addShortcutKeypress(kbAltP);
122 addShortcutKeypress(kbAltQ);
123 addShortcutKeypress(kbAltR);
124 addShortcutKeypress(kbAltS);
125 addShortcutKeypress(kbAltT);
126 addShortcutKeypress(kbAltU);
127 addShortcutKeypress(kbAltV);
128 addShortcutKeypress(kbAltW);
129 addShortcutKeypress(kbAltX);
130 addShortcutKeypress(kbAltY);
131 addShortcutKeypress(kbAltZ);
132 }
133
134 /**
135 * Public constructor spawns a shell.
136 *
137 * @param application TApplication that manages this window
138 * @param x column relative to parent
139 * @param y row relative to parent
140 * @param flags mask of CENTERED, MODAL, or RESIZABLE
141 */
142 public TTerminalWindow(final TApplication application, final int x,
143 final int y, final int flags) {
144
145 super(application, "Terminal", x, y, 80 + 2, 24 + 2, flags);
146
147 vScroller = new TVScroller(this, getWidth() - 2, 0, getHeight() - 2);
148 setBottomValue(0);
149
150 // Assume XTERM
151 ECMA48.DeviceType deviceType = ECMA48.DeviceType.XTERM;
152
153 try {
154 String [] cmdShellWindows = {
155 "cmd.exe"
156 };
157
158 // You cannot run a login shell in a bare Process interactively,
159 // due to libc's behavior of buffering when stdin/stdout aren't a
160 // tty. Use 'script' instead to run a shell in a pty. And
161 // because BSD and GNU differ on the '-f' vs '-F' flags, we need
162 // two different commands. Lovely.
163 String [] cmdShellGNU = {
164 "script", "-fqe", "/dev/null"
165 };
166 String [] cmdShellBSD = {
167 "script", "-q", "-F", "/dev/null"
168 };
169 // Spawn a shell and pass its I/O to the other constructor.
170
171 ProcessBuilder pb;
172 if (System.getProperty("os.name").startsWith("Windows")) {
173 pb = new ProcessBuilder(cmdShellWindows);
174 } else if (System.getProperty("os.name").startsWith("Mac")) {
175 pb = new ProcessBuilder(cmdShellBSD);
176 } else if (System.getProperty("os.name").startsWith("Linux")) {
177 pb = new ProcessBuilder(cmdShellGNU);
178 } else {
179 // When all else fails, assume GNU.
180 pb = new ProcessBuilder(cmdShellGNU);
181 }
182 Map<String, String> env = pb.environment();
183 env.put("TERM", ECMA48.deviceTypeTerm(deviceType));
184 env.put("LANG", ECMA48.deviceTypeLang(deviceType, "en"));
185 env.put("COLUMNS", "80");
186 env.put("LINES", "24");
187 pb.redirectErrorStream(true);
188 shell = pb.start();
189 emulator = new ECMA48(deviceType, shell.getInputStream(),
190 shell.getOutputStream());
191 } catch (IOException e) {
192 e.printStackTrace();
193 }
194
195 // Setup the scroll bars
196 onResize(new TResizeEvent(TResizeEvent.Type.WIDGET, getWidth(),
197 getHeight()));
198
199 // Claim the keystrokes the emulator will need.
200 addShortcutKeys();
201
202 // Add shortcut text
203 newStatusBar("Terminal session executing...");
204 }
205
206 /**
207 * Terminate the child of the 'script' process used on POSIX. This may
208 * or may not work.
209 */
210 private void terminateShellChildProcess() {
211 int pid = -1;
212 if (shell.getClass().getName().equals("java.lang.UNIXProcess")) {
213 /* get the PID on unix/linux systems */
214 try {
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.
220 return;
221 }
222 }
223 if (pid != -1) {
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)
229 };
230 try {
231 Runtime.getRuntime().exec(cmdKillIt);
232 } catch (Throwable e) {
233 // SQUASH, this didn't work. Just bail out quietly.
234 return;
235 }
236 }
237 }
238
239 /**
240 * Public constructor.
241 *
242 * @param application TApplication that manages this window
243 * @param x column relative to parent
244 * @param y row relative to parent
245 * @param flags mask of CENTERED, MODAL, or RESIZABLE
246 * @param input an InputStream connected to the remote side. For type ==
247 * XTERM, input is converted to a Reader with UTF-8 encoding.
248 * @param output an OutputStream connected to the remote user. For type
249 * == XTERM, output is converted to a Writer with UTF-8 encoding.
250 * @throws UnsupportedEncodingException if an exception is thrown when
251 * creating the InputStreamReader
252 */
253 public TTerminalWindow(final TApplication application, final int x,
254 final int y, final int flags, final InputStream input,
255 final OutputStream output) throws UnsupportedEncodingException {
256
257 super(application, "Terminal", x, y, 80 + 2, 24 + 2, flags);
258
259 emulator = new ECMA48(ECMA48.DeviceType.XTERM, input, output);
260
261 // Setup the scroll bars
262 onResize(new TResizeEvent(TResizeEvent.Type.WIDGET, getWidth(),
263 getHeight()));
264
265 // Claim the keystrokes the emulator will need.
266 addShortcutKeys();
267
268 // Add shortcut text
269 newStatusBar("Terminal session executing...");
270 }
271
272 /**
273 * Draw the display buffer.
274 */
275 @Override
276 public void draw() {
277 // Synchronize against the emulator so we don't stomp on its reader
278 // thread.
279 synchronized (emulator) {
280
281 // Update the scroll bars
282 reflowData();
283
284 // Draw the box using my superclass
285 super.draw();
286
287 List<DisplayLine> scrollback = emulator.getScrollbackBuffer();
288 List<DisplayLine> display = emulator.getDisplayBuffer();
289
290 // Put together the visible rows
291 int visibleHeight = getHeight() - 2;
292 int visibleBottom = scrollback.size() + display.size()
293 + getVerticalValue();
294 assert (visibleBottom >= 0);
295
296 List<DisplayLine> preceedingBlankLines = new LinkedList<DisplayLine>();
297 int visibleTop = visibleBottom - visibleHeight;
298 if (visibleTop < 0) {
299 for (int i = visibleTop; i < 0; i++) {
300 preceedingBlankLines.add(emulator.getBlankDisplayLine());
301 }
302 visibleTop = 0;
303 }
304 assert (visibleTop >= 0);
305
306 List<DisplayLine> displayLines = new LinkedList<DisplayLine>();
307 displayLines.addAll(scrollback);
308 displayLines.addAll(display);
309
310 List<DisplayLine> visibleLines = new LinkedList<DisplayLine>();
311 visibleLines.addAll(preceedingBlankLines);
312 visibleLines.addAll(displayLines.subList(visibleTop,
313 visibleBottom));
314
315 visibleHeight -= visibleLines.size();
316 assert (visibleHeight >= 0);
317
318 // Now draw the emulator screen
319 int row = 1;
320 for (DisplayLine line: visibleLines) {
321 int widthMax = emulator.getWidth();
322 if (line.isDoubleWidth()) {
323 widthMax /= 2;
324 }
325 if (widthMax > getWidth() - 2) {
326 widthMax = getWidth() - 2;
327 }
328 for (int i = 0; i < widthMax; i++) {
329 Cell ch = line.charAt(i);
330 Cell newCell = new Cell();
331 newCell.setTo(ch);
332 boolean reverse = line.isReverseColor() ^ ch.isReverse();
333 newCell.setReverse(false);
334 if (reverse) {
335 newCell.setBackColor(ch.getForeColor());
336 newCell.setForeColor(ch.getBackColor());
337 }
338 if (line.isDoubleWidth()) {
339 getScreen().putCharXY((i * 2) + 1, row, newCell);
340 getScreen().putCharXY((i * 2) + 2, row, ' ', newCell);
341 } else {
342 getScreen().putCharXY(i + 1, row, newCell);
343 }
344 }
345 row++;
346 if (row == getHeight() - 1) {
347 // Don't overwrite the box edge
348 break;
349 }
350 }
351 CellAttributes background = new CellAttributes();
352 // Fill in the blank lines on bottom
353 for (int i = 0; i < visibleHeight; i++) {
354 getScreen().hLineXY(1, i + row, getWidth() - 2, ' ',
355 background);
356 }
357
358 } // synchronized (emulator)
359
360 }
361
362 /**
363 * Handle window close.
364 */
365 @Override
366 public void onClose() {
367 emulator.close();
368 if (shell != null) {
369 terminateShellChildProcess();
370 shell.destroy();
371 shell = null;
372 }
373 }
374
375 /**
376 * Copy out variables from the emulator that TTerminal has to expose on
377 * screen.
378 */
379 private void readEmulatorState() {
380 // Synchronize against the emulator so we don't stomp on its reader
381 // thread.
382 synchronized (emulator) {
383
384 setCursorX(emulator.getCursorX() + 1);
385 setCursorY(emulator.getCursorY() + 1
386 + (getHeight() - 2 - emulator.getHeight())
387 - getVerticalValue());
388 setCursorVisible(emulator.isCursorVisible());
389 if (getCursorX() > getWidth() - 2) {
390 setCursorVisible(false);
391 }
392 if ((getCursorY() > getHeight() - 2) || (getCursorY() < 0)) {
393 setCursorVisible(false);
394 }
395 if (emulator.getScreenTitle().length() > 0) {
396 // Only update the title if the shell is still alive
397 if (shell != null) {
398 setTitle(emulator.getScreenTitle());
399 }
400 }
401
402 // Check to see if the shell has died.
403 if (!emulator.isReading() && (shell != null)) {
404 try {
405 int rc = shell.exitValue();
406 // The emulator exited on its own, all is fine
407 setTitle(String.format("%s [Completed - %d]",
408 getTitle(), rc));
409 shell = null;
410 emulator.close();
411 clearShortcutKeypresses();
412 statusBar.setText("Terminal session completed, exit " +
413 "code " + rc + ".");
414 } catch (IllegalThreadStateException e) {
415 // The emulator thread has exited, but the shell Process
416 // hasn't figured that out yet. Do nothing, we will see
417 // this in a future tick.
418 }
419 } else if (emulator.isReading() && (shell != null)) {
420 // The shell might be dead, let's check
421 try {
422 int rc = shell.exitValue();
423 // If we got here, the shell died.
424 setTitle(String.format("%s [Completed - %d]",
425 getTitle(), rc));
426 shell = null;
427 emulator.close();
428 clearShortcutKeypresses();
429 statusBar.setText("Terminal session completed, exit " +
430 "code " + rc + ".");
431 } catch (IllegalThreadStateException e) {
432 // The shell is still running, do nothing.
433 }
434 }
435
436 } // synchronized (emulator)
437 }
438
439 /**
440 * Handle window/screen resize events.
441 *
442 * @param resize resize event
443 */
444 @Override
445 public void onResize(final TResizeEvent resize) {
446
447 // Synchronize against the emulator so we don't stomp on its reader
448 // thread.
449 synchronized (emulator) {
450
451 if (resize.getType() == TResizeEvent.Type.WIDGET) {
452 // Resize the scroll bars
453 reflowData();
454 placeScrollbars();
455
456 // Get out of scrollback
457 setVerticalValue(0);
458 }
459 return;
460
461 } // synchronized (emulator)
462 }
463
464 /**
465 * Resize scrollbars for a new width/height.
466 */
467 @Override
468 public void reflowData() {
469
470 // Synchronize against the emulator so we don't stomp on its reader
471 // thread.
472 synchronized (emulator) {
473
474 // Pull cursor information
475 readEmulatorState();
476
477 // Vertical scrollbar
478 setTopValue(getHeight() - 2
479 - (emulator.getScrollbackBuffer().size()
480 + emulator.getDisplayBuffer().size()));
481 setVerticalBigChange(getHeight() - 2);
482
483 } // synchronized (emulator)
484 }
485
486 /**
487 * Check if a mouse press/release/motion event coordinate is over the
488 * emulator.
489 *
490 * @param mouse a mouse-based event
491 * @return whether or not the mouse is on the emulator
492 */
493 private final boolean mouseOnEmulator(final TMouseEvent mouse) {
494
495 synchronized (emulator) {
496 if (!emulator.isReading()) {
497 return false;
498 }
499 }
500
501 if ((mouse.getAbsoluteX() >= getAbsoluteX() + 1)
502 && (mouse.getAbsoluteX() < getAbsoluteX() + getWidth() - 1)
503 && (mouse.getAbsoluteY() >= getAbsoluteY() + 1)
504 && (mouse.getAbsoluteY() < getAbsoluteY() + getHeight() - 1)
505 ) {
506 return true;
507 }
508 return false;
509 }
510
511 /**
512 * Handle keystrokes.
513 *
514 * @param keypress keystroke event
515 */
516 @Override
517 public void onKeypress(final TKeypressEvent keypress) {
518
519 // Scrollback up/down
520 if (keypress.equals(kbShiftPgUp)
521 || keypress.equals(kbCtrlPgUp)
522 || keypress.equals(kbAltPgUp)
523 ) {
524 bigVerticalDecrement();
525 return;
526 }
527 if (keypress.equals(kbShiftPgDn)
528 || keypress.equals(kbCtrlPgDn)
529 || keypress.equals(kbAltPgDn)
530 ) {
531 bigVerticalIncrement();
532 return;
533 }
534
535 // Synchronize against the emulator so we don't stomp on its reader
536 // thread.
537 synchronized (emulator) {
538 if (emulator.isReading()) {
539 // Get out of scrollback
540 setVerticalValue(0);
541 emulator.keypress(keypress.getKey());
542
543 // UGLY HACK TIME! cmd.exe needs CRLF, not just CR, so if
544 // this is kBEnter then also send kbCtrlJ.
545 if (System.getProperty("os.name").startsWith("Windows")) {
546 if (keypress.equals(kbEnter)) {
547 emulator.keypress(kbCtrlJ);
548 }
549 }
550
551 readEmulatorState();
552 return;
553 }
554 }
555
556 // Process is closed, honor "normal" TUI keystrokes
557 super.onKeypress(keypress);
558 }
559
560 /**
561 * Handle mouse press events.
562 *
563 * @param mouse mouse button press event
564 */
565 @Override
566 public void onMouseDown(final TMouseEvent mouse) {
567 if (inWindowMove || inWindowResize) {
568 // TWindow needs to deal with this.
569 super.onMouseDown(mouse);
570 return;
571 }
572
573 if (mouse.isMouseWheelUp()) {
574 verticalDecrement();
575 return;
576 }
577 if (mouse.isMouseWheelDown()) {
578 verticalIncrement();
579 return;
580 }
581 if (mouseOnEmulator(mouse)) {
582 synchronized (emulator) {
583 mouse.setX(mouse.getX() - 1);
584 mouse.setY(mouse.getY() - 1);
585 emulator.mouse(mouse);
586 readEmulatorState();
587 return;
588 }
589 }
590
591 // Emulator didn't consume it, pass it on
592 super.onMouseDown(mouse);
593 }
594
595 /**
596 * Handle mouse release events.
597 *
598 * @param mouse mouse button release event
599 */
600 @Override
601 public void onMouseUp(final TMouseEvent mouse) {
602 if (inWindowMove || inWindowResize) {
603 // TWindow needs to deal with this.
604 super.onMouseUp(mouse);
605 return;
606 }
607
608 if (mouseOnEmulator(mouse)) {
609 synchronized (emulator) {
610 mouse.setX(mouse.getX() - 1);
611 mouse.setY(mouse.getY() - 1);
612 emulator.mouse(mouse);
613 readEmulatorState();
614 return;
615 }
616 }
617
618 // Emulator didn't consume it, pass it on
619 super.onMouseUp(mouse);
620 }
621
622 /**
623 * Handle mouse motion events.
624 *
625 * @param mouse mouse motion event
626 */
627 @Override
628 public void onMouseMotion(final TMouseEvent mouse) {
629 if (inWindowMove || inWindowResize) {
630 // TWindow needs to deal with this.
631 super.onMouseMotion(mouse);
632 return;
633 }
634
635 if (mouseOnEmulator(mouse)) {
636 synchronized (emulator) {
637 mouse.setX(mouse.getX() - 1);
638 mouse.setY(mouse.getY() - 1);
639 emulator.mouse(mouse);
640 readEmulatorState();
641 return;
642 }
643 }
644
645 // Emulator didn't consume it, pass it on
646 super.onMouseMotion(mouse);
647 }
648
649 }