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