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