mlterm fully supports features
[nikiroo-utils.git] / src / jexer / TTerminalWindow.java
CommitLineData
daa4106c 1/*
34a42e78
KL
2 * Jexer - Java Text User Interface
3 *
e16dda65 4 * The MIT License (MIT)
34a42e78 5 *
a69ed767 6 * Copyright (C) 2019 Kevin Lamonte
34a42e78 7 *
e16dda65
KL
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:
34a42e78 14 *
e16dda65
KL
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
34a42e78 17 *
e16dda65
KL
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.
34a42e78
KL
25 *
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
27 * @version 1
28 */
29package jexer;
30
d1115203
KL
31import java.awt.Font;
32import java.awt.FontMetrics;
33import java.awt.Graphics2D;
5fc7bf09 34import java.awt.image.BufferedImage;
d1115203
KL
35
36import java.io.InputStream;
34a42e78 37import java.io.IOException;
55d2b2c2 38import java.lang.reflect.Field;
339652cc 39import java.text.MessageFormat;
a69ed767 40import java.util.ArrayList;
d1115203 41import java.util.HashMap;
34a42e78 42import java.util.List;
bd8d51fa 43import java.util.Map;
339652cc 44import java.util.ResourceBundle;
34a42e78 45
d1115203
KL
46import jexer.backend.ECMA48Terminal;
47import jexer.backend.MultiScreen;
48import jexer.backend.SwingTerminal;
34a42e78
KL
49import jexer.bits.Cell;
50import jexer.bits.CellAttributes;
51import jexer.event.TKeypressEvent;
b2d49e0f 52import jexer.event.TMenuEvent;
34a42e78
KL
53import jexer.event.TMouseEvent;
54import jexer.event.TResizeEvent;
b2d49e0f 55import jexer.menu.TMenu;
34a42e78 56import jexer.tterminal.DisplayLine;
be72cb5c 57import jexer.tterminal.DisplayListener;
34a42e78
KL
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 */
be72cb5c
KL
64public class TTerminalWindow extends TScrollableWindow
65 implements DisplayListener {
34a42e78 66
339652cc
KL
67 /**
68 * Translated strings.
69 */
70 private static final ResourceBundle i18n = ResourceBundle.getBundle(TTerminalWindow.class.getName());
71
615a0d99
KL
72 // ------------------------------------------------------------------------
73 // Variables --------------------------------------------------------------
74 // ------------------------------------------------------------------------
75
34a42e78
KL
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
1d99a38f
KL
86 /**
87 * If true, we are using the ptypipe utility to support dynamic window
88 * resizing. ptypipe is available at
a69ed767 89 * https://gitlab.com/klamonte/ptypipe .
1d99a38f
KL
90 */
91 private boolean ptypipe = false;
92
a69ed767
KL
93 /**
94 * If true, close the window when the shell exits.
95 */
96 private boolean closeOnExit = false;
97
d1115203
KL
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
b3d79e99
KL
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
615a0d99
KL
147 // ------------------------------------------------------------------------
148 // Constructors -----------------------------------------------------------
149 // ------------------------------------------------------------------------
34a42e78 150
b2d49e0f
KL
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
00691e80 162 this(application, x, y, RESIZABLE, commandLine.split("\\s+"),
a69ed767
KL
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
00691e80 179 this(application, x, y, RESIZABLE, commandLine.split("\\s+"),
a69ed767 180 closeOnExit);
b2d49e0f
KL
181 }
182
6f8ff91a
KL
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
a0d734e6 190 * @param command the command line to execute
6f8ff91a
KL
191 */
192 public TTerminalWindow(final TApplication application, final int x,
a0d734e6 193 final int y, final int flags, final String [] command) {
6f8ff91a 194
a69ed767
KL
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
6f8ff91a
KL
214 super(application, i18n.getString("windowTitle"), x, y,
215 80 + 2, 24 + 2, flags);
216
a69ed767
KL
217 this.closeOnExit = closeOnExit;
218
a0d734e6 219 String [] fullCommand;
6f8ff91a
KL
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;
a0d734e6
KL
227 fullCommand = new String[command.length + 1];
228 fullCommand[0] = "ptypipe";
229 System.arraycopy(command, 0, fullCommand, 1, command.length);
6f8ff91a 230 } else if (System.getProperty("os.name").startsWith("Windows")) {
a0d734e6
KL
231 fullCommand = new String[3];
232 fullCommand[0] = "cmd";
233 fullCommand[1] = "/c";
234 fullCommand[2] = stringArrayToString(command);
6f8ff91a 235 } else if (System.getProperty("os.name").startsWith("Mac")) {
a0d734e6
KL
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);
6f8ff91a 243 } else {
a0d734e6
KL
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);
6f8ff91a 251 }
a0d734e6 252 spawnShell(fullCommand);
6f8ff91a
KL
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
a69ed767
KL
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
6f8ff91a
KL
284 super(application, i18n.getString("windowTitle"), x, y,
285 80 + 2, 24 + 2, flags);
286
a69ed767
KL
287 this.closeOnExit = closeOnExit;
288
6f8ff91a
KL
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;
00691e80 308 spawnShell(cmdShellPtypipe.split("\\s+"));
6f8ff91a 309 } else if (System.getProperty("os.name").startsWith("Windows")) {
00691e80 310 spawnShell(cmdShellWindows.split("\\s+"));
6f8ff91a 311 } else if (System.getProperty("os.name").startsWith("Mac")) {
00691e80 312 spawnShell(cmdShellBSD.split("\\s+"));
6f8ff91a 313 } else if (System.getProperty("os.name").startsWith("Linux")) {
00691e80 314 spawnShell(cmdShellGNU.split("\\s+"));
6f8ff91a
KL
315 } else {
316 // When all else fails, assume GNU.
00691e80 317 spawnShell(cmdShellGNU.split("\\s+"));
6f8ff91a
KL
318 }
319 }
320
615a0d99
KL
321 // ------------------------------------------------------------------------
322 // TScrollableWindow ------------------------------------------------------
323 // ------------------------------------------------------------------------
55d2b2c2 324
34a42e78
KL
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
56661844 335 reflowData();
34a42e78
KL
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
34a42e78 344 int visibleHeight = getHeight() - 2;
34a42e78 345 int visibleBottom = scrollback.size() + display.size()
56661844 346 + getVerticalValue();
34a42e78
KL
347 assert (visibleBottom >= 0);
348
a69ed767 349 List<DisplayLine> preceedingBlankLines = new ArrayList<DisplayLine>();
34a42e78 350 int visibleTop = visibleBottom - visibleHeight;
34a42e78
KL
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
a69ed767 359 List<DisplayLine> displayLines = new ArrayList<DisplayLine>();
34a42e78
KL
360 displayLines.addAll(scrollback);
361 displayLines.addAll(display);
34a42e78 362
a69ed767 363 List<DisplayLine> visibleLines = new ArrayList<DisplayLine>();
34a42e78
KL
364 visibleLines.addAll(preceedingBlankLines);
365 visibleLines.addAll(displayLines.subList(visibleTop,
366 visibleBottom));
34a42e78
KL
367
368 visibleHeight -= visibleLines.size();
34a42e78
KL
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);
7c870d89 385 boolean reverse = line.isReverseColor() ^ ch.isReverse();
34a42e78
KL
386 newCell.setReverse(false);
387 if (reverse) {
051e2913
KL
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 }
34a42e78
KL
400 }
401 if (line.isDoubleWidth()) {
d1115203 402 putDoubleWidthCharXY(line, (i * 2) + 1, row, newCell);
34a42e78 403 } else {
a69ed767 404 putCharXY(i + 1, row, newCell);
34a42e78
KL
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++) {
a69ed767 416 hLineXY(1, i + row, getWidth() - 2, ' ', background);
34a42e78
KL
417 }
418
419 } // synchronized (emulator)
420
421 }
422
107bba16
KL
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
be72cb5c 436 /**
615a0d99 437 * Handle window/screen resize events.
aa77d682 438 *
615a0d99 439 * @param resize resize event
aa77d682 440 */
615a0d99
KL
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)
aa77d682
KL
467 }
468
469 /**
615a0d99 470 * Resize scrollbars for a new width/height.
aa77d682 471 */
615a0d99
KL
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)
aa77d682
KL
489 }
490
b2d49e0f 491 /**
615a0d99
KL
492 * Handle keystrokes.
493 *
494 * @param keypress keystroke event
34a42e78 495 */
615a0d99
KL
496 @Override
497 public void onKeypress(final TKeypressEvent keypress) {
34a42e78
KL
498
499 // Scrollback up/down
500 if (keypress.equals(kbShiftPgUp)
501 || keypress.equals(kbCtrlPgUp)
502 || keypress.equals(kbAltPgUp)
503 ) {
56661844 504 bigVerticalDecrement();
34a42e78
KL
505 return;
506 }
507 if (keypress.equals(kbShiftPgDn)
508 || keypress.equals(kbCtrlPgDn)
509 || keypress.equals(kbAltPgDn)
510 ) {
56661844 511 bigVerticalIncrement();
34a42e78
KL
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
56661844 520 setVerticalValue(0);
34a42e78 521 emulator.keypress(keypress.getKey());
92554d64
KL
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
34a42e78
KL
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) {
bd8d51fa
KL
547 if (inWindowMove || inWindowResize) {
548 // TWindow needs to deal with this.
549 super.onMouseDown(mouse);
550 return;
551 }
34a42e78 552
69a8c368
KL
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 }
34a42e78 564 }
bd8d51fa
KL
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 }
34a42e78 574
bd8d51fa 575 // Emulator didn't consume it, pass it on
34a42e78
KL
576 super.onMouseDown(mouse);
577 }
578
bd8d51fa
KL
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
615a0d99
KL
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"));
5fc7bf09
KL
768
769 // Pass the correct text cell width/height to the emulator
03ae544a
KL
770 emulator.setTextWidth(getScreen().getTextWidth());
771 emulator.setTextHeight(getScreen().getTextHeight());
615a0d99
KL
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() {
a69ed767
KL
842 if (closeOnExit) {
843 close();
844 }
615a0d99
KL
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) {
978a5d8f 856 setHiddenMouse(emulator.hasHiddenMousePointer());
9696a8f6 857
615a0d99
KL
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 */
c88c4ced 922 private boolean mouseOnEmulator(final TMouseEvent mouse) {
615a0d99
KL
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
d1115203
KL
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
03ae544a
KL
952 int textWidth = getScreen().getTextWidth();
953 int textHeight = getScreen().getTextHeight();
b3d79e99 954 boolean cursorBlinkVisible = true;
d1115203
KL
955
956 if (getScreen() instanceof SwingTerminal) {
957 SwingTerminal terminal = (SwingTerminal) getScreen();
b3d79e99 958 cursorBlinkVisible = terminal.getCursorBlinkVisible();
d1115203
KL
959 } else if (getScreen() instanceof ECMA48Terminal) {
960 ECMA48Terminal terminal = (ECMA48Terminal) getScreen();
961
5fc7bf09
KL
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 }
b3d79e99 969 cursorBlinkVisible = blinkState;
d1115203
KL
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;
b3d79e99
KL
987 if (cell.isBlink() && !cursorBlinkVisible) {
988 image = glyphCacheBlink.get(cell);
989 } else {
990 image = glyphCache.get(cell);
991 }
d1115203
KL
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.
9d990083
KL
1000 gr2.setColor(SwingTerminal.attrToBackgroundColor(cell));
1001 gr2.fillRect(0, 0, image.getWidth(), image.getHeight());
b3d79e99
KL
1002 if (!cell.isBlink()
1003 || (cell.isBlink() && cursorBlinkVisible)
1004 ) {
1005 gr2.setColor(SwingTerminal.attrToForegroundColor(cell));
1006 char [] chars = new char[1];
1007 chars[0] = cell.getChar();
1008 gr2.drawChars(chars, 0, 1, doubleTextAdjustX,
1009 (textHeight * 2) - doubleMaxDescent + doubleTextAdjustY);
1010
1011 if (cell.isUnderline() && (line.getDoubleHeight() != 1)) {
1012 gr2.fillRect(0, textHeight - 2, textWidth, 2);
1013 }
d1115203
KL
1014 }
1015 gr2.dispose();
1016
1017 // Now save this generated image, using a new key that will not
1018 // be mutated by invertCell().
1019 Cell key = new Cell();
1020 key.setTo(cell);
b3d79e99
KL
1021 if (cell.isBlink() && !cursorBlinkVisible) {
1022 glyphCacheBlink.put(key, image);
1023 } else {
1024 glyphCache.put(key, image);
1025 }
d1115203
KL
1026 }
1027
1028 // Now that we have the double-wide glyph drawn, copy the right
1029 // pieces of it to the cells.
1030 Cell left = new Cell();
1031 Cell right = new Cell();
1032 left.setTo(cell);
1033 right.setTo(cell);
1034 right.setChar(' ');
1035 BufferedImage leftImage = null;
1036 BufferedImage rightImage = null;
1037 switch (line.getDoubleHeight()) {
1038 case 1:
1039 // Top half double height
1040 leftImage = image.getSubimage(0, 0, textWidth, textHeight);
1041 rightImage = image.getSubimage(textWidth, 0, textWidth, textHeight);
1042 break;
1043 case 2:
1044 // Bottom half double height
1045 leftImage = image.getSubimage(0, textHeight, textWidth, textHeight);
1046 rightImage = image.getSubimage(textWidth, textHeight,
1047 textWidth, textHeight);
1048 break;
1049 default:
1050 // Either single height double-width, or error fallback
1051 BufferedImage wideImage = new BufferedImage(textWidth * 2,
1052 textHeight, BufferedImage.TYPE_INT_ARGB);
1053 Graphics2D grWide = wideImage.createGraphics();
1054 grWide.drawImage(image, 0, 0, wideImage.getWidth(),
1055 wideImage.getHeight(), null);
1056 grWide.dispose();
1057 leftImage = wideImage.getSubimage(0, 0, textWidth, textHeight);
1058 rightImage = wideImage.getSubimage(textWidth, 0, textWidth,
1059 textHeight);
1060 break;
1061 }
1062 left.setImage(leftImage);
1063 right.setImage(rightImage);
49380c21
KL
1064 // Since we have image data, ditch the character here. Otherwise, a
1065 // drawBoxShadow() over the terminal window will show the characters
1066 // which looks wrong.
1067 left.setChar(' ');
1068 right.setChar(' ');
d1115203
KL
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
b3d79e99 1105 // (Re)create the glyph caches.
d1115203 1106 glyphCache = new HashMap<Cell, BufferedImage>();
b3d79e99
KL
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
d1115203
KL
1124 }
1125
34a42e78 1126}