refactor, sixel performance
[fanfix.git] / src / jexer / TTerminalWindow.java
... / ...
CommitLineData
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 */
29package jexer;
30
31import java.awt.Font;
32import java.awt.FontMetrics;
33import java.awt.Graphics2D;
34import java.awt.image.BufferedImage;
35
36import java.io.InputStream;
37import java.io.IOException;
38import java.lang.reflect.Field;
39import java.text.MessageFormat;
40import java.util.ArrayList;
41import java.util.HashMap;
42import java.util.List;
43import java.util.Map;
44import java.util.ResourceBundle;
45
46import jexer.backend.ECMA48Terminal;
47import jexer.backend.MultiScreen;
48import jexer.backend.SwingTerminal;
49import jexer.bits.Cell;
50import jexer.bits.CellAttributes;
51import jexer.event.TKeypressEvent;
52import jexer.event.TMenuEvent;
53import jexer.event.TMouseEvent;
54import jexer.event.TResizeEvent;
55import jexer.menu.TMenu;
56import jexer.tterminal.DisplayLine;
57import jexer.tterminal.DisplayListener;
58import jexer.tterminal.ECMA48;
59import static jexer.TKeypress.*;
60
61/**
62 * TTerminalWindow exposes a ECMA-48 / ANSI X3.64 style terminal in a window.
63 */
64public 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 the emulator is tracking mouse buttons, it needs to see wheel
554 // events.
555 if (emulator.getMouseProtocol() == ECMA48.MouseProtocol.OFF) {
556 if (mouse.isMouseWheelUp()) {
557 verticalDecrement();
558 return;
559 }
560 if (mouse.isMouseWheelDown()) {
561 verticalIncrement();
562 return;
563 }
564 }
565 if (mouseOnEmulator(mouse)) {
566 synchronized (emulator) {
567 mouse.setX(mouse.getX() - 1);
568 mouse.setY(mouse.getY() - 1);
569 emulator.mouse(mouse);
570 readEmulatorState();
571 return;
572 }
573 }
574
575 // Emulator didn't consume it, pass it on
576 super.onMouseDown(mouse);
577 }
578
579 /**
580 * Handle mouse release events.
581 *
582 * @param mouse mouse button release event
583 */
584 @Override
585 public void onMouseUp(final TMouseEvent mouse) {
586 if (inWindowMove || inWindowResize) {
587 // TWindow needs to deal with this.
588 super.onMouseUp(mouse);
589 return;
590 }
591
592 if (mouseOnEmulator(mouse)) {
593 synchronized (emulator) {
594 mouse.setX(mouse.getX() - 1);
595 mouse.setY(mouse.getY() - 1);
596 emulator.mouse(mouse);
597 readEmulatorState();
598 return;
599 }
600 }
601
602 // Emulator didn't consume it, pass it on
603 super.onMouseUp(mouse);
604 }
605
606 /**
607 * Handle mouse motion events.
608 *
609 * @param mouse mouse motion event
610 */
611 @Override
612 public void onMouseMotion(final TMouseEvent mouse) {
613 if (inWindowMove || inWindowResize) {
614 // TWindow needs to deal with this.
615 super.onMouseMotion(mouse);
616 return;
617 }
618
619 if (mouseOnEmulator(mouse)) {
620 synchronized (emulator) {
621 mouse.setX(mouse.getX() - 1);
622 mouse.setY(mouse.getY() - 1);
623 emulator.mouse(mouse);
624 readEmulatorState();
625 return;
626 }
627 }
628
629 // Emulator didn't consume it, pass it on
630 super.onMouseMotion(mouse);
631 }
632
633 // ------------------------------------------------------------------------
634 // TTerminalWindow --------------------------------------------------------
635 // ------------------------------------------------------------------------
636
637 /**
638 * Claim the keystrokes the emulator will need.
639 */
640 private void addShortcutKeys() {
641 addShortcutKeypress(kbCtrlA);
642 addShortcutKeypress(kbCtrlB);
643 addShortcutKeypress(kbCtrlC);
644 addShortcutKeypress(kbCtrlD);
645 addShortcutKeypress(kbCtrlE);
646 addShortcutKeypress(kbCtrlF);
647 addShortcutKeypress(kbCtrlG);
648 addShortcutKeypress(kbCtrlH);
649 addShortcutKeypress(kbCtrlU);
650 addShortcutKeypress(kbCtrlJ);
651 addShortcutKeypress(kbCtrlK);
652 addShortcutKeypress(kbCtrlL);
653 addShortcutKeypress(kbCtrlM);
654 addShortcutKeypress(kbCtrlN);
655 addShortcutKeypress(kbCtrlO);
656 addShortcutKeypress(kbCtrlP);
657 addShortcutKeypress(kbCtrlQ);
658 addShortcutKeypress(kbCtrlR);
659 addShortcutKeypress(kbCtrlS);
660 addShortcutKeypress(kbCtrlT);
661 addShortcutKeypress(kbCtrlU);
662 addShortcutKeypress(kbCtrlV);
663 addShortcutKeypress(kbCtrlW);
664 addShortcutKeypress(kbCtrlX);
665 addShortcutKeypress(kbCtrlY);
666 addShortcutKeypress(kbCtrlZ);
667 addShortcutKeypress(kbF1);
668 addShortcutKeypress(kbF2);
669 addShortcutKeypress(kbF3);
670 addShortcutKeypress(kbF4);
671 addShortcutKeypress(kbF5);
672 addShortcutKeypress(kbF6);
673 addShortcutKeypress(kbF7);
674 addShortcutKeypress(kbF8);
675 addShortcutKeypress(kbF9);
676 addShortcutKeypress(kbF10);
677 addShortcutKeypress(kbF11);
678 addShortcutKeypress(kbF12);
679 addShortcutKeypress(kbAltA);
680 addShortcutKeypress(kbAltB);
681 addShortcutKeypress(kbAltC);
682 addShortcutKeypress(kbAltD);
683 addShortcutKeypress(kbAltE);
684 addShortcutKeypress(kbAltF);
685 addShortcutKeypress(kbAltG);
686 addShortcutKeypress(kbAltH);
687 addShortcutKeypress(kbAltU);
688 addShortcutKeypress(kbAltJ);
689 addShortcutKeypress(kbAltK);
690 addShortcutKeypress(kbAltL);
691 addShortcutKeypress(kbAltM);
692 addShortcutKeypress(kbAltN);
693 addShortcutKeypress(kbAltO);
694 addShortcutKeypress(kbAltP);
695 addShortcutKeypress(kbAltQ);
696 addShortcutKeypress(kbAltR);
697 addShortcutKeypress(kbAltS);
698 addShortcutKeypress(kbAltT);
699 addShortcutKeypress(kbAltU);
700 addShortcutKeypress(kbAltV);
701 addShortcutKeypress(kbAltW);
702 addShortcutKeypress(kbAltX);
703 addShortcutKeypress(kbAltY);
704 addShortcutKeypress(kbAltZ);
705 }
706
707 /**
708 * Convert a string array to a whitespace-separated string.
709 *
710 * @param array the string array
711 * @return a single string
712 */
713 private String stringArrayToString(final String [] array) {
714 StringBuilder sb = new StringBuilder(array[0].length());
715 for (int i = 0; i < array.length; i++) {
716 sb.append(array[i]);
717 if (i < array.length - 1) {
718 sb.append(' ');
719 }
720 }
721 return sb.toString();
722 }
723
724 /**
725 * Spawn the shell.
726 *
727 * @param command the command line to execute
728 */
729 private void spawnShell(final String [] command) {
730
731 /*
732 System.err.printf("spawnShell(): '%s'\n",
733 stringArrayToString(command));
734 */
735
736 vScroller = new TVScroller(this, getWidth() - 2, 0, getHeight() - 2);
737 setBottomValue(0);
738
739 // Assume XTERM
740 ECMA48.DeviceType deviceType = ECMA48.DeviceType.XTERM;
741
742 try {
743 ProcessBuilder pb = new ProcessBuilder(command);
744 Map<String, String> env = pb.environment();
745 env.put("TERM", ECMA48.deviceTypeTerm(deviceType));
746 env.put("LANG", ECMA48.deviceTypeLang(deviceType, "en"));
747 env.put("COLUMNS", "80");
748 env.put("LINES", "24");
749 pb.redirectErrorStream(true);
750 shell = pb.start();
751 emulator = new ECMA48(deviceType, shell.getInputStream(),
752 shell.getOutputStream(), this);
753 } catch (IOException e) {
754 messageBox(i18n.getString("errorLaunchingShellTitle"),
755 MessageFormat.format(i18n.getString("errorLaunchingShellText"),
756 e.getMessage()));
757 }
758
759 // Setup the scroll bars
760 onResize(new TResizeEvent(TResizeEvent.Type.WIDGET, getWidth(),
761 getHeight()));
762
763 // Claim the keystrokes the emulator will need.
764 addShortcutKeys();
765
766 // Add shortcut text
767 newStatusBar(i18n.getString("statusBarRunning"));
768
769 // Pass the correct text cell width/height to the emulator
770 emulator.setTextWidth(getScreen().getTextWidth());
771 emulator.setTextHeight(getScreen().getTextHeight());
772 }
773
774 /**
775 * Terminate the child of the 'script' process used on POSIX. This may
776 * or may not work.
777 */
778 private void terminateShellChildProcess() {
779 int pid = -1;
780 if (shell.getClass().getName().equals("java.lang.UNIXProcess")) {
781 /* get the PID on unix/linux systems */
782 try {
783 Field field = shell.getClass().getDeclaredField("pid");
784 field.setAccessible(true);
785 pid = field.getInt(shell);
786 } catch (Throwable e) {
787 // SQUASH, this didn't work. Just bail out quietly.
788 return;
789 }
790 }
791 if (pid != -1) {
792 // shell.destroy() works successfully at killing this side of
793 // 'script'. But we need to make sure the other side (child
794 // process) is also killed.
795 String [] cmdKillIt = {
796 "pkill", "-P", Integer.toString(pid)
797 };
798 try {
799 Runtime.getRuntime().exec(cmdKillIt);
800 } catch (Throwable e) {
801 // SQUASH, this didn't work. Just bail out quietly.
802 return;
803 }
804 }
805 }
806
807 /**
808 * Called by emulator when fresh data has come in.
809 */
810 public void displayChanged() {
811 getApplication().postEvent(new TMenuEvent(TMenu.MID_REPAINT));
812 }
813
814 /**
815 * Function to call to obtain the display width.
816 *
817 * @return the number of columns in the display
818 */
819 public int getDisplayWidth() {
820 if (ptypipe) {
821 return getWidth() - 2;
822 }
823 return 80;
824 }
825
826 /**
827 * Function to call to obtain the display height.
828 *
829 * @return the number of rows in the display
830 */
831 public int getDisplayHeight() {
832 if (ptypipe) {
833 return getHeight() - 2;
834 }
835 return 24;
836 }
837
838 /**
839 * Hook for subclasses to be notified of the shell termination.
840 */
841 public void onShellExit() {
842 if (closeOnExit) {
843 close();
844 }
845 getApplication().postEvent(new TMenuEvent(TMenu.MID_REPAINT));
846 }
847
848 /**
849 * Copy out variables from the emulator that TTerminal has to expose on
850 * screen.
851 */
852 private void readEmulatorState() {
853 // Synchronize against the emulator so we don't stomp on its reader
854 // thread.
855 synchronized (emulator) {
856 setHiddenMouse(emulator.hasHiddenMousePointer());
857
858 setCursorX(emulator.getCursorX() + 1);
859 setCursorY(emulator.getCursorY() + 1
860 + (getHeight() - 2 - emulator.getHeight())
861 - getVerticalValue());
862 setCursorVisible(emulator.isCursorVisible());
863 if (getCursorX() > getWidth() - 2) {
864 setCursorVisible(false);
865 }
866 if ((getCursorY() > getHeight() - 2) || (getCursorY() < 0)) {
867 setCursorVisible(false);
868 }
869 if (emulator.getScreenTitle().length() > 0) {
870 // Only update the title if the shell is still alive
871 if (shell != null) {
872 setTitle(emulator.getScreenTitle());
873 }
874 }
875
876 // Check to see if the shell has died.
877 if (!emulator.isReading() && (shell != null)) {
878 try {
879 int rc = shell.exitValue();
880 // The emulator exited on its own, all is fine
881 setTitle(MessageFormat.format(i18n.
882 getString("windowTitleCompleted"), getTitle(), rc));
883 shell = null;
884 emulator.close();
885 clearShortcutKeypresses();
886 statusBar.setText(MessageFormat.format(i18n.
887 getString("statusBarCompleted"), rc));
888 onShellExit();
889 } catch (IllegalThreadStateException e) {
890 // The emulator thread has exited, but the shell Process
891 // hasn't figured that out yet. Do nothing, we will see
892 // this in a future tick.
893 }
894 } else if (emulator.isReading() && (shell != null)) {
895 // The shell might be dead, let's check
896 try {
897 int rc = shell.exitValue();
898 // If we got here, the shell died.
899 setTitle(MessageFormat.format(i18n.
900 getString("windowTitleCompleted"), getTitle(), rc));
901 shell = null;
902 emulator.close();
903 clearShortcutKeypresses();
904 statusBar.setText(MessageFormat.format(i18n.
905 getString("statusBarCompleted"), rc));
906 onShellExit();
907 } catch (IllegalThreadStateException e) {
908 // The shell is still running, do nothing.
909 }
910 }
911
912 } // synchronized (emulator)
913 }
914
915 /**
916 * Check if a mouse press/release/motion event coordinate is over the
917 * emulator.
918 *
919 * @param mouse a mouse-based event
920 * @return whether or not the mouse is on the emulator
921 */
922 private boolean mouseOnEmulator(final TMouseEvent mouse) {
923
924 synchronized (emulator) {
925 if (!emulator.isReading()) {
926 return false;
927 }
928 }
929
930 if ((mouse.getAbsoluteX() >= getAbsoluteX() + 1)
931 && (mouse.getAbsoluteX() < getAbsoluteX() + getWidth() - 1)
932 && (mouse.getAbsoluteY() >= getAbsoluteY() + 1)
933 && (mouse.getAbsoluteY() < getAbsoluteY() + getHeight() - 1)
934 ) {
935 return true;
936 }
937 return false;
938 }
939
940 /**
941 * Draw glyphs for a double-width or double-height VT100 cell to two
942 * screen cells.
943 *
944 * @param line the line this VT100 cell is in
945 * @param x the X position to draw the left half to
946 * @param y the Y position to draw to
947 * @param cell the cell to draw
948 */
949 private void putDoubleWidthCharXY(final DisplayLine line, final int x,
950 final int y, final Cell cell) {
951
952 int textWidth = getScreen().getTextWidth();
953 int textHeight = getScreen().getTextHeight();
954 boolean cursorBlinkVisible = true;
955
956 if (getScreen() instanceof SwingTerminal) {
957 SwingTerminal terminal = (SwingTerminal) getScreen();
958 cursorBlinkVisible = terminal.getCursorBlinkVisible();
959 } else if (getScreen() instanceof ECMA48Terminal) {
960 ECMA48Terminal terminal = (ECMA48Terminal) getScreen();
961
962 if (!terminal.hasSixel()) {
963 // The backend does not have sixel support, draw this as text
964 // and bail out.
965 putCharXY(x, y, cell);
966 putCharXY(x + 1, y, ' ', cell);
967 return;
968 }
969 cursorBlinkVisible = blinkState;
970 } else {
971 // We don't know how to dray glyphs to this screen, draw them as
972 // text and bail out.
973 putCharXY(x, y, cell);
974 putCharXY(x + 1, y, ' ', cell);
975 return;
976 }
977
978 if ((textWidth != lastTextWidth) || (textHeight != lastTextHeight)) {
979 // Screen size has changed, reset all fonts.
980 setupFonts(textHeight);
981 lastTextWidth = textWidth;
982 lastTextHeight = textHeight;
983 }
984 assert (doubleFont != null);
985
986 BufferedImage image = null;
987 if (cell.isBlink() && !cursorBlinkVisible) {
988 image = glyphCacheBlink.get(cell);
989 } else {
990 image = glyphCache.get(cell);
991 }
992 if (image == null) {
993 // Generate glyph and draw it to an image.
994 image = new BufferedImage(textWidth * 2, textHeight * 2,
995 BufferedImage.TYPE_INT_ARGB);
996 Graphics2D gr2 = image.createGraphics();
997 gr2.setFont(doubleFont);
998
999 // Draw the background rectangle, then the foreground character.
1000 if (getScreen() instanceof ECMA48Terminal) {
1001 // BUG: the background color is coming in the same as the
1002 // foreground color. For now, don't draw it.
1003 } else {
1004 gr2.setColor(SwingTerminal.attrToBackgroundColor(cell));
1005 gr2.fillRect(0, 0, image.getWidth(), image.getHeight());
1006 }
1007 if (!cell.isBlink()
1008 || (cell.isBlink() && cursorBlinkVisible)
1009 ) {
1010 gr2.setColor(SwingTerminal.attrToForegroundColor(cell));
1011 char [] chars = new char[1];
1012 chars[0] = cell.getChar();
1013 gr2.drawChars(chars, 0, 1, doubleTextAdjustX,
1014 (textHeight * 2) - doubleMaxDescent + doubleTextAdjustY);
1015
1016 if (cell.isUnderline() && (line.getDoubleHeight() != 1)) {
1017 gr2.fillRect(0, textHeight - 2, textWidth, 2);
1018 }
1019 }
1020 gr2.dispose();
1021
1022 // Now save this generated image, using a new key that will not
1023 // be mutated by invertCell().
1024 Cell key = new Cell();
1025 key.setTo(cell);
1026 if (cell.isBlink() && !cursorBlinkVisible) {
1027 glyphCacheBlink.put(key, image);
1028 } else {
1029 glyphCache.put(key, image);
1030 }
1031 }
1032
1033 // Now that we have the double-wide glyph drawn, copy the right
1034 // pieces of it to the cells.
1035 Cell left = new Cell();
1036 Cell right = new Cell();
1037 left.setTo(cell);
1038 right.setTo(cell);
1039 right.setChar(' ');
1040 BufferedImage leftImage = null;
1041 BufferedImage rightImage = null;
1042 switch (line.getDoubleHeight()) {
1043 case 1:
1044 // Top half double height
1045 leftImage = image.getSubimage(0, 0, textWidth, textHeight);
1046 rightImage = image.getSubimage(textWidth, 0, textWidth, textHeight);
1047 break;
1048 case 2:
1049 // Bottom half double height
1050 leftImage = image.getSubimage(0, textHeight, textWidth, textHeight);
1051 rightImage = image.getSubimage(textWidth, textHeight,
1052 textWidth, textHeight);
1053 break;
1054 default:
1055 // Either single height double-width, or error fallback
1056 BufferedImage wideImage = new BufferedImage(textWidth * 2,
1057 textHeight, BufferedImage.TYPE_INT_ARGB);
1058 Graphics2D grWide = wideImage.createGraphics();
1059 grWide.drawImage(image, 0, 0, wideImage.getWidth(),
1060 wideImage.getHeight(), null);
1061 grWide.dispose();
1062 leftImage = wideImage.getSubimage(0, 0, textWidth, textHeight);
1063 rightImage = wideImage.getSubimage(textWidth, 0, textWidth,
1064 textHeight);
1065 break;
1066 }
1067 left.setImage(leftImage);
1068 right.setImage(rightImage);
1069 putCharXY(x, y, left);
1070 putCharXY(x + 1, y, right);
1071 }
1072
1073 /**
1074 * Set up the single and double-width fonts.
1075 *
1076 * @param fontSize the size of font to request for the single-width font.
1077 * The double-width font will be 2x this value.
1078 */
1079 private void setupFonts(final int fontSize) {
1080 try {
1081 ClassLoader loader = Thread.currentThread().getContextClassLoader();
1082 InputStream in = loader.getResourceAsStream(SwingTerminal.FONTFILE);
1083 Font terminusRoot = Font.createFont(Font.TRUETYPE_FONT, in);
1084 Font terminusDouble = terminusRoot.deriveFont(Font.PLAIN,
1085 fontSize * 2);
1086 doubleFont = terminusDouble;
1087 } catch (java.awt.FontFormatException e) {
1088 new TExceptionDialog(getApplication(), e);
1089 doubleFont = new Font(Font.MONOSPACED, Font.PLAIN, fontSize * 2);
1090 } catch (java.io.IOException e) {
1091 new TExceptionDialog(getApplication(), e);
1092 doubleFont = new Font(Font.MONOSPACED, Font.PLAIN, fontSize * 2);
1093 }
1094
1095 // Get font descent.
1096 BufferedImage image = new BufferedImage(fontSize * 10, fontSize * 10,
1097 BufferedImage.TYPE_INT_ARGB);
1098 Graphics2D gr = image.createGraphics();
1099 gr.setFont(doubleFont);
1100 FontMetrics fm = gr.getFontMetrics();
1101 doubleMaxDescent = fm.getMaxDescent();
1102
1103 gr.dispose();
1104
1105 // (Re)create the glyph caches.
1106 glyphCache = new HashMap<Cell, BufferedImage>();
1107 glyphCacheBlink = new HashMap<Cell, BufferedImage>();
1108
1109 // Special case: the ECMA48 backend needs to have a timer to drive
1110 // its blink state.
1111 if (getScreen() instanceof jexer.backend.ECMA48Terminal) {
1112 // Blink every 500 millis.
1113 long millis = 500;
1114 getApplication().addTimer(millis, true,
1115 new TAction() {
1116 public void DO() {
1117 blinkState = !blinkState;
1118 getApplication().doRepaint();
1119 }
1120 }
1121 );
1122 }
1123
1124 }
1125
1126}