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