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