Add 'src/jexer/' from commit 'cf01c92f5809a0732409e280fb0f32f27393618d'
[fanfix.git] / src / jexer / TTerminalWidget.java
1 /*
2 * Jexer - Java Text User Interface
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (C) 2019 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.awt.Font;
32 import java.awt.FontMetrics;
33 import java.awt.Graphics2D;
34 import java.awt.image.BufferedImage;
35
36 import java.io.InputStream;
37 import java.io.IOException;
38 import java.lang.reflect.Field;
39 import java.text.MessageFormat;
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.ResourceBundle;
45
46 import jexer.backend.ECMA48Terminal;
47 import jexer.backend.GlyphMaker;
48 import jexer.backend.MultiScreen;
49 import jexer.backend.SwingTerminal;
50 import jexer.bits.Cell;
51 import jexer.bits.CellAttributes;
52 import jexer.event.TKeypressEvent;
53 import jexer.event.TMenuEvent;
54 import jexer.event.TMouseEvent;
55 import jexer.event.TResizeEvent;
56 import jexer.menu.TMenu;
57 import jexer.tterminal.DisplayLine;
58 import jexer.tterminal.DisplayListener;
59 import jexer.tterminal.ECMA48;
60 import static jexer.TKeypress.*;
61
62 /**
63 * TTerminalWidget exposes a ECMA-48 / ANSI X3.64 style terminal in a widget.
64 */
65 public class TTerminalWidget extends TScrollableWidget
66 implements DisplayListener {
67
68 /**
69 * Translated strings.
70 */
71 private static final ResourceBundle i18n = ResourceBundle.getBundle(TTerminalWidget.class.getName());
72
73 // ------------------------------------------------------------------------
74 // Variables --------------------------------------------------------------
75 // ------------------------------------------------------------------------
76
77 /**
78 * The emulator.
79 */
80 private ECMA48 emulator;
81
82 /**
83 * The Process created by the shell spawning constructor.
84 */
85 private Process shell;
86
87 /**
88 * If true, we are using the ptypipe utility to support dynamic window
89 * resizing. ptypipe is available at
90 * https://gitlab.com/klamonte/ptypipe .
91 */
92 private boolean ptypipe = false;
93
94 /**
95 * Double-height font.
96 */
97 private GlyphMaker doubleFont;
98
99 /**
100 * Last text width value.
101 */
102 private int lastTextWidth = -1;
103
104 /**
105 * Last text height value.
106 */
107 private int lastTextHeight = -1;
108
109 /**
110 * The blink state, used only by ECMA48 backend and when double-width
111 * chars must be drawn.
112 */
113 private boolean blinkState = true;
114
115 /**
116 * Timer flag, used only by ECMA48 backend and when double-width chars
117 * must be drawn.
118 */
119 private boolean haveTimer = false;
120
121 /**
122 * The last seen visible display.
123 */
124 private List<DisplayLine> display;
125
126 /**
127 * If true, the display has changed and needs updating.
128 */
129 private volatile boolean dirty = true;
130
131 /**
132 * Time that the display was last updated.
133 */
134 private long lastUpdateTime = 0;
135
136 /**
137 * If true, hide the mouse after typing a keystroke.
138 */
139 private boolean hideMouseWhenTyping = true;
140
141 /**
142 * If true, the mouse should not be displayed because a keystroke was
143 * typed.
144 */
145 private boolean typingHidMouse = false;
146
147 /**
148 * The return value from the emulator.
149 */
150 private int exitValue = -1;
151
152 /**
153 * Title to expose to a window.
154 */
155 private String title = "";
156
157 /**
158 * Action to perform when the terminal exits.
159 */
160 private TAction closeAction = null;
161
162 // ------------------------------------------------------------------------
163 // Constructors -----------------------------------------------------------
164 // ------------------------------------------------------------------------
165
166 /**
167 * Public constructor spawns a custom command line.
168 *
169 * @param parent parent widget
170 * @param x column relative to parent
171 * @param y row relative to parent
172 * @param commandLine the command line to execute
173 */
174 public TTerminalWidget(final TWidget parent, final int x, final int y,
175 final String commandLine) {
176
177 this(parent, x, y, commandLine.split("\\s+"));
178 }
179
180 /**
181 * Public constructor spawns a custom command line.
182 *
183 * @param parent parent widget
184 * @param x column relative to parent
185 * @param y row relative to parent
186 * @param command the command line to execute
187 */
188 public TTerminalWidget(final TWidget parent, final int x, final int y,
189 final String [] command) {
190
191 this(parent, x, y, command, null);
192 }
193
194 /**
195 * Public constructor spawns a custom command line.
196 *
197 * @param parent parent widget
198 * @param x column relative to parent
199 * @param y row relative to parent
200 * @param command the command line to execute
201 * @param closeAction action to perform when the shell sxits
202 */
203 public TTerminalWidget(final TWidget parent, final int x, final int y,
204 final String [] command, final TAction closeAction) {
205
206 this(parent, x, y, 80, 24, command, closeAction);
207 }
208
209 /**
210 * Public constructor spawns a custom command line.
211 *
212 * @param parent parent widget
213 * @param x column relative to parent
214 * @param y row relative to parent
215 * @param width width of widget
216 * @param height height of widget
217 * @param command the command line to execute
218 * @param closeAction action to perform when the shell sxits
219 */
220 public TTerminalWidget(final TWidget parent, final int x, final int y,
221 final int width, final int height, final String [] command,
222 final TAction closeAction) {
223
224 super(parent, x, y, width, height);
225
226 this.closeAction = closeAction;
227
228 String [] fullCommand;
229
230 // Spawn a shell and pass its I/O to the other constructor.
231 if ((System.getProperty("jexer.TTerminal.ptypipe") != null)
232 && (System.getProperty("jexer.TTerminal.ptypipe").
233 equals("true"))
234 ) {
235 ptypipe = true;
236 fullCommand = new String[command.length + 1];
237 fullCommand[0] = "ptypipe";
238 System.arraycopy(command, 0, fullCommand, 1, command.length);
239 } else if (System.getProperty("os.name").startsWith("Windows")) {
240 fullCommand = new String[3];
241 fullCommand[0] = "cmd";
242 fullCommand[1] = "/c";
243 fullCommand[2] = stringArrayToString(command);
244 } else if (System.getProperty("os.name").startsWith("Mac")) {
245 fullCommand = new String[6];
246 fullCommand[0] = "script";
247 fullCommand[1] = "-q";
248 fullCommand[2] = "-F";
249 fullCommand[3] = "/dev/null";
250 fullCommand[4] = "-c";
251 fullCommand[5] = stringArrayToString(command);
252 } else {
253 // Default: behave like Linux
254 fullCommand = new String[5];
255 fullCommand[0] = "script";
256 fullCommand[1] = "-fqe";
257 fullCommand[2] = "/dev/null";
258 fullCommand[3] = "-c";
259 fullCommand[4] = stringArrayToString(command);
260 }
261 spawnShell(fullCommand);
262 }
263
264 /**
265 * Public constructor spawns a shell.
266 *
267 * @param parent parent widget
268 * @param x column relative to parent
269 * @param y row relative to parent
270 */
271 public TTerminalWidget(final TWidget parent, final int x, final int y) {
272 this(parent, x, y, (TAction) null);
273 }
274
275 /**
276 * Public constructor spawns a shell.
277 *
278 * @param parent parent widget
279 * @param x column relative to parent
280 * @param y row relative to parent
281 * @param closeAction action to perform when the shell sxits
282 */
283 public TTerminalWidget(final TWidget parent, final int x, final int y,
284 final TAction closeAction) {
285
286 this(parent, x, y, 80, 24, closeAction);
287 }
288
289 /**
290 * Public constructor spawns a shell.
291 *
292 * @param parent parent widget
293 * @param x column relative to parent
294 * @param y row relative to parent
295 * @param width width of widget
296 * @param height height of widget
297 * @param closeAction action to perform when the shell sxits
298 */
299 public TTerminalWidget(final TWidget parent, final int x, final int y,
300 final int width, final int height, final TAction closeAction) {
301
302 super(parent, x, y, width, height);
303
304 this.closeAction = closeAction;
305
306 if (System.getProperty("jexer.TTerminal.shell") != null) {
307 String shell = System.getProperty("jexer.TTerminal.shell");
308 if (shell.trim().startsWith("ptypipe")) {
309 ptypipe = true;
310 }
311 spawnShell(shell.split("\\s+"));
312 return;
313 }
314
315 String cmdShellWindows = "cmd.exe";
316
317 // You cannot run a login shell in a bare Process interactively, due
318 // to libc's behavior of buffering when stdin/stdout aren't a tty.
319 // Use 'script' instead to run a shell in a pty. And because BSD and
320 // GNU differ on the '-f' vs '-F' flags, we need two different
321 // commands. Lovely.
322 String cmdShellGNU = "script -fqe /dev/null";
323 String cmdShellBSD = "script -q -F /dev/null";
324
325 // ptypipe is another solution that permits dynamic window resizing.
326 String cmdShellPtypipe = "ptypipe /bin/bash --login";
327
328 // Spawn a shell and pass its I/O to the other constructor.
329 if ((System.getProperty("jexer.TTerminal.ptypipe") != null)
330 && (System.getProperty("jexer.TTerminal.ptypipe").
331 equals("true"))
332 ) {
333 ptypipe = true;
334 spawnShell(cmdShellPtypipe.split("\\s+"));
335 } else if (System.getProperty("os.name").startsWith("Windows")) {
336 spawnShell(cmdShellWindows.split("\\s+"));
337 } else if (System.getProperty("os.name").startsWith("Mac")) {
338 spawnShell(cmdShellBSD.split("\\s+"));
339 } else if (System.getProperty("os.name").startsWith("Linux")) {
340 spawnShell(cmdShellGNU.split("\\s+"));
341 } else {
342 // When all else fails, assume GNU.
343 spawnShell(cmdShellGNU.split("\\s+"));
344 }
345 }
346
347 // ------------------------------------------------------------------------
348 // Event handlers ---------------------------------------------------------
349 // ------------------------------------------------------------------------
350
351 /**
352 * Handle window/screen resize events.
353 *
354 * @param resize resize event
355 */
356 @Override
357 public void onResize(final TResizeEvent resize) {
358 // Let TWidget set my size.
359 super.onResize(resize);
360
361 if (emulator == null) {
362 return;
363 }
364
365 // Synchronize against the emulator so we don't stomp on its reader
366 // thread.
367 synchronized (emulator) {
368
369 if (resize.getType() == TResizeEvent.Type.WIDGET) {
370 // Resize the scroll bars
371 reflowData();
372 placeScrollbars();
373
374 // Get out of scrollback
375 setVerticalValue(0);
376
377 if (ptypipe) {
378 emulator.setWidth(getWidth());
379 emulator.setHeight(getHeight());
380
381 emulator.writeRemote("\033[8;" + getHeight() + ";" +
382 getWidth() + "t");
383 }
384
385 // Pass the correct text cell width/height to the emulator
386 if (getScreen() != null) {
387 emulator.setTextWidth(getScreen().getTextWidth());
388 emulator.setTextHeight(getScreen().getTextHeight());
389 }
390 }
391 return;
392
393 } // synchronized (emulator)
394 }
395
396 /**
397 * Handle keystrokes.
398 *
399 * @param keypress keystroke event
400 */
401 @Override
402 public void onKeypress(final TKeypressEvent keypress) {
403 if (hideMouseWhenTyping) {
404 typingHidMouse = true;
405 }
406
407 // Scrollback up/down
408 if (keypress.equals(kbShiftPgUp)
409 || keypress.equals(kbCtrlPgUp)
410 || keypress.equals(kbAltPgUp)
411 ) {
412 bigVerticalDecrement();
413 dirty = true;
414 return;
415 }
416 if (keypress.equals(kbShiftPgDn)
417 || keypress.equals(kbCtrlPgDn)
418 || keypress.equals(kbAltPgDn)
419 ) {
420 bigVerticalIncrement();
421 dirty = true;
422 return;
423 }
424
425 if ((emulator != null) && (emulator.isReading())) {
426 // Get out of scrollback
427 setVerticalValue(0);
428 emulator.addUserEvent(keypress);
429
430 // UGLY HACK TIME! cmd.exe needs CRLF, not just CR, so if
431 // this is kBEnter then also send kbCtrlJ.
432 if (keypress.equals(kbEnter)) {
433 if (System.getProperty("os.name").startsWith("Windows")
434 && (System.getProperty("jexer.TTerminal.cmdHack",
435 "true").equals("true"))
436 ) {
437 emulator.addUserEvent(new TKeypressEvent(kbCtrlJ));
438 }
439 }
440
441 readEmulatorState();
442 return;
443 }
444
445 // Process is closed, honor "normal" TUI keystrokes
446 super.onKeypress(keypress);
447 }
448
449 /**
450 * Handle mouse press events.
451 *
452 * @param mouse mouse button press event
453 */
454 @Override
455 public void onMouseDown(final TMouseEvent mouse) {
456 if (hideMouseWhenTyping) {
457 typingHidMouse = false;
458 }
459
460 if (emulator != null) {
461 // If the emulator is tracking mouse buttons, it needs to see
462 // wheel events.
463 if (emulator.getMouseProtocol() == ECMA48.MouseProtocol.OFF) {
464 if (mouse.isMouseWheelUp()) {
465 verticalDecrement();
466 dirty = true;
467 return;
468 }
469 if (mouse.isMouseWheelDown()) {
470 verticalIncrement();
471 dirty = true;
472 return;
473 }
474 }
475 if (mouseOnEmulator(mouse)) {
476 emulator.addUserEvent(mouse);
477 readEmulatorState();
478 return;
479 }
480 }
481
482 // Emulator didn't consume it, pass it on
483 super.onMouseDown(mouse);
484 }
485
486 /**
487 * Handle mouse release events.
488 *
489 * @param mouse mouse button release event
490 */
491 @Override
492 public void onMouseUp(final TMouseEvent mouse) {
493 if (hideMouseWhenTyping) {
494 typingHidMouse = false;
495 }
496
497 if ((emulator != null) && (mouseOnEmulator(mouse))) {
498 emulator.addUserEvent(mouse);
499 readEmulatorState();
500 return;
501 }
502
503 // Emulator didn't consume it, pass it on
504 super.onMouseUp(mouse);
505 }
506
507 /**
508 * Handle mouse motion events.
509 *
510 * @param mouse mouse motion event
511 */
512 @Override
513 public void onMouseMotion(final TMouseEvent mouse) {
514 if (hideMouseWhenTyping) {
515 typingHidMouse = false;
516 }
517
518 if ((emulator != null) && (mouseOnEmulator(mouse))) {
519 emulator.addUserEvent(mouse);
520 readEmulatorState();
521 return;
522 }
523
524 // Emulator didn't consume it, pass it on
525 super.onMouseMotion(mouse);
526 }
527
528 // ------------------------------------------------------------------------
529 // TScrollableWidget ------------------------------------------------------
530 // ------------------------------------------------------------------------
531
532 /**
533 * Draw the display buffer.
534 */
535 @Override
536 public void draw() {
537 if (emulator == null) {
538 return;
539 }
540
541 int width = getDisplayWidth();
542
543 boolean syncEmulator = false;
544 if ((System.currentTimeMillis() - lastUpdateTime >= 20)
545 && (dirty == true)
546 ) {
547 // Too much time has passed, draw it all.
548 syncEmulator = true;
549 } else if (emulator.isReading() && (dirty == false)) {
550 // Wait until the emulator has brought more data in.
551 syncEmulator = false;
552 } else if (!emulator.isReading() && (dirty == true)) {
553 // The emulator won't receive more data, update the display.
554 syncEmulator = true;
555 }
556
557 if ((syncEmulator == true)
558 || (display == null)
559 ) {
560 // We want to minimize the amount of time we have the emulator
561 // locked. Grab a copy of its display.
562 synchronized (emulator) {
563 // Update the scroll bars
564 reflowData();
565
566 if (!isDrawable()) {
567 // We lost the connection, onShellExit() called an action
568 // that ultimately removed this widget from the UI
569 // hierarchy, so no one cares if we update the display.
570 // Bail out.
571 return;
572 }
573
574 if ((display == null) || emulator.isReading()) {
575 display = emulator.getVisibleDisplay(getHeight(),
576 -getVerticalValue());
577 assert (display.size() == getHeight());
578 }
579 width = emulator.getWidth();
580 }
581 dirty = false;
582 }
583
584 // Now draw the emulator screen
585 int row = 0;
586 for (DisplayLine line: display) {
587 int widthMax = width;
588 if (line.isDoubleWidth()) {
589 widthMax /= 2;
590 }
591 if (widthMax > getWidth()) {
592 widthMax = getWidth();
593 }
594 for (int i = 0; i < widthMax; i++) {
595 Cell ch = line.charAt(i);
596
597 if (ch.isImage()) {
598 putCharXY(i, row, ch);
599 continue;
600 }
601
602 Cell newCell = new Cell(ch);
603 boolean reverse = line.isReverseColor() ^ ch.isReverse();
604 newCell.setReverse(false);
605 if (reverse) {
606 if (ch.getForeColorRGB() < 0) {
607 newCell.setBackColor(ch.getForeColor());
608 newCell.setBackColorRGB(-1);
609 } else {
610 newCell.setBackColorRGB(ch.getForeColorRGB());
611 }
612 if (ch.getBackColorRGB() < 0) {
613 newCell.setForeColor(ch.getBackColor());
614 newCell.setForeColorRGB(-1);
615 } else {
616 newCell.setForeColorRGB(ch.getBackColorRGB());
617 }
618 }
619 if (line.isDoubleWidth()) {
620 putDoubleWidthCharXY(line, (i * 2), row, newCell);
621 } else {
622 putCharXY(i, row, newCell);
623 }
624 }
625 row++;
626 }
627 }
628
629 /**
630 * Set current value of the vertical scroll.
631 *
632 * @param value the new scroll value
633 */
634 @Override
635 public void setVerticalValue(final int value) {
636 super.setVerticalValue(value);
637 dirty = true;
638 }
639
640 /**
641 * Perform a small step change up.
642 */
643 @Override
644 public void verticalDecrement() {
645 super.verticalDecrement();
646 dirty = true;
647 }
648
649 /**
650 * Perform a small step change down.
651 */
652 @Override
653 public void verticalIncrement() {
654 super.verticalIncrement();
655 dirty = true;
656 }
657
658 /**
659 * Perform a big step change up.
660 */
661 public void bigVerticalDecrement() {
662 super.bigVerticalDecrement();
663 dirty = true;
664 }
665
666 /**
667 * Perform a big step change down.
668 */
669 public void bigVerticalIncrement() {
670 super.bigVerticalIncrement();
671 dirty = true;
672 }
673
674 /**
675 * Go to the top edge of the vertical scroller.
676 */
677 public void toTop() {
678 super.toTop();
679 dirty = true;
680 }
681
682 /**
683 * Go to the bottom edge of the vertical scroller.
684 */
685 public void toBottom() {
686 super.toBottom();
687 dirty = true;
688 }
689
690 /**
691 * Handle widget close.
692 */
693 @Override
694 public void close() {
695 if (emulator != null) {
696 emulator.close();
697 }
698 if (shell != null) {
699 terminateShellChildProcess();
700 shell.destroy();
701 shell = null;
702 }
703 }
704
705 /**
706 * Resize scrollbars for a new width/height.
707 */
708 @Override
709 public void reflowData() {
710 if (emulator == null) {
711 return;
712 }
713
714 // Synchronize against the emulator so we don't stomp on its reader
715 // thread.
716 synchronized (emulator) {
717
718 // Pull cursor information
719 readEmulatorState();
720
721 // Vertical scrollbar
722 setTopValue(getHeight()
723 - (emulator.getScrollbackBuffer().size()
724 + emulator.getDisplayBuffer().size()));
725 setVerticalBigChange(getHeight());
726
727 } // synchronized (emulator)
728 }
729
730 // ------------------------------------------------------------------------
731 // TTerminalWidget --------------------------------------------------------
732 // ------------------------------------------------------------------------
733
734 /**
735 * Get the desired window title.
736 *
737 * @return the title
738 */
739 public String getTitle() {
740 return title;
741 }
742
743 /**
744 * Returns true if this widget does not want the application-wide mouse
745 * cursor drawn over it.
746 *
747 * @return true if this widget does not want the application-wide mouse
748 * cursor drawn over it
749 */
750 public boolean hasHiddenMouse() {
751 if (emulator == null) {
752 return false;
753 }
754 return (emulator.hasHiddenMousePointer() || typingHidMouse);
755 }
756
757 /**
758 * See if the terminal is still running.
759 *
760 * @return if true, we are still connected to / reading from the remote
761 * side
762 */
763 public boolean isReading() {
764 if (emulator == null) {
765 return false;
766 }
767 return emulator.isReading();
768 }
769
770 /**
771 * Convert a string array to a whitespace-separated string.
772 *
773 * @param array the string array
774 * @return a single string
775 */
776 private String stringArrayToString(final String [] array) {
777 StringBuilder sb = new StringBuilder(array[0].length());
778 for (int i = 0; i < array.length; i++) {
779 sb.append(array[i]);
780 if (i < array.length - 1) {
781 sb.append(' ');
782 }
783 }
784 return sb.toString();
785 }
786
787 /**
788 * Spawn the shell.
789 *
790 * @param command the command line to execute
791 */
792 private void spawnShell(final String [] command) {
793
794 /*
795 System.err.printf("spawnShell(): '%s'\n",
796 stringArrayToString(command));
797 */
798
799 // We will have vScroller for its data fields and mouse event
800 // handling, but do not want to draw it.
801 vScroller = new TVScroller(null, getWidth(), 0, getHeight());
802 vScroller.setVisible(false);
803 setBottomValue(0);
804
805 title = i18n.getString("windowTitle");
806
807 // Assume XTERM
808 ECMA48.DeviceType deviceType = ECMA48.DeviceType.XTERM;
809
810 try {
811 ProcessBuilder pb = new ProcessBuilder(command);
812 Map<String, String> env = pb.environment();
813 env.put("TERM", ECMA48.deviceTypeTerm(deviceType));
814 env.put("LANG", ECMA48.deviceTypeLang(deviceType, "en"));
815 env.put("COLUMNS", "80");
816 env.put("LINES", "24");
817 pb.redirectErrorStream(true);
818 shell = pb.start();
819 emulator = new ECMA48(deviceType, shell.getInputStream(),
820 shell.getOutputStream(), this);
821 } catch (IOException e) {
822 messageBox(i18n.getString("errorLaunchingShellTitle"),
823 MessageFormat.format(i18n.getString("errorLaunchingShellText"),
824 e.getMessage()));
825 }
826
827 // Setup the scroll bars
828 onResize(new TResizeEvent(TResizeEvent.Type.WIDGET, getWidth(),
829 getHeight()));
830
831 // Hide mouse when typing option
832 if (System.getProperty("jexer.TTerminal.hideMouseWhenTyping",
833 "true").equals("false")) {
834
835 hideMouseWhenTyping = false;
836 }
837 }
838
839 /**
840 * Terminate the child of the 'script' process used on POSIX. This may
841 * or may not work.
842 */
843 private void terminateShellChildProcess() {
844 int pid = -1;
845 if (shell.getClass().getName().equals("java.lang.UNIXProcess")) {
846 /* get the PID on unix/linux systems */
847 try {
848 Field field = shell.getClass().getDeclaredField("pid");
849 field.setAccessible(true);
850 pid = field.getInt(shell);
851 } catch (Throwable e) {
852 // SQUASH, this didn't work. Just bail out quietly.
853 return;
854 }
855 }
856 if (pid != -1) {
857 // shell.destroy() works successfully at killing this side of
858 // 'script'. But we need to make sure the other side (child
859 // process) is also killed.
860 String [] cmdKillIt = {
861 "pkill", "-P", Integer.toString(pid)
862 };
863 try {
864 Runtime.getRuntime().exec(cmdKillIt);
865 } catch (Throwable e) {
866 // SQUASH, this didn't work. Just bail out quietly.
867 return;
868 }
869 }
870 }
871
872 /**
873 * Hook for subclasses to be notified of the shell termination.
874 */
875 public void onShellExit() {
876 TApplication app = getApplication();
877 if (app != null) {
878 if (closeAction != null) {
879 // We have to put this action inside invokeLater() because it
880 // could be executed during draw() when syncing with ECMA48.
881 app.invokeLater(new Runnable() {
882 public void run() {
883 closeAction.DO(TTerminalWidget.this);
884 }
885 });
886 }
887 if (getApplication() != null) {
888 getApplication().postEvent(new TMenuEvent(
889 TMenu.MID_REPAINT));
890 }
891 }
892 }
893
894 /**
895 * Copy out variables from the emulator that TTerminal has to expose on
896 * screen.
897 */
898 private void readEmulatorState() {
899 if (emulator == null) {
900 return;
901 }
902
903 // Synchronize against the emulator so we don't stomp on its reader
904 // thread.
905 synchronized (emulator) {
906
907 setCursorX(emulator.getCursorX());
908 setCursorY(emulator.getCursorY()
909 + (getHeight() - emulator.getHeight())
910 - getVerticalValue());
911 setCursorVisible(emulator.isCursorVisible());
912 if (getCursorX() > getWidth()) {
913 setCursorVisible(false);
914 }
915 if ((getCursorY() >= getHeight()) || (getCursorY() < 0)) {
916 setCursorVisible(false);
917 }
918 if (emulator.getScreenTitle().length() > 0) {
919 // Only update the title if the shell is still alive
920 if (shell != null) {
921 title = emulator.getScreenTitle();
922 }
923 }
924
925 // Check to see if the shell has died.
926 if (!emulator.isReading() && (shell != null)) {
927 try {
928 int rc = shell.exitValue();
929 // The emulator exited on its own, all is fine
930 title = MessageFormat.format(i18n.
931 getString("windowTitleCompleted"), title, rc);
932 exitValue = rc;
933 shell = null;
934 emulator.close();
935 onShellExit();
936 } catch (IllegalThreadStateException e) {
937 // The emulator thread has exited, but the shell Process
938 // hasn't figured that out yet. Do nothing, we will see
939 // this in a future tick.
940 }
941 } else if (emulator.isReading() && (shell != null)) {
942 // The shell might be dead, let's check
943 try {
944 int rc = shell.exitValue();
945 // If we got here, the shell died.
946 title = MessageFormat.format(i18n.
947 getString("windowTitleCompleted"), title, rc);
948 exitValue = rc;
949 shell = null;
950 emulator.close();
951 onShellExit();
952 } catch (IllegalThreadStateException e) {
953 // The shell is still running, do nothing.
954 }
955 }
956
957 } // synchronized (emulator)
958 }
959
960 /**
961 * Check if a mouse press/release/motion event coordinate is over the
962 * emulator.
963 *
964 * @param mouse a mouse-based event
965 * @return whether or not the mouse is on the emulator
966 */
967 private boolean mouseOnEmulator(final TMouseEvent mouse) {
968 if (emulator == null) {
969 return false;
970 }
971
972 if (!emulator.isReading()) {
973 return false;
974 }
975
976 if ((mouse.getX() >= 0)
977 && (mouse.getX() < getWidth() - 1)
978 && (mouse.getY() >= 0)
979 && (mouse.getY() < getHeight())
980 ) {
981 return true;
982 }
983 return false;
984 }
985
986 /**
987 * Draw glyphs for a double-width or double-height VT100 cell to two
988 * screen cells.
989 *
990 * @param line the line this VT100 cell is in
991 * @param x the X position to draw the left half to
992 * @param y the Y position to draw to
993 * @param cell the cell to draw
994 */
995 private void putDoubleWidthCharXY(final DisplayLine line, final int x,
996 final int y, final Cell cell) {
997
998 int textWidth = getScreen().getTextWidth();
999 int textHeight = getScreen().getTextHeight();
1000 boolean cursorBlinkVisible = true;
1001
1002 if (getScreen() instanceof SwingTerminal) {
1003 SwingTerminal terminal = (SwingTerminal) getScreen();
1004 cursorBlinkVisible = terminal.getCursorBlinkVisible();
1005 } else if (getScreen() instanceof ECMA48Terminal) {
1006 ECMA48Terminal terminal = (ECMA48Terminal) getScreen();
1007
1008 if (!terminal.hasSixel()) {
1009 // The backend does not have sixel support, draw this as text
1010 // and bail out.
1011 putCharXY(x, y, cell);
1012 putCharXY(x + 1, y, ' ', cell);
1013 return;
1014 }
1015 cursorBlinkVisible = blinkState;
1016 } else {
1017 // We don't know how to dray glyphs to this screen, draw them as
1018 // text and bail out.
1019 putCharXY(x, y, cell);
1020 putCharXY(x + 1, y, ' ', cell);
1021 return;
1022 }
1023
1024 if ((textWidth != lastTextWidth) || (textHeight != lastTextHeight)) {
1025 // Screen size has changed, reset the font.
1026 setupFont(textHeight);
1027 lastTextWidth = textWidth;
1028 lastTextHeight = textHeight;
1029 }
1030 assert (doubleFont != null);
1031
1032 BufferedImage image;
1033 if (line.getDoubleHeight() == 1) {
1034 // Double-height top half: don't draw the underline.
1035 Cell newCell = new Cell(cell);
1036 newCell.setUnderline(false);
1037 image = doubleFont.getImage(newCell, textWidth * 2, textHeight * 2,
1038 cursorBlinkVisible);
1039 } else {
1040 image = doubleFont.getImage(cell, textWidth * 2, textHeight * 2,
1041 cursorBlinkVisible);
1042 }
1043
1044 // Now that we have the double-wide glyph drawn, copy the right
1045 // pieces of it to the cells.
1046 Cell left = new Cell(cell);
1047 Cell right = new Cell(cell);
1048 right.setChar(' ');
1049 BufferedImage leftImage = null;
1050 BufferedImage rightImage = null;
1051 /*
1052 System.err.println("image " + image + " textWidth " + textWidth +
1053 " textHeight " + textHeight);
1054 */
1055
1056 switch (line.getDoubleHeight()) {
1057 case 1:
1058 // Top half double height
1059 leftImage = image.getSubimage(0, 0, textWidth, textHeight);
1060 rightImage = image.getSubimage(textWidth, 0, textWidth, textHeight);
1061 break;
1062 case 2:
1063 // Bottom half double height
1064 leftImage = image.getSubimage(0, textHeight, textWidth, textHeight);
1065 rightImage = image.getSubimage(textWidth, textHeight,
1066 textWidth, textHeight);
1067 break;
1068 default:
1069 // Either single height double-width, or error fallback
1070 BufferedImage wideImage = new BufferedImage(textWidth * 2,
1071 textHeight, BufferedImage.TYPE_INT_ARGB);
1072 Graphics2D grWide = wideImage.createGraphics();
1073 grWide.drawImage(image, 0, 0, wideImage.getWidth(),
1074 wideImage.getHeight(), null);
1075 grWide.dispose();
1076 leftImage = wideImage.getSubimage(0, 0, textWidth, textHeight);
1077 rightImage = wideImage.getSubimage(textWidth, 0, textWidth,
1078 textHeight);
1079 break;
1080 }
1081 left.setImage(leftImage);
1082 right.setImage(rightImage);
1083 // Since we have image data, ditch the character here. Otherwise, a
1084 // drawBoxShadow() over the terminal window will show the characters
1085 // which looks wrong.
1086 left.setChar(' ');
1087 right.setChar(' ');
1088 putCharXY(x, y, left);
1089 putCharXY(x + 1, y, right);
1090 }
1091
1092 /**
1093 * Set up the double-width font.
1094 *
1095 * @param fontSize the size of font to request for the single-width font.
1096 * The double-width font will be 2x this value.
1097 */
1098 private void setupFont(final int fontSize) {
1099 doubleFont = GlyphMaker.getInstance(fontSize * 2);
1100
1101 // Special case: the ECMA48 backend needs to have a timer to drive
1102 // its blink state.
1103 if (getScreen() instanceof jexer.backend.ECMA48Terminal) {
1104 if (!haveTimer) {
1105 // Blink every 500 millis.
1106 long millis = 500;
1107 getApplication().addTimer(millis, true,
1108 new TAction() {
1109 public void DO() {
1110 blinkState = !blinkState;
1111 getApplication().doRepaint();
1112 }
1113 }
1114 );
1115 haveTimer = true;
1116 }
1117 }
1118 }
1119
1120 // ------------------------------------------------------------------------
1121 // DisplayListener --------------------------------------------------------
1122 // ------------------------------------------------------------------------
1123
1124 /**
1125 * Called by emulator when fresh data has come in.
1126 */
1127 public void displayChanged() {
1128 dirty = true;
1129 getApplication().postEvent(new TMenuEvent(TMenu.MID_REPAINT));
1130 }
1131
1132 /**
1133 * Function to call to obtain the display width.
1134 *
1135 * @return the number of columns in the display
1136 */
1137 public int getDisplayWidth() {
1138 if (ptypipe) {
1139 return getWidth();
1140 }
1141 return 80;
1142 }
1143
1144 /**
1145 * Function to call to obtain the display height.
1146 *
1147 * @return the number of rows in the display
1148 */
1149 public int getDisplayHeight() {
1150 if (ptypipe) {
1151 return getHeight();
1152 }
1153 return 24;
1154 }
1155
1156 }