Add versioned about box, set title
[nikiroo-utils.git] / src / jexer / TTerminalWindow.java
1 /*
2 * Jexer - Java Text User Interface
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (C) 2016 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 TWindow {
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 * Vertical scrollbar.
66 */
67 private TVScroller vScroller;
68
69 /**
70 * Claim the keystrokes the emulator will need.
71 */
72 private void addShortcutKeys() {
73 addShortcutKeypress(kbCtrlA);
74 addShortcutKeypress(kbCtrlB);
75 addShortcutKeypress(kbCtrlC);
76 addShortcutKeypress(kbCtrlD);
77 addShortcutKeypress(kbCtrlE);
78 addShortcutKeypress(kbCtrlF);
79 addShortcutKeypress(kbCtrlG);
80 addShortcutKeypress(kbCtrlH);
81 addShortcutKeypress(kbCtrlU);
82 addShortcutKeypress(kbCtrlJ);
83 addShortcutKeypress(kbCtrlK);
84 addShortcutKeypress(kbCtrlL);
85 addShortcutKeypress(kbCtrlM);
86 addShortcutKeypress(kbCtrlN);
87 addShortcutKeypress(kbCtrlO);
88 addShortcutKeypress(kbCtrlP);
89 addShortcutKeypress(kbCtrlQ);
90 addShortcutKeypress(kbCtrlR);
91 addShortcutKeypress(kbCtrlS);
92 addShortcutKeypress(kbCtrlT);
93 addShortcutKeypress(kbCtrlU);
94 addShortcutKeypress(kbCtrlV);
95 addShortcutKeypress(kbCtrlW);
96 addShortcutKeypress(kbCtrlX);
97 addShortcutKeypress(kbCtrlY);
98 addShortcutKeypress(kbCtrlZ);
99 addShortcutKeypress(kbF1);
100 addShortcutKeypress(kbF2);
101 addShortcutKeypress(kbF3);
102 addShortcutKeypress(kbF4);
103 addShortcutKeypress(kbF5);
104 addShortcutKeypress(kbF6);
105 addShortcutKeypress(kbF7);
106 addShortcutKeypress(kbF8);
107 addShortcutKeypress(kbF9);
108 addShortcutKeypress(kbF10);
109 addShortcutKeypress(kbF11);
110 addShortcutKeypress(kbF12);
111 addShortcutKeypress(kbAltA);
112 addShortcutKeypress(kbAltB);
113 addShortcutKeypress(kbAltC);
114 addShortcutKeypress(kbAltD);
115 addShortcutKeypress(kbAltE);
116 addShortcutKeypress(kbAltF);
117 addShortcutKeypress(kbAltG);
118 addShortcutKeypress(kbAltH);
119 addShortcutKeypress(kbAltU);
120 addShortcutKeypress(kbAltJ);
121 addShortcutKeypress(kbAltK);
122 addShortcutKeypress(kbAltL);
123 addShortcutKeypress(kbAltM);
124 addShortcutKeypress(kbAltN);
125 addShortcutKeypress(kbAltO);
126 addShortcutKeypress(kbAltP);
127 addShortcutKeypress(kbAltQ);
128 addShortcutKeypress(kbAltR);
129 addShortcutKeypress(kbAltS);
130 addShortcutKeypress(kbAltT);
131 addShortcutKeypress(kbAltU);
132 addShortcutKeypress(kbAltV);
133 addShortcutKeypress(kbAltW);
134 addShortcutKeypress(kbAltX);
135 addShortcutKeypress(kbAltY);
136 addShortcutKeypress(kbAltZ);
137 }
138
139 /**
140 * Public constructor spawns a shell.
141 *
142 * @param application TApplication that manages this window
143 * @param x column relative to parent
144 * @param y row relative to parent
145 * @param flags mask of CENTERED, MODAL, or RESIZABLE
146 */
147 public TTerminalWindow(final TApplication application, final int x,
148 final int y, final int flags) {
149
150 super(application, "Terminal", x, y, 80 + 2, 24 + 2, flags);
151
152 // Assume XTERM
153 ECMA48.DeviceType deviceType = ECMA48.DeviceType.XTERM;
154
155 try {
156 String [] cmdShellWindows = {
157 "cmd.exe"
158 };
159
160 // You cannot run a login shell in a bare Process interactively,
161 // due to libc's behavior of buffering when stdin/stdout aren't a
162 // tty. Use 'script' instead to run a shell in a pty. And
163 // because BSD and GNU differ on the '-f' vs '-F' flags, we need
164 // two different commands. Lovely.
165 String [] cmdShellGNU = {
166 "script", "-fqe", "/dev/null"
167 };
168 String [] cmdShellBSD = {
169 "script", "-qe", "-F", "/dev/null"
170 };
171 // Spawn a shell and pass its I/O to the other constructor.
172
173 ProcessBuilder pb;
174 if (System.getProperty("os.name").startsWith("Windows")) {
175 pb = new ProcessBuilder(cmdShellWindows);
176 } else if (System.getProperty("os.name").startsWith("Mac")) {
177 pb = new ProcessBuilder(cmdShellBSD);
178 } else if (System.getProperty("os.name").startsWith("Linux")) {
179 pb = new ProcessBuilder(cmdShellGNU);
180 } else {
181 // When all else fails, assume GNU.
182 pb = new ProcessBuilder(cmdShellGNU);
183 }
184 Map<String, String> env = pb.environment();
185 env.put("TERM", ECMA48.deviceTypeTerm(deviceType));
186 env.put("LANG", ECMA48.deviceTypeLang(deviceType, "en"));
187 env.put("COLUMNS", "80");
188 env.put("LINES", "24");
189 pb.redirectErrorStream(true);
190 shell = pb.start();
191 emulator = new ECMA48(deviceType, shell.getInputStream(),
192 shell.getOutputStream());
193 } catch (IOException e) {
194 e.printStackTrace();
195 }
196
197 // Setup the scroll bars
198 onResize(new TResizeEvent(TResizeEvent.Type.WIDGET, getWidth(),
199 getHeight()));
200
201 // Claim the keystrokes the emulator will need.
202 addShortcutKeys();
203 }
204
205 /**
206 * Terminate the child of the 'script' process used on POSIX. This may
207 * or may not work.
208 */
209 private void terminateShellChildProcess() {
210 int pid = -1;
211 if (shell.getClass().getName().equals("java.lang.UNIXProcess")) {
212 /* get the PID on unix/linux systems */
213 try {
214 Field field = shell.getClass().getDeclaredField("pid");
215 field.setAccessible(true);
216 pid = field.getInt(shell);
217 } catch (Throwable e) {
218 // SQUASH, this didn't work. Just bail out quietly.
219 return;
220 }
221 }
222 if (pid != -1) {
223 // shell.destroy() works successfully at killing this side of
224 // 'script'. But we need to make sure the other side (child
225 // process) is also killed.
226 String [] cmdKillIt = {
227 "pkill", "-P", Integer.toString(pid)
228 };
229 try {
230 Runtime.getRuntime().exec(cmdKillIt);
231 } catch (Throwable e) {
232 // SQUASH, this didn't work. Just bail out quietly.
233 return;
234 }
235 }
236 }
237
238 /**
239 * Public constructor.
240 *
241 * @param application TApplication that manages this window
242 * @param x column relative to parent
243 * @param y row relative to parent
244 * @param flags mask of CENTERED, MODAL, or RESIZABLE
245 * @param input an InputStream connected to the remote side. For type ==
246 * XTERM, input is converted to a Reader with UTF-8 encoding.
247 * @param output an OutputStream connected to the remote user. For type
248 * == XTERM, output is converted to a Writer with UTF-8 encoding.
249 * @throws UnsupportedEncodingException if an exception is thrown when
250 * creating the InputStreamReader
251 */
252 public TTerminalWindow(final TApplication application, final int x,
253 final int y, final int flags, final InputStream input,
254 final OutputStream output) throws UnsupportedEncodingException {
255
256 super(application, "Terminal", x, y, 80 + 2, 24 + 2, flags);
257
258 emulator = new ECMA48(ECMA48.DeviceType.XTERM, input, output);
259
260 // Setup the scroll bars
261 onResize(new TResizeEvent(TResizeEvent.Type.WIDGET, getWidth(),
262 getHeight()));
263
264 // Claim the keystrokes the emulator will need.
265 addShortcutKeys();
266 }
267
268 /**
269 * Draw the display buffer.
270 */
271 @Override
272 public void draw() {
273 // Synchronize against the emulator so we don't stomp on its reader
274 // thread.
275 synchronized (emulator) {
276
277 // Update the scroll bars
278 reflow();
279
280 // Draw the box using my superclass
281 super.draw();
282
283 List<DisplayLine> scrollback = emulator.getScrollbackBuffer();
284 List<DisplayLine> display = emulator.getDisplayBuffer();
285
286 // Put together the visible rows
287 int visibleHeight = getHeight() - 2;
288 int visibleBottom = scrollback.size() + display.size()
289 + vScroller.getValue();
290 assert (visibleBottom >= 0);
291
292 List<DisplayLine> preceedingBlankLines = new LinkedList<DisplayLine>();
293 int visibleTop = visibleBottom - visibleHeight;
294 if (visibleTop < 0) {
295 for (int i = visibleTop; i < 0; i++) {
296 preceedingBlankLines.add(emulator.getBlankDisplayLine());
297 }
298 visibleTop = 0;
299 }
300 assert (visibleTop >= 0);
301
302 List<DisplayLine> displayLines = new LinkedList<DisplayLine>();
303 displayLines.addAll(scrollback);
304 displayLines.addAll(display);
305
306 List<DisplayLine> visibleLines = new LinkedList<DisplayLine>();
307 visibleLines.addAll(preceedingBlankLines);
308 visibleLines.addAll(displayLines.subList(visibleTop,
309 visibleBottom));
310
311 visibleHeight -= visibleLines.size();
312 assert (visibleHeight >= 0);
313
314 // Now draw the emulator screen
315 int row = 1;
316 for (DisplayLine line: visibleLines) {
317 int widthMax = emulator.getWidth();
318 if (line.isDoubleWidth()) {
319 widthMax /= 2;
320 }
321 if (widthMax > getWidth() - 2) {
322 widthMax = getWidth() - 2;
323 }
324 for (int i = 0; i < widthMax; i++) {
325 Cell ch = line.charAt(i);
326 Cell newCell = new Cell();
327 newCell.setTo(ch);
328 boolean reverse = line.isReverseColor() ^ ch.isReverse();
329 newCell.setReverse(false);
330 if (reverse) {
331 newCell.setBackColor(ch.getForeColor());
332 newCell.setForeColor(ch.getBackColor());
333 }
334 if (line.isDoubleWidth()) {
335 getScreen().putCharXY((i * 2) + 1, row, newCell);
336 getScreen().putCharXY((i * 2) + 2, row, ' ', newCell);
337 } else {
338 getScreen().putCharXY(i + 1, row, newCell);
339 }
340 }
341 row++;
342 if (row == getHeight() - 1) {
343 // Don't overwrite the box edge
344 break;
345 }
346 }
347 CellAttributes background = new CellAttributes();
348 // Fill in the blank lines on bottom
349 for (int i = 0; i < visibleHeight; i++) {
350 getScreen().hLineXY(1, i + row, getWidth() - 2, ' ',
351 background);
352 }
353
354 } // synchronized (emulator)
355
356 }
357
358 /**
359 * Handle window close.
360 */
361 @Override public void onClose() {
362 emulator.close();
363 if (shell != null) {
364 terminateShellChildProcess();
365 shell.destroy();
366 shell = null;
367 }
368 }
369
370 /**
371 * Copy out variables from the emulator that TTerminal has to expose on
372 * screen.
373 */
374 private void readEmulatorState() {
375 // Synchronize against the emulator so we don't stomp on its reader
376 // thread.
377 synchronized (emulator) {
378
379 setCursorX(emulator.getCursorX() + 1);
380 setCursorY(emulator.getCursorY() + 1
381 + (getHeight() - 2 - emulator.getHeight()));
382 if (vScroller != null) {
383 setCursorY(getCursorY() - vScroller.getValue());
384 }
385 setCursorVisible(emulator.isCursorVisible());
386 if (getCursorX() > getWidth() - 2) {
387 setCursorVisible(false);
388 }
389 if ((getCursorY() > getHeight() - 2) || (getCursorY() < 0)) {
390 setCursorVisible(false);
391 }
392 if (emulator.getScreenTitle().length() > 0) {
393 // Only update the title if the shell is still alive
394 if (shell != null) {
395 setTitle(emulator.getScreenTitle());
396 }
397 }
398
399 // Check to see if the shell has died.
400 if (!emulator.isReading() && (shell != null)) {
401 try {
402 int rc = shell.exitValue();
403 // The emulator exited on its own, all is fine
404 setTitle(String.format("%s [Completed - %d]",
405 getTitle(), rc));
406 shell = null;
407 emulator.close();
408 clearShortcutKeypresses();
409 } catch (IllegalThreadStateException e) {
410 // The emulator thread has exited, but the shell Process
411 // hasn't figured that out yet. Do nothing, we will see
412 // this in a future tick.
413 }
414 } else if (emulator.isReading() && (shell != null)) {
415 // The shell might be dead, let's check
416 try {
417 int rc = shell.exitValue();
418 // If we got here, the shell died.
419 setTitle(String.format("%s [Completed - %d]",
420 getTitle(), rc));
421 shell = null;
422 emulator.close();
423 clearShortcutKeypresses();
424 } catch (IllegalThreadStateException e) {
425 // The shell is still running, do nothing.
426 }
427 }
428
429 } // synchronized (emulator)
430 }
431
432 /**
433 * Handle window/screen resize events.
434 *
435 * @param resize resize event
436 */
437 @Override
438 public void onResize(final TResizeEvent resize) {
439
440 // Synchronize against the emulator so we don't stomp on its reader
441 // thread.
442 synchronized (emulator) {
443
444 if (resize.getType() == TResizeEvent.Type.WIDGET) {
445 // Resize the scroll bars
446 reflow();
447
448 // Get out of scrollback
449 vScroller.setValue(0);
450 }
451 return;
452
453 } // synchronized (emulator)
454 }
455
456 /**
457 * Resize scrollbars for a new width/height.
458 */
459 private void reflow() {
460
461 // Synchronize against the emulator so we don't stomp on its reader
462 // thread.
463 synchronized (emulator) {
464
465 // Pull cursor information
466 readEmulatorState();
467
468 // Vertical scrollbar
469 if (vScroller == null) {
470 vScroller = new TVScroller(this, getWidth() - 2, 0,
471 getHeight() - 2);
472 vScroller.setBottomValue(0);
473 vScroller.setValue(0);
474 } else {
475 vScroller.setX(getWidth() - 2);
476 vScroller.setHeight(getHeight() - 2);
477 }
478 vScroller.setTopValue(getHeight() - 2
479 - (emulator.getScrollbackBuffer().size()
480 + emulator.getDisplayBuffer().size()));
481 vScroller.setBigChange(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 vScroller.bigDecrement();
525 return;
526 }
527 if (keypress.equals(kbShiftPgDn)
528 || keypress.equals(kbCtrlPgDn)
529 || keypress.equals(kbAltPgDn)
530 ) {
531 vScroller.bigIncrement();
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 vScroller.setValue(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 vScroller.decrement();
575 return;
576 }
577 if (mouse.isMouseWheelDown()) {
578 vScroller.increment();
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 }