#42 clamp list height
[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() {
ab215e38
KL
329 int width = getDisplayWidth();
330 boolean syncEmulator = false;
027de5ae 331 if ((System.currentTimeMillis() - lastUpdateTime >= 25)
ab215e38
KL
332 && (dirty == true)
333 ) {
334 // Too much time has passed, draw it all.
335 syncEmulator = true;
336 } else if (emulator.isReading() && (dirty == false)) {
337 // Wait until the emulator has brought more data in.
338 syncEmulator = false;
339 } else if (!emulator.isReading() && (dirty == true)) {
340 // The emulator won't receive more data, update the display.
341 syncEmulator = true;
342 }
34a42e78 343
ab215e38
KL
344 if ((syncEmulator == true)
345 || (scrollback == null)
346 || (display == null)
347 ) {
348 // We want to minimize the amount of time we have the emulator
349 // locked. Grab a copy of its display.
350 synchronized (emulator) {
351 // Update the scroll bars
352 reflowData();
34a42e78 353
ab215e38
KL
354 if ((scrollback == null) || emulator.isReading()) {
355 scrollback = copyBuffer(emulator.getScrollbackBuffer());
356 display = copyBuffer(emulator.getDisplayBuffer());
34a42e78 357 }
ab215e38 358 width = emulator.getWidth();
34a42e78 359 }
ab215e38
KL
360 dirty = false;
361 }
34a42e78 362
ab215e38
KL
363 // Draw the box using my superclass
364 super.draw();
34a42e78 365
ab215e38
KL
366 // Put together the visible rows
367 int visibleHeight = getHeight() - 2;
368 int visibleBottom = scrollback.size() + display.size()
369 + getVerticalValue();
370 assert (visibleBottom >= 0);
34a42e78 371
ab215e38
KL
372 List<DisplayLine> preceedingBlankLines = new ArrayList<DisplayLine>();
373 int visibleTop = visibleBottom - visibleHeight;
374 if (visibleTop < 0) {
375 for (int i = visibleTop; i < 0; i++) {
376 preceedingBlankLines.add(emulator.getBlankDisplayLine());
377 }
378 visibleTop = 0;
379 }
380 assert (visibleTop >= 0);
381
382 List<DisplayLine> displayLines = new ArrayList<DisplayLine>();
383 displayLines.addAll(scrollback);
384 displayLines.addAll(display);
385
386 List<DisplayLine> visibleLines = new ArrayList<DisplayLine>();
387 visibleLines.addAll(preceedingBlankLines);
388 visibleLines.addAll(displayLines.subList(visibleTop,
389 visibleBottom));
390
391 visibleHeight -= visibleLines.size();
392 assert (visibleHeight >= 0);
393
394 // Now draw the emulator screen
395 int row = 1;
396 for (DisplayLine line: visibleLines) {
397 int widthMax = width;
398 if (line.isDoubleWidth()) {
399 widthMax /= 2;
400 }
401 if (widthMax > getWidth() - 2) {
402 widthMax = getWidth() - 2;
403 }
404 for (int i = 0; i < widthMax; i++) {
405 Cell ch = line.charAt(i);
34a42e78 406
ab215e38
KL
407 if (ch.isImage()) {
408 putCharXY(i + 1, row, ch);
409 continue;
34a42e78 410 }
9588c713 411
027de5ae 412 Cell newCell = new Cell(ch);
ab215e38
KL
413 boolean reverse = line.isReverseColor() ^ ch.isReverse();
414 newCell.setReverse(false);
415 if (reverse) {
416 if (ch.getForeColorRGB() < 0) {
417 newCell.setBackColor(ch.getForeColor());
418 newCell.setBackColorRGB(-1);
419 } else {
420 newCell.setBackColorRGB(ch.getForeColorRGB());
34a42e78 421 }
ab215e38
KL
422 if (ch.getBackColorRGB() < 0) {
423 newCell.setForeColor(ch.getBackColor());
424 newCell.setForeColorRGB(-1);
34a42e78 425 } else {
ab215e38 426 newCell.setForeColorRGB(ch.getBackColorRGB());
34a42e78
KL
427 }
428 }
ab215e38
KL
429 if (line.isDoubleWidth()) {
430 putDoubleWidthCharXY(line, (i * 2) + 1, row, newCell);
431 } else {
432 putCharXY(i + 1, row, newCell);
34a42e78
KL
433 }
434 }
ab215e38
KL
435 row++;
436 if (row == getHeight() - 1) {
437 // Don't overwrite the box edge
438 break;
34a42e78 439 }
ab215e38
KL
440 }
441 CellAttributes background = new CellAttributes();
442 // Fill in the blank lines on bottom
443 for (int i = 0; i < visibleHeight; i++) {
444 hLineXY(1, i + row, getWidth() - 2, ' ', background);
445 }
34a42e78
KL
446
447 }
448
107bba16
KL
449 /**
450 * Handle window close.
451 */
452 @Override
453 public void onClose() {
454 emulator.close();
455 if (shell != null) {
456 terminateShellChildProcess();
457 shell.destroy();
458 shell = null;
459 }
460 }
461
be72cb5c 462 /**
615a0d99 463 * Handle window/screen resize events.
aa77d682 464 *
615a0d99 465 * @param resize resize event
aa77d682 466 */
615a0d99
KL
467 @Override
468 public void onResize(final TResizeEvent resize) {
469
470 // Synchronize against the emulator so we don't stomp on its reader
471 // thread.
472 synchronized (emulator) {
473
474 if (resize.getType() == TResizeEvent.Type.WIDGET) {
475 // Resize the scroll bars
476 reflowData();
477 placeScrollbars();
478
479 // Get out of scrollback
480 setVerticalValue(0);
481
482 if (ptypipe) {
483 emulator.setWidth(getWidth() - 2);
484 emulator.setHeight(getHeight() - 2);
485
486 emulator.writeRemote("\033[8;" + (getHeight() - 2) + ";" +
487 (getWidth() - 2) + "t");
488 }
489 }
490 return;
491
492 } // synchronized (emulator)
aa77d682
KL
493 }
494
495 /**
615a0d99 496 * Resize scrollbars for a new width/height.
aa77d682 497 */
615a0d99
KL
498 @Override
499 public void reflowData() {
500
501 // Synchronize against the emulator so we don't stomp on its reader
502 // thread.
503 synchronized (emulator) {
504
505 // Pull cursor information
506 readEmulatorState();
507
508 // Vertical scrollbar
509 setTopValue(getHeight() - 2
510 - (emulator.getScrollbackBuffer().size()
511 + emulator.getDisplayBuffer().size()));
512 setVerticalBigChange(getHeight() - 2);
513
514 } // synchronized (emulator)
aa77d682
KL
515 }
516
b2d49e0f 517 /**
615a0d99
KL
518 * Handle keystrokes.
519 *
520 * @param keypress keystroke event
34a42e78 521 */
615a0d99
KL
522 @Override
523 public void onKeypress(final TKeypressEvent keypress) {
34a42e78
KL
524
525 // Scrollback up/down
526 if (keypress.equals(kbShiftPgUp)
527 || keypress.equals(kbCtrlPgUp)
528 || keypress.equals(kbAltPgUp)
529 ) {
56661844 530 bigVerticalDecrement();
34a42e78
KL
531 return;
532 }
533 if (keypress.equals(kbShiftPgDn)
534 || keypress.equals(kbCtrlPgDn)
535 || keypress.equals(kbAltPgDn)
536 ) {
56661844 537 bigVerticalIncrement();
34a42e78
KL
538 return;
539 }
540
ab215e38
KL
541 if (emulator.isReading()) {
542 // Get out of scrollback
543 setVerticalValue(0);
544 emulator.addUserEvent(keypress);
92554d64 545
ab215e38
KL
546 // UGLY HACK TIME! cmd.exe needs CRLF, not just CR, so if
547 // this is kBEnter then also send kbCtrlJ.
548 if (System.getProperty("os.name").startsWith("Windows")) {
549 if (keypress.equals(kbEnter)) {
550 emulator.addUserEvent(new TKeypressEvent(kbCtrlJ));
92554d64 551 }
34a42e78 552 }
ab215e38
KL
553
554 readEmulatorState();
555 return;
34a42e78
KL
556 }
557
558 // Process is closed, honor "normal" TUI keystrokes
559 super.onKeypress(keypress);
560 }
561
562 /**
563 * Handle mouse press events.
564 *
565 * @param mouse mouse button press event
566 */
567 @Override
568 public void onMouseDown(final TMouseEvent mouse) {
bd8d51fa
KL
569 if (inWindowMove || inWindowResize) {
570 // TWindow needs to deal with this.
571 super.onMouseDown(mouse);
572 return;
573 }
34a42e78 574
69a8c368
KL
575 // If the emulator is tracking mouse buttons, it needs to see wheel
576 // events.
577 if (emulator.getMouseProtocol() == ECMA48.MouseProtocol.OFF) {
578 if (mouse.isMouseWheelUp()) {
579 verticalDecrement();
580 return;
581 }
582 if (mouse.isMouseWheelDown()) {
583 verticalIncrement();
584 return;
585 }
34a42e78 586 }
bd8d51fa 587 if (mouseOnEmulator(mouse)) {
ab215e38
KL
588 mouse.setX(mouse.getX() - 1);
589 mouse.setY(mouse.getY() - 1);
590 emulator.addUserEvent(mouse);
591 readEmulatorState();
592 return;
bd8d51fa 593 }
34a42e78 594
bd8d51fa 595 // Emulator didn't consume it, pass it on
34a42e78
KL
596 super.onMouseDown(mouse);
597 }
598
bd8d51fa
KL
599 /**
600 * Handle mouse release events.
601 *
602 * @param mouse mouse button release event
603 */
604 @Override
605 public void onMouseUp(final TMouseEvent mouse) {
606 if (inWindowMove || inWindowResize) {
607 // TWindow needs to deal with this.
608 super.onMouseUp(mouse);
609 return;
610 }
611
612 if (mouseOnEmulator(mouse)) {
ab215e38
KL
613 mouse.setX(mouse.getX() - 1);
614 mouse.setY(mouse.getY() - 1);
615 emulator.addUserEvent(mouse);
616 readEmulatorState();
617 return;
bd8d51fa
KL
618 }
619
620 // Emulator didn't consume it, pass it on
621 super.onMouseUp(mouse);
622 }
623
624 /**
625 * Handle mouse motion events.
626 *
627 * @param mouse mouse motion event
628 */
629 @Override
630 public void onMouseMotion(final TMouseEvent mouse) {
631 if (inWindowMove || inWindowResize) {
632 // TWindow needs to deal with this.
633 super.onMouseMotion(mouse);
634 return;
635 }
636
637 if (mouseOnEmulator(mouse)) {
ab215e38
KL
638 mouse.setX(mouse.getX() - 1);
639 mouse.setY(mouse.getY() - 1);
640 emulator.addUserEvent(mouse);
641 readEmulatorState();
642 return;
bd8d51fa
KL
643 }
644
645 // Emulator didn't consume it, pass it on
646 super.onMouseMotion(mouse);
647 }
648
615a0d99
KL
649 // ------------------------------------------------------------------------
650 // TTerminalWindow --------------------------------------------------------
651 // ------------------------------------------------------------------------
652
653 /**
654 * Claim the keystrokes the emulator will need.
655 */
656 private void addShortcutKeys() {
657 addShortcutKeypress(kbCtrlA);
658 addShortcutKeypress(kbCtrlB);
659 addShortcutKeypress(kbCtrlC);
660 addShortcutKeypress(kbCtrlD);
661 addShortcutKeypress(kbCtrlE);
662 addShortcutKeypress(kbCtrlF);
663 addShortcutKeypress(kbCtrlG);
664 addShortcutKeypress(kbCtrlH);
665 addShortcutKeypress(kbCtrlU);
666 addShortcutKeypress(kbCtrlJ);
667 addShortcutKeypress(kbCtrlK);
668 addShortcutKeypress(kbCtrlL);
669 addShortcutKeypress(kbCtrlM);
670 addShortcutKeypress(kbCtrlN);
671 addShortcutKeypress(kbCtrlO);
672 addShortcutKeypress(kbCtrlP);
673 addShortcutKeypress(kbCtrlQ);
674 addShortcutKeypress(kbCtrlR);
675 addShortcutKeypress(kbCtrlS);
676 addShortcutKeypress(kbCtrlT);
677 addShortcutKeypress(kbCtrlU);
678 addShortcutKeypress(kbCtrlV);
679 addShortcutKeypress(kbCtrlW);
680 addShortcutKeypress(kbCtrlX);
681 addShortcutKeypress(kbCtrlY);
682 addShortcutKeypress(kbCtrlZ);
683 addShortcutKeypress(kbF1);
684 addShortcutKeypress(kbF2);
685 addShortcutKeypress(kbF3);
686 addShortcutKeypress(kbF4);
687 addShortcutKeypress(kbF5);
688 addShortcutKeypress(kbF6);
689 addShortcutKeypress(kbF7);
690 addShortcutKeypress(kbF8);
691 addShortcutKeypress(kbF9);
692 addShortcutKeypress(kbF10);
693 addShortcutKeypress(kbF11);
694 addShortcutKeypress(kbF12);
695 addShortcutKeypress(kbAltA);
696 addShortcutKeypress(kbAltB);
697 addShortcutKeypress(kbAltC);
698 addShortcutKeypress(kbAltD);
699 addShortcutKeypress(kbAltE);
700 addShortcutKeypress(kbAltF);
701 addShortcutKeypress(kbAltG);
702 addShortcutKeypress(kbAltH);
703 addShortcutKeypress(kbAltU);
704 addShortcutKeypress(kbAltJ);
705 addShortcutKeypress(kbAltK);
706 addShortcutKeypress(kbAltL);
707 addShortcutKeypress(kbAltM);
708 addShortcutKeypress(kbAltN);
709 addShortcutKeypress(kbAltO);
710 addShortcutKeypress(kbAltP);
711 addShortcutKeypress(kbAltQ);
712 addShortcutKeypress(kbAltR);
713 addShortcutKeypress(kbAltS);
714 addShortcutKeypress(kbAltT);
715 addShortcutKeypress(kbAltU);
716 addShortcutKeypress(kbAltV);
717 addShortcutKeypress(kbAltW);
718 addShortcutKeypress(kbAltX);
719 addShortcutKeypress(kbAltY);
720 addShortcutKeypress(kbAltZ);
721 }
722
723 /**
724 * Convert a string array to a whitespace-separated string.
725 *
726 * @param array the string array
727 * @return a single string
728 */
729 private String stringArrayToString(final String [] array) {
730 StringBuilder sb = new StringBuilder(array[0].length());
731 for (int i = 0; i < array.length; i++) {
732 sb.append(array[i]);
733 if (i < array.length - 1) {
734 sb.append(' ');
735 }
736 }
737 return sb.toString();
738 }
739
740 /**
741 * Spawn the shell.
742 *
743 * @param command the command line to execute
744 */
745 private void spawnShell(final String [] command) {
746
747 /*
748 System.err.printf("spawnShell(): '%s'\n",
749 stringArrayToString(command));
750 */
751
752 vScroller = new TVScroller(this, getWidth() - 2, 0, getHeight() - 2);
753 setBottomValue(0);
754
755 // Assume XTERM
756 ECMA48.DeviceType deviceType = ECMA48.DeviceType.XTERM;
757
758 try {
759 ProcessBuilder pb = new ProcessBuilder(command);
760 Map<String, String> env = pb.environment();
761 env.put("TERM", ECMA48.deviceTypeTerm(deviceType));
762 env.put("LANG", ECMA48.deviceTypeLang(deviceType, "en"));
763 env.put("COLUMNS", "80");
764 env.put("LINES", "24");
765 pb.redirectErrorStream(true);
766 shell = pb.start();
767 emulator = new ECMA48(deviceType, shell.getInputStream(),
768 shell.getOutputStream(), this);
769 } catch (IOException e) {
770 messageBox(i18n.getString("errorLaunchingShellTitle"),
771 MessageFormat.format(i18n.getString("errorLaunchingShellText"),
772 e.getMessage()));
773 }
774
775 // Setup the scroll bars
776 onResize(new TResizeEvent(TResizeEvent.Type.WIDGET, getWidth(),
777 getHeight()));
778
779 // Claim the keystrokes the emulator will need.
780 addShortcutKeys();
781
782 // Add shortcut text
783 newStatusBar(i18n.getString("statusBarRunning"));
5fc7bf09
KL
784
785 // Pass the correct text cell width/height to the emulator
03ae544a
KL
786 emulator.setTextWidth(getScreen().getTextWidth());
787 emulator.setTextHeight(getScreen().getTextHeight());
615a0d99
KL
788 }
789
790 /**
791 * Terminate the child of the 'script' process used on POSIX. This may
792 * or may not work.
793 */
794 private void terminateShellChildProcess() {
795 int pid = -1;
796 if (shell.getClass().getName().equals("java.lang.UNIXProcess")) {
797 /* get the PID on unix/linux systems */
798 try {
799 Field field = shell.getClass().getDeclaredField("pid");
800 field.setAccessible(true);
801 pid = field.getInt(shell);
802 } catch (Throwable e) {
803 // SQUASH, this didn't work. Just bail out quietly.
804 return;
805 }
806 }
807 if (pid != -1) {
808 // shell.destroy() works successfully at killing this side of
809 // 'script'. But we need to make sure the other side (child
810 // process) is also killed.
811 String [] cmdKillIt = {
812 "pkill", "-P", Integer.toString(pid)
813 };
814 try {
815 Runtime.getRuntime().exec(cmdKillIt);
816 } catch (Throwable e) {
817 // SQUASH, this didn't work. Just bail out quietly.
818 return;
819 }
820 }
821 }
822
615a0d99
KL
823 /**
824 * Hook for subclasses to be notified of the shell termination.
825 */
826 public void onShellExit() {
a69ed767
KL
827 if (closeOnExit) {
828 close();
829 }
615a0d99
KL
830 getApplication().postEvent(new TMenuEvent(TMenu.MID_REPAINT));
831 }
832
833 /**
834 * Copy out variables from the emulator that TTerminal has to expose on
835 * screen.
836 */
837 private void readEmulatorState() {
838 // Synchronize against the emulator so we don't stomp on its reader
839 // thread.
840 synchronized (emulator) {
978a5d8f 841 setHiddenMouse(emulator.hasHiddenMousePointer());
9696a8f6 842
615a0d99
KL
843 setCursorX(emulator.getCursorX() + 1);
844 setCursorY(emulator.getCursorY() + 1
845 + (getHeight() - 2 - emulator.getHeight())
846 - getVerticalValue());
847 setCursorVisible(emulator.isCursorVisible());
848 if (getCursorX() > getWidth() - 2) {
849 setCursorVisible(false);
850 }
851 if ((getCursorY() > getHeight() - 2) || (getCursorY() < 0)) {
852 setCursorVisible(false);
853 }
854 if (emulator.getScreenTitle().length() > 0) {
855 // Only update the title if the shell is still alive
856 if (shell != null) {
857 setTitle(emulator.getScreenTitle());
858 }
859 }
860
861 // Check to see if the shell has died.
862 if (!emulator.isReading() && (shell != null)) {
863 try {
864 int rc = shell.exitValue();
865 // The emulator exited on its own, all is fine
866 setTitle(MessageFormat.format(i18n.
867 getString("windowTitleCompleted"), getTitle(), rc));
868 shell = null;
869 emulator.close();
870 clearShortcutKeypresses();
871 statusBar.setText(MessageFormat.format(i18n.
872 getString("statusBarCompleted"), rc));
873 onShellExit();
874 } catch (IllegalThreadStateException e) {
875 // The emulator thread has exited, but the shell Process
876 // hasn't figured that out yet. Do nothing, we will see
877 // this in a future tick.
878 }
879 } else if (emulator.isReading() && (shell != null)) {
880 // The shell might be dead, let's check
881 try {
882 int rc = shell.exitValue();
883 // If we got here, the shell died.
884 setTitle(MessageFormat.format(i18n.
885 getString("windowTitleCompleted"), getTitle(), rc));
886 shell = null;
887 emulator.close();
888 clearShortcutKeypresses();
889 statusBar.setText(MessageFormat.format(i18n.
890 getString("statusBarCompleted"), rc));
891 onShellExit();
892 } catch (IllegalThreadStateException e) {
893 // The shell is still running, do nothing.
894 }
895 }
896
897 } // synchronized (emulator)
898 }
899
900 /**
901 * Check if a mouse press/release/motion event coordinate is over the
902 * emulator.
903 *
904 * @param mouse a mouse-based event
905 * @return whether or not the mouse is on the emulator
906 */
c88c4ced 907 private boolean mouseOnEmulator(final TMouseEvent mouse) {
615a0d99 908
ab215e38
KL
909 if (!emulator.isReading()) {
910 return false;
615a0d99
KL
911 }
912
913 if ((mouse.getAbsoluteX() >= getAbsoluteX() + 1)
914 && (mouse.getAbsoluteX() < getAbsoluteX() + getWidth() - 1)
915 && (mouse.getAbsoluteY() >= getAbsoluteY() + 1)
916 && (mouse.getAbsoluteY() < getAbsoluteY() + getHeight() - 1)
917 ) {
918 return true;
919 }
920 return false;
921 }
922
ab215e38
KL
923 /**
924 * Copy a display buffer.
925 *
926 * @param buffer the buffer to copy
927 * @return a deep copy of the buffer's data
928 */
929 private List<DisplayLine> copyBuffer(final List<DisplayLine> buffer) {
930 ArrayList<DisplayLine> result = new ArrayList<DisplayLine>(buffer.size());
931 for (DisplayLine line: buffer) {
932 result.add(new DisplayLine(line));
933 }
934 return result;
935 }
936
d1115203
KL
937 /**
938 * Draw glyphs for a double-width or double-height VT100 cell to two
939 * screen cells.
940 *
941 * @param line the line this VT100 cell is in
942 * @param x the X position to draw the left half to
943 * @param y the Y position to draw to
944 * @param cell the cell to draw
945 */
946 private void putDoubleWidthCharXY(final DisplayLine line, final int x,
947 final int y, final Cell cell) {
948
03ae544a
KL
949 int textWidth = getScreen().getTextWidth();
950 int textHeight = getScreen().getTextHeight();
b3d79e99 951 boolean cursorBlinkVisible = true;
d1115203
KL
952
953 if (getScreen() instanceof SwingTerminal) {
954 SwingTerminal terminal = (SwingTerminal) getScreen();
b3d79e99 955 cursorBlinkVisible = terminal.getCursorBlinkVisible();
d1115203
KL
956 } else if (getScreen() instanceof ECMA48Terminal) {
957 ECMA48Terminal terminal = (ECMA48Terminal) getScreen();
958
5fc7bf09
KL
959 if (!terminal.hasSixel()) {
960 // The backend does not have sixel support, draw this as text
961 // and bail out.
962 putCharXY(x, y, cell);
963 putCharXY(x + 1, y, ' ', cell);
964 return;
965 }
b3d79e99 966 cursorBlinkVisible = blinkState;
d1115203
KL
967 } else {
968 // We don't know how to dray glyphs to this screen, draw them as
969 // text and bail out.
970 putCharXY(x, y, cell);
971 putCharXY(x + 1, y, ' ', cell);
972 return;
973 }
974
975 if ((textWidth != lastTextWidth) || (textHeight != lastTextHeight)) {
0d86ab84
KL
976 // Screen size has changed, reset the font.
977 setupFont(textHeight);
d1115203
KL
978 lastTextWidth = textWidth;
979 lastTextHeight = textHeight;
980 }
981 assert (doubleFont != null);
982
0d86ab84
KL
983 BufferedImage image;
984 if (line.getDoubleHeight() == 1) {
985 // Double-height top half: don't draw the underline.
027de5ae 986 Cell newCell = new Cell(cell);
0d86ab84
KL
987 newCell.setUnderline(false);
988 image = doubleFont.getImage(newCell, textWidth * 2, textHeight * 2,
989 cursorBlinkVisible);
b3d79e99 990 } else {
0d86ab84
KL
991 image = doubleFont.getImage(cell, textWidth * 2, textHeight * 2,
992 cursorBlinkVisible);
d1115203
KL
993 }
994
995 // Now that we have the double-wide glyph drawn, copy the right
996 // pieces of it to the cells.
027de5ae
KL
997 Cell left = new Cell(cell);
998 Cell right = new Cell(cell);
d1115203
KL
999 right.setChar(' ');
1000 BufferedImage leftImage = null;
1001 BufferedImage rightImage = null;
0d86ab84
KL
1002 /*
1003 System.err.println("image " + image + " textWidth " + textWidth +
1004 " textHeight " + textHeight);
1005 */
1006
d1115203
KL
1007 switch (line.getDoubleHeight()) {
1008 case 1:
1009 // Top half double height
1010 leftImage = image.getSubimage(0, 0, textWidth, textHeight);
1011 rightImage = image.getSubimage(textWidth, 0, textWidth, textHeight);
1012 break;
1013 case 2:
1014 // Bottom half double height
1015 leftImage = image.getSubimage(0, textHeight, textWidth, textHeight);
1016 rightImage = image.getSubimage(textWidth, textHeight,
1017 textWidth, textHeight);
1018 break;
1019 default:
1020 // Either single height double-width, or error fallback
1021 BufferedImage wideImage = new BufferedImage(textWidth * 2,
1022 textHeight, BufferedImage.TYPE_INT_ARGB);
1023 Graphics2D grWide = wideImage.createGraphics();
1024 grWide.drawImage(image, 0, 0, wideImage.getWidth(),
1025 wideImage.getHeight(), null);
1026 grWide.dispose();
1027 leftImage = wideImage.getSubimage(0, 0, textWidth, textHeight);
1028 rightImage = wideImage.getSubimage(textWidth, 0, textWidth,
1029 textHeight);
1030 break;
1031 }
1032 left.setImage(leftImage);
1033 right.setImage(rightImage);
49380c21
KL
1034 // Since we have image data, ditch the character here. Otherwise, a
1035 // drawBoxShadow() over the terminal window will show the characters
1036 // which looks wrong.
1037 left.setChar(' ');
1038 right.setChar(' ');
d1115203
KL
1039 putCharXY(x, y, left);
1040 putCharXY(x + 1, y, right);
1041 }
1042
1043 /**
0d86ab84 1044 * Set up the double-width font.
d1115203
KL
1045 *
1046 * @param fontSize the size of font to request for the single-width font.
1047 * The double-width font will be 2x this value.
1048 */
0d86ab84 1049 private void setupFont(final int fontSize) {
9588c713 1050 doubleFont = GlyphMaker.getInstance(fontSize * 2);
b3d79e99
KL
1051
1052 // Special case: the ECMA48 backend needs to have a timer to drive
1053 // its blink state.
1054 if (getScreen() instanceof jexer.backend.ECMA48Terminal) {
0d86ab84
KL
1055 if (!haveTimer) {
1056 // Blink every 500 millis.
1057 long millis = 500;
1058 getApplication().addTimer(millis, true,
1059 new TAction() {
1060 public void DO() {
1061 blinkState = !blinkState;
1062 getApplication().doRepaint();
1063 }
b3d79e99 1064 }
0d86ab84
KL
1065 );
1066 haveTimer = true;
1067 }
b3d79e99 1068 }
d1115203
KL
1069 }
1070
ab215e38
KL
1071 // ------------------------------------------------------------------------
1072 // DisplayListener --------------------------------------------------------
1073 // ------------------------------------------------------------------------
1074
1075 /**
1076 * Called by emulator when fresh data has come in.
1077 */
1078 public void displayChanged() {
1079 dirty = true;
1080 getApplication().postEvent(new TMenuEvent(TMenu.MID_REPAINT));
1081 }
1082
1083 /**
1084 * Function to call to obtain the display width.
1085 *
1086 * @return the number of columns in the display
1087 */
1088 public int getDisplayWidth() {
1089 if (ptypipe) {
1090 return getWidth() - 2;
1091 }
1092 return 80;
1093 }
1094
1095 /**
1096 * Function to call to obtain the display height.
1097 *
1098 * @return the number of rows in the display
1099 */
1100 public int getDisplayHeight() {
1101 if (ptypipe) {
1102 return getHeight() - 2;
1103 }
1104 return 24;
1105 }
1106
34a42e78 1107}