TTerminalWindow sixel support wip
[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.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.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 // Pass the correct text cell width/height to the emulator
766 int textWidth = 16;
767 int textHeight = 20;
768 if (getScreen() instanceof SwingTerminal) {
769 SwingTerminal terminal = (SwingTerminal) getScreen();
770
771 textWidth = terminal.getTextWidth();
772 textHeight = terminal.getTextHeight();
773 } else if (getScreen() instanceof ECMA48Terminal) {
774 ECMA48Terminal terminal = (ECMA48Terminal) getScreen();
775 textWidth = terminal.getTextWidth();
776 textHeight = terminal.getTextHeight();
777 }
778 emulator.setTextWidth(textWidth);
779 emulator.setTextHeight(textHeight);
780 }
781
782 /**
783 * Terminate the child of the 'script' process used on POSIX. This may
784 * or may not work.
785 */
786 private void terminateShellChildProcess() {
787 int pid = -1;
788 if (shell.getClass().getName().equals("java.lang.UNIXProcess")) {
789 /* get the PID on unix/linux systems */
790 try {
791 Field field = shell.getClass().getDeclaredField("pid");
792 field.setAccessible(true);
793 pid = field.getInt(shell);
794 } catch (Throwable e) {
795 // SQUASH, this didn't work. Just bail out quietly.
796 return;
797 }
798 }
799 if (pid != -1) {
800 // shell.destroy() works successfully at killing this side of
801 // 'script'. But we need to make sure the other side (child
802 // process) is also killed.
803 String [] cmdKillIt = {
804 "pkill", "-P", Integer.toString(pid)
805 };
806 try {
807 Runtime.getRuntime().exec(cmdKillIt);
808 } catch (Throwable e) {
809 // SQUASH, this didn't work. Just bail out quietly.
810 return;
811 }
812 }
813 }
814
815 /**
816 * Called by emulator when fresh data has come in.
817 */
818 public void displayChanged() {
819 getApplication().postEvent(new TMenuEvent(TMenu.MID_REPAINT));
820 }
821
822 /**
823 * Function to call to obtain the display width.
824 *
825 * @return the number of columns in the display
826 */
827 public int getDisplayWidth() {
828 if (ptypipe) {
829 return getWidth() - 2;
830 }
831 return 80;
832 }
833
834 /**
835 * Function to call to obtain the display height.
836 *
837 * @return the number of rows in the display
838 */
839 public int getDisplayHeight() {
840 if (ptypipe) {
841 return getHeight() - 2;
842 }
843 return 24;
844 }
845
846 /**
847 * Hook for subclasses to be notified of the shell termination.
848 */
849 public void onShellExit() {
850 if (closeOnExit) {
851 close();
852 }
853 getApplication().postEvent(new TMenuEvent(TMenu.MID_REPAINT));
854 }
855
856 /**
857 * Copy out variables from the emulator that TTerminal has to expose on
858 * screen.
859 */
860 private void readEmulatorState() {
861 // Synchronize against the emulator so we don't stomp on its reader
862 // thread.
863 synchronized (emulator) {
864 setHiddenMouse(emulator.hasHiddenMousePointer());
865
866 setCursorX(emulator.getCursorX() + 1);
867 setCursorY(emulator.getCursorY() + 1
868 + (getHeight() - 2 - emulator.getHeight())
869 - getVerticalValue());
870 setCursorVisible(emulator.isCursorVisible());
871 if (getCursorX() > getWidth() - 2) {
872 setCursorVisible(false);
873 }
874 if ((getCursorY() > getHeight() - 2) || (getCursorY() < 0)) {
875 setCursorVisible(false);
876 }
877 if (emulator.getScreenTitle().length() > 0) {
878 // Only update the title if the shell is still alive
879 if (shell != null) {
880 setTitle(emulator.getScreenTitle());
881 }
882 }
883
884 // Check to see if the shell has died.
885 if (!emulator.isReading() && (shell != null)) {
886 try {
887 int rc = shell.exitValue();
888 // The emulator exited on its own, all is fine
889 setTitle(MessageFormat.format(i18n.
890 getString("windowTitleCompleted"), getTitle(), rc));
891 shell = null;
892 emulator.close();
893 clearShortcutKeypresses();
894 statusBar.setText(MessageFormat.format(i18n.
895 getString("statusBarCompleted"), rc));
896 onShellExit();
897 } catch (IllegalThreadStateException e) {
898 // The emulator thread has exited, but the shell Process
899 // hasn't figured that out yet. Do nothing, we will see
900 // this in a future tick.
901 }
902 } else if (emulator.isReading() && (shell != null)) {
903 // The shell might be dead, let's check
904 try {
905 int rc = shell.exitValue();
906 // If we got here, the shell died.
907 setTitle(MessageFormat.format(i18n.
908 getString("windowTitleCompleted"), getTitle(), rc));
909 shell = null;
910 emulator.close();
911 clearShortcutKeypresses();
912 statusBar.setText(MessageFormat.format(i18n.
913 getString("statusBarCompleted"), rc));
914 onShellExit();
915 } catch (IllegalThreadStateException e) {
916 // The shell is still running, do nothing.
917 }
918 }
919
920 } // synchronized (emulator)
921 }
922
923 /**
924 * Check if a mouse press/release/motion event coordinate is over the
925 * emulator.
926 *
927 * @param mouse a mouse-based event
928 * @return whether or not the mouse is on the emulator
929 */
930 private boolean mouseOnEmulator(final TMouseEvent mouse) {
931
932 synchronized (emulator) {
933 if (!emulator.isReading()) {
934 return false;
935 }
936 }
937
938 if ((mouse.getAbsoluteX() >= getAbsoluteX() + 1)
939 && (mouse.getAbsoluteX() < getAbsoluteX() + getWidth() - 1)
940 && (mouse.getAbsoluteY() >= getAbsoluteY() + 1)
941 && (mouse.getAbsoluteY() < getAbsoluteY() + getHeight() - 1)
942 ) {
943 return true;
944 }
945 return false;
946 }
947
948 /**
949 * Draw glyphs for a double-width or double-height VT100 cell to two
950 * screen cells.
951 *
952 * @param line the line this VT100 cell is in
953 * @param x the X position to draw the left half to
954 * @param y the Y position to draw to
955 * @param cell the cell to draw
956 */
957 private void putDoubleWidthCharXY(final DisplayLine line, final int x,
958 final int y, final Cell cell) {
959
960 int textWidth = 16;
961 int textHeight = 20;
962 boolean cursorBlinkVisible = true;
963
964 if (getScreen() instanceof SwingTerminal) {
965 SwingTerminal terminal = (SwingTerminal) getScreen();
966
967 textWidth = terminal.getTextWidth();
968 textHeight = terminal.getTextHeight();
969 cursorBlinkVisible = terminal.getCursorBlinkVisible();
970 } else if (getScreen() instanceof ECMA48Terminal) {
971 ECMA48Terminal terminal = (ECMA48Terminal) getScreen();
972
973 if (!terminal.hasSixel()) {
974 // The backend does not have sixel support, draw this as text
975 // and bail out.
976 putCharXY(x, y, cell);
977 putCharXY(x + 1, y, ' ', cell);
978 return;
979 }
980
981 textWidth = terminal.getTextWidth();
982 textHeight = terminal.getTextHeight();
983 cursorBlinkVisible = blinkState;
984 } else {
985 // We don't know how to dray glyphs to this screen, draw them as
986 // text and bail out.
987 putCharXY(x, y, cell);
988 putCharXY(x + 1, y, ' ', cell);
989 return;
990 }
991
992 if ((textWidth != lastTextWidth) || (textHeight != lastTextHeight)) {
993 // Screen size has changed, reset all fonts.
994 setupFonts(textHeight);
995 lastTextWidth = textWidth;
996 lastTextHeight = textHeight;
997 }
998 assert (doubleFont != null);
999
1000 BufferedImage image = null;
1001 if (cell.isBlink() && !cursorBlinkVisible) {
1002 image = glyphCacheBlink.get(cell);
1003 } else {
1004 image = glyphCache.get(cell);
1005 }
1006 if (image == null) {
1007 // Generate glyph and draw it to an image.
1008 image = new BufferedImage(textWidth * 2, textHeight * 2,
1009 BufferedImage.TYPE_INT_ARGB);
1010 Graphics2D gr2 = image.createGraphics();
1011 gr2.setFont(doubleFont);
1012
1013 // Draw the background rectangle, then the foreground character.
1014 if (getScreen() instanceof ECMA48Terminal) {
1015 // BUG: the background color is coming in the same as the
1016 // foreground color. For now, don't draw it.
1017 } else {
1018 gr2.setColor(SwingTerminal.attrToBackgroundColor(cell));
1019 gr2.fillRect(0, 0, image.getWidth(), image.getHeight());
1020 }
1021 if (!cell.isBlink()
1022 || (cell.isBlink() && cursorBlinkVisible)
1023 ) {
1024 gr2.setColor(SwingTerminal.attrToForegroundColor(cell));
1025 char [] chars = new char[1];
1026 chars[0] = cell.getChar();
1027 gr2.drawChars(chars, 0, 1, doubleTextAdjustX,
1028 (textHeight * 2) - doubleMaxDescent + doubleTextAdjustY);
1029
1030 if (cell.isUnderline() && (line.getDoubleHeight() != 1)) {
1031 gr2.fillRect(0, textHeight - 2, textWidth, 2);
1032 }
1033 }
1034 gr2.dispose();
1035
1036 // Now save this generated image, using a new key that will not
1037 // be mutated by invertCell().
1038 Cell key = new Cell();
1039 key.setTo(cell);
1040 if (cell.isBlink() && !cursorBlinkVisible) {
1041 glyphCacheBlink.put(key, image);
1042 } else {
1043 glyphCache.put(key, image);
1044 }
1045 }
1046
1047 // Now that we have the double-wide glyph drawn, copy the right
1048 // pieces of it to the cells.
1049 Cell left = new Cell();
1050 Cell right = new Cell();
1051 left.setTo(cell);
1052 right.setTo(cell);
1053 right.setChar(' ');
1054 BufferedImage leftImage = null;
1055 BufferedImage rightImage = null;
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 putCharXY(x, y, left);
1084 putCharXY(x + 1, y, right);
1085 }
1086
1087 /**
1088 * Set up the single and double-width fonts.
1089 *
1090 * @param fontSize the size of font to request for the single-width font.
1091 * The double-width font will be 2x this value.
1092 */
1093 private void setupFonts(final int fontSize) {
1094 try {
1095 ClassLoader loader = Thread.currentThread().getContextClassLoader();
1096 InputStream in = loader.getResourceAsStream(SwingTerminal.FONTFILE);
1097 Font terminusRoot = Font.createFont(Font.TRUETYPE_FONT, in);
1098 Font terminusDouble = terminusRoot.deriveFont(Font.PLAIN,
1099 fontSize * 2);
1100 doubleFont = terminusDouble;
1101 } catch (java.awt.FontFormatException e) {
1102 new TExceptionDialog(getApplication(), e);
1103 doubleFont = new Font(Font.MONOSPACED, Font.PLAIN, fontSize * 2);
1104 } catch (java.io.IOException e) {
1105 new TExceptionDialog(getApplication(), e);
1106 doubleFont = new Font(Font.MONOSPACED, Font.PLAIN, fontSize * 2);
1107 }
1108
1109 // Get font descent.
1110 BufferedImage image = new BufferedImage(fontSize * 10, fontSize * 10,
1111 BufferedImage.TYPE_INT_ARGB);
1112 Graphics2D gr = image.createGraphics();
1113 gr.setFont(doubleFont);
1114 FontMetrics fm = gr.getFontMetrics();
1115 doubleMaxDescent = fm.getMaxDescent();
1116
1117 gr.dispose();
1118
1119 // (Re)create the glyph caches.
1120 glyphCache = new HashMap<Cell, BufferedImage>();
1121 glyphCacheBlink = new HashMap<Cell, BufferedImage>();
1122
1123 // Special case: the ECMA48 backend needs to have a timer to drive
1124 // its blink state.
1125 if (getScreen() instanceof jexer.backend.ECMA48Terminal) {
1126 // Blink every 500 millis.
1127 long millis = 500;
1128 getApplication().addTimer(millis, true,
1129 new TAction() {
1130 public void DO() {
1131 blinkState = !blinkState;
1132 getApplication().doRepaint();
1133 }
1134 }
1135 );
1136 }
1137
1138 }
1139
1140 }