2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2019 Kevin Lamonte
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:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
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.
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
29 package jexer
.backend
;
31 import java
.awt
.image
.BufferedImage
;
32 import java
.io
.BufferedReader
;
33 import java
.io
.ByteArrayOutputStream
;
34 import java
.io
.FileDescriptor
;
35 import java
.io
.FileInputStream
;
36 import java
.io
.InputStream
;
37 import java
.io
.InputStreamReader
;
38 import java
.io
.IOException
;
39 import java
.io
.OutputStream
;
40 import java
.io
.OutputStreamWriter
;
41 import java
.io
.PrintWriter
;
42 import java
.io
.Reader
;
43 import java
.io
.UnsupportedEncodingException
;
44 import java
.util
.ArrayList
;
45 import java
.util
.Collections
;
46 import java
.util
.HashMap
;
47 import java
.util
.List
;
48 import javax
.imageio
.ImageIO
;
51 import jexer
.bits
.Cell
;
52 import jexer
.bits
.CellAttributes
;
53 import jexer
.bits
.Color
;
54 import jexer
.event
.TCommandEvent
;
55 import jexer
.event
.TInputEvent
;
56 import jexer
.event
.TKeypressEvent
;
57 import jexer
.event
.TMouseEvent
;
58 import jexer
.event
.TResizeEvent
;
59 import static jexer
.TCommand
.*;
60 import static jexer
.TKeypress
.*;
63 * This class reads keystrokes and mouse events and emits output to ANSI
64 * X3.64 / ECMA-48 type terminals e.g. xterm, linux, vt100, ansi.sys, etc.
66 public class ECMA48Terminal
extends LogicalScreen
67 implements TerminalReader
, Runnable
{
69 // ------------------------------------------------------------------------
70 // Constants --------------------------------------------------------------
71 // ------------------------------------------------------------------------
74 * States in the input parser.
76 private enum ParseState
{
86 // ------------------------------------------------------------------------
87 // Variables --------------------------------------------------------------
88 // ------------------------------------------------------------------------
91 * Emit debugging to stderr.
93 private boolean debugToStderr
= false;
96 * If true, emit T.416-style RGB colors for normal system colors. This
97 * is a) expensive in bandwidth, and b) potentially terrible looking for
100 private static boolean doRgbColor
= false;
103 * The session information.
105 private SessionInfo sessionInfo
;
108 * The event queue, filled up by a thread reading on input.
110 private List
<TInputEvent
> eventQueue
;
113 * If true, we want the reader thread to exit gracefully.
115 private boolean stopReaderThread
;
120 private Thread readerThread
;
123 * Parameters being collected. E.g. if the string is \033[1;3m, then
124 * params[0] will be 1 and params[1] will be 3.
126 private List
<String
> params
;
129 * Current parsing state.
131 private ParseState state
;
134 * The time we entered ESCAPE. If we get a bare escape without a code
135 * following it, this is used to return that bare escape.
137 private long escapeTime
;
140 * The time we last checked the window size. We try not to spawn stty
141 * more than once per second.
143 private long windowSizeTime
;
146 * true if mouse1 was down. Used to report mouse1 on the release event.
148 private boolean mouse1
;
151 * true if mouse2 was down. Used to report mouse2 on the release event.
153 private boolean mouse2
;
156 * true if mouse3 was down. Used to report mouse3 on the release event.
158 private boolean mouse3
;
161 * Cache the cursor visibility value so we only emit the sequence when we
164 private boolean cursorOn
= true;
167 * Cache the last window size to figure out if a TResizeEvent needs to be
170 private TResizeEvent windowResize
= null;
173 * If true, emit wide-char (CJK/Emoji) characters as sixel images.
175 private boolean wideCharImages
= true;
178 * Window width in pixels. Used for sixel support.
180 private int widthPixels
= 640;
183 * Window height in pixels. Used for sixel support.
185 private int heightPixels
= 400;
188 * If true, emit image data via sixel.
190 private boolean sixel
= true;
193 * The sixel palette handler.
195 private SixelPalette palette
= null;
198 * The sixel post-rendered string cache.
200 private ImageCache sixelCache
= null;
203 * Number of colors in the sixel palette. Xterm 335 defines the max as
204 * 1024. Valid values are: 2 (black and white), 256, 512, 1024, and
207 private int sixelPaletteSize
= 1024;
210 * If true, emit image data via iTerm2 image protocol.
212 private boolean iterm2Images
= false;
215 * The iTerm2 post-rendered string cache.
217 private ImageCache iterm2Cache
= null;
220 * Base64 encoder used by iTerm2 images.
222 private java
.util
.Base64
.Encoder base64
= null;
225 * If true, then we changed System.in and need to change it back.
227 private boolean setRawMode
= false;
230 * The terminal's input. If an InputStream is not specified in the
231 * constructor, then this InputStreamReader will be bound to System.in
232 * with UTF-8 encoding.
234 private Reader input
;
237 * The terminal's raw InputStream. If an InputStream is not specified in
238 * the constructor, then this InputReader will be bound to System.in.
239 * This is used by run() to see if bytes are available() before calling
240 * (Reader)input.read().
242 private InputStream inputStream
;
245 * The terminal's output. If an OutputStream is not specified in the
246 * constructor, then this PrintWriter will be bound to System.out with
249 private PrintWriter output
;
252 * The listening object that run() wakes up on new input.
254 private Object listener
;
256 // Colors to map DOS colors to AWT colors.
257 private static java
.awt
.Color MYBLACK
;
258 private static java
.awt
.Color MYRED
;
259 private static java
.awt
.Color MYGREEN
;
260 private static java
.awt
.Color MYYELLOW
;
261 private static java
.awt
.Color MYBLUE
;
262 private static java
.awt
.Color MYMAGENTA
;
263 private static java
.awt
.Color MYCYAN
;
264 private static java
.awt
.Color MYWHITE
;
265 private static java
.awt
.Color MYBOLD_BLACK
;
266 private static java
.awt
.Color MYBOLD_RED
;
267 private static java
.awt
.Color MYBOLD_GREEN
;
268 private static java
.awt
.Color MYBOLD_YELLOW
;
269 private static java
.awt
.Color MYBOLD_BLUE
;
270 private static java
.awt
.Color MYBOLD_MAGENTA
;
271 private static java
.awt
.Color MYBOLD_CYAN
;
272 private static java
.awt
.Color MYBOLD_WHITE
;
275 * SixelPalette is used to manage the conversion of images between 24-bit
276 * RGB color and a palette of sixelPaletteSize colors.
278 private class SixelPalette
{
281 * Color palette for sixel output, sorted low to high.
283 private List
<Integer
> rgbColors
= new ArrayList
<Integer
>();
286 * Map of color palette index for sixel output, from the order it was
287 * generated by makePalette() to rgbColors.
289 private int [] rgbSortedIndex
= new int[sixelPaletteSize
];
292 * The color palette, organized by hue, saturation, and luminance.
293 * This is used for a fast color match.
295 private ArrayList
<ArrayList
<ArrayList
<ColorIdx
>>> hslColors
;
298 * Number of bits for hue.
300 private int hueBits
= -1;
303 * Number of bits for saturation.
305 private int satBits
= -1;
308 * Number of bits for luminance.
310 private int lumBits
= -1;
313 * Step size for hue bins.
315 private int hueStep
= -1;
318 * Step size for saturation bins.
320 private int satStep
= -1;
323 * Cached RGB to HSL result.
325 private int hsl
[] = new int[3];
328 * ColorIdx records a RGB color and its palette index.
330 private class ColorIdx
{
332 * The 24-bit RGB color.
337 * The palette index for this color.
342 * Public constructor.
344 * @param color the 24-bit RGB color
345 * @param index the palette index for this color
347 public ColorIdx(final int color
, final int index
) {
354 * Public constructor.
356 public SixelPalette() {
361 * Find the nearest match for a color in the palette.
363 * @param color the RGB color
364 * @return the index in rgbColors that is closest to color
366 public int matchColor(final int color
) {
371 * matchColor() is a critical performance bottleneck. To make it
372 * decent, we do the following:
374 * 1. Find the nearest two hues that bracket this color.
376 * 2. Find the nearest two saturations that bracket this color.
378 * 3. Iterate within these four bands of luminance values,
379 * returning the closest color by Euclidean distance.
381 * This strategy reduces the search space by about 97%.
383 int red
= (color
>>> 16) & 0xFF;
384 int green
= (color
>>> 8) & 0xFF;
385 int blue
= color
& 0xFF;
387 if (sixelPaletteSize
== 2) {
388 if (((red
* red
) + (green
* green
) + (blue
* blue
)) < 35568) {
397 rgbToHsl(red
, green
, blue
, hsl
);
401 // System.err.printf("%d %d %d\n", hue, sat, lum);
403 double diff
= Double
.MAX_VALUE
;
406 int hue1
= hue
/ (360/hueStep
);
408 if (hue1
>= hslColors
.size() - 1) {
409 // Bracket pure red from above.
410 hue1
= hslColors
.size() - 1;
412 } else if (hue1
== 0) {
413 // Bracket pure red from below.
414 hue2
= hslColors
.size() - 1;
417 for (int hI
= hue1
; hI
!= -1;) {
418 ArrayList
<ArrayList
<ColorIdx
>> sats
= hslColors
.get(hI
);
421 } else if (hI
== hue2
) {
425 int sMin
= (sat
/ satStep
) - 1;
430 } else if (sMin
== sats
.size() - 1) {
435 assert (sMax
- sMin
== 1);
438 // int sMax = sats.size() - 1;
440 for (int sI
= sMin
; sI
<= sMax
; sI
++) {
441 ArrayList
<ColorIdx
> lums
= sats
.get(sI
);
443 // True 3D colorspace match for the remaining values
444 for (ColorIdx c
: lums
) {
445 int rgbColor
= c
.color
;
447 int red2
= (rgbColor
>>> 16) & 0xFF;
448 int green2
= (rgbColor
>>> 8) & 0xFF;
449 int blue2
= rgbColor
& 0xFF;
450 newDiff
+= Math
.pow(red2
- red
, 2);
451 newDiff
+= Math
.pow(green2
- green
, 2);
452 newDiff
+= Math
.pow(blue2
- blue
, 2);
453 if (newDiff
< diff
) {
454 idx
= rgbSortedIndex
[c
.index
];
461 if (((red
* red
) + (green
* green
) + (blue
* blue
)) < diff
) {
462 // Black is a closer match.
464 } else if ((((255 - red
) * (255 - red
)) +
465 ((255 - green
) * (255 - green
)) +
466 ((255 - blue
) * (255 - blue
))) < diff
) {
468 // White is a closer match.
469 idx
= sixelPaletteSize
- 1;
476 * Clamp an int value to [0, 255].
478 * @param x the int value
479 * @return an int between 0 and 255.
481 private int clamp(final int x
) {
492 * Dither an image to a sixelPaletteSize palette. The dithered
493 * image cells will contain indexes into the palette.
495 * @param image the image to dither
496 * @return the dithered image. Every pixel is an index into the
499 public BufferedImage
ditherImage(final BufferedImage image
) {
501 BufferedImage ditheredImage
= new BufferedImage(image
.getWidth(),
502 image
.getHeight(), BufferedImage
.TYPE_INT_ARGB
);
504 int [] rgbArray
= image
.getRGB(0, 0, image
.getWidth(),
505 image
.getHeight(), null, 0, image
.getWidth());
506 ditheredImage
.setRGB(0, 0, image
.getWidth(), image
.getHeight(),
507 rgbArray
, 0, image
.getWidth());
509 for (int imageY
= 0; imageY
< image
.getHeight(); imageY
++) {
510 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
511 int oldPixel
= ditheredImage
.getRGB(imageX
,
513 int colorIdx
= matchColor(oldPixel
);
514 assert (colorIdx
>= 0);
515 assert (colorIdx
< sixelPaletteSize
);
516 int newPixel
= rgbColors
.get(colorIdx
);
517 ditheredImage
.setRGB(imageX
, imageY
, colorIdx
);
519 int oldRed
= (oldPixel
>>> 16) & 0xFF;
520 int oldGreen
= (oldPixel
>>> 8) & 0xFF;
521 int oldBlue
= oldPixel
& 0xFF;
523 int newRed
= (newPixel
>>> 16) & 0xFF;
524 int newGreen
= (newPixel
>>> 8) & 0xFF;
525 int newBlue
= newPixel
& 0xFF;
527 int redError
= (oldRed
- newRed
) / 16;
528 int greenError
= (oldGreen
- newGreen
) / 16;
529 int blueError
= (oldBlue
- newBlue
) / 16;
531 int red
, green
, blue
;
532 if (imageX
< image
.getWidth() - 1) {
533 int pXpY
= ditheredImage
.getRGB(imageX
+ 1, imageY
);
534 red
= ((pXpY
>>> 16) & 0xFF) + (7 * redError
);
535 green
= ((pXpY
>>> 8) & 0xFF) + (7 * greenError
);
536 blue
= ( pXpY
& 0xFF) + (7 * blueError
);
538 green
= clamp(green
);
540 pXpY
= ((red
& 0xFF) << 16);
541 pXpY
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
542 ditheredImage
.setRGB(imageX
+ 1, imageY
, pXpY
);
544 if (imageY
< image
.getHeight() - 1) {
545 int pXpYp
= ditheredImage
.getRGB(imageX
+ 1,
547 red
= ((pXpYp
>>> 16) & 0xFF) + redError
;
548 green
= ((pXpYp
>>> 8) & 0xFF) + greenError
;
549 blue
= ( pXpYp
& 0xFF) + blueError
;
551 green
= clamp(green
);
553 pXpYp
= ((red
& 0xFF) << 16);
554 pXpYp
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
555 ditheredImage
.setRGB(imageX
+ 1, imageY
+ 1, pXpYp
);
557 } else if (imageY
< image
.getHeight() - 1) {
558 int pXmYp
= ditheredImage
.getRGB(imageX
- 1,
560 int pXYp
= ditheredImage
.getRGB(imageX
,
563 red
= ((pXmYp
>>> 16) & 0xFF) + (3 * redError
);
564 green
= ((pXmYp
>>> 8) & 0xFF) + (3 * greenError
);
565 blue
= ( pXmYp
& 0xFF) + (3 * blueError
);
567 green
= clamp(green
);
569 pXmYp
= ((red
& 0xFF) << 16);
570 pXmYp
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
571 ditheredImage
.setRGB(imageX
- 1, imageY
+ 1, pXmYp
);
573 red
= ((pXYp
>>> 16) & 0xFF) + (5 * redError
);
574 green
= ((pXYp
>>> 8) & 0xFF) + (5 * greenError
);
575 blue
= ( pXYp
& 0xFF) + (5 * blueError
);
577 green
= clamp(green
);
579 pXYp
= ((red
& 0xFF) << 16);
580 pXYp
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
581 ditheredImage
.setRGB(imageX
, imageY
+ 1, pXYp
);
583 } // for (int imageY = 0; imageY < image.getHeight(); imageY++)
584 } // for (int imageX = 0; imageX < image.getWidth(); imageX++)
586 return ditheredImage
;
590 * Convert an RGB color to HSL.
592 * @param red red color, between 0 and 255
593 * @param green green color, between 0 and 255
594 * @param blue blue color, between 0 and 255
595 * @param hsl the hsl color as [hue, saturation, luminance]
597 private void rgbToHsl(final int red
, final int green
,
598 final int blue
, final int [] hsl
) {
600 assert ((red
>= 0) && (red
<= 255));
601 assert ((green
>= 0) && (green
<= 255));
602 assert ((blue
>= 0) && (blue
<= 255));
604 double R
= red
/ 255.0;
605 double G
= green
/ 255.0;
606 double B
= blue
/ 255.0;
607 boolean Rmax
= false;
608 boolean Gmax
= false;
609 boolean Bmax
= false;
610 double min
= (R
< G ? R
: G
);
611 min
= (min
< B ? min
: B
);
613 if ((R
>= G
) && (R
>= B
)) {
616 } else if ((G
>= R
) && (G
>= B
)) {
619 } else if ((B
>= G
) && (B
>= R
)) {
624 double L
= (min
+ max
) / 2.0;
629 S
= (max
- min
) / (max
+ min
);
631 S
= (max
- min
) / (2.0 - max
- min
);
635 assert (Gmax
== false);
636 assert (Bmax
== false);
637 H
= (G
- B
) / (max
- min
);
639 assert (Rmax
== false);
640 assert (Bmax
== false);
641 H
= 2.0 + (B
- R
) / (max
- min
);
643 assert (Rmax
== false);
644 assert (Gmax
== false);
645 H
= 4.0 + (R
- G
) / (max
- min
);
650 hsl
[0] = (int) (H
* 60.0);
651 hsl
[1] = (int) (S
* 100.0);
652 hsl
[2] = (int) (L
* 100.0);
654 assert ((hsl
[0] >= 0) && (hsl
[0] <= 360));
655 assert ((hsl
[1] >= 0) && (hsl
[1] <= 100));
656 assert ((hsl
[2] >= 0) && (hsl
[2] <= 100));
660 * Convert a HSL color to RGB.
662 * @param hue hue, between 0 and 359
663 * @param sat saturation, between 0 and 100
664 * @param lum luminance, between 0 and 100
665 * @return the rgb color as 0x00RRGGBB
667 private int hslToRgb(final int hue
, final int sat
, final int lum
) {
668 assert ((hue
>= 0) && (hue
<= 360));
669 assert ((sat
>= 0) && (sat
<= 100));
670 assert ((lum
>= 0) && (lum
<= 100));
672 double S
= sat
/ 100.0;
673 double L
= lum
/ 100.0;
674 double C
= (1.0 - Math
.abs((2.0 * L
) - 1.0)) * S
;
675 double Hp
= hue
/ 60.0;
676 double X
= C
* (1.0 - Math
.abs((Hp
% 2) - 1.0));
683 } else if (Hp
<= 2.0) {
686 } else if (Hp
<= 3.0) {
689 } else if (Hp
<= 4.0) {
692 } else if (Hp
<= 5.0) {
695 } else if (Hp
<= 6.0) {
699 double m
= L
- (C
/ 2.0);
700 int red
= ((int) ((Rp
+ m
) * 255.0)) << 16;
701 int green
= ((int) ((Gp
+ m
) * 255.0)) << 8;
702 int blue
= (int) ((Bp
+ m
) * 255.0);
704 return (red
| green
| blue
);
708 * Create the sixel palette.
710 private void makePalette() {
711 // Generate the sixel palette. Because we have no idea at this
712 // layer which image(s) will be shown, we have to use a common
713 // palette with sixelPaletteSize colors for everything, and
714 // map the BufferedImage colors to their nearest neighbor in RGB
717 if (sixelPaletteSize
== 2) {
719 rgbColors
.add(0xFFFFFF);
720 rgbSortedIndex
[0] = 0;
721 rgbSortedIndex
[1] = 1;
725 // We build a palette using the Hue-Saturation-Luminence model,
726 // with 5+ bits for Hue, 2+ bits for Saturation, and 1+ bit for
727 // Luminance. We convert these colors to 24-bit RGB, sort them
728 // ascending, and steal the first index for pure black and the
729 // last for pure white. The 8-bit final palette favors bright
730 // colors, somewhere between pastel and classic television
731 // technicolor. 9- and 10-bit palettes are more uniform.
733 // Default at 256 colors.
738 assert (sixelPaletteSize
>= 256);
739 assert ((sixelPaletteSize
== 256)
740 || (sixelPaletteSize
== 512)
741 || (sixelPaletteSize
== 1024)
742 || (sixelPaletteSize
== 2048));
744 switch (sixelPaletteSize
) {
761 hueStep
= (int) (Math
.pow(2, hueBits
));
762 satStep
= (int) (100 / Math
.pow(2, satBits
));
763 // 1 bit for luminance: 40 and 70.
768 // 2 bits: 20, 40, 60, 80
773 // 3 bits: 8, 20, 32, 44, 56, 68, 80, 92
779 // System.err.printf("<html><body>\n");
780 // Hue is evenly spaced around the wheel.
781 hslColors
= new ArrayList
<ArrayList
<ArrayList
<ColorIdx
>>>();
783 final boolean DEBUG
= false;
784 ArrayList
<Integer
> rawRgbList
= new ArrayList
<Integer
>();
786 for (int hue
= 0; hue
< (360 - (360 % hueStep
));
787 hue
+= (360/hueStep
)) {
789 ArrayList
<ArrayList
<ColorIdx
>> satList
= null;
790 satList
= new ArrayList
<ArrayList
<ColorIdx
>>();
791 hslColors
.add(satList
);
793 // Saturation is linearly spaced between pastel and pure.
794 for (int sat
= satStep
; sat
<= 100; sat
+= satStep
) {
796 ArrayList
<ColorIdx
> lumList
= new ArrayList
<ColorIdx
>();
797 satList
.add(lumList
);
799 // Luminance brackets the pure color, but leaning toward
801 for (int lum
= lumBegin
; lum
< 100; lum
+= lumStep
) {
803 System.err.printf("<font style = \"color:");
804 System.err.printf("hsl(%d, %d%%, %d%%)",
806 System.err.printf(";\">=</font>\n");
808 int rgbColor
= hslToRgb(hue
, sat
, lum
);
809 rgbColors
.add(rgbColor
);
810 ColorIdx colorIdx
= new ColorIdx(rgbColor
,
811 rgbColors
.size() - 1);
812 lumList
.add(colorIdx
);
814 rawRgbList
.add(rgbColor
);
816 int red
= (rgbColor
>>> 16) & 0xFF;
817 int green
= (rgbColor
>>> 8) & 0xFF;
818 int blue
= rgbColor
& 0xFF;
819 int [] backToHsl
= new int[3];
820 rgbToHsl(red
, green
, blue
, backToHsl
);
821 System
.err
.printf("%d [%d] %d [%d] %d [%d]\n",
822 hue
, backToHsl
[0], sat
, backToHsl
[1],
828 // System.err.printf("\n</body></html>\n");
830 assert (rgbColors
.size() == sixelPaletteSize
);
833 * We need to sort rgbColors, so that toSixel() can know where
834 * BLACK and WHITE are in it. But we also need to be able to
835 * find the sorted values using the old unsorted indexes. So we
836 * will sort it, put all the indexes into a HashMap, and then
837 * build rgbSortedIndex[].
839 Collections
.sort(rgbColors
);
840 HashMap
<Integer
, Integer
> rgbColorIndices
= null;
841 rgbColorIndices
= new HashMap
<Integer
, Integer
>();
842 for (int i
= 0; i
< sixelPaletteSize
; i
++) {
843 rgbColorIndices
.put(rgbColors
.get(i
), i
);
845 for (int i
= 0; i
< sixelPaletteSize
; i
++) {
846 int rawColor
= rawRgbList
.get(i
);
847 rgbSortedIndex
[i
] = rgbColorIndices
.get(rawColor
);
850 for (int i
= 0; i
< sixelPaletteSize
; i
++) {
851 assert (rawRgbList
!= null);
852 int idx
= rgbSortedIndex
[i
];
853 int rgbColor
= rgbColors
.get(idx
);
854 if ((idx
!= 0) && (idx
!= sixelPaletteSize
- 1)) {
856 System.err.printf("%d %06x --> %d %06x\n",
857 i, rawRgbList.get(i), idx, rgbColors.get(idx));
859 assert (rgbColor
== rawRgbList
.get(i
));
864 // Set the dimmest color as true black, and the brightest as true
867 rgbColors
.set(sixelPaletteSize
- 1, 0xFFFFFF);
870 System.err.printf("<html><body>\n");
871 for (Integer rgb: rgbColors) {
872 System.err.printf("<font style = \"color:");
873 System.err.printf("#%06x", rgb);
874 System.err.printf(";\">=</font>\n");
876 System.err.printf("\n</body></html>\n");
882 * Emit the sixel palette.
884 * @param sb the StringBuilder to append to
885 * @param used array of booleans set to true for each color actually
886 * used in this cell, or null to emit the entire palette
887 * @return the string to emit to an ANSI / ECMA-style terminal
889 public String
emitPalette(final StringBuilder sb
,
890 final boolean [] used
) {
892 for (int i
= 0; i
< sixelPaletteSize
; i
++) {
893 if (((used
!= null) && (used
[i
] == true)) || (used
== null)) {
894 int rgbColor
= rgbColors
.get(i
);
895 sb
.append(String
.format("#%d;2;%d;%d;%d", i
,
896 ((rgbColor
>>> 16) & 0xFF) * 100 / 255,
897 ((rgbColor
>>> 8) & 0xFF) * 100 / 255,
898 ( rgbColor
& 0xFF) * 100 / 255));
901 return sb
.toString();
906 * ImageCache is a least-recently-used cache that hangs on to the
907 * post-rendered sixel or iTerm2 string for a particular set of cells.
909 private class ImageCache
{
912 * Maximum size of the cache.
914 private int maxSize
= 100;
917 * The entries stored in the cache.
919 private HashMap
<String
, CacheEntry
> cache
= null;
922 * CacheEntry is one entry in the cache.
924 private class CacheEntry
{
936 * The last time this entry was used.
938 public long millis
= 0;
941 * Public constructor.
943 * @param key the cache entry key
944 * @param data the cache entry data
946 public CacheEntry(final String key
, final String data
) {
949 this.millis
= System
.currentTimeMillis();
954 * Public constructor.
956 * @param maxSize the maximum size of the cache
958 public ImageCache(final int maxSize
) {
959 this.maxSize
= maxSize
;
960 cache
= new HashMap
<String
, CacheEntry
>();
964 * Make a unique key for a list of cells.
966 * @param cells the cells
969 private String
makeKey(final ArrayList
<Cell
> cells
) {
970 StringBuilder sb
= new StringBuilder();
971 for (Cell cell
: cells
) {
972 sb
.append(cell
.hashCode());
974 return sb
.toString();
978 * Get an entry from the cache.
980 * @param cells the list of cells that are the cache key
981 * @return the sixel string representing these cells, or null if this
982 * list of cells is not in the cache
984 public String
get(final ArrayList
<Cell
> cells
) {
985 CacheEntry entry
= cache
.get(makeKey(cells
));
989 entry
.millis
= System
.currentTimeMillis();
994 * Put an entry into the cache.
996 * @param cells the list of cells that are the cache key
997 * @param data the sixel string representing these cells
999 public void put(final ArrayList
<Cell
> cells
, final String data
) {
1000 String key
= makeKey(cells
);
1002 // System.err.println("put() " + key + " size " + cache.size());
1004 assert (!cache
.containsKey(key
));
1006 assert (cache
.size() <= maxSize
);
1007 if (cache
.size() == maxSize
) {
1008 // Cache is at limit, evict oldest entry.
1009 long oldestTime
= Long
.MAX_VALUE
;
1010 String keyToRemove
= null;
1011 for (CacheEntry entry
: cache
.values()) {
1012 if ((entry
.millis
< oldestTime
) || (keyToRemove
== null)) {
1013 keyToRemove
= entry
.key
;
1014 oldestTime
= entry
.millis
;
1018 System.err.println("put() remove key = " + keyToRemove +
1019 " size " + cache.size());
1021 assert (keyToRemove
!= null);
1022 cache
.remove(keyToRemove
);
1024 System.err.println("put() removed, size " + cache.size());
1027 assert (cache
.size() <= maxSize
);
1028 CacheEntry entry
= new CacheEntry(key
, data
);
1029 assert (key
.equals(entry
.key
));
1030 cache
.put(key
, entry
);
1032 System.err.println("put() added key " + key + " " +
1033 " size " + cache.size());
1039 // ------------------------------------------------------------------------
1040 // Constructors -----------------------------------------------------------
1041 // ------------------------------------------------------------------------
1044 * Constructor sets up state for getEvent(). If either windowWidth or
1045 * windowHeight are less than 1, the terminal is not resized.
1047 * @param listener the object this backend needs to wake up when new
1049 * @param input an InputStream connected to the remote user, or null for
1050 * System.in. If System.in is used, then on non-Windows systems it will
1051 * be put in raw mode; closeTerminal() will (blindly!) put System.in in
1052 * cooked mode. input is always converted to a Reader with UTF-8
1054 * @param output an OutputStream connected to the remote user, or null
1055 * for System.out. output is always converted to a Writer with UTF-8
1057 * @param windowWidth the number of text columns to start with
1058 * @param windowHeight the number of text rows to start with
1059 * @throws UnsupportedEncodingException if an exception is thrown when
1060 * creating the InputStreamReader
1062 public ECMA48Terminal(final Object listener
, final InputStream input
,
1063 final OutputStream output
, final int windowWidth
,
1064 final int windowHeight
) throws UnsupportedEncodingException
{
1066 this(listener
, input
, output
);
1068 // Send dtterm/xterm sequences, which will probably not work because
1069 // allowWindowOps is defaulted to false.
1070 if ((windowWidth
> 0) && (windowHeight
> 0)) {
1071 String resizeString
= String
.format("\033[8;%d;%dt", windowHeight
,
1073 this.output
.write(resizeString
);
1074 this.output
.flush();
1079 * Constructor sets up state for getEvent().
1081 * @param listener the object this backend needs to wake up when new
1083 * @param input an InputStream connected to the remote user, or null for
1084 * System.in. If System.in is used, then on non-Windows systems it will
1085 * be put in raw mode; closeTerminal() will (blindly!) put System.in in
1086 * cooked mode. input is always converted to a Reader with UTF-8
1088 * @param output an OutputStream connected to the remote user, or null
1089 * for System.out. output is always converted to a Writer with UTF-8
1091 * @throws UnsupportedEncodingException if an exception is thrown when
1092 * creating the InputStreamReader
1094 public ECMA48Terminal(final Object listener
, final InputStream input
,
1095 final OutputStream output
) throws UnsupportedEncodingException
{
1101 stopReaderThread
= false;
1102 this.listener
= listener
;
1104 if (input
== null) {
1105 // inputStream = System.in;
1106 inputStream
= new FileInputStream(FileDescriptor
.in
);
1110 inputStream
= input
;
1112 this.input
= new InputStreamReader(inputStream
, "UTF-8");
1114 if (input
instanceof SessionInfo
) {
1115 // This is a TelnetInputStream that exposes window size and
1116 // environment variables from the telnet layer.
1117 sessionInfo
= (SessionInfo
) input
;
1119 if (sessionInfo
== null) {
1120 if (input
== null) {
1121 // Reading right off the tty
1122 sessionInfo
= new TTYSessionInfo();
1124 sessionInfo
= new TSessionInfo();
1128 if (output
== null) {
1129 this.output
= new PrintWriter(new OutputStreamWriter(System
.out
,
1132 this.output
= new PrintWriter(new OutputStreamWriter(output
,
1136 // Request xterm report window dimensions in pixels
1137 this.output
.printf("%s", xtermReportWindowPixelDimensions());
1139 // Enable mouse reporting and metaSendsEscape
1140 this.output
.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
1141 this.output
.flush();
1143 // Query the screen size
1144 sessionInfo
.queryWindowSize();
1145 setDimensions(sessionInfo
.getWindowWidth(),
1146 sessionInfo
.getWindowHeight());
1148 // Hang onto the window size
1149 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
1150 sessionInfo
.getWindowWidth(), sessionInfo
.getWindowHeight());
1154 // Spin up the input reader
1155 eventQueue
= new ArrayList
<TInputEvent
>();
1156 readerThread
= new Thread(this);
1157 readerThread
.start();
1160 this.output
.write(clearAll());
1161 this.output
.flush();
1165 * Constructor sets up state for getEvent().
1167 * @param listener the object this backend needs to wake up when new
1169 * @param input the InputStream underlying 'reader'. Its available()
1170 * method is used to determine if reader.read() will block or not.
1171 * @param reader a Reader connected to the remote user.
1172 * @param writer a PrintWriter connected to the remote user.
1173 * @param setRawMode if true, set System.in into raw mode with stty.
1174 * This should in general not be used. It is here solely for Demo3,
1175 * which uses System.in.
1176 * @throws IllegalArgumentException if input, reader, or writer are null.
1178 public ECMA48Terminal(final Object listener
, final InputStream input
,
1179 final Reader reader
, final PrintWriter writer
,
1180 final boolean setRawMode
) {
1182 if (input
== null) {
1183 throw new IllegalArgumentException("InputStream must be specified");
1185 if (reader
== null) {
1186 throw new IllegalArgumentException("Reader must be specified");
1188 if (writer
== null) {
1189 throw new IllegalArgumentException("Writer must be specified");
1195 stopReaderThread
= false;
1196 this.listener
= listener
;
1198 inputStream
= input
;
1199 this.input
= reader
;
1201 if (setRawMode
== true) {
1204 this.setRawMode
= setRawMode
;
1206 if (input
instanceof SessionInfo
) {
1207 // This is a TelnetInputStream that exposes window size and
1208 // environment variables from the telnet layer.
1209 sessionInfo
= (SessionInfo
) input
;
1211 if (sessionInfo
== null) {
1212 if (setRawMode
== true) {
1213 // Reading right off the tty
1214 sessionInfo
= new TTYSessionInfo();
1216 sessionInfo
= new TSessionInfo();
1220 this.output
= writer
;
1222 // Request xterm report window dimensions in pixels
1223 this.output
.printf("%s", xtermReportWindowPixelDimensions());
1225 // Enable mouse reporting and metaSendsEscape
1226 this.output
.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
1227 this.output
.flush();
1229 // Query the screen size
1230 sessionInfo
.queryWindowSize();
1231 setDimensions(sessionInfo
.getWindowWidth(),
1232 sessionInfo
.getWindowHeight());
1234 // Hang onto the window size
1235 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
1236 sessionInfo
.getWindowWidth(), sessionInfo
.getWindowHeight());
1240 // Spin up the input reader
1241 eventQueue
= new ArrayList
<TInputEvent
>();
1242 readerThread
= new Thread(this);
1243 readerThread
.start();
1246 this.output
.write(clearAll());
1247 this.output
.flush();
1251 * Constructor sets up state for getEvent().
1253 * @param listener the object this backend needs to wake up when new
1255 * @param input the InputStream underlying 'reader'. Its available()
1256 * method is used to determine if reader.read() will block or not.
1257 * @param reader a Reader connected to the remote user.
1258 * @param writer a PrintWriter connected to the remote user.
1259 * @throws IllegalArgumentException if input, reader, or writer are null.
1261 public ECMA48Terminal(final Object listener
, final InputStream input
,
1262 final Reader reader
, final PrintWriter writer
) {
1264 this(listener
, input
, reader
, writer
, false);
1267 // ------------------------------------------------------------------------
1268 // LogicalScreen ----------------------------------------------------------
1269 // ------------------------------------------------------------------------
1272 * Set the window title.
1274 * @param title the new title
1277 public void setTitle(final String title
) {
1278 output
.write(getSetTitleString(title
));
1283 * Push the logical screen to the physical device.
1286 public void flushPhysical() {
1287 StringBuilder sb
= new StringBuilder();
1291 && (cursorY
<= height
- 1)
1292 && (cursorX
<= width
- 1)
1295 sb
.append(cursor(true));
1296 sb
.append(gotoXY(cursorX
, cursorY
));
1298 sb
.append(cursor(false));
1301 output
.write(sb
.toString());
1306 * Resize the physical screen to match the logical screen dimensions.
1309 public void resizeToScreen() {
1310 // Send dtterm/xterm sequences, which will probably not work because
1311 // allowWindowOps is defaulted to false.
1312 String resizeString
= String
.format("\033[8;%d;%dt", getHeight(),
1314 this.output
.write(resizeString
);
1315 this.output
.flush();
1318 // ------------------------------------------------------------------------
1319 // TerminalReader ---------------------------------------------------------
1320 // ------------------------------------------------------------------------
1323 * Check if there are events in the queue.
1325 * @return if true, getEvents() has something to return to the backend
1327 public boolean hasEvents() {
1328 synchronized (eventQueue
) {
1329 return (eventQueue
.size() > 0);
1334 * Return any events in the IO queue.
1336 * @param queue list to append new events to
1338 public void getEvents(final List
<TInputEvent
> queue
) {
1339 synchronized (eventQueue
) {
1340 if (eventQueue
.size() > 0) {
1341 synchronized (queue
) {
1342 queue
.addAll(eventQueue
);
1350 * Restore terminal to normal state.
1352 public void closeTerminal() {
1354 // System.err.println("=== closeTerminal() ==="); System.err.flush();
1356 // Tell the reader thread to stop looking at input
1357 stopReaderThread
= true;
1359 readerThread
.join();
1360 } catch (InterruptedException e
) {
1361 if (debugToStderr
) {
1362 e
.printStackTrace();
1366 // Disable mouse reporting and show cursor. Defensive null check
1367 // here in case closeTerminal() is called twice.
1368 if (output
!= null) {
1369 output
.printf("%s%s%s", mouse(false), cursor(true), defaultColor());
1376 // We don't close System.in/out
1378 // Shut down the streams, this should wake up the reader thread
1379 // and make it exit.
1380 if (input
!= null) {
1383 } catch (IOException e
) {
1388 if (output
!= null) {
1396 * Set listener to a different Object.
1398 * @param listener the new listening object that run() wakes up on new
1401 public void setListener(final Object listener
) {
1402 this.listener
= listener
;
1406 * Reload options from System properties.
1408 public void reloadOptions() {
1409 // Permit RGB colors only if externally requested.
1410 if (System
.getProperty("jexer.ECMA48.rgbColor",
1411 "false").equals("true")
1418 // Default to using images for full-width characters.
1419 if (System
.getProperty("jexer.ECMA48.wideCharImages",
1420 "true").equals("true")) {
1421 wideCharImages
= true;
1423 wideCharImages
= false;
1426 // Pull the system properties for sixel output.
1427 if (System
.getProperty("jexer.ECMA48.sixel", "true").equals("true")) {
1434 int paletteSize
= 1024;
1436 paletteSize
= Integer
.parseInt(System
.getProperty(
1437 "jexer.ECMA48.sixelPaletteSize", "1024"));
1438 switch (paletteSize
) {
1444 sixelPaletteSize
= paletteSize
;
1450 } catch (NumberFormatException e
) {
1454 // Default to using images for full-width characters.
1455 if (System
.getProperty("jexer.ECMA48.iTerm2Images",
1456 "false").equals("true")) {
1457 iterm2Images
= true;
1459 iterm2Images
= false;
1462 // Set custom colors
1463 setCustomSystemColors();
1466 // ------------------------------------------------------------------------
1467 // Runnable ---------------------------------------------------------------
1468 // ------------------------------------------------------------------------
1471 * Read function runs on a separate thread.
1474 boolean done
= false;
1475 // available() will often return > 1, so we need to read in chunks to
1477 char [] readBuffer
= new char[128];
1478 List
<TInputEvent
> events
= new ArrayList
<TInputEvent
>();
1480 while (!done
&& !stopReaderThread
) {
1482 // We assume that if inputStream has bytes available, then
1483 // input won't block on read().
1484 int n
= inputStream
.available();
1487 System.err.printf("inputStream.available(): %d\n", n);
1492 if (readBuffer
.length
< n
) {
1493 // The buffer wasn't big enough, make it huger
1494 readBuffer
= new char[readBuffer
.length
* 2];
1497 // System.err.printf("BEFORE read()\n"); System.err.flush();
1499 int rc
= input
.read(readBuffer
, 0, readBuffer
.length
);
1502 System.err.printf("AFTER read() %d\n", rc);
1510 for (int i
= 0; i
< rc
; i
++) {
1511 int ch
= readBuffer
[i
];
1512 processChar(events
, (char)ch
);
1514 getIdleEvents(events
);
1515 if (events
.size() > 0) {
1516 // Add to the queue for the backend thread to
1517 // be able to obtain.
1518 synchronized (eventQueue
) {
1519 eventQueue
.addAll(events
);
1521 if (listener
!= null) {
1522 synchronized (listener
) {
1523 listener
.notifyAll();
1530 getIdleEvents(events
);
1531 if (events
.size() > 0) {
1532 synchronized (eventQueue
) {
1533 eventQueue
.addAll(events
);
1535 if (listener
!= null) {
1536 synchronized (listener
) {
1537 listener
.notifyAll();
1543 if (output
.checkError()) {
1548 // Wait 20 millis for more data
1551 // System.err.println("end while loop"); System.err.flush();
1552 } catch (InterruptedException e
) {
1554 } catch (IOException e
) {
1555 e
.printStackTrace();
1558 } // while ((done == false) && (stopReaderThread == false))
1560 // Pass an event up to TApplication to tell it this Backend is done.
1561 synchronized (eventQueue
) {
1562 eventQueue
.add(new TCommandEvent(cmBackendDisconnect
));
1564 if (listener
!= null) {
1565 synchronized (listener
) {
1566 listener
.notifyAll();
1570 // System.err.println("*** run() exiting..."); System.err.flush();
1573 // ------------------------------------------------------------------------
1574 // ECMA48Terminal ---------------------------------------------------------
1575 // ------------------------------------------------------------------------
1578 * Get the width of a character cell in pixels.
1580 * @return the width in pixels of a character cell
1582 public int getTextWidth() {
1583 return (widthPixels
/ sessionInfo
.getWindowWidth());
1587 * Get the height of a character cell in pixels.
1589 * @return the height in pixels of a character cell
1591 public int getTextHeight() {
1592 return (heightPixels
/ sessionInfo
.getWindowHeight());
1596 * Getter for sessionInfo.
1598 * @return the SessionInfo
1600 public SessionInfo
getSessionInfo() {
1605 * Get the output writer.
1607 * @return the Writer
1609 public PrintWriter
getOutput() {
1614 * Call 'stty' to set cooked mode.
1616 * <p>Actually executes '/bin/sh -c stty sane cooked < /dev/tty'
1618 private void sttyCooked() {
1623 * Call 'stty' to set raw mode.
1625 * <p>Actually executes '/bin/sh -c stty -ignbrk -brkint -parmrk -istrip
1626 * -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten
1627 * -parenb cs8 min 1 < /dev/tty'
1629 private void sttyRaw() {
1634 * Call 'stty' to set raw or cooked mode.
1636 * @param mode if true, set raw mode, otherwise set cooked mode
1638 private void doStty(final boolean mode
) {
1639 String
[] cmdRaw
= {
1640 "/bin/sh", "-c", "stty -ignbrk -brkint -parmrk -istrip -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten -parenb cs8 min 1 < /dev/tty"
1642 String
[] cmdCooked
= {
1643 "/bin/sh", "-c", "stty sane cooked < /dev/tty"
1648 process
= Runtime
.getRuntime().exec(cmdRaw
);
1650 process
= Runtime
.getRuntime().exec(cmdCooked
);
1652 BufferedReader in
= new BufferedReader(new InputStreamReader(process
.getInputStream(), "UTF-8"));
1653 String line
= in
.readLine();
1654 if ((line
!= null) && (line
.length() > 0)) {
1655 System
.err
.println("WEIRD?! Normal output from stty: " + line
);
1658 BufferedReader err
= new BufferedReader(new InputStreamReader(process
.getErrorStream(), "UTF-8"));
1659 line
= err
.readLine();
1660 if ((line
!= null) && (line
.length() > 0)) {
1661 System
.err
.println("Error output from stty: " + line
);
1666 } catch (InterruptedException e
) {
1667 if (debugToStderr
) {
1668 e
.printStackTrace();
1672 int rc
= process
.exitValue();
1674 System
.err
.println("stty returned error code: " + rc
);
1676 } catch (IOException e
) {
1677 e
.printStackTrace();
1684 public void flush() {
1689 * Perform a somewhat-optimal rendering of a line.
1691 * @param y row coordinate. 0 is the top-most row.
1692 * @param sb StringBuilder to write escape sequences to
1693 * @param lastAttr cell attributes from the last call to flushLine
1695 private void flushLine(final int y
, final StringBuilder sb
,
1696 CellAttributes lastAttr
) {
1700 for (int x
= 0; x
< width
; x
++) {
1701 Cell lCell
= logical
[x
][y
];
1702 if (!lCell
.isBlank()) {
1706 // Push textEnd to first column beyond the text area
1710 // reallyCleared = true;
1712 boolean hasImage
= false;
1714 for (int x
= 0; x
< width
; x
++) {
1715 Cell lCell
= logical
[x
][y
];
1716 Cell pCell
= physical
[x
][y
];
1718 if (!lCell
.equals(pCell
) || reallyCleared
) {
1720 if (debugToStderr
) {
1721 System
.err
.printf("\n--\n");
1722 System
.err
.printf(" Y: %d X: %d\n", y
, x
);
1723 System
.err
.printf(" lCell: %s\n", lCell
);
1724 System
.err
.printf(" pCell: %s\n", pCell
);
1725 System
.err
.printf(" ==== \n");
1728 if (lastAttr
== null) {
1729 lastAttr
= new CellAttributes();
1730 sb
.append(normal());
1734 if ((lastX
!= (x
- 1)) || (lastX
== -1)) {
1735 // Advancing at least one cell, or the first gotoXY
1736 sb
.append(gotoXY(x
, y
));
1739 assert (lastAttr
!= null);
1741 if ((x
== textEnd
) && (textEnd
< width
- 1)) {
1742 assert (lCell
.isBlank());
1744 for (int i
= x
; i
< width
; i
++) {
1745 assert (logical
[i
][y
].isBlank());
1746 // Physical is always updated
1747 physical
[i
][y
].reset();
1750 // Clear remaining line
1751 sb
.append(clearRemainingLine());
1756 // Image cell: bypass the rest of the loop, it is not
1758 if ((wideCharImages
&& lCell
.isImage())
1761 && (lCell
.getWidth() == Cell
.Width
.SINGLE
))
1765 // Save the last rendered cell
1768 // Physical is always updated
1769 physical
[x
][y
].setTo(lCell
);
1773 assert ((wideCharImages
&& !lCell
.isImage())
1775 && (!lCell
.isImage()
1777 && (lCell
.getWidth() != Cell
.Width
.SINGLE
)))));
1779 if (!wideCharImages
&& (lCell
.getWidth() == Cell
.Width
.RIGHT
)) {
1785 sb
.append(gotoXY(x
, y
));
1788 // Now emit only the modified attributes
1789 if ((lCell
.getForeColor() != lastAttr
.getForeColor())
1790 && (lCell
.getBackColor() != lastAttr
.getBackColor())
1792 && (lCell
.isBold() == lastAttr
.isBold())
1793 && (lCell
.isReverse() == lastAttr
.isReverse())
1794 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1795 && (lCell
.isBlink() == lastAttr
.isBlink())
1797 // Both colors changed, attributes the same
1798 sb
.append(color(lCell
.isBold(),
1799 lCell
.getForeColor(), lCell
.getBackColor()));
1801 if (debugToStderr
) {
1802 System
.err
.printf("1 Change only fore/back colors\n");
1805 } else if (lCell
.isRGB()
1806 && (lCell
.getForeColorRGB() != lastAttr
.getForeColorRGB())
1807 && (lCell
.getBackColorRGB() != lastAttr
.getBackColorRGB())
1808 && (lCell
.isBold() == lastAttr
.isBold())
1809 && (lCell
.isReverse() == lastAttr
.isReverse())
1810 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1811 && (lCell
.isBlink() == lastAttr
.isBlink())
1813 // Both colors changed, attributes the same
1814 sb
.append(colorRGB(lCell
.getForeColorRGB(),
1815 lCell
.getBackColorRGB()));
1817 if (debugToStderr
) {
1818 System
.err
.printf("1 Change only fore/back colors (RGB)\n");
1820 } else if ((lCell
.getForeColor() != lastAttr
.getForeColor())
1821 && (lCell
.getBackColor() != lastAttr
.getBackColor())
1823 && (lCell
.isBold() != lastAttr
.isBold())
1824 && (lCell
.isReverse() != lastAttr
.isReverse())
1825 && (lCell
.isUnderline() != lastAttr
.isUnderline())
1826 && (lCell
.isBlink() != lastAttr
.isBlink())
1828 // Everything is different
1829 sb
.append(color(lCell
.getForeColor(),
1830 lCell
.getBackColor(),
1831 lCell
.isBold(), lCell
.isReverse(),
1833 lCell
.isUnderline()));
1835 if (debugToStderr
) {
1836 System
.err
.printf("2 Set all attributes\n");
1838 } else if ((lCell
.getForeColor() != lastAttr
.getForeColor())
1839 && (lCell
.getBackColor() == lastAttr
.getBackColor())
1841 && (lCell
.isBold() == lastAttr
.isBold())
1842 && (lCell
.isReverse() == lastAttr
.isReverse())
1843 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1844 && (lCell
.isBlink() == lastAttr
.isBlink())
1847 // Attributes same, foreColor different
1848 sb
.append(color(lCell
.isBold(),
1849 lCell
.getForeColor(), true));
1851 if (debugToStderr
) {
1852 System
.err
.printf("3 Change foreColor\n");
1854 } else if (lCell
.isRGB()
1855 && (lCell
.getForeColorRGB() != lastAttr
.getForeColorRGB())
1856 && (lCell
.getBackColorRGB() == lastAttr
.getBackColorRGB())
1857 && (lCell
.getForeColorRGB() >= 0)
1858 && (lCell
.getBackColorRGB() >= 0)
1859 && (lCell
.isBold() == lastAttr
.isBold())
1860 && (lCell
.isReverse() == lastAttr
.isReverse())
1861 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1862 && (lCell
.isBlink() == lastAttr
.isBlink())
1864 // Attributes same, foreColor different
1865 sb
.append(colorRGB(lCell
.getForeColorRGB(), true));
1867 if (debugToStderr
) {
1868 System
.err
.printf("3 Change foreColor (RGB)\n");
1870 } else if ((lCell
.getForeColor() == lastAttr
.getForeColor())
1871 && (lCell
.getBackColor() != lastAttr
.getBackColor())
1873 && (lCell
.isBold() == lastAttr
.isBold())
1874 && (lCell
.isReverse() == lastAttr
.isReverse())
1875 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1876 && (lCell
.isBlink() == lastAttr
.isBlink())
1878 // Attributes same, backColor different
1879 sb
.append(color(lCell
.isBold(),
1880 lCell
.getBackColor(), false));
1882 if (debugToStderr
) {
1883 System
.err
.printf("4 Change backColor\n");
1885 } else if (lCell
.isRGB()
1886 && (lCell
.getForeColorRGB() == lastAttr
.getForeColorRGB())
1887 && (lCell
.getBackColorRGB() != lastAttr
.getBackColorRGB())
1888 && (lCell
.isBold() == lastAttr
.isBold())
1889 && (lCell
.isReverse() == lastAttr
.isReverse())
1890 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1891 && (lCell
.isBlink() == lastAttr
.isBlink())
1893 // Attributes same, foreColor different
1894 sb
.append(colorRGB(lCell
.getBackColorRGB(), false));
1896 if (debugToStderr
) {
1897 System
.err
.printf("4 Change backColor (RGB)\n");
1899 } else if ((lCell
.getForeColor() == lastAttr
.getForeColor())
1900 && (lCell
.getBackColor() == lastAttr
.getBackColor())
1901 && (lCell
.getForeColorRGB() == lastAttr
.getForeColorRGB())
1902 && (lCell
.getBackColorRGB() == lastAttr
.getBackColorRGB())
1903 && (lCell
.isBold() == lastAttr
.isBold())
1904 && (lCell
.isReverse() == lastAttr
.isReverse())
1905 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1906 && (lCell
.isBlink() == lastAttr
.isBlink())
1909 // All attributes the same, just print the char
1912 if (debugToStderr
) {
1913 System
.err
.printf("5 Only emit character\n");
1916 // Just reset everything again
1917 if (!lCell
.isRGB()) {
1918 sb
.append(color(lCell
.getForeColor(),
1919 lCell
.getBackColor(),
1923 lCell
.isUnderline()));
1925 if (debugToStderr
) {
1926 System
.err
.printf("6 Change all attributes\n");
1929 sb
.append(colorRGB(lCell
.getForeColorRGB(),
1930 lCell
.getBackColorRGB(),
1934 lCell
.isUnderline()));
1935 if (debugToStderr
) {
1936 System
.err
.printf("6 Change all attributes (RGB)\n");
1941 // Emit the character
1943 // Don't emit the right-half of full-width chars.
1945 && (lCell
.getWidth() != Cell
.Width
.RIGHT
))
1947 sb
.append(Character
.toChars(lCell
.getChar()));
1950 // Save the last rendered cell
1952 lastAttr
.setTo(lCell
);
1954 // Physical is always updated
1955 physical
[x
][y
].setTo(lCell
);
1957 } // if (!lCell.equals(pCell) || (reallyCleared == true))
1959 } // for (int x = 0; x < width; x++)
1963 * Render the screen to a string that can be emitted to something that
1964 * knows how to process ECMA-48/ANSI X3.64 escape sequences.
1966 * @param sb StringBuilder to write escape sequences to
1967 * @return escape sequences string that provides the updates to the
1970 private String
flushString(final StringBuilder sb
) {
1971 CellAttributes attr
= null;
1973 if (reallyCleared
) {
1974 attr
= new CellAttributes();
1975 sb
.append(clearAll());
1979 * For images support, draw all of the image output first, and then
1980 * draw everything else afterwards. This works OK, but performance
1981 * is still a drag on larger pictures.
1983 for (int y
= 0; y
< height
; y
++) {
1984 for (int x
= 0; x
< width
; x
++) {
1985 // If physical had non-image data that is now image data, the
1986 // entire row must be redrawn.
1987 Cell lCell
= logical
[x
][y
];
1988 Cell pCell
= physical
[x
][y
];
1989 if (lCell
.isImage() && !pCell
.isImage()) {
1995 for (int y
= 0; y
< height
; y
++) {
1996 for (int x
= 0; x
< width
; x
++) {
1997 Cell lCell
= logical
[x
][y
];
1998 Cell pCell
= physical
[x
][y
];
2000 if (!lCell
.isImage()
2002 && (lCell
.getWidth() != Cell
.Width
.SINGLE
))
2009 while ((right
< width
)
2010 && (logical
[right
][y
].isImage())
2011 && (!logical
[right
][y
].equals(physical
[right
][y
])
2016 ArrayList
<Cell
> cellsToDraw
= new ArrayList
<Cell
>();
2017 for (int i
= 0; i
< (right
- x
); i
++) {
2018 assert (logical
[x
+ i
][y
].isImage());
2019 cellsToDraw
.add(logical
[x
+ i
][y
]);
2021 // Physical is always updated.
2022 physical
[x
+ i
][y
].setTo(lCell
);
2024 if (cellsToDraw
.size() > 0) {
2026 sb
.append(toIterm2Image(x
, y
, cellsToDraw
));
2028 sb
.append(toSixel(x
, y
, cellsToDraw
));
2036 // Draw the text part now.
2037 for (int y
= 0; y
< height
; y
++) {
2038 flushLine(y
, sb
, attr
);
2041 reallyCleared
= false;
2043 String result
= sb
.toString();
2044 if (debugToStderr
) {
2045 System
.err
.printf("flushString(): %s\n", result
);
2051 * Reset keyboard/mouse input parser.
2053 private void resetParser() {
2054 state
= ParseState
.GROUND
;
2055 params
= new ArrayList
<String
>();
2061 * Produce a control character or one of the special ones (ENTER, TAB,
2064 * @param ch Unicode code point
2065 * @param alt if true, set alt on the TKeypress
2066 * @return one TKeypress event, either a control character (e.g. isKey ==
2067 * false, ch == 'A', ctrl == true), or a special key (e.g. isKey == true,
2070 private TKeypressEvent
controlChar(final char ch
, final boolean alt
) {
2071 // System.err.printf("controlChar: %02x\n", ch);
2075 // Carriage return --> ENTER
2076 return new TKeypressEvent(kbEnter
, alt
, false, false);
2078 // Linefeed --> ENTER
2079 return new TKeypressEvent(kbEnter
, alt
, false, false);
2082 return new TKeypressEvent(kbEsc
, alt
, false, false);
2085 return new TKeypressEvent(kbTab
, alt
, false, false);
2087 // Make all other control characters come back as the alphabetic
2088 // character with the ctrl field set. So SOH would be 'A' +
2090 return new TKeypressEvent(false, 0, (char)(ch
+ 0x40),
2096 * Produce special key from CSI Pn ; Pm ; ... ~
2098 * @return one KEYPRESS event representing a special key
2100 private TInputEvent
csiFnKey() {
2102 if (params
.size() > 0) {
2103 key
= Integer
.parseInt(params
.get(0));
2105 boolean alt
= false;
2106 boolean ctrl
= false;
2107 boolean shift
= false;
2108 if (params
.size() > 1) {
2109 shift
= csiIsShift(params
.get(1));
2110 alt
= csiIsAlt(params
.get(1));
2111 ctrl
= csiIsCtrl(params
.get(1));
2116 return new TKeypressEvent(kbHome
, alt
, ctrl
, shift
);
2118 return new TKeypressEvent(kbIns
, alt
, ctrl
, shift
);
2120 return new TKeypressEvent(kbDel
, alt
, ctrl
, shift
);
2122 return new TKeypressEvent(kbEnd
, alt
, ctrl
, shift
);
2124 return new TKeypressEvent(kbPgUp
, alt
, ctrl
, shift
);
2126 return new TKeypressEvent(kbPgDn
, alt
, ctrl
, shift
);
2128 return new TKeypressEvent(kbF5
, alt
, ctrl
, shift
);
2130 return new TKeypressEvent(kbF6
, alt
, ctrl
, shift
);
2132 return new TKeypressEvent(kbF7
, alt
, ctrl
, shift
);
2134 return new TKeypressEvent(kbF8
, alt
, ctrl
, shift
);
2136 return new TKeypressEvent(kbF9
, alt
, ctrl
, shift
);
2138 return new TKeypressEvent(kbF10
, alt
, ctrl
, shift
);
2140 return new TKeypressEvent(kbF11
, alt
, ctrl
, shift
);
2142 return new TKeypressEvent(kbF12
, alt
, ctrl
, shift
);
2150 * Produce mouse events based on "Any event tracking" and UTF-8
2152 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
2154 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
2156 private TInputEvent
parseMouse() {
2157 int buttons
= params
.get(0).charAt(0) - 32;
2158 int x
= params
.get(0).charAt(1) - 32 - 1;
2159 int y
= params
.get(0).charAt(2) - 32 - 1;
2161 // Clamp X and Y to the physical screen coordinates.
2162 if (x
>= windowResize
.getWidth()) {
2163 x
= windowResize
.getWidth() - 1;
2165 if (y
>= windowResize
.getHeight()) {
2166 y
= windowResize
.getHeight() - 1;
2169 TMouseEvent
.Type eventType
= TMouseEvent
.Type
.MOUSE_DOWN
;
2170 boolean eventMouse1
= false;
2171 boolean eventMouse2
= false;
2172 boolean eventMouse3
= false;
2173 boolean eventMouseWheelUp
= false;
2174 boolean eventMouseWheelDown
= false;
2176 // System.err.printf("buttons: %04x\r\n", buttons);
2193 if (!mouse1
&& !mouse2
&& !mouse3
) {
2194 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2196 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
2213 // Dragging with mouse1 down
2216 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2220 // Dragging with mouse2 down
2223 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2227 // Dragging with mouse3 down
2230 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2234 // Dragging with mouse2 down after wheelUp
2237 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2241 // Dragging with mouse2 down after wheelDown
2244 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2248 eventMouseWheelUp
= true;
2252 eventMouseWheelDown
= true;
2256 // Unknown, just make it motion
2257 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2260 return new TMouseEvent(eventType
, x
, y
, x
, y
,
2261 eventMouse1
, eventMouse2
, eventMouse3
,
2262 eventMouseWheelUp
, eventMouseWheelDown
);
2266 * Produce mouse events based on "Any event tracking" and SGR
2268 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
2270 * @param release if true, this was a release ('m')
2271 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
2273 private TInputEvent
parseMouseSGR(final boolean release
) {
2274 // SGR extended coordinates - mode 1006
2275 if (params
.size() < 3) {
2276 // Invalid position, bail out.
2279 int buttons
= Integer
.parseInt(params
.get(0));
2280 int x
= Integer
.parseInt(params
.get(1)) - 1;
2281 int y
= Integer
.parseInt(params
.get(2)) - 1;
2283 // Clamp X and Y to the physical screen coordinates.
2284 if (x
>= windowResize
.getWidth()) {
2285 x
= windowResize
.getWidth() - 1;
2287 if (y
>= windowResize
.getHeight()) {
2288 y
= windowResize
.getHeight() - 1;
2291 TMouseEvent
.Type eventType
= TMouseEvent
.Type
.MOUSE_DOWN
;
2292 boolean eventMouse1
= false;
2293 boolean eventMouse2
= false;
2294 boolean eventMouse3
= false;
2295 boolean eventMouseWheelUp
= false;
2296 boolean eventMouseWheelDown
= false;
2299 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
2313 // Motion only, no buttons down
2314 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2318 // Dragging with mouse1 down
2320 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2324 // Dragging with mouse2 down
2326 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2330 // Dragging with mouse3 down
2332 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2336 // Dragging with mouse2 down after wheelUp
2338 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2342 // Dragging with mouse2 down after wheelDown
2344 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2348 eventMouseWheelUp
= true;
2352 eventMouseWheelDown
= true;
2356 // Unknown, bail out
2359 return new TMouseEvent(eventType
, x
, y
, x
, y
,
2360 eventMouse1
, eventMouse2
, eventMouse3
,
2361 eventMouseWheelUp
, eventMouseWheelDown
);
2365 * Return any events in the IO queue due to timeout.
2367 * @param queue list to append new events to
2369 private void getIdleEvents(final List
<TInputEvent
> queue
) {
2370 long nowTime
= System
.currentTimeMillis();
2372 // Check for new window size
2373 long windowSizeDelay
= nowTime
- windowSizeTime
;
2374 if (windowSizeDelay
> 1000) {
2375 int oldTextWidth
= getTextWidth();
2376 int oldTextHeight
= getTextHeight();
2378 sessionInfo
.queryWindowSize();
2379 int newWidth
= sessionInfo
.getWindowWidth();
2380 int newHeight
= sessionInfo
.getWindowHeight();
2382 if ((newWidth
!= windowResize
.getWidth())
2383 || (newHeight
!= windowResize
.getHeight())
2386 // Request xterm report window dimensions in pixels again.
2387 // Between now and then, ensure that the reported text cell
2388 // size is the same by setting widthPixels and heightPixels
2389 // to match the new dimensions.
2390 widthPixels
= oldTextWidth
* newWidth
;
2391 heightPixels
= oldTextHeight
* newHeight
;
2393 if (debugToStderr
) {
2394 System
.err
.println("Screen size changed, old size " +
2396 System
.err
.println(" new size " +
2397 newWidth
+ " x " + newHeight
);
2398 System
.err
.println(" old pixels " +
2399 oldTextWidth
+ " x " + oldTextHeight
);
2400 System
.err
.println(" new pixels " +
2401 getTextWidth() + " x " + getTextHeight());
2404 this.output
.printf("%s", xtermReportWindowPixelDimensions());
2405 this.output
.flush();
2407 TResizeEvent event
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
2408 newWidth
, newHeight
);
2409 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
2410 newWidth
, newHeight
);
2413 windowSizeTime
= nowTime
;
2416 // ESCDELAY type timeout
2417 if (state
== ParseState
.ESCAPE
) {
2418 long escDelay
= nowTime
- escapeTime
;
2419 if (escDelay
> 100) {
2420 // After 0.1 seconds, assume a true escape character
2421 queue
.add(controlChar((char)0x1B, false));
2428 * Returns true if the CSI parameter for a keyboard command means that
2431 private boolean csiIsShift(final String x
) {
2443 * Returns true if the CSI parameter for a keyboard command means that
2446 private boolean csiIsAlt(final String x
) {
2458 * Returns true if the CSI parameter for a keyboard command means that
2461 private boolean csiIsCtrl(final String x
) {
2473 * Parses the next character of input to see if an InputEvent is
2476 * @param events list to append new events to
2477 * @param ch Unicode code point
2479 private void processChar(final List
<TInputEvent
> events
, final char ch
) {
2481 // ESCDELAY type timeout
2482 long nowTime
= System
.currentTimeMillis();
2483 if (state
== ParseState
.ESCAPE
) {
2484 long escDelay
= nowTime
- escapeTime
;
2485 if (escDelay
> 250) {
2486 // After 0.25 seconds, assume a true escape character
2487 events
.add(controlChar((char)0x1B, false));
2493 boolean ctrl
= false;
2494 boolean alt
= false;
2495 boolean shift
= false;
2497 // System.err.printf("state: %s ch %c\r\n", state, ch);
2503 state
= ParseState
.ESCAPE
;
2504 escapeTime
= nowTime
;
2509 // Control character
2510 events
.add(controlChar(ch
, false));
2517 events
.add(new TKeypressEvent(false, 0, ch
,
2518 false, false, false));
2527 // ALT-Control character
2528 events
.add(controlChar(ch
, true));
2534 // This will be one of the function keys
2535 state
= ParseState
.ESCAPE_INTERMEDIATE
;
2539 // '[' goes to CSI_ENTRY
2541 state
= ParseState
.CSI_ENTRY
;
2545 // Everything else is assumed to be Alt-keystroke
2546 if ((ch
>= 'A') && (ch
<= 'Z')) {
2550 events
.add(new TKeypressEvent(false, 0, ch
, alt
, ctrl
, shift
));
2554 case ESCAPE_INTERMEDIATE
:
2555 if ((ch
>= 'P') && (ch
<= 'S')) {
2559 events
.add(new TKeypressEvent(kbF1
));
2562 events
.add(new TKeypressEvent(kbF2
));
2565 events
.add(new TKeypressEvent(kbF3
));
2568 events
.add(new TKeypressEvent(kbF4
));
2577 // Unknown keystroke, ignore
2582 // Numbers - parameter values
2583 if ((ch
>= '0') && (ch
<= '9')) {
2584 params
.set(params
.size() - 1,
2585 params
.get(params
.size() - 1) + ch
);
2586 state
= ParseState
.CSI_PARAM
;
2589 // Parameter separator
2595 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
2599 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
2604 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
2609 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
2614 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
2619 events
.add(new TKeypressEvent(kbHome
));
2624 events
.add(new TKeypressEvent(kbEnd
));
2628 // CBT - Cursor backward X tab stops (default 1)
2629 events
.add(new TKeypressEvent(kbBackTab
));
2634 state
= ParseState
.MOUSE
;
2637 // Mouse position, SGR (1006) coordinates
2638 state
= ParseState
.MOUSE_SGR
;
2645 // Unknown keystroke, ignore
2650 // Numbers - parameter values
2651 if ((ch
>= '0') && (ch
<= '9')) {
2652 params
.set(params
.size() - 1,
2653 params
.get(params
.size() - 1) + ch
);
2656 // Parameter separator
2664 // Generate a mouse press event
2665 TInputEvent event
= parseMouseSGR(false);
2666 if (event
!= null) {
2672 // Generate a mouse release event
2673 event
= parseMouseSGR(true);
2674 if (event
!= null) {
2683 // Unknown keystroke, ignore
2688 // Numbers - parameter values
2689 if ((ch
>= '0') && (ch
<= '9')) {
2690 params
.set(params
.size() - 1,
2691 params
.get(params
.size() - 1) + ch
);
2692 state
= ParseState
.CSI_PARAM
;
2695 // Parameter separator
2702 events
.add(csiFnKey());
2707 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
2711 if (params
.size() > 1) {
2712 shift
= csiIsShift(params
.get(1));
2713 alt
= csiIsAlt(params
.get(1));
2714 ctrl
= csiIsCtrl(params
.get(1));
2716 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
2721 if (params
.size() > 1) {
2722 shift
= csiIsShift(params
.get(1));
2723 alt
= csiIsAlt(params
.get(1));
2724 ctrl
= csiIsCtrl(params
.get(1));
2726 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
2731 if (params
.size() > 1) {
2732 shift
= csiIsShift(params
.get(1));
2733 alt
= csiIsAlt(params
.get(1));
2734 ctrl
= csiIsCtrl(params
.get(1));
2736 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
2741 if (params
.size() > 1) {
2742 shift
= csiIsShift(params
.get(1));
2743 alt
= csiIsAlt(params
.get(1));
2744 ctrl
= csiIsCtrl(params
.get(1));
2746 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
2751 if (params
.size() > 1) {
2752 shift
= csiIsShift(params
.get(1));
2753 alt
= csiIsAlt(params
.get(1));
2754 ctrl
= csiIsCtrl(params
.get(1));
2756 events
.add(new TKeypressEvent(kbHome
, alt
, ctrl
, shift
));
2761 if (params
.size() > 1) {
2762 shift
= csiIsShift(params
.get(1));
2763 alt
= csiIsAlt(params
.get(1));
2764 ctrl
= csiIsCtrl(params
.get(1));
2766 events
.add(new TKeypressEvent(kbEnd
, alt
, ctrl
, shift
));
2771 if ((params
.size() > 2) && (params
.get(0).equals("4"))) {
2772 if (debugToStderr
) {
2773 System
.err
.printf("windowOp pixels: " +
2774 "height %s width %s\n",
2775 params
.get(1), params
.get(2));
2778 widthPixels
= Integer
.parseInt(params
.get(2));
2779 heightPixels
= Integer
.parseInt(params
.get(1));
2780 } catch (NumberFormatException e
) {
2781 if (debugToStderr
) {
2782 e
.printStackTrace();
2785 if (widthPixels
<= 0) {
2788 if (heightPixels
<= 0) {
2792 if ((params
.size() > 2) && (params
.get(0).equals("6"))) {
2793 if (debugToStderr
) {
2794 System
.err
.printf("windowOp text cell pixels: " +
2795 "height %s width %s\n",
2796 params
.get(1), params
.get(2));
2799 widthPixels
= width
* Integer
.parseInt(params
.get(2));
2800 heightPixels
= height
* Integer
.parseInt(params
.get(1));
2801 } catch (NumberFormatException e
) {
2802 if (debugToStderr
) {
2803 e
.printStackTrace();
2806 if (widthPixels
<= 0) {
2809 if (heightPixels
<= 0) {
2820 // Unknown keystroke, ignore
2825 params
.set(0, params
.get(params
.size() - 1) + ch
);
2826 if (params
.get(0).length() == 3) {
2827 // We have enough to generate a mouse event
2828 events
.add(parseMouse());
2837 // This "should" be impossible to reach
2842 * Request (u)xterm to report the current window size dimensions.
2844 * @return the string to emit to xterm
2846 private String
xtermReportWindowPixelDimensions() {
2847 // We will ask for both window and text cell dimensions, and
2848 // hopefully one of them will work.
2849 return "\033[14t\033[16t";
2853 * Tell (u)xterm that we want alt- keystrokes to send escape + character
2854 * rather than set the 8th bit. Anyone who wants UTF8 should want this
2857 * @param on if true, enable metaSendsEscape
2858 * @return the string to emit to xterm
2860 private String
xtermMetaSendsEscape(final boolean on
) {
2862 return "\033[?1036h\033[?1034l";
2864 return "\033[?1036l";
2868 * Create an xterm OSC sequence to change the window title.
2870 * @param title the new title
2871 * @return the string to emit to xterm
2873 private String
getSetTitleString(final String title
) {
2874 return "\033]2;" + title
+ "\007";
2877 // ------------------------------------------------------------------------
2878 // Sixel output support ---------------------------------------------------
2879 // ------------------------------------------------------------------------
2882 * Get the number of colors in the sixel palette.
2884 * @return the palette size
2886 public int getSixelPaletteSize() {
2887 return sixelPaletteSize
;
2891 * Set the number of colors in the sixel palette.
2893 * @param paletteSize the new palette size
2895 public void setSixelPaletteSize(final int paletteSize
) {
2896 if (paletteSize
== sixelPaletteSize
) {
2900 switch (paletteSize
) {
2908 throw new IllegalArgumentException("Unsupported sixel palette " +
2909 " size: " + paletteSize
);
2912 // Don't step on the screen refresh thread.
2913 synchronized (this) {
2914 sixelPaletteSize
= paletteSize
;
2922 * Start a sixel string for display one row's worth of bitmap data.
2924 * @param x column coordinate. 0 is the left-most column.
2925 * @param y row coordinate. 0 is the top-most row.
2926 * @return the string to emit to an ANSI / ECMA-style terminal
2928 private String
startSixel(final int x
, final int y
) {
2929 StringBuilder sb
= new StringBuilder();
2931 assert (sixel
== true);
2934 sb
.append(gotoXY(x
, y
));
2937 sb
.append("\033Pq");
2939 if (palette
== null) {
2940 palette
= new SixelPalette();
2943 return sb
.toString();
2947 * End a sixel string for display one row's worth of bitmap data.
2949 * @return the string to emit to an ANSI / ECMA-style terminal
2951 private String
endSixel() {
2952 assert (sixel
== true);
2959 * Create a sixel string representing a row of several cells containing
2962 * @param x column coordinate. 0 is the left-most column.
2963 * @param y row coordinate. 0 is the top-most row.
2964 * @param cells the cells containing the bitmap data
2965 * @return the string to emit to an ANSI / ECMA-style terminal
2967 private String
toSixel(final int x
, final int y
,
2968 final ArrayList
<Cell
> cells
) {
2970 StringBuilder sb
= new StringBuilder();
2972 assert (cells
!= null);
2973 assert (cells
.size() > 0);
2974 assert (cells
.get(0).getImage() != null);
2976 if (sixel
== false) {
2977 sb
.append(normal());
2978 sb
.append(gotoXY(x
, y
));
2979 for (int i
= 0; i
< cells
.size(); i
++) {
2982 return sb
.toString();
2985 if (sixelCache
== null) {
2986 sixelCache
= new ImageCache(height
* 10);
2989 // Save and get rows to/from the cache that do NOT have inverted
2991 boolean saveInCache
= true;
2992 for (Cell cell
: cells
) {
2993 if (cell
.isInvertedImage()) {
2994 saveInCache
= false;
2998 String cachedResult
= sixelCache
.get(cells
);
2999 if (cachedResult
!= null) {
3000 // System.err.println("CACHE HIT");
3001 sb
.append(startSixel(x
, y
));
3002 sb
.append(cachedResult
);
3003 sb
.append(endSixel());
3004 return sb
.toString();
3006 // System.err.println("CACHE MISS");
3009 int imageWidth
= cells
.get(0).getImage().getWidth();
3010 int imageHeight
= cells
.get(0).getImage().getHeight();
3012 // cells.get(x).getImage() has a dithered bitmap containing indexes
3013 // into the color palette. Piece these together into one larger
3014 // image for final rendering.
3016 int fullWidth
= cells
.size() * getTextWidth();
3017 int fullHeight
= getTextHeight();
3018 for (int i
= 0; i
< cells
.size(); i
++) {
3019 totalWidth
+= cells
.get(i
).getImage().getWidth();
3022 BufferedImage image
= new BufferedImage(fullWidth
,
3023 fullHeight
, BufferedImage
.TYPE_INT_ARGB
);
3026 for (int i
= 0; i
< cells
.size() - 1; i
++) {
3027 int tileWidth
= Math
.min(cells
.get(i
).getImage().getWidth(),
3029 int tileHeight
= Math
.min(cells
.get(i
).getImage().getHeight(),
3031 if (false && cells
.get(i
).isInvertedImage()) {
3032 // I used to put an all-white cell over the cursor, don't do
3034 rgbArray
= new int[imageWidth
* imageHeight
];
3035 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3036 rgbArray
[j
] = 0xFFFFFF;
3040 rgbArray
= cells
.get(i
).getImage().getRGB(0, 0,
3041 tileWidth
, tileHeight
, null, 0, tileWidth
);
3042 } catch (Exception e
) {
3043 throw new RuntimeException("image " + imageWidth
+ "x" +
3045 "tile " + tileWidth
+ "x" +
3047 " cells.get(i).getImage() " +
3048 cells
.get(i
).getImage() +
3050 " fullWidth " + fullWidth
+
3051 " fullHeight " + fullHeight
, e
);
3056 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
3057 i * imageWidth, 0, imageWidth, imageHeight,
3059 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
3060 fullWidth, fullHeight, cells.size(), getTextWidth());
3063 image
.setRGB(i
* imageWidth
, 0, tileWidth
, tileHeight
,
3064 rgbArray
, 0, tileWidth
);
3065 if (tileHeight
< fullHeight
) {
3066 int backgroundColor
= cells
.get(i
).getBackground().getRGB();
3067 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3068 for (int imageY
= imageHeight
; imageY
< fullHeight
;
3071 image
.setRGB(imageX
, imageY
, backgroundColor
);
3076 totalWidth
-= ((cells
.size() - 1) * imageWidth
);
3077 if (false && cells
.get(cells
.size() - 1).isInvertedImage()) {
3078 // I used to put an all-white cell over the cursor, don't do that
3080 rgbArray
= new int[totalWidth
* imageHeight
];
3081 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3082 rgbArray
[j
] = 0xFFFFFF;
3086 rgbArray
= cells
.get(cells
.size() - 1).getImage().getRGB(0, 0,
3087 totalWidth
, imageHeight
, null, 0, totalWidth
);
3088 } catch (Exception e
) {
3089 throw new RuntimeException("image " + imageWidth
+ "x" +
3090 imageHeight
+ " cells.get(cells.size() - 1).getImage() " +
3091 cells
.get(cells
.size() - 1).getImage(), e
);
3094 image
.setRGB((cells
.size() - 1) * imageWidth
, 0, totalWidth
,
3095 imageHeight
, rgbArray
, 0, totalWidth
);
3097 if (totalWidth
< getTextWidth()) {
3098 int backgroundColor
= cells
.get(cells
.size() - 1).getBackground().getRGB();
3100 for (int imageX
= image
.getWidth() - totalWidth
;
3101 imageX
< image
.getWidth(); imageX
++) {
3103 for (int imageY
= 0; imageY
< fullHeight
; imageY
++) {
3104 image
.setRGB(imageX
, imageY
, backgroundColor
);
3109 // Dither the image. It is ok to lose the original here.
3110 if (palette
== null) {
3111 palette
= new SixelPalette();
3113 image
= palette
.ditherImage(image
);
3115 // Collect the raster information
3116 int rasterHeight
= 0;
3117 int rasterWidth
= image
.getWidth();
3119 // Emit the palette, but only for the colors actually used by these
3121 boolean [] usedColors
= new boolean[sixelPaletteSize
];
3122 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3123 for (int imageY
= 0; imageY
< image
.getHeight(); imageY
++) {
3124 usedColors
[image
.getRGB(imageX
, imageY
)] = true;
3127 palette
.emitPalette(sb
, usedColors
);
3129 // Render the entire row of cells.
3130 for (int currentRow
= 0; currentRow
< fullHeight
; currentRow
+= 6) {
3131 int [][] sixels
= new int[image
.getWidth()][6];
3133 // See which colors are actually used in this band of sixels.
3134 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3135 for (int imageY
= 0;
3136 (imageY
< 6) && (imageY
+ currentRow
< fullHeight
);
3139 int colorIdx
= image
.getRGB(imageX
, imageY
+ currentRow
);
3140 assert (colorIdx
>= 0);
3141 assert (colorIdx
< sixelPaletteSize
);
3143 sixels
[imageX
][imageY
] = colorIdx
;
3147 for (int i
= 0; i
< sixelPaletteSize
; i
++) {
3148 boolean isUsed
= false;
3149 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3150 for (int j
= 0; j
< 6; j
++) {
3151 if (sixels
[imageX
][j
] == i
) {
3156 if (isUsed
== false) {
3160 // Set to the beginning of scan line for the next set of
3161 // colored pixels, and select the color.
3162 sb
.append(String
.format("$#%d", i
));
3165 int oldDataCount
= 0;
3166 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3168 // Add up all the pixels that match this color.
3171 (j
< 6) && (currentRow
+ j
< fullHeight
);
3174 if (sixels
[imageX
][j
] == i
) {
3195 if ((currentRow
+ j
+ 1) > rasterHeight
) {
3196 rasterHeight
= currentRow
+ j
+ 1;
3204 if (data
== oldData
) {
3207 if (oldDataCount
== 1) {
3208 sb
.append((char) oldData
);
3209 } else if (oldDataCount
> 1) {
3210 sb
.append(String
.format("!%d", oldDataCount
));
3211 sb
.append((char) oldData
);
3217 } // for (int imageX = 0; imageX < image.getWidth(); imageX++)
3219 // Emit the last sequence.
3220 if (oldDataCount
== 1) {
3221 sb
.append((char) oldData
);
3222 } else if (oldDataCount
> 1) {
3223 sb
.append(String
.format("!%d", oldDataCount
));
3224 sb
.append((char) oldData
);
3227 } // for (int i = 0; i < sixelPaletteSize; i++)
3229 // Advance to the next scan line.
3232 } // for (int currentRow = 0; currentRow < imageHeight; currentRow += 6)
3234 // Kill the very last "-", because it is unnecessary.
3235 sb
.deleteCharAt(sb
.length() - 1);
3237 // Add the raster information
3238 sb
.insert(0, String
.format("\"1;1;%d;%d", rasterWidth
, rasterHeight
));
3241 // This row is OK to save into the cache.
3242 sixelCache
.put(cells
, sb
.toString());
3245 return (startSixel(x
, y
) + sb
.toString() + endSixel());
3249 * Get the sixel support flag.
3251 * @return true if this terminal is emitting sixel
3253 public boolean hasSixel() {
3257 // ------------------------------------------------------------------------
3258 // End sixel output support -----------------------------------------------
3259 // ------------------------------------------------------------------------
3261 // ------------------------------------------------------------------------
3262 // iTerm2 image output support --------------------------------------------
3263 // ------------------------------------------------------------------------
3266 * Create an iTerm2 images string representing a row of several cells
3267 * containing bitmap data.
3269 * @param x column coordinate. 0 is the left-most column.
3270 * @param y row coordinate. 0 is the top-most row.
3271 * @param cells the cells containing the bitmap data
3272 * @return the string to emit to an ANSI / ECMA-style terminal
3274 private String
toIterm2Image(final int x
, final int y
,
3275 final ArrayList
<Cell
> cells
) {
3277 StringBuilder sb
= new StringBuilder();
3279 assert (cells
!= null);
3280 assert (cells
.size() > 0);
3281 assert (cells
.get(0).getImage() != null);
3283 if (iterm2Images
== false) {
3284 sb
.append(normal());
3285 sb
.append(gotoXY(x
, y
));
3286 for (int i
= 0; i
< cells
.size(); i
++) {
3289 return sb
.toString();
3292 if (iterm2Cache
== null) {
3293 iterm2Cache
= new ImageCache(height
* 10);
3294 base64
= java
.util
.Base64
.getEncoder();
3297 // Save and get rows to/from the cache that do NOT have inverted
3299 boolean saveInCache
= true;
3300 for (Cell cell
: cells
) {
3301 if (cell
.isInvertedImage()) {
3302 saveInCache
= false;
3306 String cachedResult
= iterm2Cache
.get(cells
);
3307 if (cachedResult
!= null) {
3308 // System.err.println("CACHE HIT");
3309 sb
.append(gotoXY(x
, y
));
3310 sb
.append(cachedResult
);
3311 return sb
.toString();
3313 // System.err.println("CACHE MISS");
3316 int imageWidth
= cells
.get(0).getImage().getWidth();
3317 int imageHeight
= cells
.get(0).getImage().getHeight();
3319 // cells.get(x).getImage() has a dithered bitmap containing indexes
3320 // into the color palette. Piece these together into one larger
3321 // image for final rendering.
3323 int fullWidth
= cells
.size() * getTextWidth();
3324 int fullHeight
= getTextHeight();
3325 for (int i
= 0; i
< cells
.size(); i
++) {
3326 totalWidth
+= cells
.get(i
).getImage().getWidth();
3329 BufferedImage image
= new BufferedImage(fullWidth
,
3330 fullHeight
, BufferedImage
.TYPE_INT_ARGB
);
3333 for (int i
= 0; i
< cells
.size() - 1; i
++) {
3334 int tileWidth
= Math
.min(cells
.get(i
).getImage().getWidth(),
3336 int tileHeight
= Math
.min(cells
.get(i
).getImage().getHeight(),
3338 if (false && cells
.get(i
).isInvertedImage()) {
3339 // I used to put an all-white cell over the cursor, don't do
3341 rgbArray
= new int[imageWidth
* imageHeight
];
3342 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3343 rgbArray
[j
] = 0xFFFFFF;
3347 rgbArray
= cells
.get(i
).getImage().getRGB(0, 0,
3348 tileWidth
, tileHeight
, null, 0, tileWidth
);
3349 } catch (Exception e
) {
3350 throw new RuntimeException("image " + imageWidth
+ "x" +
3352 "tile " + tileWidth
+ "x" +
3354 " cells.get(i).getImage() " +
3355 cells
.get(i
).getImage() +
3357 " fullWidth " + fullWidth
+
3358 " fullHeight " + fullHeight
, e
);
3363 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
3364 i * imageWidth, 0, imageWidth, imageHeight,
3366 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
3367 fullWidth, fullHeight, cells.size(), getTextWidth());
3370 image
.setRGB(i
* imageWidth
, 0, tileWidth
, tileHeight
,
3371 rgbArray
, 0, tileWidth
);
3372 if (tileHeight
< fullHeight
) {
3373 int backgroundColor
= cells
.get(i
).getBackground().getRGB();
3374 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3375 for (int imageY
= imageHeight
; imageY
< fullHeight
;
3378 image
.setRGB(imageX
, imageY
, backgroundColor
);
3383 totalWidth
-= ((cells
.size() - 1) * imageWidth
);
3384 if (false && cells
.get(cells
.size() - 1).isInvertedImage()) {
3385 // I used to put an all-white cell over the cursor, don't do that
3387 rgbArray
= new int[totalWidth
* imageHeight
];
3388 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3389 rgbArray
[j
] = 0xFFFFFF;
3393 rgbArray
= cells
.get(cells
.size() - 1).getImage().getRGB(0, 0,
3394 totalWidth
, imageHeight
, null, 0, totalWidth
);
3395 } catch (Exception e
) {
3396 throw new RuntimeException("image " + imageWidth
+ "x" +
3397 imageHeight
+ " cells.get(cells.size() - 1).getImage() " +
3398 cells
.get(cells
.size() - 1).getImage(), e
);
3401 image
.setRGB((cells
.size() - 1) * imageWidth
, 0, totalWidth
,
3402 imageHeight
, rgbArray
, 0, totalWidth
);
3404 if (totalWidth
< getTextWidth()) {
3405 int backgroundColor
= cells
.get(cells
.size() - 1).getBackground().getRGB();
3407 for (int imageX
= image
.getWidth() - totalWidth
;
3408 imageX
< image
.getWidth(); imageX
++) {
3410 for (int imageY
= 0; imageY
< fullHeight
; imageY
++) {
3411 image
.setRGB(imageX
, imageY
, backgroundColor
);
3417 * From https://iterm2.com/documentation-images.html:
3421 * iTerm2 extends the xterm protocol with a set of proprietary escape
3422 * sequences. In general, the pattern is:
3424 * ESC ] 1337 ; key = value ^G
3426 * Whitespace is shown here for ease of reading: in practice, no
3427 * spaces should be used.
3429 * For file transfer and inline images, the code is:
3431 * ESC ] 1337 ; File = [optional arguments] : base-64 encoded file contents ^G
3433 * The optional arguments are formatted as key=value with a semicolon
3434 * between each key-value pair. They are described below:
3436 * Key Description of value
3437 * name base-64 encoded filename. Defaults to "Unnamed file".
3438 * size File size in bytes. Optional; this is only used by the
3439 * progress indicator.
3440 * width Width to render. See notes below.
3441 * height Height to render. See notes below.
3442 * preserveAspectRatio If set to 0, then the image's inherent aspect
3443 * ratio will not be respected; otherwise, it
3444 * will fill the specified width and height as
3445 * much as possible without stretching. Defaults
3447 * inline If set to 1, the file will be displayed inline. Otherwise,
3448 * it will be downloaded with no visual representation in the
3449 * terminal session. Defaults to 0.
3451 * The width and height are given as a number followed by a unit, or
3454 * N: N character cells.
3456 * N%: N percent of the session's width or height.
3457 * auto: The image's inherent size will be used to determine an
3458 * appropriate dimension.
3462 // File contents can be several image formats. We will use PNG.
3463 ByteArrayOutputStream pngOutputStream
= new ByteArrayOutputStream(1024);
3465 if (!ImageIO
.write(image
.getSubimage(0, 0, image
.getWidth(),
3466 Math
.min(image
.getHeight(), fullHeight
)),
3467 "PNG", pngOutputStream
)
3469 // We failed to render image, bail out.
3472 } catch (IOException e
) {
3473 // We failed to render image, bail out.
3477 // iTerm2 does not advance the cursor automatically, so place it
3479 sb
.append("\033]1337;File=");
3481 sb.append(String.format("width=$d;height=1;preserveAspectRatio=1;",
3485 sb.append(String.format("width=$dpx;height=%dpx;preserveAspectRatio=1;",
3486 image.getWidth(), Math.min(image.getHeight(),
3489 sb
.append("inline=1:");
3490 sb
.append(base64
.encodeToString(pngOutputStream
.toByteArray()));
3494 // This row is OK to save into the cache.
3495 iterm2Cache
.put(cells
, sb
.toString());
3498 return (gotoXY(x
, y
) + sb
.toString());
3502 * Get the iTerm2 images support flag.
3504 * @return true if this terminal is emitting iTerm2 images
3506 public boolean hasIterm2Images() {
3507 return iterm2Images
;
3510 // ------------------------------------------------------------------------
3511 // End iTerm2 image output support ----------------------------------------
3512 // ------------------------------------------------------------------------
3515 * Setup system colors to match DOS color palette.
3517 private void setDOSColors() {
3518 MYBLACK
= new java
.awt
.Color(0x00, 0x00, 0x00);
3519 MYRED
= new java
.awt
.Color(0xa8, 0x00, 0x00);
3520 MYGREEN
= new java
.awt
.Color(0x00, 0xa8, 0x00);
3521 MYYELLOW
= new java
.awt
.Color(0xa8, 0x54, 0x00);
3522 MYBLUE
= new java
.awt
.Color(0x00, 0x00, 0xa8);
3523 MYMAGENTA
= new java
.awt
.Color(0xa8, 0x00, 0xa8);
3524 MYCYAN
= new java
.awt
.Color(0x00, 0xa8, 0xa8);
3525 MYWHITE
= new java
.awt
.Color(0xa8, 0xa8, 0xa8);
3526 MYBOLD_BLACK
= new java
.awt
.Color(0x54, 0x54, 0x54);
3527 MYBOLD_RED
= new java
.awt
.Color(0xfc, 0x54, 0x54);
3528 MYBOLD_GREEN
= new java
.awt
.Color(0x54, 0xfc, 0x54);
3529 MYBOLD_YELLOW
= new java
.awt
.Color(0xfc, 0xfc, 0x54);
3530 MYBOLD_BLUE
= new java
.awt
.Color(0x54, 0x54, 0xfc);
3531 MYBOLD_MAGENTA
= new java
.awt
.Color(0xfc, 0x54, 0xfc);
3532 MYBOLD_CYAN
= new java
.awt
.Color(0x54, 0xfc, 0xfc);
3533 MYBOLD_WHITE
= new java
.awt
.Color(0xfc, 0xfc, 0xfc);
3537 * Setup ECMA48 colors to match those provided in system properties.
3539 private void setCustomSystemColors() {
3542 MYBLACK
= getCustomColor("jexer.ECMA48.color0", MYBLACK
);
3543 MYRED
= getCustomColor("jexer.ECMA48.color1", MYRED
);
3544 MYGREEN
= getCustomColor("jexer.ECMA48.color2", MYGREEN
);
3545 MYYELLOW
= getCustomColor("jexer.ECMA48.color3", MYYELLOW
);
3546 MYBLUE
= getCustomColor("jexer.ECMA48.color4", MYBLUE
);
3547 MYMAGENTA
= getCustomColor("jexer.ECMA48.color5", MYMAGENTA
);
3548 MYCYAN
= getCustomColor("jexer.ECMA48.color6", MYCYAN
);
3549 MYWHITE
= getCustomColor("jexer.ECMA48.color7", MYWHITE
);
3550 MYBOLD_BLACK
= getCustomColor("jexer.ECMA48.color8", MYBOLD_BLACK
);
3551 MYBOLD_RED
= getCustomColor("jexer.ECMA48.color9", MYBOLD_RED
);
3552 MYBOLD_GREEN
= getCustomColor("jexer.ECMA48.color10", MYBOLD_GREEN
);
3553 MYBOLD_YELLOW
= getCustomColor("jexer.ECMA48.color11", MYBOLD_YELLOW
);
3554 MYBOLD_BLUE
= getCustomColor("jexer.ECMA48.color12", MYBOLD_BLUE
);
3555 MYBOLD_MAGENTA
= getCustomColor("jexer.ECMA48.color13", MYBOLD_MAGENTA
);
3556 MYBOLD_CYAN
= getCustomColor("jexer.ECMA48.color14", MYBOLD_CYAN
);
3557 MYBOLD_WHITE
= getCustomColor("jexer.ECMA48.color15", MYBOLD_WHITE
);
3561 * Setup one system color to match the RGB value provided in system
3564 * @param key the system property key
3565 * @param defaultColor the default color to return if key is not set, or
3567 * @return a color from the RGB string, or defaultColor
3569 private java
.awt
.Color
getCustomColor(final String key
,
3570 final java
.awt
.Color defaultColor
) {
3572 String rgb
= System
.getProperty(key
);
3574 return defaultColor
;
3576 if (rgb
.startsWith("#")) {
3577 rgb
= rgb
.substring(1);
3581 rgbInt
= Integer
.parseInt(rgb
, 16);
3582 } catch (NumberFormatException e
) {
3583 return defaultColor
;
3585 java
.awt
.Color color
= new java
.awt
.Color((rgbInt
& 0xFF0000) >>> 16,
3586 (rgbInt
& 0x00FF00) >>> 8,
3587 (rgbInt
& 0x0000FF));
3593 * Create a T.416 RGB parameter sequence for a custom system color.
3595 * @param color one of the MYBLACK, MYBOLD_BLUE, etc. colors
3596 * @return the color portion of the string to emit to an ANSI /
3597 * ECMA-style terminal
3599 private String
systemColorRGB(final java
.awt
.Color color
) {
3600 return String
.format("%d;%d;%d", color
.getRed(), color
.getGreen(),
3605 * Create a SGR parameter sequence for a single color change.
3607 * @param bold if true, set bold
3608 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
3609 * @param foreground if true, this is a foreground color
3610 * @return the string to emit to an ANSI / ECMA-style terminal,
3613 private String
color(final boolean bold
, final Color color
,
3614 final boolean foreground
) {
3615 return color(color
, foreground
, true) +
3616 rgbColor(bold
, color
, foreground
);
3620 * Create a T.416 RGB parameter sequence for a single color change.
3622 * @param colorRGB a 24-bit RGB value for foreground color
3623 * @param foreground if true, this is a foreground color
3624 * @return the string to emit to an ANSI / ECMA-style terminal,
3627 private String
colorRGB(final int colorRGB
, final boolean foreground
) {
3629 int colorRed
= (colorRGB
>>> 16) & 0xFF;
3630 int colorGreen
= (colorRGB
>>> 8) & 0xFF;
3631 int colorBlue
= colorRGB
& 0xFF;
3633 StringBuilder sb
= new StringBuilder();
3635 sb
.append("\033[38;2;");
3637 sb
.append("\033[48;2;");
3639 sb
.append(String
.format("%d;%d;%dm", colorRed
, colorGreen
, colorBlue
));
3640 return sb
.toString();
3644 * Create a T.416 RGB parameter sequence for both foreground and
3645 * background color change.
3647 * @param foreColorRGB a 24-bit RGB value for foreground color
3648 * @param backColorRGB a 24-bit RGB value for foreground color
3649 * @return the string to emit to an ANSI / ECMA-style terminal,
3652 private String
colorRGB(final int foreColorRGB
, final int backColorRGB
) {
3653 int foreColorRed
= (foreColorRGB
>>> 16) & 0xFF;
3654 int foreColorGreen
= (foreColorRGB
>>> 8) & 0xFF;
3655 int foreColorBlue
= foreColorRGB
& 0xFF;
3656 int backColorRed
= (backColorRGB
>>> 16) & 0xFF;
3657 int backColorGreen
= (backColorRGB
>>> 8) & 0xFF;
3658 int backColorBlue
= backColorRGB
& 0xFF;
3660 StringBuilder sb
= new StringBuilder();
3661 sb
.append(String
.format("\033[38;2;%d;%d;%dm",
3662 foreColorRed
, foreColorGreen
, foreColorBlue
));
3663 sb
.append(String
.format("\033[48;2;%d;%d;%dm",
3664 backColorRed
, backColorGreen
, backColorBlue
));
3665 return sb
.toString();
3669 * Create a T.416 RGB parameter sequence for a single color change.
3671 * @param bold if true, set bold
3672 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
3673 * @param foreground if true, this is a foreground color
3674 * @return the string to emit to an xterm terminal with RGB support,
3675 * e.g. "\033[38;2;RR;GG;BBm"
3677 private String
rgbColor(final boolean bold
, final Color color
,
3678 final boolean foreground
) {
3679 if (doRgbColor
== false) {
3682 StringBuilder sb
= new StringBuilder("\033[");
3684 // Bold implies foreground only
3686 if (color
.equals(Color
.BLACK
)) {
3687 sb
.append(systemColorRGB(MYBOLD_BLACK
));
3688 } else if (color
.equals(Color
.RED
)) {
3689 sb
.append(systemColorRGB(MYBOLD_RED
));
3690 } else if (color
.equals(Color
.GREEN
)) {
3691 sb
.append(systemColorRGB(MYBOLD_GREEN
));
3692 } else if (color
.equals(Color
.YELLOW
)) {
3693 sb
.append(systemColorRGB(MYBOLD_YELLOW
));
3694 } else if (color
.equals(Color
.BLUE
)) {
3695 sb
.append(systemColorRGB(MYBOLD_BLUE
));
3696 } else if (color
.equals(Color
.MAGENTA
)) {
3697 sb
.append(systemColorRGB(MYBOLD_MAGENTA
));
3698 } else if (color
.equals(Color
.CYAN
)) {
3699 sb
.append(systemColorRGB(MYBOLD_CYAN
));
3700 } else if (color
.equals(Color
.WHITE
)) {
3701 sb
.append(systemColorRGB(MYBOLD_WHITE
));
3709 if (color
.equals(Color
.BLACK
)) {
3710 sb
.append(systemColorRGB(MYBLACK
));
3711 } else if (color
.equals(Color
.RED
)) {
3712 sb
.append(systemColorRGB(MYRED
));
3713 } else if (color
.equals(Color
.GREEN
)) {
3714 sb
.append(systemColorRGB(MYGREEN
));
3715 } else if (color
.equals(Color
.YELLOW
)) {
3716 sb
.append(systemColorRGB(MYYELLOW
));
3717 } else if (color
.equals(Color
.BLUE
)) {
3718 sb
.append(systemColorRGB(MYBLUE
));
3719 } else if (color
.equals(Color
.MAGENTA
)) {
3720 sb
.append(systemColorRGB(MYMAGENTA
));
3721 } else if (color
.equals(Color
.CYAN
)) {
3722 sb
.append(systemColorRGB(MYCYAN
));
3723 } else if (color
.equals(Color
.WHITE
)) {
3724 sb
.append(systemColorRGB(MYWHITE
));
3728 return sb
.toString();
3732 * Create a T.416 RGB parameter sequence for both foreground and
3733 * background color change.
3735 * @param bold if true, set bold
3736 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3737 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3738 * @return the string to emit to an xterm terminal with RGB support,
3739 * e.g. "\033[38;2;RR;GG;BB;48;2;RR;GG;BBm"
3741 private String
rgbColor(final boolean bold
, final Color foreColor
,
3742 final Color backColor
) {
3743 if (doRgbColor
== false) {
3747 return rgbColor(bold
, foreColor
, true) +
3748 rgbColor(false, backColor
, false);
3752 * Create a SGR parameter sequence for a single color change.
3754 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
3755 * @param foreground if true, this is a foreground color
3756 * @param header if true, make the full header, otherwise just emit the
3757 * color parameter e.g. "42;"
3758 * @return the string to emit to an ANSI / ECMA-style terminal,
3761 private String
color(final Color color
, final boolean foreground
,
3762 final boolean header
) {
3764 int ecmaColor
= color
.getValue();
3766 // Convert Color.* values to SGR numerics
3774 return String
.format("\033[%dm", ecmaColor
);
3776 return String
.format("%d;", ecmaColor
);
3781 * Create a SGR parameter sequence for both foreground and background
3784 * @param bold if true, set bold
3785 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3786 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3787 * @return the string to emit to an ANSI / ECMA-style terminal,
3788 * e.g. "\033[31;42m"
3790 private String
color(final boolean bold
, final Color foreColor
,
3791 final Color backColor
) {
3792 return color(foreColor
, backColor
, true) +
3793 rgbColor(bold
, foreColor
, backColor
);
3797 * Create a SGR parameter sequence for both foreground and
3798 * background color change.
3800 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3801 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3802 * @param header if true, make the full header, otherwise just emit the
3803 * color parameter e.g. "31;42;"
3804 * @return the string to emit to an ANSI / ECMA-style terminal,
3805 * e.g. "\033[31;42m"
3807 private String
color(final Color foreColor
, final Color backColor
,
3808 final boolean header
) {
3810 int ecmaForeColor
= foreColor
.getValue();
3811 int ecmaBackColor
= backColor
.getValue();
3813 // Convert Color.* values to SGR numerics
3814 ecmaBackColor
+= 40;
3815 ecmaForeColor
+= 30;
3818 return String
.format("\033[%d;%dm", ecmaForeColor
, ecmaBackColor
);
3820 return String
.format("%d;%d;", ecmaForeColor
, ecmaBackColor
);
3825 * Create a SGR parameter sequence for foreground, background, and
3826 * several attributes. This sequence first resets all attributes to
3827 * default, then sets attributes as per the parameters.
3829 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3830 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3831 * @param bold if true, set bold
3832 * @param reverse if true, set reverse
3833 * @param blink if true, set blink
3834 * @param underline if true, set underline
3835 * @return the string to emit to an ANSI / ECMA-style terminal,
3836 * e.g. "\033[0;1;31;42m"
3838 private String
color(final Color foreColor
, final Color backColor
,
3839 final boolean bold
, final boolean reverse
, final boolean blink
,
3840 final boolean underline
) {
3842 int ecmaForeColor
= foreColor
.getValue();
3843 int ecmaBackColor
= backColor
.getValue();
3845 // Convert Color.* values to SGR numerics
3846 ecmaBackColor
+= 40;
3847 ecmaForeColor
+= 30;
3849 StringBuilder sb
= new StringBuilder();
3850 if ( bold
&& reverse
&& blink
&& !underline
) {
3851 sb
.append("\033[0;1;7;5;");
3852 } else if ( bold
&& reverse
&& !blink
&& !underline
) {
3853 sb
.append("\033[0;1;7;");
3854 } else if ( !bold
&& reverse
&& blink
&& !underline
) {
3855 sb
.append("\033[0;7;5;");
3856 } else if ( bold
&& !reverse
&& blink
&& !underline
) {
3857 sb
.append("\033[0;1;5;");
3858 } else if ( bold
&& !reverse
&& !blink
&& !underline
) {
3859 sb
.append("\033[0;1;");
3860 } else if ( !bold
&& reverse
&& !blink
&& !underline
) {
3861 sb
.append("\033[0;7;");
3862 } else if ( !bold
&& !reverse
&& blink
&& !underline
) {
3863 sb
.append("\033[0;5;");
3864 } else if ( bold
&& reverse
&& blink
&& underline
) {
3865 sb
.append("\033[0;1;7;5;4;");
3866 } else if ( bold
&& reverse
&& !blink
&& underline
) {
3867 sb
.append("\033[0;1;7;4;");
3868 } else if ( !bold
&& reverse
&& blink
&& underline
) {
3869 sb
.append("\033[0;7;5;4;");
3870 } else if ( bold
&& !reverse
&& blink
&& underline
) {
3871 sb
.append("\033[0;1;5;4;");
3872 } else if ( bold
&& !reverse
&& !blink
&& underline
) {
3873 sb
.append("\033[0;1;4;");
3874 } else if ( !bold
&& reverse
&& !blink
&& underline
) {
3875 sb
.append("\033[0;7;4;");
3876 } else if ( !bold
&& !reverse
&& blink
&& underline
) {
3877 sb
.append("\033[0;5;4;");
3878 } else if ( !bold
&& !reverse
&& !blink
&& underline
) {
3879 sb
.append("\033[0;4;");
3881 assert (!bold
&& !reverse
&& !blink
&& !underline
);
3882 sb
.append("\033[0;");
3884 sb
.append(String
.format("%d;%dm", ecmaForeColor
, ecmaBackColor
));
3885 sb
.append(rgbColor(bold
, foreColor
, backColor
));
3886 return sb
.toString();
3890 * Create a SGR parameter sequence for foreground, background, and
3891 * several attributes. This sequence first resets all attributes to
3892 * default, then sets attributes as per the parameters.
3894 * @param foreColorRGB a 24-bit RGB value for foreground color
3895 * @param backColorRGB a 24-bit RGB value for foreground color
3896 * @param bold if true, set bold
3897 * @param reverse if true, set reverse
3898 * @param blink if true, set blink
3899 * @param underline if true, set underline
3900 * @return the string to emit to an ANSI / ECMA-style terminal,
3901 * e.g. "\033[0;1;31;42m"
3903 private String
colorRGB(final int foreColorRGB
, final int backColorRGB
,
3904 final boolean bold
, final boolean reverse
, final boolean blink
,
3905 final boolean underline
) {
3907 int foreColorRed
= (foreColorRGB
>>> 16) & 0xFF;
3908 int foreColorGreen
= (foreColorRGB
>>> 8) & 0xFF;
3909 int foreColorBlue
= foreColorRGB
& 0xFF;
3910 int backColorRed
= (backColorRGB
>>> 16) & 0xFF;
3911 int backColorGreen
= (backColorRGB
>>> 8) & 0xFF;
3912 int backColorBlue
= backColorRGB
& 0xFF;
3914 StringBuilder sb
= new StringBuilder();
3915 if ( bold
&& reverse
&& blink
&& !underline
) {
3916 sb
.append("\033[0;1;7;5;");
3917 } else if ( bold
&& reverse
&& !blink
&& !underline
) {
3918 sb
.append("\033[0;1;7;");
3919 } else if ( !bold
&& reverse
&& blink
&& !underline
) {
3920 sb
.append("\033[0;7;5;");
3921 } else if ( bold
&& !reverse
&& blink
&& !underline
) {
3922 sb
.append("\033[0;1;5;");
3923 } else if ( bold
&& !reverse
&& !blink
&& !underline
) {
3924 sb
.append("\033[0;1;");
3925 } else if ( !bold
&& reverse
&& !blink
&& !underline
) {
3926 sb
.append("\033[0;7;");
3927 } else if ( !bold
&& !reverse
&& blink
&& !underline
) {
3928 sb
.append("\033[0;5;");
3929 } else if ( bold
&& reverse
&& blink
&& underline
) {
3930 sb
.append("\033[0;1;7;5;4;");
3931 } else if ( bold
&& reverse
&& !blink
&& underline
) {
3932 sb
.append("\033[0;1;7;4;");
3933 } else if ( !bold
&& reverse
&& blink
&& underline
) {
3934 sb
.append("\033[0;7;5;4;");
3935 } else if ( bold
&& !reverse
&& blink
&& underline
) {
3936 sb
.append("\033[0;1;5;4;");
3937 } else if ( bold
&& !reverse
&& !blink
&& underline
) {
3938 sb
.append("\033[0;1;4;");
3939 } else if ( !bold
&& reverse
&& !blink
&& underline
) {
3940 sb
.append("\033[0;7;4;");
3941 } else if ( !bold
&& !reverse
&& blink
&& underline
) {
3942 sb
.append("\033[0;5;4;");
3943 } else if ( !bold
&& !reverse
&& !blink
&& underline
) {
3944 sb
.append("\033[0;4;");
3946 assert (!bold
&& !reverse
&& !blink
&& !underline
);
3947 sb
.append("\033[0;");
3950 sb
.append("m\033[38;2;");
3951 sb
.append(String
.format("%d;%d;%d", foreColorRed
, foreColorGreen
,
3953 sb
.append("m\033[48;2;");
3954 sb
.append(String
.format("%d;%d;%d", backColorRed
, backColorGreen
,
3957 return sb
.toString();
3961 * Create a SGR parameter sequence to reset to VT100 defaults.
3963 * @return the string to emit to an ANSI / ECMA-style terminal,
3966 private String
normal() {
3967 return normal(true) + rgbColor(false, Color
.WHITE
, Color
.BLACK
);
3971 * Create a SGR parameter sequence to reset to ECMA-48 default
3972 * foreground/background.
3974 * @return the string to emit to an ANSI / ECMA-style terminal,
3977 private String
defaultColor() {
3980 * Normal (neither bold nor faint).
3983 * Steady (not blinking).
3984 * Positive (not inverse).
3985 * Visible (not hidden).
3987 * Default foreground color.
3988 * Default background color.
3990 return "\033[0;22;23;24;25;27;28;29;39;49m";
3994 * Create a SGR parameter sequence to reset to defaults.
3996 * @param header if true, make the full header, otherwise just emit the
3997 * bare parameter e.g. "0;"
3998 * @return the string to emit to an ANSI / ECMA-style terminal,
4001 private String
normal(final boolean header
) {
4003 return "\033[0;37;40m";
4009 * Create a SGR parameter sequence for enabling the visible cursor.
4011 * @param on if true, turn on cursor
4012 * @return the string to emit to an ANSI / ECMA-style terminal
4014 private String
cursor(final boolean on
) {
4015 if (on
&& !cursorOn
) {
4019 if (!on
&& cursorOn
) {
4027 * Clear the entire screen. Because some terminals use back-color-erase,
4028 * set the color to white-on-black beforehand.
4030 * @return the string to emit to an ANSI / ECMA-style terminal
4032 private String
clearAll() {
4033 return "\033[0;37;40m\033[2J";
4037 * Clear the line from the cursor (inclusive) to the end of the screen.
4038 * Because some terminals use back-color-erase, set the color to
4039 * white-on-black beforehand.
4041 * @return the string to emit to an ANSI / ECMA-style terminal
4043 private String
clearRemainingLine() {
4044 return "\033[0;37;40m\033[K";
4048 * Move the cursor to (x, y).
4050 * @param x column coordinate. 0 is the left-most column.
4051 * @param y row coordinate. 0 is the top-most row.
4052 * @return the string to emit to an ANSI / ECMA-style terminal
4054 private String
gotoXY(final int x
, final int y
) {
4055 return String
.format("\033[%d;%dH", y
+ 1, x
+ 1);
4059 * Tell (u)xterm that we want to receive mouse events based on "Any event
4060 * tracking", UTF-8 coordinates, and then SGR coordinates. Ideally we
4061 * will end up with SGR coordinates with UTF-8 coordinates as a fallback.
4063 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
4065 * Note that this also sets the alternate/primary screen buffer.
4067 * Finally, also emit a Privacy Message sequence that Jexer recognizes to
4068 * mean "hide the mouse pointer." We have to use our own sequence to do
4069 * this because there is no standard in xterm for unilaterally hiding the
4070 * pointer all the time (regardless of typing).
4072 * @param on If true, enable mouse report and use the alternate screen
4073 * buffer. If false disable mouse reporting and use the primary screen
4075 * @return the string to emit to xterm
4077 private String
mouse(final boolean on
) {
4079 return "\033[?1002;1003;1005;1006h\033[?1049h\033^hideMousePointer\033\\";
4081 return "\033[?1002;1003;1006;1005l\033[?1049l\033^showMousePointer\033\\";