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
.bits
.StringUtils
;
55 import jexer
.event
.TCommandEvent
;
56 import jexer
.event
.TInputEvent
;
57 import jexer
.event
.TKeypressEvent
;
58 import jexer
.event
.TMouseEvent
;
59 import jexer
.event
.TResizeEvent
;
60 import static jexer
.TCommand
.*;
61 import static jexer
.TKeypress
.*;
64 * This class reads keystrokes and mouse events and emits output to ANSI
65 * X3.64 / ECMA-48 type terminals e.g. xterm, linux, vt100, ansi.sys, etc.
67 public class ECMA48Terminal
extends LogicalScreen
68 implements TerminalReader
, Runnable
{
70 // ------------------------------------------------------------------------
71 // Constants --------------------------------------------------------------
72 // ------------------------------------------------------------------------
75 * States in the input parser.
77 private enum ParseState
{
88 * Available Jexer images support.
90 private enum JexerImageOption
{
97 // ------------------------------------------------------------------------
98 // Variables --------------------------------------------------------------
99 // ------------------------------------------------------------------------
102 * Emit debugging to stderr.
104 private boolean debugToStderr
= false;
107 * If true, emit T.416-style RGB colors for normal system colors. This
108 * is a) expensive in bandwidth, and b) potentially terrible looking for
111 private static boolean doRgbColor
= false;
114 * The session information.
116 private SessionInfo sessionInfo
;
119 * The event queue, filled up by a thread reading on input.
121 private List
<TInputEvent
> eventQueue
;
124 * If true, we want the reader thread to exit gracefully.
126 private boolean stopReaderThread
;
131 private Thread readerThread
;
134 * Parameters being collected. E.g. if the string is \033[1;3m, then
135 * params[0] will be 1 and params[1] will be 3.
137 private List
<String
> params
;
140 * Current parsing state.
142 private ParseState state
;
145 * The time we entered ESCAPE. If we get a bare escape without a code
146 * following it, this is used to return that bare escape.
148 private long escapeTime
;
151 * The time we last checked the window size. We try not to spawn stty
152 * more than once per second.
154 private long windowSizeTime
;
157 * true if mouse1 was down. Used to report mouse1 on the release event.
159 private boolean mouse1
;
162 * true if mouse2 was down. Used to report mouse2 on the release event.
164 private boolean mouse2
;
167 * true if mouse3 was down. Used to report mouse3 on the release event.
169 private boolean mouse3
;
172 * Cache the cursor visibility value so we only emit the sequence when we
175 private boolean cursorOn
= true;
178 * Cache the last window size to figure out if a TResizeEvent needs to be
181 private TResizeEvent windowResize
= null;
184 * If true, emit wide-char (CJK/Emoji) characters as sixel images.
186 private boolean wideCharImages
= true;
189 * Window width in pixels. Used for sixel support.
191 private int widthPixels
= 640;
194 * Window height in pixels. Used for sixel support.
196 private int heightPixels
= 400;
199 * If true, emit image data via sixel.
201 private boolean sixel
= true;
204 * If true, use a single shared palette for sixel.
206 private boolean sixelSharedPalette
= true;
209 * The sixel palette handler.
211 private SixelPalette palette
= null;
214 * The sixel post-rendered string cache.
216 private ImageCache sixelCache
= null;
219 * Number of colors in the sixel palette. Xterm 335 defines the max as
220 * 1024. Valid values are: 2 (black and white), 256, 512, 1024, and
223 private int sixelPaletteSize
= 1024;
226 * If true, emit image data via iTerm2 image protocol.
228 private boolean iterm2Images
= false;
231 * The iTerm2 post-rendered string cache.
233 private ImageCache iterm2Cache
= null;
236 * If not DISABLED, emit image data via Jexer image protocol if the
237 * terminal supports it.
239 private JexerImageOption jexerImageOption
= JexerImageOption
.JPG
;
242 * The Jexer post-rendered string cache.
244 private ImageCache jexerCache
= null;
247 * If true, then we changed System.in and need to change it back.
249 private boolean setRawMode
= false;
252 * If true, '?' was seen in terminal response.
254 private boolean decPrivateModeFlag
= false;
257 * The terminal's input. If an InputStream is not specified in the
258 * constructor, then this InputStreamReader will be bound to System.in
259 * with UTF-8 encoding.
261 private Reader input
;
264 * The terminal's raw InputStream. If an InputStream is not specified in
265 * the constructor, then this InputReader will be bound to System.in.
266 * This is used by run() to see if bytes are available() before calling
267 * (Reader)input.read().
269 private InputStream inputStream
;
272 * The terminal's output. If an OutputStream is not specified in the
273 * constructor, then this PrintWriter will be bound to System.out with
276 private PrintWriter output
;
279 * The listening object that run() wakes up on new input.
281 private Object listener
;
283 // Colors to map DOS colors to AWT colors.
284 private static java
.awt
.Color MYBLACK
;
285 private static java
.awt
.Color MYRED
;
286 private static java
.awt
.Color MYGREEN
;
287 private static java
.awt
.Color MYYELLOW
;
288 private static java
.awt
.Color MYBLUE
;
289 private static java
.awt
.Color MYMAGENTA
;
290 private static java
.awt
.Color MYCYAN
;
291 private static java
.awt
.Color MYWHITE
;
292 private static java
.awt
.Color MYBOLD_BLACK
;
293 private static java
.awt
.Color MYBOLD_RED
;
294 private static java
.awt
.Color MYBOLD_GREEN
;
295 private static java
.awt
.Color MYBOLD_YELLOW
;
296 private static java
.awt
.Color MYBOLD_BLUE
;
297 private static java
.awt
.Color MYBOLD_MAGENTA
;
298 private static java
.awt
.Color MYBOLD_CYAN
;
299 private static java
.awt
.Color MYBOLD_WHITE
;
302 * SixelPalette is used to manage the conversion of images between 24-bit
303 * RGB color and a palette of sixelPaletteSize colors.
305 private class SixelPalette
{
308 * Color palette for sixel output, sorted low to high.
310 private List
<Integer
> rgbColors
= new ArrayList
<Integer
>();
313 * Map of color palette index for sixel output, from the order it was
314 * generated by makePalette() to rgbColors.
316 private int [] rgbSortedIndex
= new int[sixelPaletteSize
];
319 * The color palette, organized by hue, saturation, and luminance.
320 * This is used for a fast color match.
322 private ArrayList
<ArrayList
<ArrayList
<ColorIdx
>>> hslColors
;
325 * Number of bits for hue.
327 private int hueBits
= -1;
330 * Number of bits for saturation.
332 private int satBits
= -1;
335 * Number of bits for luminance.
337 private int lumBits
= -1;
340 * Step size for hue bins.
342 private int hueStep
= -1;
345 * Step size for saturation bins.
347 private int satStep
= -1;
350 * Cached RGB to HSL result.
352 private int hsl
[] = new int[3];
355 * ColorIdx records a RGB color and its palette index.
357 private class ColorIdx
{
359 * The 24-bit RGB color.
364 * The palette index for this color.
369 * Public constructor.
371 * @param color the 24-bit RGB color
372 * @param index the palette index for this color
374 public ColorIdx(final int color
, final int index
) {
381 * Public constructor.
383 public SixelPalette() {
388 * Find the nearest match for a color in the palette.
390 * @param color the RGB color
391 * @return the index in rgbColors that is closest to color
393 public int matchColor(final int color
) {
398 * matchColor() is a critical performance bottleneck. To make it
399 * decent, we do the following:
401 * 1. Find the nearest two hues that bracket this color.
403 * 2. Find the nearest two saturations that bracket this color.
405 * 3. Iterate within these four bands of luminance values,
406 * returning the closest color by Euclidean distance.
408 * This strategy reduces the search space by about 97%.
410 int red
= (color
>>> 16) & 0xFF;
411 int green
= (color
>>> 8) & 0xFF;
412 int blue
= color
& 0xFF;
414 if (sixelPaletteSize
== 2) {
415 if (((red
* red
) + (green
* green
) + (blue
* blue
)) < 35568) {
424 rgbToHsl(red
, green
, blue
, hsl
);
428 // System.err.printf("%d %d %d\n", hue, sat, lum);
430 double diff
= Double
.MAX_VALUE
;
433 int hue1
= hue
/ (360/hueStep
);
435 if (hue1
>= hslColors
.size() - 1) {
436 // Bracket pure red from above.
437 hue1
= hslColors
.size() - 1;
439 } else if (hue1
== 0) {
440 // Bracket pure red from below.
441 hue2
= hslColors
.size() - 1;
444 for (int hI
= hue1
; hI
!= -1;) {
445 ArrayList
<ArrayList
<ColorIdx
>> sats
= hslColors
.get(hI
);
448 } else if (hI
== hue2
) {
452 int sMin
= (sat
/ satStep
) - 1;
457 } else if (sMin
== sats
.size() - 1) {
462 assert (sMax
- sMin
== 1);
465 // int sMax = sats.size() - 1;
467 for (int sI
= sMin
; sI
<= sMax
; sI
++) {
468 ArrayList
<ColorIdx
> lums
= sats
.get(sI
);
470 // True 3D colorspace match for the remaining values
471 for (ColorIdx c
: lums
) {
472 int rgbColor
= c
.color
;
474 int red2
= (rgbColor
>>> 16) & 0xFF;
475 int green2
= (rgbColor
>>> 8) & 0xFF;
476 int blue2
= rgbColor
& 0xFF;
477 newDiff
+= Math
.pow(red2
- red
, 2);
478 newDiff
+= Math
.pow(green2
- green
, 2);
479 newDiff
+= Math
.pow(blue2
- blue
, 2);
480 if (newDiff
< diff
) {
481 idx
= rgbSortedIndex
[c
.index
];
488 if (((red
* red
) + (green
* green
) + (blue
* blue
)) < diff
) {
489 // Black is a closer match.
491 } else if ((((255 - red
) * (255 - red
)) +
492 ((255 - green
) * (255 - green
)) +
493 ((255 - blue
) * (255 - blue
))) < diff
) {
495 // White is a closer match.
496 idx
= sixelPaletteSize
- 1;
503 * Clamp an int value to [0, 255].
505 * @param x the int value
506 * @return an int between 0 and 255.
508 private int clamp(final int x
) {
519 * Dither an image to a sixelPaletteSize palette. The dithered
520 * image cells will contain indexes into the palette.
522 * @param image the image to dither
523 * @return the dithered image. Every pixel is an index into the
526 public BufferedImage
ditherImage(final BufferedImage image
) {
528 BufferedImage ditheredImage
= new BufferedImage(image
.getWidth(),
529 image
.getHeight(), BufferedImage
.TYPE_INT_ARGB
);
531 int [] rgbArray
= image
.getRGB(0, 0, image
.getWidth(),
532 image
.getHeight(), null, 0, image
.getWidth());
533 ditheredImage
.setRGB(0, 0, image
.getWidth(), image
.getHeight(),
534 rgbArray
, 0, image
.getWidth());
536 for (int imageY
= 0; imageY
< image
.getHeight(); imageY
++) {
537 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
538 int oldPixel
= ditheredImage
.getRGB(imageX
,
540 int colorIdx
= matchColor(oldPixel
);
541 assert (colorIdx
>= 0);
542 assert (colorIdx
< sixelPaletteSize
);
543 int newPixel
= rgbColors
.get(colorIdx
);
544 ditheredImage
.setRGB(imageX
, imageY
, colorIdx
);
546 int oldRed
= (oldPixel
>>> 16) & 0xFF;
547 int oldGreen
= (oldPixel
>>> 8) & 0xFF;
548 int oldBlue
= oldPixel
& 0xFF;
550 int newRed
= (newPixel
>>> 16) & 0xFF;
551 int newGreen
= (newPixel
>>> 8) & 0xFF;
552 int newBlue
= newPixel
& 0xFF;
554 int redError
= (oldRed
- newRed
) / 16;
555 int greenError
= (oldGreen
- newGreen
) / 16;
556 int blueError
= (oldBlue
- newBlue
) / 16;
558 int red
, green
, blue
;
559 if (imageX
< image
.getWidth() - 1) {
560 int pXpY
= ditheredImage
.getRGB(imageX
+ 1, imageY
);
561 red
= ((pXpY
>>> 16) & 0xFF) + (7 * redError
);
562 green
= ((pXpY
>>> 8) & 0xFF) + (7 * greenError
);
563 blue
= ( pXpY
& 0xFF) + (7 * blueError
);
565 green
= clamp(green
);
567 pXpY
= ((red
& 0xFF) << 16);
568 pXpY
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
569 ditheredImage
.setRGB(imageX
+ 1, imageY
, pXpY
);
571 if (imageY
< image
.getHeight() - 1) {
572 int pXpYp
= ditheredImage
.getRGB(imageX
+ 1,
574 red
= ((pXpYp
>>> 16) & 0xFF) + redError
;
575 green
= ((pXpYp
>>> 8) & 0xFF) + greenError
;
576 blue
= ( pXpYp
& 0xFF) + blueError
;
578 green
= clamp(green
);
580 pXpYp
= ((red
& 0xFF) << 16);
581 pXpYp
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
582 ditheredImage
.setRGB(imageX
+ 1, imageY
+ 1, pXpYp
);
584 } else if (imageY
< image
.getHeight() - 1) {
585 int pXmYp
= ditheredImage
.getRGB(imageX
- 1,
587 int pXYp
= ditheredImage
.getRGB(imageX
,
590 red
= ((pXmYp
>>> 16) & 0xFF) + (3 * redError
);
591 green
= ((pXmYp
>>> 8) & 0xFF) + (3 * greenError
);
592 blue
= ( pXmYp
& 0xFF) + (3 * blueError
);
594 green
= clamp(green
);
596 pXmYp
= ((red
& 0xFF) << 16);
597 pXmYp
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
598 ditheredImage
.setRGB(imageX
- 1, imageY
+ 1, pXmYp
);
600 red
= ((pXYp
>>> 16) & 0xFF) + (5 * redError
);
601 green
= ((pXYp
>>> 8) & 0xFF) + (5 * greenError
);
602 blue
= ( pXYp
& 0xFF) + (5 * blueError
);
604 green
= clamp(green
);
606 pXYp
= ((red
& 0xFF) << 16);
607 pXYp
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
608 ditheredImage
.setRGB(imageX
, imageY
+ 1, pXYp
);
610 } // for (int imageY = 0; imageY < image.getHeight(); imageY++)
611 } // for (int imageX = 0; imageX < image.getWidth(); imageX++)
613 return ditheredImage
;
617 * Convert an RGB color to HSL.
619 * @param red red color, between 0 and 255
620 * @param green green color, between 0 and 255
621 * @param blue blue color, between 0 and 255
622 * @param hsl the hsl color as [hue, saturation, luminance]
624 private void rgbToHsl(final int red
, final int green
,
625 final int blue
, final int [] hsl
) {
627 assert ((red
>= 0) && (red
<= 255));
628 assert ((green
>= 0) && (green
<= 255));
629 assert ((blue
>= 0) && (blue
<= 255));
631 double R
= red
/ 255.0;
632 double G
= green
/ 255.0;
633 double B
= blue
/ 255.0;
634 boolean Rmax
= false;
635 boolean Gmax
= false;
636 boolean Bmax
= false;
637 double min
= (R
< G ? R
: G
);
638 min
= (min
< B ? min
: B
);
640 if ((R
>= G
) && (R
>= B
)) {
643 } else if ((G
>= R
) && (G
>= B
)) {
646 } else if ((B
>= G
) && (B
>= R
)) {
651 double L
= (min
+ max
) / 2.0;
656 S
= (max
- min
) / (max
+ min
);
658 S
= (max
- min
) / (2.0 - max
- min
);
662 assert (Gmax
== false);
663 assert (Bmax
== false);
664 H
= (G
- B
) / (max
- min
);
666 assert (Rmax
== false);
667 assert (Bmax
== false);
668 H
= 2.0 + (B
- R
) / (max
- min
);
670 assert (Rmax
== false);
671 assert (Gmax
== false);
672 H
= 4.0 + (R
- G
) / (max
- min
);
677 hsl
[0] = (int) (H
* 60.0);
678 hsl
[1] = (int) (S
* 100.0);
679 hsl
[2] = (int) (L
* 100.0);
681 assert ((hsl
[0] >= 0) && (hsl
[0] <= 360));
682 assert ((hsl
[1] >= 0) && (hsl
[1] <= 100));
683 assert ((hsl
[2] >= 0) && (hsl
[2] <= 100));
687 * Convert a HSL color to RGB.
689 * @param hue hue, between 0 and 359
690 * @param sat saturation, between 0 and 100
691 * @param lum luminance, between 0 and 100
692 * @return the rgb color as 0x00RRGGBB
694 private int hslToRgb(final int hue
, final int sat
, final int lum
) {
695 assert ((hue
>= 0) && (hue
<= 360));
696 assert ((sat
>= 0) && (sat
<= 100));
697 assert ((lum
>= 0) && (lum
<= 100));
699 double S
= sat
/ 100.0;
700 double L
= lum
/ 100.0;
701 double C
= (1.0 - Math
.abs((2.0 * L
) - 1.0)) * S
;
702 double Hp
= hue
/ 60.0;
703 double X
= C
* (1.0 - Math
.abs((Hp
% 2) - 1.0));
710 } else if (Hp
<= 2.0) {
713 } else if (Hp
<= 3.0) {
716 } else if (Hp
<= 4.0) {
719 } else if (Hp
<= 5.0) {
722 } else if (Hp
<= 6.0) {
726 double m
= L
- (C
/ 2.0);
727 int red
= ((int) ((Rp
+ m
) * 255.0)) << 16;
728 int green
= ((int) ((Gp
+ m
) * 255.0)) << 8;
729 int blue
= (int) ((Bp
+ m
) * 255.0);
731 return (red
| green
| blue
);
735 * Create the sixel palette.
737 private void makePalette() {
738 // Generate the sixel palette. Because we have no idea at this
739 // layer which image(s) will be shown, we have to use a common
740 // palette with sixelPaletteSize colors for everything, and
741 // map the BufferedImage colors to their nearest neighbor in RGB
744 if (sixelPaletteSize
== 2) {
746 rgbColors
.add(0xFFFFFF);
747 rgbSortedIndex
[0] = 0;
748 rgbSortedIndex
[1] = 1;
752 // We build a palette using the Hue-Saturation-Luminence model,
753 // with 5+ bits for Hue, 2+ bits for Saturation, and 1+ bit for
754 // Luminance. We convert these colors to 24-bit RGB, sort them
755 // ascending, and steal the first index for pure black and the
756 // last for pure white. The 8-bit final palette favors bright
757 // colors, somewhere between pastel and classic television
758 // technicolor. 9- and 10-bit palettes are more uniform.
760 // Default at 256 colors.
765 assert (sixelPaletteSize
>= 256);
766 assert ((sixelPaletteSize
== 256)
767 || (sixelPaletteSize
== 512)
768 || (sixelPaletteSize
== 1024)
769 || (sixelPaletteSize
== 2048));
771 switch (sixelPaletteSize
) {
788 hueStep
= (int) (Math
.pow(2, hueBits
));
789 satStep
= (int) (100 / Math
.pow(2, satBits
));
790 // 1 bit for luminance: 40 and 70.
795 // 2 bits: 20, 40, 60, 80
800 // 3 bits: 8, 20, 32, 44, 56, 68, 80, 92
806 // System.err.printf("<html><body>\n");
807 // Hue is evenly spaced around the wheel.
808 hslColors
= new ArrayList
<ArrayList
<ArrayList
<ColorIdx
>>>();
810 final boolean DEBUG
= false;
811 ArrayList
<Integer
> rawRgbList
= new ArrayList
<Integer
>();
813 for (int hue
= 0; hue
< (360 - (360 % hueStep
));
814 hue
+= (360/hueStep
)) {
816 ArrayList
<ArrayList
<ColorIdx
>> satList
= null;
817 satList
= new ArrayList
<ArrayList
<ColorIdx
>>();
818 hslColors
.add(satList
);
820 // Saturation is linearly spaced between pastel and pure.
821 for (int sat
= satStep
; sat
<= 100; sat
+= satStep
) {
823 ArrayList
<ColorIdx
> lumList
= new ArrayList
<ColorIdx
>();
824 satList
.add(lumList
);
826 // Luminance brackets the pure color, but leaning toward
828 for (int lum
= lumBegin
; lum
< 100; lum
+= lumStep
) {
830 System.err.printf("<font style = \"color:");
831 System.err.printf("hsl(%d, %d%%, %d%%)",
833 System.err.printf(";\">=</font>\n");
835 int rgbColor
= hslToRgb(hue
, sat
, lum
);
836 rgbColors
.add(rgbColor
);
837 ColorIdx colorIdx
= new ColorIdx(rgbColor
,
838 rgbColors
.size() - 1);
839 lumList
.add(colorIdx
);
841 rawRgbList
.add(rgbColor
);
843 int red
= (rgbColor
>>> 16) & 0xFF;
844 int green
= (rgbColor
>>> 8) & 0xFF;
845 int blue
= rgbColor
& 0xFF;
846 int [] backToHsl
= new int[3];
847 rgbToHsl(red
, green
, blue
, backToHsl
);
848 System
.err
.printf("%d [%d] %d [%d] %d [%d]\n",
849 hue
, backToHsl
[0], sat
, backToHsl
[1],
855 // System.err.printf("\n</body></html>\n");
857 assert (rgbColors
.size() == sixelPaletteSize
);
860 * We need to sort rgbColors, so that toSixel() can know where
861 * BLACK and WHITE are in it. But we also need to be able to
862 * find the sorted values using the old unsorted indexes. So we
863 * will sort it, put all the indexes into a HashMap, and then
864 * build rgbSortedIndex[].
866 Collections
.sort(rgbColors
);
867 HashMap
<Integer
, Integer
> rgbColorIndices
= null;
868 rgbColorIndices
= new HashMap
<Integer
, Integer
>();
869 for (int i
= 0; i
< sixelPaletteSize
; i
++) {
870 rgbColorIndices
.put(rgbColors
.get(i
), i
);
872 for (int i
= 0; i
< sixelPaletteSize
; i
++) {
873 int rawColor
= rawRgbList
.get(i
);
874 rgbSortedIndex
[i
] = rgbColorIndices
.get(rawColor
);
877 for (int i
= 0; i
< sixelPaletteSize
; i
++) {
878 assert (rawRgbList
!= null);
879 int idx
= rgbSortedIndex
[i
];
880 int rgbColor
= rgbColors
.get(idx
);
881 if ((idx
!= 0) && (idx
!= sixelPaletteSize
- 1)) {
883 System.err.printf("%d %06x --> %d %06x\n",
884 i, rawRgbList.get(i), idx, rgbColors.get(idx));
886 assert (rgbColor
== rawRgbList
.get(i
));
891 // Set the dimmest color as true black, and the brightest as true
894 rgbColors
.set(sixelPaletteSize
- 1, 0xFFFFFF);
897 System.err.printf("<html><body>\n");
898 for (Integer rgb: rgbColors) {
899 System.err.printf("<font style = \"color:");
900 System.err.printf("#%06x", rgb);
901 System.err.printf(";\">=</font>\n");
903 System.err.printf("\n</body></html>\n");
909 * Emit the sixel palette.
911 * @param sb the StringBuilder to append to
912 * @param used array of booleans set to true for each color actually
913 * used in this cell, or null to emit the entire palette
914 * @return the string to emit to an ANSI / ECMA-style terminal
916 public String
emitPalette(final StringBuilder sb
,
917 final boolean [] used
) {
919 for (int i
= 0; i
< sixelPaletteSize
; i
++) {
920 if (((used
!= null) && (used
[i
] == true)) || (used
== null)) {
921 int rgbColor
= rgbColors
.get(i
);
922 sb
.append(String
.format("#%d;2;%d;%d;%d", i
,
923 ((rgbColor
>>> 16) & 0xFF) * 100 / 255,
924 ((rgbColor
>>> 8) & 0xFF) * 100 / 255,
925 ( rgbColor
& 0xFF) * 100 / 255));
928 return sb
.toString();
933 * ImageCache is a least-recently-used cache that hangs on to the
934 * post-rendered sixel or iTerm2 string for a particular set of cells.
936 private class ImageCache
{
939 * Maximum size of the cache.
941 private int maxSize
= 100;
944 * The entries stored in the cache.
946 private HashMap
<String
, CacheEntry
> cache
= null;
949 * CacheEntry is one entry in the cache.
951 private class CacheEntry
{
963 * The last time this entry was used.
965 public long millis
= 0;
968 * Public constructor.
970 * @param key the cache entry key
971 * @param data the cache entry data
973 public CacheEntry(final String key
, final String data
) {
976 this.millis
= System
.currentTimeMillis();
981 * Public constructor.
983 * @param maxSize the maximum size of the cache
985 public ImageCache(final int maxSize
) {
986 this.maxSize
= maxSize
;
987 cache
= new HashMap
<String
, CacheEntry
>();
991 * Make a unique key for a list of cells.
993 * @param cells the cells
996 private String
makeKey(final ArrayList
<Cell
> cells
) {
997 StringBuilder sb
= new StringBuilder();
998 for (Cell cell
: cells
) {
999 sb
.append(cell
.hashCode());
1001 return sb
.toString();
1005 * Get an entry from the cache.
1007 * @param cells the list of cells that are the cache key
1008 * @return the sixel string representing these cells, or null if this
1009 * list of cells is not in the cache
1011 public String
get(final ArrayList
<Cell
> cells
) {
1012 CacheEntry entry
= cache
.get(makeKey(cells
));
1013 if (entry
== null) {
1016 entry
.millis
= System
.currentTimeMillis();
1021 * Put an entry into the cache.
1023 * @param cells the list of cells that are the cache key
1024 * @param data the sixel string representing these cells
1026 public void put(final ArrayList
<Cell
> cells
, final String data
) {
1027 String key
= makeKey(cells
);
1029 // System.err.println("put() " + key + " size " + cache.size());
1031 assert (!cache
.containsKey(key
));
1033 assert (cache
.size() <= maxSize
);
1034 if (cache
.size() == maxSize
) {
1035 // Cache is at limit, evict oldest entry.
1036 long oldestTime
= Long
.MAX_VALUE
;
1037 String keyToRemove
= null;
1038 for (CacheEntry entry
: cache
.values()) {
1039 if ((entry
.millis
< oldestTime
) || (keyToRemove
== null)) {
1040 keyToRemove
= entry
.key
;
1041 oldestTime
= entry
.millis
;
1045 System.err.println("put() remove key = " + keyToRemove +
1046 " size " + cache.size());
1048 assert (keyToRemove
!= null);
1049 cache
.remove(keyToRemove
);
1051 System.err.println("put() removed, size " + cache.size());
1054 assert (cache
.size() <= maxSize
);
1055 CacheEntry entry
= new CacheEntry(key
, data
);
1056 assert (key
.equals(entry
.key
));
1057 cache
.put(key
, entry
);
1059 System.err.println("put() added key " + key + " " +
1060 " size " + cache.size());
1066 // ------------------------------------------------------------------------
1067 // Constructors -----------------------------------------------------------
1068 // ------------------------------------------------------------------------
1071 * Constructor sets up state for getEvent(). If either windowWidth or
1072 * windowHeight are less than 1, the terminal is not resized.
1074 * @param listener the object this backend needs to wake up when new
1076 * @param input an InputStream connected to the remote user, or null for
1077 * System.in. If System.in is used, then on non-Windows systems it will
1078 * be put in raw mode; closeTerminal() will (blindly!) put System.in in
1079 * cooked mode. input is always converted to a Reader with UTF-8
1081 * @param output an OutputStream connected to the remote user, or null
1082 * for System.out. output is always converted to a Writer with UTF-8
1084 * @param windowWidth the number of text columns to start with
1085 * @param windowHeight the number of text rows to start with
1086 * @throws UnsupportedEncodingException if an exception is thrown when
1087 * creating the InputStreamReader
1089 public ECMA48Terminal(final Object listener
, final InputStream input
,
1090 final OutputStream output
, final int windowWidth
,
1091 final int windowHeight
) throws UnsupportedEncodingException
{
1093 this(listener
, input
, output
);
1095 // Send dtterm/xterm sequences, which will probably not work because
1096 // allowWindowOps is defaulted to false.
1097 if ((windowWidth
> 0) && (windowHeight
> 0)) {
1098 String resizeString
= String
.format("\033[8;%d;%dt", windowHeight
,
1100 this.output
.write(resizeString
);
1101 this.output
.flush();
1106 * Constructor sets up state for getEvent().
1108 * @param listener the object this backend needs to wake up when new
1110 * @param input an InputStream connected to the remote user, or null for
1111 * System.in. If System.in is used, then on non-Windows systems it will
1112 * be put in raw mode; closeTerminal() will (blindly!) put System.in in
1113 * cooked mode. input is always converted to a Reader with UTF-8
1115 * @param output an OutputStream connected to the remote user, or null
1116 * for System.out. output is always converted to a Writer with UTF-8
1118 * @throws UnsupportedEncodingException if an exception is thrown when
1119 * creating the InputStreamReader
1121 public ECMA48Terminal(final Object listener
, final InputStream input
,
1122 final OutputStream output
) throws UnsupportedEncodingException
{
1128 stopReaderThread
= false;
1129 this.listener
= listener
;
1131 if (input
== null) {
1132 // inputStream = System.in;
1133 inputStream
= new FileInputStream(FileDescriptor
.in
);
1137 inputStream
= input
;
1139 this.input
= new InputStreamReader(inputStream
, "UTF-8");
1141 if (input
instanceof SessionInfo
) {
1142 // This is a TelnetInputStream that exposes window size and
1143 // environment variables from the telnet layer.
1144 sessionInfo
= (SessionInfo
) input
;
1146 if (sessionInfo
== null) {
1147 if (input
== null) {
1148 // Reading right off the tty
1149 sessionInfo
= new TTYSessionInfo();
1151 sessionInfo
= new TSessionInfo();
1155 if (output
== null) {
1156 this.output
= new PrintWriter(new OutputStreamWriter(System
.out
,
1159 this.output
= new PrintWriter(new OutputStreamWriter(output
,
1163 // Request Device Attributes
1164 this.output
.printf("\033[c");
1166 // Request xterm report window/cell dimensions in pixels
1167 this.output
.printf("%s", xtermReportPixelDimensions());
1169 // Enable mouse reporting and metaSendsEscape
1170 this.output
.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
1172 // Request xterm use the sixel settings we want
1173 this.output
.printf("%s", xtermSetSixelSettings());
1175 this.output
.flush();
1177 // Query the screen size
1178 sessionInfo
.queryWindowSize();
1179 setDimensions(sessionInfo
.getWindowWidth(),
1180 sessionInfo
.getWindowHeight());
1182 // Hang onto the window size
1183 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
1184 sessionInfo
.getWindowWidth(), sessionInfo
.getWindowHeight());
1188 // Spin up the input reader
1189 eventQueue
= new ArrayList
<TInputEvent
>();
1190 readerThread
= new Thread(this);
1191 readerThread
.start();
1194 this.output
.write(clearAll());
1195 this.output
.flush();
1199 * Constructor sets up state for getEvent().
1201 * @param listener the object this backend needs to wake up when new
1203 * @param input the InputStream underlying 'reader'. Its available()
1204 * method is used to determine if reader.read() will block or not.
1205 * @param reader a Reader connected to the remote user.
1206 * @param writer a PrintWriter connected to the remote user.
1207 * @param setRawMode if true, set System.in into raw mode with stty.
1208 * This should in general not be used. It is here solely for Demo3,
1209 * which uses System.in.
1210 * @throws IllegalArgumentException if input, reader, or writer are null.
1212 public ECMA48Terminal(final Object listener
, final InputStream input
,
1213 final Reader reader
, final PrintWriter writer
,
1214 final boolean setRawMode
) {
1216 if (input
== null) {
1217 throw new IllegalArgumentException("InputStream must be specified");
1219 if (reader
== null) {
1220 throw new IllegalArgumentException("Reader must be specified");
1222 if (writer
== null) {
1223 throw new IllegalArgumentException("Writer must be specified");
1229 stopReaderThread
= false;
1230 this.listener
= listener
;
1232 inputStream
= input
;
1233 this.input
= reader
;
1235 if (setRawMode
== true) {
1238 this.setRawMode
= setRawMode
;
1240 if (input
instanceof SessionInfo
) {
1241 // This is a TelnetInputStream that exposes window size and
1242 // environment variables from the telnet layer.
1243 sessionInfo
= (SessionInfo
) input
;
1245 if (sessionInfo
== null) {
1246 if (setRawMode
== true) {
1247 // Reading right off the tty
1248 sessionInfo
= new TTYSessionInfo();
1250 sessionInfo
= new TSessionInfo();
1254 this.output
= writer
;
1256 // Request Device Attributes
1257 this.output
.printf("\033[c");
1259 // Request xterm report window/cell dimensions in pixels
1260 this.output
.printf("%s", xtermReportPixelDimensions());
1262 // Enable mouse reporting and metaSendsEscape
1263 this.output
.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
1265 // Request xterm use the sixel settings we want
1266 this.output
.printf("%s", xtermSetSixelSettings());
1268 this.output
.flush();
1270 // Query the screen size
1271 sessionInfo
.queryWindowSize();
1272 setDimensions(sessionInfo
.getWindowWidth(),
1273 sessionInfo
.getWindowHeight());
1275 // Hang onto the window size
1276 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
1277 sessionInfo
.getWindowWidth(), sessionInfo
.getWindowHeight());
1281 // Spin up the input reader
1282 eventQueue
= new ArrayList
<TInputEvent
>();
1283 readerThread
= new Thread(this);
1284 readerThread
.start();
1287 this.output
.write(clearAll());
1288 this.output
.flush();
1292 * Constructor sets up state for getEvent().
1294 * @param listener the object this backend needs to wake up when new
1296 * @param input the InputStream underlying 'reader'. Its available()
1297 * method is used to determine if reader.read() will block or not.
1298 * @param reader a Reader connected to the remote user.
1299 * @param writer a PrintWriter connected to the remote user.
1300 * @throws IllegalArgumentException if input, reader, or writer are null.
1302 public ECMA48Terminal(final Object listener
, final InputStream input
,
1303 final Reader reader
, final PrintWriter writer
) {
1305 this(listener
, input
, reader
, writer
, false);
1308 // ------------------------------------------------------------------------
1309 // LogicalScreen ----------------------------------------------------------
1310 // ------------------------------------------------------------------------
1313 * Set the window title.
1315 * @param title the new title
1318 public void setTitle(final String title
) {
1319 output
.write(getSetTitleString(title
));
1324 * Push the logical screen to the physical device.
1327 public void flushPhysical() {
1328 StringBuilder sb
= new StringBuilder();
1332 && (cursorY
<= height
- 1)
1333 && (cursorX
<= width
- 1)
1336 sb
.append(cursor(true));
1337 sb
.append(gotoXY(cursorX
, cursorY
));
1339 sb
.append(cursor(false));
1342 output
.write(sb
.toString());
1347 * Resize the physical screen to match the logical screen dimensions.
1350 public void resizeToScreen() {
1351 // Send dtterm/xterm sequences, which will probably not work because
1352 // allowWindowOps is defaulted to false.
1353 String resizeString
= String
.format("\033[8;%d;%dt", getHeight(),
1355 this.output
.write(resizeString
);
1356 this.output
.flush();
1359 // ------------------------------------------------------------------------
1360 // TerminalReader ---------------------------------------------------------
1361 // ------------------------------------------------------------------------
1364 * Check if there are events in the queue.
1366 * @return if true, getEvents() has something to return to the backend
1368 public boolean hasEvents() {
1369 synchronized (eventQueue
) {
1370 return (eventQueue
.size() > 0);
1375 * Return any events in the IO queue.
1377 * @param queue list to append new events to
1379 public void getEvents(final List
<TInputEvent
> queue
) {
1380 synchronized (eventQueue
) {
1381 if (eventQueue
.size() > 0) {
1382 synchronized (queue
) {
1383 queue
.addAll(eventQueue
);
1391 * Restore terminal to normal state.
1393 public void closeTerminal() {
1395 // System.err.println("=== closeTerminal() ==="); System.err.flush();
1397 // Tell the reader thread to stop looking at input
1398 stopReaderThread
= true;
1400 readerThread
.join();
1401 } catch (InterruptedException e
) {
1402 if (debugToStderr
) {
1403 e
.printStackTrace();
1407 // Disable mouse reporting and show cursor. Defensive null check
1408 // here in case closeTerminal() is called twice.
1409 if (output
!= null) {
1410 output
.printf("%s%s%s%s", mouse(false), cursor(true),
1411 defaultColor(), xtermResetSixelSettings());
1418 // We don't close System.in/out
1420 // Shut down the streams, this should wake up the reader thread
1421 // and make it exit.
1422 if (input
!= null) {
1425 } catch (IOException e
) {
1430 if (output
!= null) {
1438 * Set listener to a different Object.
1440 * @param listener the new listening object that run() wakes up on new
1443 public void setListener(final Object listener
) {
1444 this.listener
= listener
;
1448 * Reload options from System properties.
1450 public void reloadOptions() {
1451 // Permit RGB colors only if externally requested.
1452 if (System
.getProperty("jexer.ECMA48.rgbColor",
1453 "false").equals("true")
1460 // Default to using images for full-width characters.
1461 if (System
.getProperty("jexer.ECMA48.wideCharImages",
1462 "true").equals("true")) {
1463 wideCharImages
= true;
1465 wideCharImages
= false;
1468 // Pull the system properties for sixel output.
1469 if (System
.getProperty("jexer.ECMA48.sixel", "true").equals("true")) {
1476 int paletteSize
= 1024;
1478 paletteSize
= Integer
.parseInt(System
.getProperty(
1479 "jexer.ECMA48.sixelPaletteSize", "1024"));
1480 switch (paletteSize
) {
1486 sixelPaletteSize
= paletteSize
;
1492 } catch (NumberFormatException e
) {
1497 if (System
.getProperty("jexer.ECMA48.sixelSharedPalette",
1498 "true").equals("false")) {
1499 sixelSharedPalette
= false;
1501 sixelSharedPalette
= true;
1504 // Default to not supporting iTerm2 images.
1505 if (System
.getProperty("jexer.ECMA48.iTerm2Images",
1506 "false").equals("true")) {
1507 iterm2Images
= true;
1509 iterm2Images
= false;
1512 // Default to using JPG Jexer images if terminal supports it.
1513 String jexerImageStr
= System
.getProperty("jexer.ECMA48.jexerImages",
1514 "jpg").toLowerCase();
1515 if (jexerImageStr
.equals("false")) {
1516 jexerImageOption
= JexerImageOption
.DISABLED
;
1517 } else if (jexerImageStr
.equals("jpg")) {
1518 jexerImageOption
= JexerImageOption
.JPG
;
1519 } else if (jexerImageStr
.equals("png")) {
1520 jexerImageOption
= JexerImageOption
.PNG
;
1521 } else if (jexerImageStr
.equals("rgb")) {
1522 jexerImageOption
= JexerImageOption
.RGB
;
1525 // Set custom colors
1526 setCustomSystemColors();
1529 // ------------------------------------------------------------------------
1530 // Runnable ---------------------------------------------------------------
1531 // ------------------------------------------------------------------------
1534 * Read function runs on a separate thread.
1537 boolean done
= false;
1538 // available() will often return > 1, so we need to read in chunks to
1540 char [] readBuffer
= new char[128];
1541 List
<TInputEvent
> events
= new ArrayList
<TInputEvent
>();
1543 while (!done
&& !stopReaderThread
) {
1545 // We assume that if inputStream has bytes available, then
1546 // input won't block on read().
1547 int n
= inputStream
.available();
1550 System.err.printf("inputStream.available(): %d\n", n);
1555 if (readBuffer
.length
< n
) {
1556 // The buffer wasn't big enough, make it huger
1557 readBuffer
= new char[readBuffer
.length
* 2];
1560 // System.err.printf("BEFORE read()\n"); System.err.flush();
1562 int rc
= input
.read(readBuffer
, 0, readBuffer
.length
);
1565 System.err.printf("AFTER read() %d\n", rc);
1573 for (int i
= 0; i
< rc
; i
++) {
1574 int ch
= readBuffer
[i
];
1575 processChar(events
, (char)ch
);
1577 getIdleEvents(events
);
1578 if (events
.size() > 0) {
1579 // Add to the queue for the backend thread to
1580 // be able to obtain.
1581 synchronized (eventQueue
) {
1582 eventQueue
.addAll(events
);
1584 if (listener
!= null) {
1585 synchronized (listener
) {
1586 listener
.notifyAll();
1593 getIdleEvents(events
);
1594 if (events
.size() > 0) {
1595 synchronized (eventQueue
) {
1596 eventQueue
.addAll(events
);
1598 if (listener
!= null) {
1599 synchronized (listener
) {
1600 listener
.notifyAll();
1606 if (output
.checkError()) {
1611 // Wait 20 millis for more data
1614 // System.err.println("end while loop"); System.err.flush();
1615 } catch (InterruptedException e
) {
1617 } catch (IOException e
) {
1618 e
.printStackTrace();
1621 } // while ((done == false) && (stopReaderThread == false))
1623 // Pass an event up to TApplication to tell it this Backend is done.
1624 synchronized (eventQueue
) {
1625 eventQueue
.add(new TCommandEvent(cmBackendDisconnect
));
1627 if (listener
!= null) {
1628 synchronized (listener
) {
1629 listener
.notifyAll();
1633 // System.err.println("*** run() exiting..."); System.err.flush();
1636 // ------------------------------------------------------------------------
1637 // ECMA48Terminal ---------------------------------------------------------
1638 // ------------------------------------------------------------------------
1641 * Get the width of a character cell in pixels.
1643 * @return the width in pixels of a character cell
1645 public int getTextWidth() {
1646 return (widthPixels
/ sessionInfo
.getWindowWidth());
1650 * Get the height of a character cell in pixels.
1652 * @return the height in pixels of a character cell
1654 public int getTextHeight() {
1655 return (heightPixels
/ sessionInfo
.getWindowHeight());
1659 * Getter for sessionInfo.
1661 * @return the SessionInfo
1663 public SessionInfo
getSessionInfo() {
1668 * Get the output writer.
1670 * @return the Writer
1672 public PrintWriter
getOutput() {
1677 * Call 'stty' to set cooked mode.
1679 * <p>Actually executes '/bin/sh -c stty sane cooked < /dev/tty'
1681 private void sttyCooked() {
1686 * Call 'stty' to set raw mode.
1688 * <p>Actually executes '/bin/sh -c stty -ignbrk -brkint -parmrk -istrip
1689 * -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten
1690 * -parenb cs8 min 1 < /dev/tty'
1692 private void sttyRaw() {
1697 * Call 'stty' to set raw or cooked mode.
1699 * @param mode if true, set raw mode, otherwise set cooked mode
1701 private void doStty(final boolean mode
) {
1702 String
[] cmdRaw
= {
1703 "/bin/sh", "-c", "stty -ignbrk -brkint -parmrk -istrip -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten -parenb cs8 min 1 < /dev/tty"
1705 String
[] cmdCooked
= {
1706 "/bin/sh", "-c", "stty sane cooked < /dev/tty"
1711 process
= Runtime
.getRuntime().exec(cmdRaw
);
1713 process
= Runtime
.getRuntime().exec(cmdCooked
);
1715 BufferedReader in
= new BufferedReader(new InputStreamReader(process
.getInputStream(), "UTF-8"));
1716 String line
= in
.readLine();
1717 if ((line
!= null) && (line
.length() > 0)) {
1718 System
.err
.println("WEIRD?! Normal output from stty: " + line
);
1721 BufferedReader err
= new BufferedReader(new InputStreamReader(process
.getErrorStream(), "UTF-8"));
1722 line
= err
.readLine();
1723 if ((line
!= null) && (line
.length() > 0)) {
1724 System
.err
.println("Error output from stty: " + line
);
1729 } catch (InterruptedException e
) {
1730 if (debugToStderr
) {
1731 e
.printStackTrace();
1735 int rc
= process
.exitValue();
1737 System
.err
.println("stty returned error code: " + rc
);
1739 } catch (IOException e
) {
1740 e
.printStackTrace();
1747 public void flush() {
1752 * Perform a somewhat-optimal rendering of a line.
1754 * @param y row coordinate. 0 is the top-most row.
1755 * @param sb StringBuilder to write escape sequences to
1756 * @param lastAttr cell attributes from the last call to flushLine
1758 private void flushLine(final int y
, final StringBuilder sb
,
1759 CellAttributes lastAttr
) {
1763 for (int x
= 0; x
< width
; x
++) {
1764 Cell lCell
= logical
[x
][y
];
1765 if (!lCell
.isBlank()) {
1769 // Push textEnd to first column beyond the text area
1773 // reallyCleared = true;
1775 boolean hasImage
= false;
1777 for (int x
= 0; x
< width
; x
++) {
1778 Cell lCell
= logical
[x
][y
];
1779 Cell pCell
= physical
[x
][y
];
1781 if (!lCell
.equals(pCell
) || reallyCleared
) {
1783 if (debugToStderr
) {
1784 System
.err
.printf("\n--\n");
1785 System
.err
.printf(" Y: %d X: %d\n", y
, x
);
1786 System
.err
.printf(" lCell: %s\n", lCell
);
1787 System
.err
.printf(" pCell: %s\n", pCell
);
1788 System
.err
.printf(" ==== \n");
1791 if (lastAttr
== null) {
1792 lastAttr
= new CellAttributes();
1793 sb
.append(normal());
1797 if ((lastX
!= (x
- 1)) || (lastX
== -1)) {
1798 // Advancing at least one cell, or the first gotoXY
1799 sb
.append(gotoXY(x
, y
));
1802 assert (lastAttr
!= null);
1804 if ((x
== textEnd
) && (textEnd
< width
- 1)) {
1805 assert (lCell
.isBlank());
1807 for (int i
= x
; i
< width
; i
++) {
1808 assert (logical
[i
][y
].isBlank());
1809 // Physical is always updated
1810 physical
[i
][y
].reset();
1813 // Clear remaining line
1814 sb
.append(clearRemainingLine());
1819 // Image cell: bypass the rest of the loop, it is not
1821 if ((wideCharImages
&& lCell
.isImage())
1824 && (lCell
.getWidth() == Cell
.Width
.SINGLE
))
1828 // Save the last rendered cell
1831 // Physical is always updated
1832 physical
[x
][y
].setTo(lCell
);
1836 assert ((wideCharImages
&& !lCell
.isImage())
1838 && (!lCell
.isImage()
1840 && (lCell
.getWidth() != Cell
.Width
.SINGLE
)))));
1842 if (!wideCharImages
&& (lCell
.getWidth() == Cell
.Width
.RIGHT
)) {
1848 sb
.append(gotoXY(x
, y
));
1851 // Now emit only the modified attributes
1852 if ((lCell
.getForeColor() != lastAttr
.getForeColor())
1853 && (lCell
.getBackColor() != lastAttr
.getBackColor())
1855 && (lCell
.isBold() == lastAttr
.isBold())
1856 && (lCell
.isReverse() == lastAttr
.isReverse())
1857 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1858 && (lCell
.isBlink() == lastAttr
.isBlink())
1860 // Both colors changed, attributes the same
1861 sb
.append(color(lCell
.isBold(),
1862 lCell
.getForeColor(), lCell
.getBackColor()));
1864 if (debugToStderr
) {
1865 System
.err
.printf("1 Change only fore/back colors\n");
1868 } else if (lCell
.isRGB()
1869 && (lCell
.getForeColorRGB() != lastAttr
.getForeColorRGB())
1870 && (lCell
.getBackColorRGB() != lastAttr
.getBackColorRGB())
1871 && (lCell
.isBold() == lastAttr
.isBold())
1872 && (lCell
.isReverse() == lastAttr
.isReverse())
1873 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1874 && (lCell
.isBlink() == lastAttr
.isBlink())
1876 // Both colors changed, attributes the same
1877 sb
.append(colorRGB(lCell
.getForeColorRGB(),
1878 lCell
.getBackColorRGB()));
1880 if (debugToStderr
) {
1881 System
.err
.printf("1 Change only fore/back colors (RGB)\n");
1883 } else if ((lCell
.getForeColor() != lastAttr
.getForeColor())
1884 && (lCell
.getBackColor() != lastAttr
.getBackColor())
1886 && (lCell
.isBold() != lastAttr
.isBold())
1887 && (lCell
.isReverse() != lastAttr
.isReverse())
1888 && (lCell
.isUnderline() != lastAttr
.isUnderline())
1889 && (lCell
.isBlink() != lastAttr
.isBlink())
1891 // Everything is different
1892 sb
.append(color(lCell
.getForeColor(),
1893 lCell
.getBackColor(),
1894 lCell
.isBold(), lCell
.isReverse(),
1896 lCell
.isUnderline()));
1898 if (debugToStderr
) {
1899 System
.err
.printf("2 Set all attributes\n");
1901 } else if ((lCell
.getForeColor() != lastAttr
.getForeColor())
1902 && (lCell
.getBackColor() == lastAttr
.getBackColor())
1904 && (lCell
.isBold() == lastAttr
.isBold())
1905 && (lCell
.isReverse() == lastAttr
.isReverse())
1906 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1907 && (lCell
.isBlink() == lastAttr
.isBlink())
1910 // Attributes same, foreColor different
1911 sb
.append(color(lCell
.isBold(),
1912 lCell
.getForeColor(), true));
1914 if (debugToStderr
) {
1915 System
.err
.printf("3 Change foreColor\n");
1917 } else if (lCell
.isRGB()
1918 && (lCell
.getForeColorRGB() != lastAttr
.getForeColorRGB())
1919 && (lCell
.getBackColorRGB() == lastAttr
.getBackColorRGB())
1920 && (lCell
.getForeColorRGB() >= 0)
1921 && (lCell
.getBackColorRGB() >= 0)
1922 && (lCell
.isBold() == lastAttr
.isBold())
1923 && (lCell
.isReverse() == lastAttr
.isReverse())
1924 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1925 && (lCell
.isBlink() == lastAttr
.isBlink())
1927 // Attributes same, foreColor different
1928 sb
.append(colorRGB(lCell
.getForeColorRGB(), true));
1930 if (debugToStderr
) {
1931 System
.err
.printf("3 Change foreColor (RGB)\n");
1933 } else if ((lCell
.getForeColor() == lastAttr
.getForeColor())
1934 && (lCell
.getBackColor() != lastAttr
.getBackColor())
1936 && (lCell
.isBold() == lastAttr
.isBold())
1937 && (lCell
.isReverse() == lastAttr
.isReverse())
1938 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1939 && (lCell
.isBlink() == lastAttr
.isBlink())
1941 // Attributes same, backColor different
1942 sb
.append(color(lCell
.isBold(),
1943 lCell
.getBackColor(), false));
1945 if (debugToStderr
) {
1946 System
.err
.printf("4 Change backColor\n");
1948 } else if (lCell
.isRGB()
1949 && (lCell
.getForeColorRGB() == lastAttr
.getForeColorRGB())
1950 && (lCell
.getBackColorRGB() != lastAttr
.getBackColorRGB())
1951 && (lCell
.isBold() == lastAttr
.isBold())
1952 && (lCell
.isReverse() == lastAttr
.isReverse())
1953 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1954 && (lCell
.isBlink() == lastAttr
.isBlink())
1956 // Attributes same, foreColor different
1957 sb
.append(colorRGB(lCell
.getBackColorRGB(), false));
1959 if (debugToStderr
) {
1960 System
.err
.printf("4 Change backColor (RGB)\n");
1962 } else if ((lCell
.getForeColor() == lastAttr
.getForeColor())
1963 && (lCell
.getBackColor() == lastAttr
.getBackColor())
1964 && (lCell
.getForeColorRGB() == lastAttr
.getForeColorRGB())
1965 && (lCell
.getBackColorRGB() == lastAttr
.getBackColorRGB())
1966 && (lCell
.isBold() == lastAttr
.isBold())
1967 && (lCell
.isReverse() == lastAttr
.isReverse())
1968 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1969 && (lCell
.isBlink() == lastAttr
.isBlink())
1972 // All attributes the same, just print the char
1975 if (debugToStderr
) {
1976 System
.err
.printf("5 Only emit character\n");
1979 // Just reset everything again
1980 if (!lCell
.isRGB()) {
1981 sb
.append(color(lCell
.getForeColor(),
1982 lCell
.getBackColor(),
1986 lCell
.isUnderline()));
1988 if (debugToStderr
) {
1989 System
.err
.printf("6 Change all attributes\n");
1992 sb
.append(colorRGB(lCell
.getForeColorRGB(),
1993 lCell
.getBackColorRGB(),
1997 lCell
.isUnderline()));
1998 if (debugToStderr
) {
1999 System
.err
.printf("6 Change all attributes (RGB)\n");
2004 // Emit the character
2006 // Don't emit the right-half of full-width chars.
2008 && (lCell
.getWidth() != Cell
.Width
.RIGHT
))
2010 sb
.append(Character
.toChars(lCell
.getChar()));
2013 // Save the last rendered cell
2015 lastAttr
.setTo(lCell
);
2017 // Physical is always updated
2018 physical
[x
][y
].setTo(lCell
);
2020 } // if (!lCell.equals(pCell) || (reallyCleared == true))
2022 } // for (int x = 0; x < width; x++)
2026 * Render the screen to a string that can be emitted to something that
2027 * knows how to process ECMA-48/ANSI X3.64 escape sequences.
2029 * @param sb StringBuilder to write escape sequences to
2030 * @return escape sequences string that provides the updates to the
2033 private String
flushString(final StringBuilder sb
) {
2034 CellAttributes attr
= null;
2036 if (reallyCleared
) {
2037 attr
= new CellAttributes();
2038 sb
.append(clearAll());
2042 * For images support, draw all of the image output first, and then
2043 * draw everything else afterwards. This works OK, but performance
2044 * is still a drag on larger pictures.
2046 for (int y
= 0; y
< height
; y
++) {
2047 for (int x
= 0; x
< width
; x
++) {
2048 // If physical had non-image data that is now image data, the
2049 // entire row must be redrawn.
2050 Cell lCell
= logical
[x
][y
];
2051 Cell pCell
= physical
[x
][y
];
2052 if (lCell
.isImage() && !pCell
.isImage()) {
2058 for (int y
= 0; y
< height
; y
++) {
2059 for (int x
= 0; x
< width
; x
++) {
2060 Cell lCell
= logical
[x
][y
];
2061 Cell pCell
= physical
[x
][y
];
2063 if (!lCell
.isImage()
2065 && (lCell
.getWidth() != Cell
.Width
.SINGLE
))
2072 while ((right
< width
)
2073 && (logical
[right
][y
].isImage())
2074 && (!logical
[right
][y
].equals(physical
[right
][y
])
2079 ArrayList
<Cell
> cellsToDraw
= new ArrayList
<Cell
>();
2080 for (int i
= 0; i
< (right
- x
); i
++) {
2081 assert (logical
[x
+ i
][y
].isImage());
2082 cellsToDraw
.add(logical
[x
+ i
][y
]);
2084 // Physical is always updated.
2085 physical
[x
+ i
][y
].setTo(lCell
);
2087 if (cellsToDraw
.size() > 0) {
2089 sb
.append(toIterm2Image(x
, y
, cellsToDraw
));
2090 } else if (jexerImageOption
!= JexerImageOption
.DISABLED
) {
2091 sb
.append(toJexerImage(x
, y
, cellsToDraw
));
2093 sb
.append(toSixel(x
, y
, cellsToDraw
));
2101 // Draw the text part now.
2102 for (int y
= 0; y
< height
; y
++) {
2103 flushLine(y
, sb
, attr
);
2106 reallyCleared
= false;
2108 String result
= sb
.toString();
2109 if (debugToStderr
) {
2110 System
.err
.printf("flushString(): %s\n", result
);
2116 * Reset keyboard/mouse input parser.
2118 private void resetParser() {
2119 state
= ParseState
.GROUND
;
2120 params
= new ArrayList
<String
>();
2123 decPrivateModeFlag
= false;
2127 * Produce a control character or one of the special ones (ENTER, TAB,
2130 * @param ch Unicode code point
2131 * @param alt if true, set alt on the TKeypress
2132 * @return one TKeypress event, either a control character (e.g. isKey ==
2133 * false, ch == 'A', ctrl == true), or a special key (e.g. isKey == true,
2136 private TKeypressEvent
controlChar(final char ch
, final boolean alt
) {
2137 // System.err.printf("controlChar: %02x\n", ch);
2141 // Carriage return --> ENTER
2142 return new TKeypressEvent(kbEnter
, alt
, false, false);
2144 // Linefeed --> ENTER
2145 return new TKeypressEvent(kbEnter
, alt
, false, false);
2148 return new TKeypressEvent(kbEsc
, alt
, false, false);
2151 return new TKeypressEvent(kbTab
, alt
, false, false);
2153 // Make all other control characters come back as the alphabetic
2154 // character with the ctrl field set. So SOH would be 'A' +
2156 return new TKeypressEvent(false, 0, (char)(ch
+ 0x40),
2162 * Produce special key from CSI Pn ; Pm ; ... ~
2164 * @return one KEYPRESS event representing a special key
2166 private TInputEvent
csiFnKey() {
2168 if (params
.size() > 0) {
2169 key
= Integer
.parseInt(params
.get(0));
2171 boolean alt
= false;
2172 boolean ctrl
= false;
2173 boolean shift
= false;
2174 if (params
.size() > 1) {
2175 shift
= csiIsShift(params
.get(1));
2176 alt
= csiIsAlt(params
.get(1));
2177 ctrl
= csiIsCtrl(params
.get(1));
2182 return new TKeypressEvent(kbHome
, alt
, ctrl
, shift
);
2184 return new TKeypressEvent(kbIns
, alt
, ctrl
, shift
);
2186 return new TKeypressEvent(kbDel
, alt
, ctrl
, shift
);
2188 return new TKeypressEvent(kbEnd
, alt
, ctrl
, shift
);
2190 return new TKeypressEvent(kbPgUp
, alt
, ctrl
, shift
);
2192 return new TKeypressEvent(kbPgDn
, alt
, ctrl
, shift
);
2194 return new TKeypressEvent(kbF5
, alt
, ctrl
, shift
);
2196 return new TKeypressEvent(kbF6
, alt
, ctrl
, shift
);
2198 return new TKeypressEvent(kbF7
, alt
, ctrl
, shift
);
2200 return new TKeypressEvent(kbF8
, alt
, ctrl
, shift
);
2202 return new TKeypressEvent(kbF9
, alt
, ctrl
, shift
);
2204 return new TKeypressEvent(kbF10
, alt
, ctrl
, shift
);
2206 return new TKeypressEvent(kbF11
, alt
, ctrl
, shift
);
2208 return new TKeypressEvent(kbF12
, alt
, ctrl
, shift
);
2216 * Produce mouse events based on "Any event tracking" and UTF-8
2218 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
2220 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
2222 private TInputEvent
parseMouse() {
2223 int buttons
= params
.get(0).charAt(0) - 32;
2224 int x
= params
.get(0).charAt(1) - 32 - 1;
2225 int y
= params
.get(0).charAt(2) - 32 - 1;
2227 // Clamp X and Y to the physical screen coordinates.
2228 if (x
>= windowResize
.getWidth()) {
2229 x
= windowResize
.getWidth() - 1;
2231 if (y
>= windowResize
.getHeight()) {
2232 y
= windowResize
.getHeight() - 1;
2235 TMouseEvent
.Type eventType
= TMouseEvent
.Type
.MOUSE_DOWN
;
2236 boolean eventMouse1
= false;
2237 boolean eventMouse2
= false;
2238 boolean eventMouse3
= false;
2239 boolean eventMouseWheelUp
= false;
2240 boolean eventMouseWheelDown
= false;
2241 boolean eventAlt
= false;
2242 boolean eventCtrl
= false;
2243 boolean eventShift
= false;
2245 // System.err.printf("buttons: %04x\r\n", buttons);
2247 switch (buttons
& 0xE3) {
2262 if (!mouse1
&& !mouse2
&& !mouse3
) {
2263 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2265 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
2282 // Dragging with mouse1 down
2285 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2289 // Dragging with mouse2 down
2292 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2296 // Dragging with mouse3 down
2299 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2303 // Dragging with mouse2 down after wheelUp
2306 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2310 // Dragging with mouse2 down after wheelDown
2313 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2317 eventMouseWheelUp
= true;
2321 eventMouseWheelDown
= true;
2325 // Unknown, just make it motion
2326 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2330 if ((buttons
& 0x04) != 0) {
2333 if ((buttons
& 0x08) != 0) {
2336 if ((buttons
& 0x10) != 0) {
2340 return new TMouseEvent(eventType
, x
, y
, x
, y
,
2341 eventMouse1
, eventMouse2
, eventMouse3
,
2342 eventMouseWheelUp
, eventMouseWheelDown
,
2343 eventAlt
, eventCtrl
, eventShift
);
2347 * Produce mouse events based on "Any event tracking" and SGR
2349 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
2351 * @param release if true, this was a release ('m')
2352 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
2354 private TInputEvent
parseMouseSGR(final boolean release
) {
2355 // SGR extended coordinates - mode 1006
2356 if (params
.size() < 3) {
2357 // Invalid position, bail out.
2360 int buttons
= Integer
.parseInt(params
.get(0));
2361 int x
= Integer
.parseInt(params
.get(1)) - 1;
2362 int y
= Integer
.parseInt(params
.get(2)) - 1;
2364 // Clamp X and Y to the physical screen coordinates.
2365 if (x
>= windowResize
.getWidth()) {
2366 x
= windowResize
.getWidth() - 1;
2368 if (y
>= windowResize
.getHeight()) {
2369 y
= windowResize
.getHeight() - 1;
2372 TMouseEvent
.Type eventType
= TMouseEvent
.Type
.MOUSE_DOWN
;
2373 boolean eventMouse1
= false;
2374 boolean eventMouse2
= false;
2375 boolean eventMouse3
= false;
2376 boolean eventMouseWheelUp
= false;
2377 boolean eventMouseWheelDown
= false;
2378 boolean eventAlt
= false;
2379 boolean eventCtrl
= false;
2380 boolean eventShift
= false;
2383 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
2386 switch (buttons
& 0xE3) {
2397 // Motion only, no buttons down
2398 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2402 // Dragging with mouse1 down
2404 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2408 // Dragging with mouse2 down
2410 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2414 // Dragging with mouse3 down
2416 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2420 // Dragging with mouse2 down after wheelUp
2422 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2426 // Dragging with mouse2 down after wheelDown
2428 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2432 eventMouseWheelUp
= true;
2436 eventMouseWheelDown
= true;
2440 // Unknown, bail out
2444 if ((buttons
& 0x04) != 0) {
2447 if ((buttons
& 0x08) != 0) {
2450 if ((buttons
& 0x10) != 0) {
2454 return new TMouseEvent(eventType
, x
, y
, x
, y
,
2455 eventMouse1
, eventMouse2
, eventMouse3
,
2456 eventMouseWheelUp
, eventMouseWheelDown
,
2457 eventAlt
, eventCtrl
, eventShift
);
2461 * Return any events in the IO queue due to timeout.
2463 * @param queue list to append new events to
2465 private void getIdleEvents(final List
<TInputEvent
> queue
) {
2466 long nowTime
= System
.currentTimeMillis();
2468 // Check for new window size
2469 long windowSizeDelay
= nowTime
- windowSizeTime
;
2470 if (windowSizeDelay
> 1000) {
2471 int oldTextWidth
= getTextWidth();
2472 int oldTextHeight
= getTextHeight();
2474 sessionInfo
.queryWindowSize();
2475 int newWidth
= sessionInfo
.getWindowWidth();
2476 int newHeight
= sessionInfo
.getWindowHeight();
2478 if ((newWidth
!= windowResize
.getWidth())
2479 || (newHeight
!= windowResize
.getHeight())
2482 // Request xterm report window dimensions in pixels again.
2483 // Between now and then, ensure that the reported text cell
2484 // size is the same by setting widthPixels and heightPixels
2485 // to match the new dimensions.
2486 widthPixels
= oldTextWidth
* newWidth
;
2487 heightPixels
= oldTextHeight
* newHeight
;
2489 if (debugToStderr
) {
2490 System
.err
.println("Screen size changed, old size " +
2492 System
.err
.println(" new size " +
2493 newWidth
+ " x " + newHeight
);
2494 System
.err
.println(" old pixels " +
2495 oldTextWidth
+ " x " + oldTextHeight
);
2496 System
.err
.println(" new pixels " +
2497 getTextWidth() + " x " + getTextHeight());
2500 this.output
.printf("%s", xtermReportPixelDimensions());
2501 this.output
.flush();
2503 TResizeEvent event
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
2504 newWidth
, newHeight
);
2505 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
2506 newWidth
, newHeight
);
2509 windowSizeTime
= nowTime
;
2512 // ESCDELAY type timeout
2513 if (state
== ParseState
.ESCAPE
) {
2514 long escDelay
= nowTime
- escapeTime
;
2515 if (escDelay
> 100) {
2516 // After 0.1 seconds, assume a true escape character
2517 queue
.add(controlChar((char)0x1B, false));
2524 * Returns true if the CSI parameter for a keyboard command means that
2527 private boolean csiIsShift(final String x
) {
2539 * Returns true if the CSI parameter for a keyboard command means that
2542 private boolean csiIsAlt(final String x
) {
2554 * Returns true if the CSI parameter for a keyboard command means that
2557 private boolean csiIsCtrl(final String x
) {
2569 * Parses the next character of input to see if an InputEvent is
2572 * @param events list to append new events to
2573 * @param ch Unicode code point
2575 private void processChar(final List
<TInputEvent
> events
, final char ch
) {
2577 // ESCDELAY type timeout
2578 long nowTime
= System
.currentTimeMillis();
2579 if (state
== ParseState
.ESCAPE
) {
2580 long escDelay
= nowTime
- escapeTime
;
2581 if (escDelay
> 250) {
2582 // After 0.25 seconds, assume a true escape character
2583 events
.add(controlChar((char)0x1B, false));
2589 boolean ctrl
= false;
2590 boolean alt
= false;
2591 boolean shift
= false;
2593 // System.err.printf("state: %s ch %c\r\n", state, ch);
2599 state
= ParseState
.ESCAPE
;
2600 escapeTime
= nowTime
;
2605 // Control character
2606 events
.add(controlChar(ch
, false));
2613 events
.add(new TKeypressEvent(false, 0, ch
,
2614 false, false, false));
2623 // ALT-Control character
2624 events
.add(controlChar(ch
, true));
2630 // This will be one of the function keys
2631 state
= ParseState
.ESCAPE_INTERMEDIATE
;
2635 // '[' goes to CSI_ENTRY
2637 state
= ParseState
.CSI_ENTRY
;
2641 // Everything else is assumed to be Alt-keystroke
2642 if ((ch
>= 'A') && (ch
<= 'Z')) {
2646 events
.add(new TKeypressEvent(false, 0, ch
, alt
, ctrl
, shift
));
2650 case ESCAPE_INTERMEDIATE
:
2651 if ((ch
>= 'P') && (ch
<= 'S')) {
2655 events
.add(new TKeypressEvent(kbF1
));
2658 events
.add(new TKeypressEvent(kbF2
));
2661 events
.add(new TKeypressEvent(kbF3
));
2664 events
.add(new TKeypressEvent(kbF4
));
2673 // Unknown keystroke, ignore
2678 // Numbers - parameter values
2679 if ((ch
>= '0') && (ch
<= '9')) {
2680 params
.set(params
.size() - 1,
2681 params
.get(params
.size() - 1) + ch
);
2682 state
= ParseState
.CSI_PARAM
;
2685 // Parameter separator
2691 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
2695 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
2700 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
2705 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
2710 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
2715 events
.add(new TKeypressEvent(kbHome
));
2720 events
.add(new TKeypressEvent(kbEnd
));
2724 // CBT - Cursor backward X tab stops (default 1)
2725 events
.add(new TKeypressEvent(kbBackTab
));
2730 state
= ParseState
.MOUSE
;
2733 // Mouse position, SGR (1006) coordinates
2734 state
= ParseState
.MOUSE_SGR
;
2737 // DEC private mode flag
2738 decPrivateModeFlag
= true;
2745 // Unknown keystroke, ignore
2750 // Numbers - parameter values
2751 if ((ch
>= '0') && (ch
<= '9')) {
2752 params
.set(params
.size() - 1,
2753 params
.get(params
.size() - 1) + ch
);
2756 // Parameter separator
2764 // Generate a mouse press event
2765 TInputEvent event
= parseMouseSGR(false);
2766 if (event
!= null) {
2772 // Generate a mouse release event
2773 event
= parseMouseSGR(true);
2774 if (event
!= null) {
2783 // Unknown keystroke, ignore
2788 // Numbers - parameter values
2789 if ((ch
>= '0') && (ch
<= '9')) {
2790 params
.set(params
.size() - 1,
2791 params
.get(params
.size() - 1) + ch
);
2792 state
= ParseState
.CSI_PARAM
;
2795 // Parameter separator
2802 events
.add(csiFnKey());
2807 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
2811 if (params
.size() > 1) {
2812 shift
= csiIsShift(params
.get(1));
2813 alt
= csiIsAlt(params
.get(1));
2814 ctrl
= csiIsCtrl(params
.get(1));
2816 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
2821 if (params
.size() > 1) {
2822 shift
= csiIsShift(params
.get(1));
2823 alt
= csiIsAlt(params
.get(1));
2824 ctrl
= csiIsCtrl(params
.get(1));
2826 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
2831 if (params
.size() > 1) {
2832 shift
= csiIsShift(params
.get(1));
2833 alt
= csiIsAlt(params
.get(1));
2834 ctrl
= csiIsCtrl(params
.get(1));
2836 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
2841 if (params
.size() > 1) {
2842 shift
= csiIsShift(params
.get(1));
2843 alt
= csiIsAlt(params
.get(1));
2844 ctrl
= csiIsCtrl(params
.get(1));
2846 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
2851 if (params
.size() > 1) {
2852 shift
= csiIsShift(params
.get(1));
2853 alt
= csiIsAlt(params
.get(1));
2854 ctrl
= csiIsCtrl(params
.get(1));
2856 events
.add(new TKeypressEvent(kbHome
, alt
, ctrl
, shift
));
2861 if (params
.size() > 1) {
2862 shift
= csiIsShift(params
.get(1));
2863 alt
= csiIsAlt(params
.get(1));
2864 ctrl
= csiIsCtrl(params
.get(1));
2866 events
.add(new TKeypressEvent(kbEnd
, alt
, ctrl
, shift
));
2870 // Device Attributes
2871 if (decPrivateModeFlag
== false) {
2874 boolean jexerImages
= false;
2875 for (String x
: params
) {
2876 if (x
.equals("4")) {
2877 // Terminal reports sixel support
2878 if (debugToStderr
) {
2879 System
.err
.println("Device Attributes: sixel");
2882 if (x
.equals("444")) {
2883 // Terminal reports Jexer images support
2884 if (debugToStderr
) {
2885 System
.err
.println("Device Attributes: Jexer images");
2889 if (x
.equals("1337")) {
2890 // Terminal reports iTerm2 images support
2891 if (debugToStderr
) {
2892 System
.err
.println("Device Attributes: iTerm2 images");
2894 iterm2Images
= true;
2897 if (jexerImages
== false) {
2898 // Terminal does not support Jexer images, disable
2900 jexerImageOption
= JexerImageOption
.DISABLED
;
2906 if ((params
.size() > 2) && (params
.get(0).equals("4"))) {
2907 if (debugToStderr
) {
2908 System
.err
.printf("windowOp pixels: " +
2909 "height %s width %s\n",
2910 params
.get(1), params
.get(2));
2913 widthPixels
= Integer
.parseInt(params
.get(2));
2914 heightPixels
= Integer
.parseInt(params
.get(1));
2915 } catch (NumberFormatException e
) {
2916 if (debugToStderr
) {
2917 e
.printStackTrace();
2920 if (widthPixels
<= 0) {
2923 if (heightPixels
<= 0) {
2927 if ((params
.size() > 2) && (params
.get(0).equals("6"))) {
2928 if (debugToStderr
) {
2929 System
.err
.printf("windowOp text cell pixels: " +
2930 "height %s width %s\n",
2931 params
.get(1), params
.get(2));
2934 widthPixels
= width
* Integer
.parseInt(params
.get(2));
2935 heightPixels
= height
* Integer
.parseInt(params
.get(1));
2936 } catch (NumberFormatException e
) {
2937 if (debugToStderr
) {
2938 e
.printStackTrace();
2941 if (widthPixels
<= 0) {
2944 if (heightPixels
<= 0) {
2955 // Unknown keystroke, ignore
2960 params
.set(0, params
.get(params
.size() - 1) + ch
);
2961 if (params
.get(0).length() == 3) {
2962 // We have enough to generate a mouse event
2963 events
.add(parseMouse());
2972 // This "should" be impossible to reach
2977 * Request (u)xterm to use the sixel settings we need:
2979 * - enable sixel scrolling
2981 * - disable private color registers (so that we can use one common
2982 * palette) if sixelSharedPalette is set
2984 * @return the string to emit to xterm
2986 private String
xtermSetSixelSettings() {
2987 if (sixelSharedPalette
== true) {
2988 return "\033[?80h\033[?1070l";
2990 return "\033[?80h\033[?1070h";
2995 * Restore (u)xterm its default sixel settings:
2997 * - enable sixel scrolling
2999 * - enable private color registers
3001 * @return the string to emit to xterm
3003 private String
xtermResetSixelSettings() {
3004 return "\033[?80h\033[?1070h";
3008 * Request (u)xterm to report the current window and cell size dimensions
3011 * @return the string to emit to xterm
3013 private String
xtermReportPixelDimensions() {
3014 // We will ask for both window and text cell dimensions, and
3015 // hopefully one of them will work.
3016 return "\033[14t\033[16t";
3020 * Tell (u)xterm that we want alt- keystrokes to send escape + character
3021 * rather than set the 8th bit. Anyone who wants UTF8 should want this
3024 * @param on if true, enable metaSendsEscape
3025 * @return the string to emit to xterm
3027 private String
xtermMetaSendsEscape(final boolean on
) {
3029 return "\033[?1036h\033[?1034l";
3031 return "\033[?1036l";
3035 * Create an xterm OSC sequence to change the window title.
3037 * @param title the new title
3038 * @return the string to emit to xterm
3040 private String
getSetTitleString(final String title
) {
3041 return "\033]2;" + title
+ "\007";
3044 // ------------------------------------------------------------------------
3045 // Sixel output support ---------------------------------------------------
3046 // ------------------------------------------------------------------------
3049 * Get the number of colors in the sixel palette.
3051 * @return the palette size
3053 public int getSixelPaletteSize() {
3054 return sixelPaletteSize
;
3058 * Set the number of colors in the sixel palette.
3060 * @param paletteSize the new palette size
3062 public void setSixelPaletteSize(final int paletteSize
) {
3063 if (paletteSize
== sixelPaletteSize
) {
3067 switch (paletteSize
) {
3075 throw new IllegalArgumentException("Unsupported sixel palette " +
3076 " size: " + paletteSize
);
3079 // Don't step on the screen refresh thread.
3080 synchronized (this) {
3081 sixelPaletteSize
= paletteSize
;
3089 * Start a sixel string for display one row's worth of bitmap data.
3091 * @param x column coordinate. 0 is the left-most column.
3092 * @param y row coordinate. 0 is the top-most row.
3093 * @return the string to emit to an ANSI / ECMA-style terminal
3095 private String
startSixel(final int x
, final int y
) {
3096 StringBuilder sb
= new StringBuilder();
3098 assert (sixel
== true);
3101 sb
.append(gotoXY(x
, y
));
3104 sb
.append("\033Pq");
3106 if (palette
== null) {
3107 palette
= new SixelPalette();
3108 if (sixelSharedPalette
== true) {
3109 palette
.emitPalette(sb
, null);
3113 return sb
.toString();
3117 * End a sixel string for display one row's worth of bitmap data.
3119 * @return the string to emit to an ANSI / ECMA-style terminal
3121 private String
endSixel() {
3122 assert (sixel
== true);
3129 * Create a sixel string representing a row of several cells containing
3132 * @param x column coordinate. 0 is the left-most column.
3133 * @param y row coordinate. 0 is the top-most row.
3134 * @param cells the cells containing the bitmap data
3135 * @return the string to emit to an ANSI / ECMA-style terminal
3137 private String
toSixel(final int x
, final int y
,
3138 final ArrayList
<Cell
> cells
) {
3140 StringBuilder sb
= new StringBuilder();
3142 assert (cells
!= null);
3143 assert (cells
.size() > 0);
3144 assert (cells
.get(0).getImage() != null);
3146 if (sixel
== false) {
3147 sb
.append(normal());
3148 sb
.append(gotoXY(x
, y
));
3149 for (int i
= 0; i
< cells
.size(); i
++) {
3152 return sb
.toString();
3155 if (y
== height
- 1) {
3156 // We are on the bottom row. If scrolling mode is enabled
3157 // (default), then VT320/xterm will scroll the entire screen if
3158 // we draw any pixels here. Do not draw the image, bail out
3160 sb
.append(normal());
3161 sb
.append(gotoXY(x
, y
));
3162 for (int j
= 0; j
< cells
.size(); j
++) {
3165 return sb
.toString();
3168 if (sixelCache
== null) {
3169 sixelCache
= new ImageCache(height
* 10);
3172 // Save and get rows to/from the cache that do NOT have inverted
3174 boolean saveInCache
= true;
3175 for (Cell cell
: cells
) {
3176 if (cell
.isInvertedImage()) {
3177 saveInCache
= false;
3181 String cachedResult
= sixelCache
.get(cells
);
3182 if (cachedResult
!= null) {
3183 // System.err.println("CACHE HIT");
3184 sb
.append(startSixel(x
, y
));
3185 sb
.append(cachedResult
);
3186 sb
.append(endSixel());
3187 return sb
.toString();
3189 // System.err.println("CACHE MISS");
3192 int imageWidth
= cells
.get(0).getImage().getWidth();
3193 int imageHeight
= cells
.get(0).getImage().getHeight();
3195 // cells.get(x).getImage() has a dithered bitmap containing indexes
3196 // into the color palette. Piece these together into one larger
3197 // image for final rendering.
3199 int fullWidth
= cells
.size() * getTextWidth();
3200 int fullHeight
= getTextHeight();
3201 for (int i
= 0; i
< cells
.size(); i
++) {
3202 totalWidth
+= cells
.get(i
).getImage().getWidth();
3205 BufferedImage image
= new BufferedImage(fullWidth
,
3206 fullHeight
, BufferedImage
.TYPE_INT_ARGB
);
3209 for (int i
= 0; i
< cells
.size() - 1; i
++) {
3210 int tileWidth
= Math
.min(cells
.get(i
).getImage().getWidth(),
3212 int tileHeight
= Math
.min(cells
.get(i
).getImage().getHeight(),
3215 if (false && cells
.get(i
).isInvertedImage()) {
3216 // I used to put an all-white cell over the cursor, don't do
3218 rgbArray
= new int[imageWidth
* imageHeight
];
3219 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3220 rgbArray
[j
] = 0xFFFFFF;
3224 rgbArray
= cells
.get(i
).getImage().getRGB(0, 0,
3225 tileWidth
, tileHeight
, null, 0, tileWidth
);
3226 } catch (Exception e
) {
3227 throw new RuntimeException("image " + imageWidth
+ "x" +
3229 "tile " + tileWidth
+ "x" +
3231 " cells.get(i).getImage() " +
3232 cells
.get(i
).getImage() +
3234 " fullWidth " + fullWidth
+
3235 " fullHeight " + fullHeight
, e
);
3240 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
3241 i * imageWidth, 0, imageWidth, imageHeight,
3243 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
3244 fullWidth, fullHeight, cells.size(), getTextWidth());
3247 image
.setRGB(i
* imageWidth
, 0, tileWidth
, tileHeight
,
3248 rgbArray
, 0, tileWidth
);
3249 if (tileHeight
< fullHeight
) {
3250 int backgroundColor
= cells
.get(i
).getBackground().getRGB();
3251 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3252 for (int imageY
= imageHeight
; imageY
< fullHeight
;
3255 image
.setRGB(imageX
, imageY
, backgroundColor
);
3260 totalWidth
-= ((cells
.size() - 1) * imageWidth
);
3261 if (false && cells
.get(cells
.size() - 1).isInvertedImage()) {
3262 // I used to put an all-white cell over the cursor, don't do that
3264 rgbArray
= new int[totalWidth
* imageHeight
];
3265 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3266 rgbArray
[j
] = 0xFFFFFF;
3270 rgbArray
= cells
.get(cells
.size() - 1).getImage().getRGB(0, 0,
3271 totalWidth
, imageHeight
, null, 0, totalWidth
);
3272 } catch (Exception e
) {
3273 throw new RuntimeException("image " + imageWidth
+ "x" +
3274 imageHeight
+ " cells.get(cells.size() - 1).getImage() " +
3275 cells
.get(cells
.size() - 1).getImage(), e
);
3278 image
.setRGB((cells
.size() - 1) * imageWidth
, 0, totalWidth
,
3279 imageHeight
, rgbArray
, 0, totalWidth
);
3281 if (totalWidth
< getTextWidth()) {
3282 int backgroundColor
= cells
.get(cells
.size() - 1).getBackground().getRGB();
3284 for (int imageX
= image
.getWidth() - totalWidth
;
3285 imageX
< image
.getWidth(); imageX
++) {
3287 for (int imageY
= 0; imageY
< fullHeight
; imageY
++) {
3288 image
.setRGB(imageX
, imageY
, backgroundColor
);
3293 // Dither the image. It is ok to lose the original here.
3294 if (palette
== null) {
3295 palette
= new SixelPalette();
3296 if (sixelSharedPalette
== true) {
3297 palette
.emitPalette(sb
, null);
3300 image
= palette
.ditherImage(image
);
3302 // Collect the raster information
3303 int rasterHeight
= 0;
3304 int rasterWidth
= image
.getWidth();
3306 if (sixelSharedPalette
== false) {
3307 // Emit the palette, but only for the colors actually used by
3309 boolean [] usedColors
= new boolean[sixelPaletteSize
];
3310 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3311 for (int imageY
= 0; imageY
< image
.getHeight(); imageY
++) {
3312 usedColors
[image
.getRGB(imageX
, imageY
)] = true;
3315 palette
.emitPalette(sb
, usedColors
);
3318 // Render the entire row of cells.
3319 for (int currentRow
= 0; currentRow
< fullHeight
; currentRow
+= 6) {
3320 int [][] sixels
= new int[image
.getWidth()][6];
3322 // See which colors are actually used in this band of sixels.
3323 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3324 for (int imageY
= 0;
3325 (imageY
< 6) && (imageY
+ currentRow
< fullHeight
);
3328 int colorIdx
= image
.getRGB(imageX
, imageY
+ currentRow
);
3329 assert (colorIdx
>= 0);
3330 assert (colorIdx
< sixelPaletteSize
);
3332 sixels
[imageX
][imageY
] = colorIdx
;
3336 for (int i
= 0; i
< sixelPaletteSize
; i
++) {
3337 boolean isUsed
= false;
3338 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3339 for (int j
= 0; j
< 6; j
++) {
3340 if (sixels
[imageX
][j
] == i
) {
3345 if (isUsed
== false) {
3349 // Set to the beginning of scan line for the next set of
3350 // colored pixels, and select the color.
3351 sb
.append(String
.format("$#%d", i
));
3354 int oldDataCount
= 0;
3355 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3357 // Add up all the pixels that match this color.
3360 (j
< 6) && (currentRow
+ j
< fullHeight
);
3363 if (sixels
[imageX
][j
] == i
) {
3384 if ((currentRow
+ j
+ 1) > rasterHeight
) {
3385 rasterHeight
= currentRow
+ j
+ 1;
3393 if (data
== oldData
) {
3396 if (oldDataCount
== 1) {
3397 sb
.append((char) oldData
);
3398 } else if (oldDataCount
> 1) {
3399 sb
.append(String
.format("!%d", oldDataCount
));
3400 sb
.append((char) oldData
);
3406 } // for (int imageX = 0; imageX < image.getWidth(); imageX++)
3408 // Emit the last sequence.
3409 if (oldDataCount
== 1) {
3410 sb
.append((char) oldData
);
3411 } else if (oldDataCount
> 1) {
3412 sb
.append(String
.format("!%d", oldDataCount
));
3413 sb
.append((char) oldData
);
3416 } // for (int i = 0; i < sixelPaletteSize; i++)
3418 // Advance to the next scan line.
3421 } // for (int currentRow = 0; currentRow < imageHeight; currentRow += 6)
3423 // Kill the very last "-", because it is unnecessary.
3424 sb
.deleteCharAt(sb
.length() - 1);
3426 // Add the raster information
3427 sb
.insert(0, String
.format("\"1;1;%d;%d", rasterWidth
, rasterHeight
));
3430 // This row is OK to save into the cache.
3431 sixelCache
.put(cells
, sb
.toString());
3434 return (startSixel(x
, y
) + sb
.toString() + endSixel());
3438 * Get the sixel support flag.
3440 * @return true if this terminal is emitting sixel
3442 public boolean hasSixel() {
3446 // ------------------------------------------------------------------------
3447 // End sixel output support -----------------------------------------------
3448 // ------------------------------------------------------------------------
3450 // ------------------------------------------------------------------------
3451 // iTerm2 image output support --------------------------------------------
3452 // ------------------------------------------------------------------------
3455 * Create an iTerm2 images string representing a row of several cells
3456 * containing bitmap data.
3458 * @param x column coordinate. 0 is the left-most column.
3459 * @param y row coordinate. 0 is the top-most row.
3460 * @param cells the cells containing the bitmap data
3461 * @return the string to emit to an ANSI / ECMA-style terminal
3463 private String
toIterm2Image(final int x
, final int y
,
3464 final ArrayList
<Cell
> cells
) {
3466 StringBuilder sb
= new StringBuilder();
3468 assert (cells
!= null);
3469 assert (cells
.size() > 0);
3470 assert (cells
.get(0).getImage() != null);
3472 if (iterm2Images
== false) {
3473 sb
.append(normal());
3474 sb
.append(gotoXY(x
, y
));
3475 for (int i
= 0; i
< cells
.size(); i
++) {
3478 return sb
.toString();
3481 if (iterm2Cache
== null) {
3482 iterm2Cache
= new ImageCache(height
* 10);
3485 // Save and get rows to/from the cache that do NOT have inverted
3487 boolean saveInCache
= true;
3488 for (Cell cell
: cells
) {
3489 if (cell
.isInvertedImage()) {
3490 saveInCache
= false;
3494 String cachedResult
= iterm2Cache
.get(cells
);
3495 if (cachedResult
!= null) {
3496 // System.err.println("CACHE HIT");
3497 sb
.append(gotoXY(x
, y
));
3498 sb
.append(cachedResult
);
3499 return sb
.toString();
3501 // System.err.println("CACHE MISS");
3504 int imageWidth
= cells
.get(0).getImage().getWidth();
3505 int imageHeight
= cells
.get(0).getImage().getHeight();
3507 // Piece cells.get(x).getImage() pieces together into one larger
3508 // image for final rendering.
3510 int fullWidth
= cells
.size() * getTextWidth();
3511 int fullHeight
= getTextHeight();
3512 for (int i
= 0; i
< cells
.size(); i
++) {
3513 totalWidth
+= cells
.get(i
).getImage().getWidth();
3516 BufferedImage image
= new BufferedImage(fullWidth
,
3517 fullHeight
, BufferedImage
.TYPE_INT_ARGB
);
3520 for (int i
= 0; i
< cells
.size() - 1; i
++) {
3521 int tileWidth
= Math
.min(cells
.get(i
).getImage().getWidth(),
3523 int tileHeight
= Math
.min(cells
.get(i
).getImage().getHeight(),
3525 if (false && cells
.get(i
).isInvertedImage()) {
3526 // I used to put an all-white cell over the cursor, don't do
3528 rgbArray
= new int[imageWidth
* imageHeight
];
3529 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3530 rgbArray
[j
] = 0xFFFFFF;
3534 rgbArray
= cells
.get(i
).getImage().getRGB(0, 0,
3535 tileWidth
, tileHeight
, null, 0, tileWidth
);
3536 } catch (Exception e
) {
3537 throw new RuntimeException("image " + imageWidth
+ "x" +
3539 "tile " + tileWidth
+ "x" +
3541 " cells.get(i).getImage() " +
3542 cells
.get(i
).getImage() +
3544 " fullWidth " + fullWidth
+
3545 " fullHeight " + fullHeight
, e
);
3550 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
3551 i * imageWidth, 0, imageWidth, imageHeight,
3553 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
3554 fullWidth, fullHeight, cells.size(), getTextWidth());
3557 image
.setRGB(i
* imageWidth
, 0, tileWidth
, tileHeight
,
3558 rgbArray
, 0, tileWidth
);
3559 if (tileHeight
< fullHeight
) {
3560 int backgroundColor
= cells
.get(i
).getBackground().getRGB();
3561 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3562 for (int imageY
= imageHeight
; imageY
< fullHeight
;
3565 image
.setRGB(imageX
, imageY
, backgroundColor
);
3570 totalWidth
-= ((cells
.size() - 1) * imageWidth
);
3571 if (false && cells
.get(cells
.size() - 1).isInvertedImage()) {
3572 // I used to put an all-white cell over the cursor, don't do that
3574 rgbArray
= new int[totalWidth
* imageHeight
];
3575 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3576 rgbArray
[j
] = 0xFFFFFF;
3580 rgbArray
= cells
.get(cells
.size() - 1).getImage().getRGB(0, 0,
3581 totalWidth
, imageHeight
, null, 0, totalWidth
);
3582 } catch (Exception e
) {
3583 throw new RuntimeException("image " + imageWidth
+ "x" +
3584 imageHeight
+ " cells.get(cells.size() - 1).getImage() " +
3585 cells
.get(cells
.size() - 1).getImage(), e
);
3588 image
.setRGB((cells
.size() - 1) * imageWidth
, 0, totalWidth
,
3589 imageHeight
, rgbArray
, 0, totalWidth
);
3591 if (totalWidth
< getTextWidth()) {
3592 int backgroundColor
= cells
.get(cells
.size() - 1).getBackground().getRGB();
3594 for (int imageX
= image
.getWidth() - totalWidth
;
3595 imageX
< image
.getWidth(); imageX
++) {
3597 for (int imageY
= 0; imageY
< fullHeight
; imageY
++) {
3598 image
.setRGB(imageX
, imageY
, backgroundColor
);
3604 * From https://iterm2.com/documentation-images.html:
3608 * iTerm2 extends the xterm protocol with a set of proprietary escape
3609 * sequences. In general, the pattern is:
3611 * ESC ] 1337 ; key = value ^G
3613 * Whitespace is shown here for ease of reading: in practice, no
3614 * spaces should be used.
3616 * For file transfer and inline images, the code is:
3618 * ESC ] 1337 ; File = [optional arguments] : base-64 encoded file contents ^G
3620 * The optional arguments are formatted as key=value with a semicolon
3621 * between each key-value pair. They are described below:
3623 * Key Description of value
3624 * name base-64 encoded filename. Defaults to "Unnamed file".
3625 * size File size in bytes. Optional; this is only used by the
3626 * progress indicator.
3627 * width Width to render. See notes below.
3628 * height Height to render. See notes below.
3629 * preserveAspectRatio If set to 0, then the image's inherent aspect
3630 * ratio will not be respected; otherwise, it
3631 * will fill the specified width and height as
3632 * much as possible without stretching. Defaults
3634 * inline If set to 1, the file will be displayed inline. Otherwise,
3635 * it will be downloaded with no visual representation in the
3636 * terminal session. Defaults to 0.
3638 * The width and height are given as a number followed by a unit, or
3641 * N: N character cells.
3643 * N%: N percent of the session's width or height.
3644 * auto: The image's inherent size will be used to determine an
3645 * appropriate dimension.
3649 // File contents can be several image formats. We will use PNG.
3650 ByteArrayOutputStream pngOutputStream
= new ByteArrayOutputStream(1024);
3652 if (!ImageIO
.write(image
.getSubimage(0, 0, image
.getWidth(),
3653 Math
.min(image
.getHeight(), fullHeight
)),
3654 "PNG", pngOutputStream
)
3656 // We failed to render image, bail out.
3659 } catch (IOException e
) {
3660 // We failed to render image, bail out.
3664 sb
.append("\033]1337;File=");
3666 sb.append(String.format("width=$d;height=1;preserveAspectRatio=1;",
3670 sb.append(String.format("width=$dpx;height=%dpx;preserveAspectRatio=1;",
3671 image.getWidth(), Math.min(image.getHeight(),
3674 sb
.append("inline=1:");
3675 sb
.append(StringUtils
.toBase64(pngOutputStream
.toByteArray()));
3679 // This row is OK to save into the cache.
3680 iterm2Cache
.put(cells
, sb
.toString());
3683 return (gotoXY(x
, y
) + sb
.toString());
3687 * Get the iTerm2 images support flag.
3689 * @return true if this terminal is emitting iTerm2 images
3691 public boolean hasIterm2Images() {
3692 return iterm2Images
;
3695 // ------------------------------------------------------------------------
3696 // End iTerm2 image output support ----------------------------------------
3697 // ------------------------------------------------------------------------
3699 // ------------------------------------------------------------------------
3700 // Jexer image output support ---------------------------------------------
3701 // ------------------------------------------------------------------------
3704 * Create a Jexer images string representing a row of several cells
3705 * containing bitmap data.
3707 * @param x column coordinate. 0 is the left-most column.
3708 * @param y row coordinate. 0 is the top-most row.
3709 * @param cells the cells containing the bitmap data
3710 * @return the string to emit to an ANSI / ECMA-style terminal
3712 private String
toJexerImage(final int x
, final int y
,
3713 final ArrayList
<Cell
> cells
) {
3715 StringBuilder sb
= new StringBuilder();
3717 assert (cells
!= null);
3718 assert (cells
.size() > 0);
3719 assert (cells
.get(0).getImage() != null);
3721 if (jexerImageOption
== JexerImageOption
.DISABLED
) {
3722 sb
.append(normal());
3723 sb
.append(gotoXY(x
, y
));
3724 for (int i
= 0; i
< cells
.size(); i
++) {
3727 return sb
.toString();
3730 if (jexerCache
== null) {
3731 jexerCache
= new ImageCache(height
* 10);
3734 // Save and get rows to/from the cache that do NOT have inverted
3736 boolean saveInCache
= true;
3737 for (Cell cell
: cells
) {
3738 if (cell
.isInvertedImage()) {
3739 saveInCache
= false;
3743 String cachedResult
= jexerCache
.get(cells
);
3744 if (cachedResult
!= null) {
3745 // System.err.println("CACHE HIT");
3746 sb
.append(gotoXY(x
, y
));
3747 sb
.append(cachedResult
);
3748 return sb
.toString();
3750 // System.err.println("CACHE MISS");
3753 int imageWidth
= cells
.get(0).getImage().getWidth();
3754 int imageHeight
= cells
.get(0).getImage().getHeight();
3756 // Piece cells.get(x).getImage() pieces together into one larger
3757 // image for final rendering.
3759 int fullWidth
= cells
.size() * getTextWidth();
3760 int fullHeight
= getTextHeight();
3761 for (int i
= 0; i
< cells
.size(); i
++) {
3762 totalWidth
+= cells
.get(i
).getImage().getWidth();
3765 BufferedImage image
= new BufferedImage(fullWidth
,
3766 fullHeight
, BufferedImage
.TYPE_INT_ARGB
);
3769 for (int i
= 0; i
< cells
.size() - 1; i
++) {
3770 int tileWidth
= Math
.min(cells
.get(i
).getImage().getWidth(),
3772 int tileHeight
= Math
.min(cells
.get(i
).getImage().getHeight(),
3774 if (false && cells
.get(i
).isInvertedImage()) {
3775 // I used to put an all-white cell over the cursor, don't do
3777 rgbArray
= new int[imageWidth
* imageHeight
];
3778 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3779 rgbArray
[j
] = 0xFFFFFF;
3783 rgbArray
= cells
.get(i
).getImage().getRGB(0, 0,
3784 tileWidth
, tileHeight
, null, 0, tileWidth
);
3785 } catch (Exception e
) {
3786 throw new RuntimeException("image " + imageWidth
+ "x" +
3788 "tile " + tileWidth
+ "x" +
3790 " cells.get(i).getImage() " +
3791 cells
.get(i
).getImage() +
3793 " fullWidth " + fullWidth
+
3794 " fullHeight " + fullHeight
, e
);
3799 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
3800 i * imageWidth, 0, imageWidth, imageHeight,
3802 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
3803 fullWidth, fullHeight, cells.size(), getTextWidth());
3806 image
.setRGB(i
* imageWidth
, 0, tileWidth
, tileHeight
,
3807 rgbArray
, 0, tileWidth
);
3808 if (tileHeight
< fullHeight
) {
3809 int backgroundColor
= cells
.get(i
).getBackground().getRGB();
3810 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3811 for (int imageY
= imageHeight
; imageY
< fullHeight
;
3814 image
.setRGB(imageX
, imageY
, backgroundColor
);
3819 totalWidth
-= ((cells
.size() - 1) * imageWidth
);
3820 if (false && cells
.get(cells
.size() - 1).isInvertedImage()) {
3821 // I used to put an all-white cell over the cursor, don't do that
3823 rgbArray
= new int[totalWidth
* imageHeight
];
3824 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3825 rgbArray
[j
] = 0xFFFFFF;
3829 rgbArray
= cells
.get(cells
.size() - 1).getImage().getRGB(0, 0,
3830 totalWidth
, imageHeight
, null, 0, totalWidth
);
3831 } catch (Exception e
) {
3832 throw new RuntimeException("image " + imageWidth
+ "x" +
3833 imageHeight
+ " cells.get(cells.size() - 1).getImage() " +
3834 cells
.get(cells
.size() - 1).getImage(), e
);
3837 image
.setRGB((cells
.size() - 1) * imageWidth
, 0, totalWidth
,
3838 imageHeight
, rgbArray
, 0, totalWidth
);
3840 if (totalWidth
< getTextWidth()) {
3841 int backgroundColor
= cells
.get(cells
.size() - 1).getBackground().getRGB();
3843 for (int imageX
= image
.getWidth() - totalWidth
;
3844 imageX
< image
.getWidth(); imageX
++) {
3846 for (int imageY
= 0; imageY
< fullHeight
; imageY
++) {
3847 image
.setRGB(imageX
, imageY
, backgroundColor
);
3852 if (jexerImageOption
== JexerImageOption
.PNG
) {
3854 ByteArrayOutputStream pngOutputStream
= new ByteArrayOutputStream(1024);
3856 if (!ImageIO
.write(image
.getSubimage(0, 0, image
.getWidth(),
3857 Math
.min(image
.getHeight(), fullHeight
)),
3858 "PNG", pngOutputStream
)
3860 // We failed to render image, bail out.
3863 } catch (IOException e
) {
3864 // We failed to render image, bail out.
3868 sb
.append("\033]444;1;0;");
3869 sb
.append(StringUtils
.toBase64(pngOutputStream
.toByteArray()));
3872 } else if (jexerImageOption
== JexerImageOption
.JPG
) {
3875 ByteArrayOutputStream jpgOutputStream
= new ByteArrayOutputStream(1024);
3877 // Convert from ARGB to RGB, otherwise the JPG encode will fail.
3878 BufferedImage jpgImage
= new BufferedImage(image
.getWidth(),
3879 image
.getHeight(), BufferedImage
.TYPE_INT_RGB
);
3880 int [] pixels
= new int[image
.getWidth() * image
.getHeight()];
3881 image
.getRGB(0, 0, image
.getWidth(), image
.getHeight(), pixels
,
3882 0, image
.getWidth());
3883 jpgImage
.setRGB(0, 0, image
.getWidth(), image
.getHeight(), pixels
,
3884 0, image
.getWidth());
3887 if (!ImageIO
.write(jpgImage
.getSubimage(0, 0,
3888 jpgImage
.getWidth(),
3889 Math
.min(jpgImage
.getHeight(), fullHeight
)),
3890 "JPG", jpgOutputStream
)
3892 // We failed to render image, bail out.
3895 } catch (IOException e
) {
3896 // We failed to render image, bail out.
3900 sb
.append("\033]444;2;0;");
3901 sb
.append(StringUtils
.toBase64(jpgOutputStream
.toByteArray()));
3904 } else if (jexerImageOption
== JexerImageOption
.RGB
) {
3907 sb
.append(String
.format("\033]444;0;%d;%d;0;", image
.getWidth(),
3908 Math
.min(image
.getHeight(), fullHeight
)));
3910 byte [] bytes
= new byte[image
.getWidth() * image
.getHeight() * 3];
3911 int stride
= image
.getWidth();
3912 for (int px
= 0; px
< stride
; px
++) {
3913 for (int py
= 0; py
< image
.getHeight(); py
++) {
3914 int rgb
= image
.getRGB(px
, py
);
3915 bytes
[(py
* stride
* 3) + (px
* 3)] = (byte) ((rgb
>>> 16) & 0xFF);
3916 bytes
[(py
* stride
* 3) + (px
* 3) + 1] = (byte) ((rgb
>>> 8) & 0xFF);
3917 bytes
[(py
* stride
* 3) + (px
* 3) + 2] = (byte) ( rgb
& 0xFF);
3920 sb
.append(StringUtils
.toBase64(bytes
));
3925 // This row is OK to save into the cache.
3926 jexerCache
.put(cells
, sb
.toString());
3929 return (gotoXY(x
, y
) + sb
.toString());
3933 * Get the Jexer images support flag.
3935 * @return true if this terminal is emitting Jexer images
3937 public boolean hasJexerImages() {
3938 return (jexerImageOption
!= JexerImageOption
.DISABLED
);
3941 // ------------------------------------------------------------------------
3942 // End Jexer image output support -----------------------------------------
3943 // ------------------------------------------------------------------------
3946 * Setup system colors to match DOS color palette.
3948 private void setDOSColors() {
3949 MYBLACK
= new java
.awt
.Color(0x00, 0x00, 0x00);
3950 MYRED
= new java
.awt
.Color(0xa8, 0x00, 0x00);
3951 MYGREEN
= new java
.awt
.Color(0x00, 0xa8, 0x00);
3952 MYYELLOW
= new java
.awt
.Color(0xa8, 0x54, 0x00);
3953 MYBLUE
= new java
.awt
.Color(0x00, 0x00, 0xa8);
3954 MYMAGENTA
= new java
.awt
.Color(0xa8, 0x00, 0xa8);
3955 MYCYAN
= new java
.awt
.Color(0x00, 0xa8, 0xa8);
3956 MYWHITE
= new java
.awt
.Color(0xa8, 0xa8, 0xa8);
3957 MYBOLD_BLACK
= new java
.awt
.Color(0x54, 0x54, 0x54);
3958 MYBOLD_RED
= new java
.awt
.Color(0xfc, 0x54, 0x54);
3959 MYBOLD_GREEN
= new java
.awt
.Color(0x54, 0xfc, 0x54);
3960 MYBOLD_YELLOW
= new java
.awt
.Color(0xfc, 0xfc, 0x54);
3961 MYBOLD_BLUE
= new java
.awt
.Color(0x54, 0x54, 0xfc);
3962 MYBOLD_MAGENTA
= new java
.awt
.Color(0xfc, 0x54, 0xfc);
3963 MYBOLD_CYAN
= new java
.awt
.Color(0x54, 0xfc, 0xfc);
3964 MYBOLD_WHITE
= new java
.awt
.Color(0xfc, 0xfc, 0xfc);
3968 * Setup ECMA48 colors to match those provided in system properties.
3970 private void setCustomSystemColors() {
3973 MYBLACK
= getCustomColor("jexer.ECMA48.color0", MYBLACK
);
3974 MYRED
= getCustomColor("jexer.ECMA48.color1", MYRED
);
3975 MYGREEN
= getCustomColor("jexer.ECMA48.color2", MYGREEN
);
3976 MYYELLOW
= getCustomColor("jexer.ECMA48.color3", MYYELLOW
);
3977 MYBLUE
= getCustomColor("jexer.ECMA48.color4", MYBLUE
);
3978 MYMAGENTA
= getCustomColor("jexer.ECMA48.color5", MYMAGENTA
);
3979 MYCYAN
= getCustomColor("jexer.ECMA48.color6", MYCYAN
);
3980 MYWHITE
= getCustomColor("jexer.ECMA48.color7", MYWHITE
);
3981 MYBOLD_BLACK
= getCustomColor("jexer.ECMA48.color8", MYBOLD_BLACK
);
3982 MYBOLD_RED
= getCustomColor("jexer.ECMA48.color9", MYBOLD_RED
);
3983 MYBOLD_GREEN
= getCustomColor("jexer.ECMA48.color10", MYBOLD_GREEN
);
3984 MYBOLD_YELLOW
= getCustomColor("jexer.ECMA48.color11", MYBOLD_YELLOW
);
3985 MYBOLD_BLUE
= getCustomColor("jexer.ECMA48.color12", MYBOLD_BLUE
);
3986 MYBOLD_MAGENTA
= getCustomColor("jexer.ECMA48.color13", MYBOLD_MAGENTA
);
3987 MYBOLD_CYAN
= getCustomColor("jexer.ECMA48.color14", MYBOLD_CYAN
);
3988 MYBOLD_WHITE
= getCustomColor("jexer.ECMA48.color15", MYBOLD_WHITE
);
3992 * Setup one system color to match the RGB value provided in system
3995 * @param key the system property key
3996 * @param defaultColor the default color to return if key is not set, or
3998 * @return a color from the RGB string, or defaultColor
4000 private java
.awt
.Color
getCustomColor(final String key
,
4001 final java
.awt
.Color defaultColor
) {
4003 String rgb
= System
.getProperty(key
);
4005 return defaultColor
;
4007 if (rgb
.startsWith("#")) {
4008 rgb
= rgb
.substring(1);
4012 rgbInt
= Integer
.parseInt(rgb
, 16);
4013 } catch (NumberFormatException e
) {
4014 return defaultColor
;
4016 java
.awt
.Color color
= new java
.awt
.Color((rgbInt
& 0xFF0000) >>> 16,
4017 (rgbInt
& 0x00FF00) >>> 8,
4018 (rgbInt
& 0x0000FF));
4024 * Create a T.416 RGB parameter sequence for a custom system color.
4026 * @param color one of the MYBLACK, MYBOLD_BLUE, etc. colors
4027 * @return the color portion of the string to emit to an ANSI /
4028 * ECMA-style terminal
4030 private String
systemColorRGB(final java
.awt
.Color color
) {
4031 return String
.format("%d;%d;%d", color
.getRed(), color
.getGreen(),
4036 * Create a SGR parameter sequence for a single color change.
4038 * @param bold if true, set bold
4039 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
4040 * @param foreground if true, this is a foreground color
4041 * @return the string to emit to an ANSI / ECMA-style terminal,
4044 private String
color(final boolean bold
, final Color color
,
4045 final boolean foreground
) {
4046 return color(color
, foreground
, true) +
4047 rgbColor(bold
, color
, foreground
);
4051 * Create a T.416 RGB parameter sequence for a single color change.
4053 * @param colorRGB a 24-bit RGB value for foreground color
4054 * @param foreground if true, this is a foreground color
4055 * @return the string to emit to an ANSI / ECMA-style terminal,
4058 private String
colorRGB(final int colorRGB
, final boolean foreground
) {
4060 int colorRed
= (colorRGB
>>> 16) & 0xFF;
4061 int colorGreen
= (colorRGB
>>> 8) & 0xFF;
4062 int colorBlue
= colorRGB
& 0xFF;
4064 StringBuilder sb
= new StringBuilder();
4066 sb
.append("\033[38;2;");
4068 sb
.append("\033[48;2;");
4070 sb
.append(String
.format("%d;%d;%dm", colorRed
, colorGreen
, colorBlue
));
4071 return sb
.toString();
4075 * Create a T.416 RGB parameter sequence for both foreground and
4076 * background color change.
4078 * @param foreColorRGB a 24-bit RGB value for foreground color
4079 * @param backColorRGB a 24-bit RGB value for foreground color
4080 * @return the string to emit to an ANSI / ECMA-style terminal,
4083 private String
colorRGB(final int foreColorRGB
, final int backColorRGB
) {
4084 int foreColorRed
= (foreColorRGB
>>> 16) & 0xFF;
4085 int foreColorGreen
= (foreColorRGB
>>> 8) & 0xFF;
4086 int foreColorBlue
= foreColorRGB
& 0xFF;
4087 int backColorRed
= (backColorRGB
>>> 16) & 0xFF;
4088 int backColorGreen
= (backColorRGB
>>> 8) & 0xFF;
4089 int backColorBlue
= backColorRGB
& 0xFF;
4091 StringBuilder sb
= new StringBuilder();
4092 sb
.append(String
.format("\033[38;2;%d;%d;%dm",
4093 foreColorRed
, foreColorGreen
, foreColorBlue
));
4094 sb
.append(String
.format("\033[48;2;%d;%d;%dm",
4095 backColorRed
, backColorGreen
, backColorBlue
));
4096 return sb
.toString();
4100 * Create a T.416 RGB parameter sequence for a single color change.
4102 * @param bold if true, set bold
4103 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
4104 * @param foreground if true, this is a foreground color
4105 * @return the string to emit to an xterm terminal with RGB support,
4106 * e.g. "\033[38;2;RR;GG;BBm"
4108 private String
rgbColor(final boolean bold
, final Color color
,
4109 final boolean foreground
) {
4110 if (doRgbColor
== false) {
4113 StringBuilder sb
= new StringBuilder("\033[");
4115 // Bold implies foreground only
4117 if (color
.equals(Color
.BLACK
)) {
4118 sb
.append(systemColorRGB(MYBOLD_BLACK
));
4119 } else if (color
.equals(Color
.RED
)) {
4120 sb
.append(systemColorRGB(MYBOLD_RED
));
4121 } else if (color
.equals(Color
.GREEN
)) {
4122 sb
.append(systemColorRGB(MYBOLD_GREEN
));
4123 } else if (color
.equals(Color
.YELLOW
)) {
4124 sb
.append(systemColorRGB(MYBOLD_YELLOW
));
4125 } else if (color
.equals(Color
.BLUE
)) {
4126 sb
.append(systemColorRGB(MYBOLD_BLUE
));
4127 } else if (color
.equals(Color
.MAGENTA
)) {
4128 sb
.append(systemColorRGB(MYBOLD_MAGENTA
));
4129 } else if (color
.equals(Color
.CYAN
)) {
4130 sb
.append(systemColorRGB(MYBOLD_CYAN
));
4131 } else if (color
.equals(Color
.WHITE
)) {
4132 sb
.append(systemColorRGB(MYBOLD_WHITE
));
4140 if (color
.equals(Color
.BLACK
)) {
4141 sb
.append(systemColorRGB(MYBLACK
));
4142 } else if (color
.equals(Color
.RED
)) {
4143 sb
.append(systemColorRGB(MYRED
));
4144 } else if (color
.equals(Color
.GREEN
)) {
4145 sb
.append(systemColorRGB(MYGREEN
));
4146 } else if (color
.equals(Color
.YELLOW
)) {
4147 sb
.append(systemColorRGB(MYYELLOW
));
4148 } else if (color
.equals(Color
.BLUE
)) {
4149 sb
.append(systemColorRGB(MYBLUE
));
4150 } else if (color
.equals(Color
.MAGENTA
)) {
4151 sb
.append(systemColorRGB(MYMAGENTA
));
4152 } else if (color
.equals(Color
.CYAN
)) {
4153 sb
.append(systemColorRGB(MYCYAN
));
4154 } else if (color
.equals(Color
.WHITE
)) {
4155 sb
.append(systemColorRGB(MYWHITE
));
4159 return sb
.toString();
4163 * Create a T.416 RGB parameter sequence for both foreground and
4164 * background color change.
4166 * @param bold if true, set bold
4167 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4168 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4169 * @return the string to emit to an xterm terminal with RGB support,
4170 * e.g. "\033[38;2;RR;GG;BB;48;2;RR;GG;BBm"
4172 private String
rgbColor(final boolean bold
, final Color foreColor
,
4173 final Color backColor
) {
4174 if (doRgbColor
== false) {
4178 return rgbColor(bold
, foreColor
, true) +
4179 rgbColor(false, backColor
, false);
4183 * Create a SGR parameter sequence for a single color change.
4185 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
4186 * @param foreground if true, this is a foreground color
4187 * @param header if true, make the full header, otherwise just emit the
4188 * color parameter e.g. "42;"
4189 * @return the string to emit to an ANSI / ECMA-style terminal,
4192 private String
color(final Color color
, final boolean foreground
,
4193 final boolean header
) {
4195 int ecmaColor
= color
.getValue();
4197 // Convert Color.* values to SGR numerics
4205 return String
.format("\033[%dm", ecmaColor
);
4207 return String
.format("%d;", ecmaColor
);
4212 * Create a SGR parameter sequence for both foreground and background
4215 * @param bold if true, set bold
4216 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4217 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4218 * @return the string to emit to an ANSI / ECMA-style terminal,
4219 * e.g. "\033[31;42m"
4221 private String
color(final boolean bold
, final Color foreColor
,
4222 final Color backColor
) {
4223 return color(foreColor
, backColor
, true) +
4224 rgbColor(bold
, foreColor
, backColor
);
4228 * Create a SGR parameter sequence for both foreground and
4229 * background color change.
4231 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4232 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4233 * @param header if true, make the full header, otherwise just emit the
4234 * color parameter e.g. "31;42;"
4235 * @return the string to emit to an ANSI / ECMA-style terminal,
4236 * e.g. "\033[31;42m"
4238 private String
color(final Color foreColor
, final Color backColor
,
4239 final boolean header
) {
4241 int ecmaForeColor
= foreColor
.getValue();
4242 int ecmaBackColor
= backColor
.getValue();
4244 // Convert Color.* values to SGR numerics
4245 ecmaBackColor
+= 40;
4246 ecmaForeColor
+= 30;
4249 return String
.format("\033[%d;%dm", ecmaForeColor
, ecmaBackColor
);
4251 return String
.format("%d;%d;", ecmaForeColor
, ecmaBackColor
);
4256 * Create a SGR parameter sequence for foreground, background, and
4257 * several attributes. This sequence first resets all attributes to
4258 * default, then sets attributes as per the parameters.
4260 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4261 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4262 * @param bold if true, set bold
4263 * @param reverse if true, set reverse
4264 * @param blink if true, set blink
4265 * @param underline if true, set underline
4266 * @return the string to emit to an ANSI / ECMA-style terminal,
4267 * e.g. "\033[0;1;31;42m"
4269 private String
color(final Color foreColor
, final Color backColor
,
4270 final boolean bold
, final boolean reverse
, final boolean blink
,
4271 final boolean underline
) {
4273 int ecmaForeColor
= foreColor
.getValue();
4274 int ecmaBackColor
= backColor
.getValue();
4276 // Convert Color.* values to SGR numerics
4277 ecmaBackColor
+= 40;
4278 ecmaForeColor
+= 30;
4280 StringBuilder sb
= new StringBuilder();
4281 if ( bold
&& reverse
&& blink
&& !underline
) {
4282 sb
.append("\033[0;1;7;5;");
4283 } else if ( bold
&& reverse
&& !blink
&& !underline
) {
4284 sb
.append("\033[0;1;7;");
4285 } else if ( !bold
&& reverse
&& blink
&& !underline
) {
4286 sb
.append("\033[0;7;5;");
4287 } else if ( bold
&& !reverse
&& blink
&& !underline
) {
4288 sb
.append("\033[0;1;5;");
4289 } else if ( bold
&& !reverse
&& !blink
&& !underline
) {
4290 sb
.append("\033[0;1;");
4291 } else if ( !bold
&& reverse
&& !blink
&& !underline
) {
4292 sb
.append("\033[0;7;");
4293 } else if ( !bold
&& !reverse
&& blink
&& !underline
) {
4294 sb
.append("\033[0;5;");
4295 } else if ( bold
&& reverse
&& blink
&& underline
) {
4296 sb
.append("\033[0;1;7;5;4;");
4297 } else if ( bold
&& reverse
&& !blink
&& underline
) {
4298 sb
.append("\033[0;1;7;4;");
4299 } else if ( !bold
&& reverse
&& blink
&& underline
) {
4300 sb
.append("\033[0;7;5;4;");
4301 } else if ( bold
&& !reverse
&& blink
&& underline
) {
4302 sb
.append("\033[0;1;5;4;");
4303 } else if ( bold
&& !reverse
&& !blink
&& underline
) {
4304 sb
.append("\033[0;1;4;");
4305 } else if ( !bold
&& reverse
&& !blink
&& underline
) {
4306 sb
.append("\033[0;7;4;");
4307 } else if ( !bold
&& !reverse
&& blink
&& underline
) {
4308 sb
.append("\033[0;5;4;");
4309 } else if ( !bold
&& !reverse
&& !blink
&& underline
) {
4310 sb
.append("\033[0;4;");
4312 assert (!bold
&& !reverse
&& !blink
&& !underline
);
4313 sb
.append("\033[0;");
4315 sb
.append(String
.format("%d;%dm", ecmaForeColor
, ecmaBackColor
));
4316 sb
.append(rgbColor(bold
, foreColor
, backColor
));
4317 return sb
.toString();
4321 * Create a SGR parameter sequence for foreground, background, and
4322 * several attributes. This sequence first resets all attributes to
4323 * default, then sets attributes as per the parameters.
4325 * @param foreColorRGB a 24-bit RGB value for foreground color
4326 * @param backColorRGB a 24-bit RGB value for foreground color
4327 * @param bold if true, set bold
4328 * @param reverse if true, set reverse
4329 * @param blink if true, set blink
4330 * @param underline if true, set underline
4331 * @return the string to emit to an ANSI / ECMA-style terminal,
4332 * e.g. "\033[0;1;31;42m"
4334 private String
colorRGB(final int foreColorRGB
, final int backColorRGB
,
4335 final boolean bold
, final boolean reverse
, final boolean blink
,
4336 final boolean underline
) {
4338 int foreColorRed
= (foreColorRGB
>>> 16) & 0xFF;
4339 int foreColorGreen
= (foreColorRGB
>>> 8) & 0xFF;
4340 int foreColorBlue
= foreColorRGB
& 0xFF;
4341 int backColorRed
= (backColorRGB
>>> 16) & 0xFF;
4342 int backColorGreen
= (backColorRGB
>>> 8) & 0xFF;
4343 int backColorBlue
= backColorRGB
& 0xFF;
4345 StringBuilder sb
= new StringBuilder();
4346 if ( bold
&& reverse
&& blink
&& !underline
) {
4347 sb
.append("\033[0;1;7;5;");
4348 } else if ( bold
&& reverse
&& !blink
&& !underline
) {
4349 sb
.append("\033[0;1;7;");
4350 } else if ( !bold
&& reverse
&& blink
&& !underline
) {
4351 sb
.append("\033[0;7;5;");
4352 } else if ( bold
&& !reverse
&& blink
&& !underline
) {
4353 sb
.append("\033[0;1;5;");
4354 } else if ( bold
&& !reverse
&& !blink
&& !underline
) {
4355 sb
.append("\033[0;1;");
4356 } else if ( !bold
&& reverse
&& !blink
&& !underline
) {
4357 sb
.append("\033[0;7;");
4358 } else if ( !bold
&& !reverse
&& blink
&& !underline
) {
4359 sb
.append("\033[0;5;");
4360 } else if ( bold
&& reverse
&& blink
&& underline
) {
4361 sb
.append("\033[0;1;7;5;4;");
4362 } else if ( bold
&& reverse
&& !blink
&& underline
) {
4363 sb
.append("\033[0;1;7;4;");
4364 } else if ( !bold
&& reverse
&& blink
&& underline
) {
4365 sb
.append("\033[0;7;5;4;");
4366 } else if ( bold
&& !reverse
&& blink
&& underline
) {
4367 sb
.append("\033[0;1;5;4;");
4368 } else if ( bold
&& !reverse
&& !blink
&& underline
) {
4369 sb
.append("\033[0;1;4;");
4370 } else if ( !bold
&& reverse
&& !blink
&& underline
) {
4371 sb
.append("\033[0;7;4;");
4372 } else if ( !bold
&& !reverse
&& blink
&& underline
) {
4373 sb
.append("\033[0;5;4;");
4374 } else if ( !bold
&& !reverse
&& !blink
&& underline
) {
4375 sb
.append("\033[0;4;");
4377 assert (!bold
&& !reverse
&& !blink
&& !underline
);
4378 sb
.append("\033[0;");
4381 sb
.append("m\033[38;2;");
4382 sb
.append(String
.format("%d;%d;%d", foreColorRed
, foreColorGreen
,
4384 sb
.append("m\033[48;2;");
4385 sb
.append(String
.format("%d;%d;%d", backColorRed
, backColorGreen
,
4388 return sb
.toString();
4392 * Create a SGR parameter sequence to reset to VT100 defaults.
4394 * @return the string to emit to an ANSI / ECMA-style terminal,
4397 private String
normal() {
4398 return normal(true) + rgbColor(false, Color
.WHITE
, Color
.BLACK
);
4402 * Create a SGR parameter sequence to reset to ECMA-48 default
4403 * foreground/background.
4405 * @return the string to emit to an ANSI / ECMA-style terminal,
4408 private String
defaultColor() {
4411 * Normal (neither bold nor faint).
4414 * Steady (not blinking).
4415 * Positive (not inverse).
4416 * Visible (not hidden).
4418 * Default foreground color.
4419 * Default background color.
4421 return "\033[0;22;23;24;25;27;28;29;39;49m";
4425 * Create a SGR parameter sequence to reset to defaults.
4427 * @param header if true, make the full header, otherwise just emit the
4428 * bare parameter e.g. "0;"
4429 * @return the string to emit to an ANSI / ECMA-style terminal,
4432 private String
normal(final boolean header
) {
4434 return "\033[0;37;40m";
4440 * Create a SGR parameter sequence for enabling the visible cursor.
4442 * @param on if true, turn on cursor
4443 * @return the string to emit to an ANSI / ECMA-style terminal
4445 private String
cursor(final boolean on
) {
4446 if (on
&& !cursorOn
) {
4450 if (!on
&& cursorOn
) {
4458 * Clear the entire screen. Because some terminals use back-color-erase,
4459 * set the color to white-on-black beforehand.
4461 * @return the string to emit to an ANSI / ECMA-style terminal
4463 private String
clearAll() {
4464 return "\033[0;37;40m\033[2J";
4468 * Clear the line from the cursor (inclusive) to the end of the screen.
4469 * Because some terminals use back-color-erase, set the color to
4470 * white-on-black beforehand.
4472 * @return the string to emit to an ANSI / ECMA-style terminal
4474 private String
clearRemainingLine() {
4475 return "\033[0;37;40m\033[K";
4479 * Move the cursor to (x, y).
4481 * @param x column coordinate. 0 is the left-most column.
4482 * @param y row coordinate. 0 is the top-most row.
4483 * @return the string to emit to an ANSI / ECMA-style terminal
4485 private String
gotoXY(final int x
, final int y
) {
4486 return String
.format("\033[%d;%dH", y
+ 1, x
+ 1);
4490 * Tell (u)xterm that we want to receive mouse events based on "Any event
4491 * tracking", UTF-8 coordinates, and then SGR coordinates. Ideally we
4492 * will end up with SGR coordinates with UTF-8 coordinates as a fallback.
4494 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
4496 * Note that this also sets the alternate/primary screen buffer.
4498 * Finally, also emit a Privacy Message sequence that Jexer recognizes to
4499 * mean "hide the mouse pointer." We have to use our own sequence to do
4500 * this because there is no standard in xterm for unilaterally hiding the
4501 * pointer all the time (regardless of typing).
4503 * @param on If true, enable mouse report and use the alternate screen
4504 * buffer. If false disable mouse reporting and use the primary screen
4506 * @return the string to emit to xterm
4508 private String
mouse(final boolean on
) {
4510 return "\033[?1002;1003;1005;1006h\033[?1049h\033^hideMousePointer\033\\";
4512 return "\033[?1002;1003;1006;1005l\033[?1049l\033^showMousePointer\033\\";