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