Better resizing under ptypipe
[nikiroo-utils.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.IOException;
32 import java.lang.reflect.Field;
33 import java.util.LinkedList;
34 import java.util.List;
35 import java.util.Map;
36
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.*;
46
47 /**
48 * TTerminalWindow exposes a ECMA-48 / ANSI X3.64 style terminal in a window.
49 */
50 public class TTerminalWindow extends TScrollableWindow
51 implements DisplayListener {
52
53 /**
54 * The emulator.
55 */
56 private ECMA48 emulator;
57
58 /**
59 * The Process created by the shell spawning constructor.
60 */
61 private Process shell;
62
63 /**
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 .
67 */
68 private boolean ptypipe = false;
69
70 /**
71 * Claim the keystrokes the emulator will need.
72 */
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);
138 }
139
140 /**
141 * Public constructor spawns a shell.
142 *
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
147 */
148 public TTerminalWindow(final TApplication application, final int x,
149 final int y, final int flags) {
150
151 super(application, "Terminal", x, y, 80 + 2, 24 + 2, flags);
152
153 vScroller = new TVScroller(this, getWidth() - 2, 0, getHeight() - 2);
154 setBottomValue(0);
155
156 // Assume XTERM
157 ECMA48.DeviceType deviceType = ECMA48.DeviceType.XTERM;
158
159 try {
160 String [] cmdShellWindows = {
161 "cmd.exe"
162 };
163
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"
171 };
172 String [] cmdShellBSD = {
173 "script", "-q", "-F", "/dev/null"
174 };
175 String [] cmdShellPtypipe = {
176 "ptypipe", "/bin/bash", "--login"
177 };
178 // Spawn a shell and pass its I/O to the other constructor.
179
180 ProcessBuilder pb;
181 if ((System.getProperty("jexer.TTerminal.ptypipe") != null)
182 && (System.getProperty("jexer.TTerminal.ptypipe").
183 equals("true"))
184 ) {
185 pb = new ProcessBuilder(cmdShellPtypipe);
186 ptypipe = true;
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);
193 } else {
194 // When all else fails, assume GNU.
195 pb = new ProcessBuilder(cmdShellGNU);
196 }
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);
203 shell = pb.start();
204 emulator = new ECMA48(deviceType, shell.getInputStream(),
205 shell.getOutputStream(), this);
206 } catch (IOException e) {
207 messageBox("Error", "Error launching shell: " + e.getMessage());
208 }
209
210 // Setup the scroll bars
211 onResize(new TResizeEvent(TResizeEvent.Type.WIDGET, getWidth(),
212 getHeight()));
213
214 // Claim the keystrokes the emulator will need.
215 addShortcutKeys();
216
217 // Add shortcut text
218 newStatusBar("Terminal session executing...");
219 }
220
221 /**
222 * Terminate the child of the 'script' process used on POSIX. This may
223 * or may not work.
224 */
225 private void terminateShellChildProcess() {
226 int pid = -1;
227 if (shell.getClass().getName().equals("java.lang.UNIXProcess")) {
228 /* get the PID on unix/linux systems */
229 try {
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.
235 return;
236 }
237 }
238 if (pid != -1) {
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)
244 };
245 try {
246 Runtime.getRuntime().exec(cmdKillIt);
247 } catch (Throwable e) {
248 // SQUASH, this didn't work. Just bail out quietly.
249 return;
250 }
251 }
252 }
253
254 /**
255 * Draw the display buffer.
256 */
257 @Override
258 public void draw() {
259 // Synchronize against the emulator so we don't stomp on its reader
260 // thread.
261 synchronized (emulator) {
262
263 // Update the scroll bars
264 reflowData();
265
266 // Draw the box using my superclass
267 super.draw();
268
269 List<DisplayLine> scrollback = emulator.getScrollbackBuffer();
270 List<DisplayLine> display = emulator.getDisplayBuffer();
271
272 // Put together the visible rows
273 int visibleHeight = getHeight() - 2;
274 int visibleBottom = scrollback.size() + display.size()
275 + getVerticalValue();
276 assert (visibleBottom >= 0);
277
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());
283 }
284 visibleTop = 0;
285 }
286 assert (visibleTop >= 0);
287
288 List<DisplayLine> displayLines = new LinkedList<DisplayLine>();
289 displayLines.addAll(scrollback);
290 displayLines.addAll(display);
291
292 List<DisplayLine> visibleLines = new LinkedList<DisplayLine>();
293 visibleLines.addAll(preceedingBlankLines);
294 visibleLines.addAll(displayLines.subList(visibleTop,
295 visibleBottom));
296
297 visibleHeight -= visibleLines.size();
298 assert (visibleHeight >= 0);
299
300 // Now draw the emulator screen
301 int row = 1;
302 for (DisplayLine line: visibleLines) {
303 int widthMax = emulator.getWidth();
304 if (line.isDoubleWidth()) {
305 widthMax /= 2;
306 }
307 if (widthMax > getWidth() - 2) {
308 widthMax = getWidth() - 2;
309 }
310 for (int i = 0; i < widthMax; i++) {
311 Cell ch = line.charAt(i);
312 Cell newCell = new Cell();
313 newCell.setTo(ch);
314 boolean reverse = line.isReverseColor() ^ ch.isReverse();
315 newCell.setReverse(false);
316 if (reverse) {
317 newCell.setBackColor(ch.getForeColor());
318 newCell.setForeColor(ch.getBackColor());
319 }
320 if (line.isDoubleWidth()) {
321 getScreen().putCharXY((i * 2) + 1, row, newCell);
322 getScreen().putCharXY((i * 2) + 2, row, ' ', newCell);
323 } else {
324 getScreen().putCharXY(i + 1, row, newCell);
325 }
326 }
327 row++;
328 if (row == getHeight() - 1) {
329 // Don't overwrite the box edge
330 break;
331 }
332 }
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, ' ',
337 background);
338 }
339
340 } // synchronized (emulator)
341
342 }
343
344 /**
345 * Called by emulator when fresh data has come in.
346 */
347 public void displayChanged() {
348 doRepaint();
349 }
350
351 /**
352 * Function to call to obtain the display width.
353 *
354 * @return the number of columns in the display
355 */
356 public int getDisplayWidth() {
357 return getWidth() - 2;
358 }
359
360 /**
361 * Function to call to obtain the display height.
362 *
363 * @return the number of rows in the display
364 */
365 public int getDisplayHeight() {
366 return getHeight() - 2;
367 }
368
369 /**
370 * Handle window close.
371 */
372 @Override
373 public void onClose() {
374 emulator.close();
375 if (shell != null) {
376 terminateShellChildProcess();
377 shell.destroy();
378 shell = null;
379 }
380 }
381
382 /**
383 * Copy out variables from the emulator that TTerminal has to expose on
384 * screen.
385 */
386 private void readEmulatorState() {
387 // Synchronize against the emulator so we don't stomp on its reader
388 // thread.
389 synchronized (emulator) {
390
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);
398 }
399 if ((getCursorY() > getHeight() - 2) || (getCursorY() < 0)) {
400 setCursorVisible(false);
401 }
402 if (emulator.getScreenTitle().length() > 0) {
403 // Only update the title if the shell is still alive
404 if (shell != null) {
405 setTitle(emulator.getScreenTitle());
406 }
407 }
408
409 // Check to see if the shell has died.
410 if (!emulator.isReading() && (shell != null)) {
411 try {
412 int rc = shell.exitValue();
413 // The emulator exited on its own, all is fine
414 setTitle(String.format("%s [Completed - %d]",
415 getTitle(), rc));
416 shell = null;
417 emulator.close();
418 clearShortcutKeypresses();
419 statusBar.setText("Terminal session completed, exit " +
420 "code " + rc + ".");
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.
425 }
426 } else if (emulator.isReading() && (shell != null)) {
427 // The shell might be dead, let's check
428 try {
429 int rc = shell.exitValue();
430 // If we got here, the shell died.
431 setTitle(String.format("%s [Completed - %d]",
432 getTitle(), rc));
433 shell = null;
434 emulator.close();
435 clearShortcutKeypresses();
436 statusBar.setText("Terminal session completed, exit " +
437 "code " + rc + ".");
438 } catch (IllegalThreadStateException e) {
439 // The shell is still running, do nothing.
440 }
441 }
442
443 } // synchronized (emulator)
444 }
445
446 /**
447 * Handle window/screen resize events.
448 *
449 * @param resize resize event
450 */
451 @Override
452 public void onResize(final TResizeEvent resize) {
453
454 // Synchronize against the emulator so we don't stomp on its reader
455 // thread.
456 synchronized (emulator) {
457
458 if (resize.getType() == TResizeEvent.Type.WIDGET) {
459 // Resize the scroll bars
460 reflowData();
461 placeScrollbars();
462
463 // Get out of scrollback
464 setVerticalValue(0);
465
466 if (ptypipe) {
467 emulator.setWidth(getWidth() - 2);
468 emulator.setHeight(getHeight() - 2);
469
470 emulator.writeRemote("\033[8;" + (getHeight() - 2) + ";" +
471 (getWidth() - 2) + "t");
472 }
473 }
474 return;
475
476 } // synchronized (emulator)
477 }
478
479 /**
480 * Resize scrollbars for a new width/height.
481 */
482 @Override
483 public void reflowData() {
484
485 // Synchronize against the emulator so we don't stomp on its reader
486 // thread.
487 synchronized (emulator) {
488
489 // Pull cursor information
490 readEmulatorState();
491
492 // Vertical scrollbar
493 setTopValue(getHeight() - 2
494 - (emulator.getScrollbackBuffer().size()
495 + emulator.getDisplayBuffer().size()));
496 setVerticalBigChange(getHeight() - 2);
497
498 } // synchronized (emulator)
499 }
500
501 /**
502 * Check if a mouse press/release/motion event coordinate is over the
503 * emulator.
504 *
505 * @param mouse a mouse-based event
506 * @return whether or not the mouse is on the emulator
507 */
508 private final boolean mouseOnEmulator(final TMouseEvent mouse) {
509
510 synchronized (emulator) {
511 if (!emulator.isReading()) {
512 return false;
513 }
514 }
515
516 if ((mouse.getAbsoluteX() >= getAbsoluteX() + 1)
517 && (mouse.getAbsoluteX() < getAbsoluteX() + getWidth() - 1)
518 && (mouse.getAbsoluteY() >= getAbsoluteY() + 1)
519 && (mouse.getAbsoluteY() < getAbsoluteY() + getHeight() - 1)
520 ) {
521 return true;
522 }
523 return false;
524 }
525
526 /**
527 * Handle keystrokes.
528 *
529 * @param keypress keystroke event
530 */
531 @Override
532 public void onKeypress(final TKeypressEvent keypress) {
533
534 // Scrollback up/down
535 if (keypress.equals(kbShiftPgUp)
536 || keypress.equals(kbCtrlPgUp)
537 || keypress.equals(kbAltPgUp)
538 ) {
539 bigVerticalDecrement();
540 return;
541 }
542 if (keypress.equals(kbShiftPgDn)
543 || keypress.equals(kbCtrlPgDn)
544 || keypress.equals(kbAltPgDn)
545 ) {
546 bigVerticalIncrement();
547 return;
548 }
549
550 // Synchronize against the emulator so we don't stomp on its reader
551 // thread.
552 synchronized (emulator) {
553 if (emulator.isReading()) {
554 // Get out of scrollback
555 setVerticalValue(0);
556 emulator.keypress(keypress.getKey());
557
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);
563 }
564 }
565
566 readEmulatorState();
567 return;
568 }
569 }
570
571 // Process is closed, honor "normal" TUI keystrokes
572 super.onKeypress(keypress);
573 }
574
575 /**
576 * Handle mouse press events.
577 *
578 * @param mouse mouse button press event
579 */
580 @Override
581 public void onMouseDown(final TMouseEvent mouse) {
582 if (inWindowMove || inWindowResize) {
583 // TWindow needs to deal with this.
584 super.onMouseDown(mouse);
585 return;
586 }
587
588 if (mouse.isMouseWheelUp()) {
589 verticalDecrement();
590 return;
591 }
592 if (mouse.isMouseWheelDown()) {
593 verticalIncrement();
594 return;
595 }
596 if (mouseOnEmulator(mouse)) {
597 synchronized (emulator) {
598 mouse.setX(mouse.getX() - 1);
599 mouse.setY(mouse.getY() - 1);
600 emulator.mouse(mouse);
601 readEmulatorState();
602 return;
603 }
604 }
605
606 // Emulator didn't consume it, pass it on
607 super.onMouseDown(mouse);
608 }
609
610 /**
611 * Handle mouse release events.
612 *
613 * @param mouse mouse button release event
614 */
615 @Override
616 public void onMouseUp(final TMouseEvent mouse) {
617 if (inWindowMove || inWindowResize) {
618 // TWindow needs to deal with this.
619 super.onMouseUp(mouse);
620 return;
621 }
622
623 if (mouseOnEmulator(mouse)) {
624 synchronized (emulator) {
625 mouse.setX(mouse.getX() - 1);
626 mouse.setY(mouse.getY() - 1);
627 emulator.mouse(mouse);
628 readEmulatorState();
629 return;
630 }
631 }
632
633 // Emulator didn't consume it, pass it on
634 super.onMouseUp(mouse);
635 }
636
637 /**
638 * Handle mouse motion events.
639 *
640 * @param mouse mouse motion event
641 */
642 @Override
643 public void onMouseMotion(final TMouseEvent mouse) {
644 if (inWindowMove || inWindowResize) {
645 // TWindow needs to deal with this.
646 super.onMouseMotion(mouse);
647 return;
648 }
649
650 if (mouseOnEmulator(mouse)) {
651 synchronized (emulator) {
652 mouse.setX(mouse.getX() - 1);
653 mouse.setY(mouse.getY() - 1);
654 emulator.mouse(mouse);
655 readEmulatorState();
656 return;
657 }
658 }
659
660 // Emulator didn't consume it, pass it on
661 super.onMouseMotion(mouse);
662 }
663
664 }