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;
2242 // System.err.printf("buttons: %04x\r\n", buttons);
2259 if (!mouse1
&& !mouse2
&& !mouse3
) {
2260 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2262 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
2279 // Dragging with mouse1 down
2282 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2286 // Dragging with mouse2 down
2289 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2293 // Dragging with mouse3 down
2296 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2300 // Dragging with mouse2 down after wheelUp
2303 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2307 // Dragging with mouse2 down after wheelDown
2310 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2314 eventMouseWheelUp
= true;
2318 eventMouseWheelDown
= true;
2322 // Unknown, just make it motion
2323 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2326 return new TMouseEvent(eventType
, x
, y
, x
, y
,
2327 eventMouse1
, eventMouse2
, eventMouse3
,
2328 eventMouseWheelUp
, eventMouseWheelDown
);
2332 * Produce mouse events based on "Any event tracking" and SGR
2334 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
2336 * @param release if true, this was a release ('m')
2337 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
2339 private TInputEvent
parseMouseSGR(final boolean release
) {
2340 // SGR extended coordinates - mode 1006
2341 if (params
.size() < 3) {
2342 // Invalid position, bail out.
2345 int buttons
= Integer
.parseInt(params
.get(0));
2346 int x
= Integer
.parseInt(params
.get(1)) - 1;
2347 int y
= Integer
.parseInt(params
.get(2)) - 1;
2349 // Clamp X and Y to the physical screen coordinates.
2350 if (x
>= windowResize
.getWidth()) {
2351 x
= windowResize
.getWidth() - 1;
2353 if (y
>= windowResize
.getHeight()) {
2354 y
= windowResize
.getHeight() - 1;
2357 TMouseEvent
.Type eventType
= TMouseEvent
.Type
.MOUSE_DOWN
;
2358 boolean eventMouse1
= false;
2359 boolean eventMouse2
= false;
2360 boolean eventMouse3
= false;
2361 boolean eventMouseWheelUp
= false;
2362 boolean eventMouseWheelDown
= false;
2365 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
2379 // Motion only, no buttons down
2380 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2384 // Dragging with mouse1 down
2386 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2390 // Dragging with mouse2 down
2392 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2396 // Dragging with mouse3 down
2398 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2402 // Dragging with mouse2 down after wheelUp
2404 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2408 // Dragging with mouse2 down after wheelDown
2410 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2414 eventMouseWheelUp
= true;
2418 eventMouseWheelDown
= true;
2422 // Unknown, bail out
2425 return new TMouseEvent(eventType
, x
, y
, x
, y
,
2426 eventMouse1
, eventMouse2
, eventMouse3
,
2427 eventMouseWheelUp
, eventMouseWheelDown
);
2431 * Return any events in the IO queue due to timeout.
2433 * @param queue list to append new events to
2435 private void getIdleEvents(final List
<TInputEvent
> queue
) {
2436 long nowTime
= System
.currentTimeMillis();
2438 // Check for new window size
2439 long windowSizeDelay
= nowTime
- windowSizeTime
;
2440 if (windowSizeDelay
> 1000) {
2441 int oldTextWidth
= getTextWidth();
2442 int oldTextHeight
= getTextHeight();
2444 sessionInfo
.queryWindowSize();
2445 int newWidth
= sessionInfo
.getWindowWidth();
2446 int newHeight
= sessionInfo
.getWindowHeight();
2448 if ((newWidth
!= windowResize
.getWidth())
2449 || (newHeight
!= windowResize
.getHeight())
2452 // Request xterm report window dimensions in pixels again.
2453 // Between now and then, ensure that the reported text cell
2454 // size is the same by setting widthPixels and heightPixels
2455 // to match the new dimensions.
2456 widthPixels
= oldTextWidth
* newWidth
;
2457 heightPixels
= oldTextHeight
* newHeight
;
2459 if (debugToStderr
) {
2460 System
.err
.println("Screen size changed, old size " +
2462 System
.err
.println(" new size " +
2463 newWidth
+ " x " + newHeight
);
2464 System
.err
.println(" old pixels " +
2465 oldTextWidth
+ " x " + oldTextHeight
);
2466 System
.err
.println(" new pixels " +
2467 getTextWidth() + " x " + getTextHeight());
2470 this.output
.printf("%s", xtermReportPixelDimensions());
2471 this.output
.flush();
2473 TResizeEvent event
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
2474 newWidth
, newHeight
);
2475 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
2476 newWidth
, newHeight
);
2479 windowSizeTime
= nowTime
;
2482 // ESCDELAY type timeout
2483 if (state
== ParseState
.ESCAPE
) {
2484 long escDelay
= nowTime
- escapeTime
;
2485 if (escDelay
> 100) {
2486 // After 0.1 seconds, assume a true escape character
2487 queue
.add(controlChar((char)0x1B, false));
2494 * Returns true if the CSI parameter for a keyboard command means that
2497 private boolean csiIsShift(final String x
) {
2509 * Returns true if the CSI parameter for a keyboard command means that
2512 private boolean csiIsAlt(final String x
) {
2524 * Returns true if the CSI parameter for a keyboard command means that
2527 private boolean csiIsCtrl(final String x
) {
2539 * Parses the next character of input to see if an InputEvent is
2542 * @param events list to append new events to
2543 * @param ch Unicode code point
2545 private void processChar(final List
<TInputEvent
> events
, final char ch
) {
2547 // ESCDELAY type timeout
2548 long nowTime
= System
.currentTimeMillis();
2549 if (state
== ParseState
.ESCAPE
) {
2550 long escDelay
= nowTime
- escapeTime
;
2551 if (escDelay
> 250) {
2552 // After 0.25 seconds, assume a true escape character
2553 events
.add(controlChar((char)0x1B, false));
2559 boolean ctrl
= false;
2560 boolean alt
= false;
2561 boolean shift
= false;
2563 // System.err.printf("state: %s ch %c\r\n", state, ch);
2569 state
= ParseState
.ESCAPE
;
2570 escapeTime
= nowTime
;
2575 // Control character
2576 events
.add(controlChar(ch
, false));
2583 events
.add(new TKeypressEvent(false, 0, ch
,
2584 false, false, false));
2593 // ALT-Control character
2594 events
.add(controlChar(ch
, true));
2600 // This will be one of the function keys
2601 state
= ParseState
.ESCAPE_INTERMEDIATE
;
2605 // '[' goes to CSI_ENTRY
2607 state
= ParseState
.CSI_ENTRY
;
2611 // Everything else is assumed to be Alt-keystroke
2612 if ((ch
>= 'A') && (ch
<= 'Z')) {
2616 events
.add(new TKeypressEvent(false, 0, ch
, alt
, ctrl
, shift
));
2620 case ESCAPE_INTERMEDIATE
:
2621 if ((ch
>= 'P') && (ch
<= 'S')) {
2625 events
.add(new TKeypressEvent(kbF1
));
2628 events
.add(new TKeypressEvent(kbF2
));
2631 events
.add(new TKeypressEvent(kbF3
));
2634 events
.add(new TKeypressEvent(kbF4
));
2643 // Unknown keystroke, ignore
2648 // Numbers - parameter values
2649 if ((ch
>= '0') && (ch
<= '9')) {
2650 params
.set(params
.size() - 1,
2651 params
.get(params
.size() - 1) + ch
);
2652 state
= ParseState
.CSI_PARAM
;
2655 // Parameter separator
2661 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
2665 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
2670 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
2675 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
2680 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
2685 events
.add(new TKeypressEvent(kbHome
));
2690 events
.add(new TKeypressEvent(kbEnd
));
2694 // CBT - Cursor backward X tab stops (default 1)
2695 events
.add(new TKeypressEvent(kbBackTab
));
2700 state
= ParseState
.MOUSE
;
2703 // Mouse position, SGR (1006) coordinates
2704 state
= ParseState
.MOUSE_SGR
;
2707 // DEC private mode flag
2708 decPrivateModeFlag
= true;
2715 // Unknown keystroke, ignore
2720 // Numbers - parameter values
2721 if ((ch
>= '0') && (ch
<= '9')) {
2722 params
.set(params
.size() - 1,
2723 params
.get(params
.size() - 1) + ch
);
2726 // Parameter separator
2734 // Generate a mouse press event
2735 TInputEvent event
= parseMouseSGR(false);
2736 if (event
!= null) {
2742 // Generate a mouse release event
2743 event
= parseMouseSGR(true);
2744 if (event
!= null) {
2753 // Unknown keystroke, ignore
2758 // Numbers - parameter values
2759 if ((ch
>= '0') && (ch
<= '9')) {
2760 params
.set(params
.size() - 1,
2761 params
.get(params
.size() - 1) + ch
);
2762 state
= ParseState
.CSI_PARAM
;
2765 // Parameter separator
2772 events
.add(csiFnKey());
2777 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
2781 if (params
.size() > 1) {
2782 shift
= csiIsShift(params
.get(1));
2783 alt
= csiIsAlt(params
.get(1));
2784 ctrl
= csiIsCtrl(params
.get(1));
2786 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
2791 if (params
.size() > 1) {
2792 shift
= csiIsShift(params
.get(1));
2793 alt
= csiIsAlt(params
.get(1));
2794 ctrl
= csiIsCtrl(params
.get(1));
2796 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
2801 if (params
.size() > 1) {
2802 shift
= csiIsShift(params
.get(1));
2803 alt
= csiIsAlt(params
.get(1));
2804 ctrl
= csiIsCtrl(params
.get(1));
2806 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
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(kbLeft
, 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(kbHome
, 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(kbEnd
, alt
, ctrl
, shift
));
2840 // Device Attributes
2841 if (decPrivateModeFlag
== false) {
2844 boolean jexerImages
= false;
2845 for (String x
: params
) {
2846 if (x
.equals("4")) {
2847 // Terminal reports sixel support
2848 if (debugToStderr
) {
2849 System
.err
.println("Device Attributes: sixel");
2852 if (x
.equals("444")) {
2853 // Terminal reports Jexer images support
2854 if (debugToStderr
) {
2855 System
.err
.println("Device Attributes: Jexer images");
2859 if (x
.equals("1337")) {
2860 // Terminal reports iTerm2 images support
2861 if (debugToStderr
) {
2862 System
.err
.println("Device Attributes: iTerm2 images");
2864 iterm2Images
= true;
2867 if (jexerImages
== false) {
2868 // Terminal does not support Jexer images, disable
2870 jexerImageOption
= JexerImageOption
.DISABLED
;
2875 if ((params
.size() > 2) && (params
.get(0).equals("4"))) {
2876 if (debugToStderr
) {
2877 System
.err
.printf("windowOp pixels: " +
2878 "height %s width %s\n",
2879 params
.get(1), params
.get(2));
2882 widthPixels
= Integer
.parseInt(params
.get(2));
2883 heightPixels
= Integer
.parseInt(params
.get(1));
2884 } catch (NumberFormatException e
) {
2885 if (debugToStderr
) {
2886 e
.printStackTrace();
2889 if (widthPixels
<= 0) {
2892 if (heightPixels
<= 0) {
2896 if ((params
.size() > 2) && (params
.get(0).equals("6"))) {
2897 if (debugToStderr
) {
2898 System
.err
.printf("windowOp text cell pixels: " +
2899 "height %s width %s\n",
2900 params
.get(1), params
.get(2));
2903 widthPixels
= width
* Integer
.parseInt(params
.get(2));
2904 heightPixels
= height
* Integer
.parseInt(params
.get(1));
2905 } catch (NumberFormatException e
) {
2906 if (debugToStderr
) {
2907 e
.printStackTrace();
2910 if (widthPixels
<= 0) {
2913 if (heightPixels
<= 0) {
2924 // Unknown keystroke, ignore
2929 params
.set(0, params
.get(params
.size() - 1) + ch
);
2930 if (params
.get(0).length() == 3) {
2931 // We have enough to generate a mouse event
2932 events
.add(parseMouse());
2941 // This "should" be impossible to reach
2946 * Request (u)xterm to use the sixel settings we need:
2948 * - enable sixel scrolling
2950 * - disable private color registers (so that we can use one common
2951 * palette) if sixelSharedPalette is set
2953 * @return the string to emit to xterm
2955 private String
xtermSetSixelSettings() {
2956 if (sixelSharedPalette
== true) {
2957 return "\033[?80h\033[?1070l";
2959 return "\033[?80h\033[?1070h";
2964 * Restore (u)xterm its default sixel settings:
2966 * - enable sixel scrolling
2968 * - enable private color registers
2970 * @return the string to emit to xterm
2972 private String
xtermResetSixelSettings() {
2973 return "\033[?80h\033[?1070h";
2977 * Request (u)xterm to report the current window and cell size dimensions
2980 * @return the string to emit to xterm
2982 private String
xtermReportPixelDimensions() {
2983 // We will ask for both window and text cell dimensions, and
2984 // hopefully one of them will work.
2985 return "\033[14t\033[16t";
2989 * Tell (u)xterm that we want alt- keystrokes to send escape + character
2990 * rather than set the 8th bit. Anyone who wants UTF8 should want this
2993 * @param on if true, enable metaSendsEscape
2994 * @return the string to emit to xterm
2996 private String
xtermMetaSendsEscape(final boolean on
) {
2998 return "\033[?1036h\033[?1034l";
3000 return "\033[?1036l";
3004 * Create an xterm OSC sequence to change the window title.
3006 * @param title the new title
3007 * @return the string to emit to xterm
3009 private String
getSetTitleString(final String title
) {
3010 return "\033]2;" + title
+ "\007";
3013 // ------------------------------------------------------------------------
3014 // Sixel output support ---------------------------------------------------
3015 // ------------------------------------------------------------------------
3018 * Get the number of colors in the sixel palette.
3020 * @return the palette size
3022 public int getSixelPaletteSize() {
3023 return sixelPaletteSize
;
3027 * Set the number of colors in the sixel palette.
3029 * @param paletteSize the new palette size
3031 public void setSixelPaletteSize(final int paletteSize
) {
3032 if (paletteSize
== sixelPaletteSize
) {
3036 switch (paletteSize
) {
3044 throw new IllegalArgumentException("Unsupported sixel palette " +
3045 " size: " + paletteSize
);
3048 // Don't step on the screen refresh thread.
3049 synchronized (this) {
3050 sixelPaletteSize
= paletteSize
;
3058 * Start a sixel string for display one row's worth of bitmap data.
3060 * @param x column coordinate. 0 is the left-most column.
3061 * @param y row coordinate. 0 is the top-most row.
3062 * @return the string to emit to an ANSI / ECMA-style terminal
3064 private String
startSixel(final int x
, final int y
) {
3065 StringBuilder sb
= new StringBuilder();
3067 assert (sixel
== true);
3070 sb
.append(gotoXY(x
, y
));
3073 sb
.append("\033Pq");
3075 if (palette
== null) {
3076 palette
= new SixelPalette();
3077 if (sixelSharedPalette
== true) {
3078 palette
.emitPalette(sb
, null);
3082 return sb
.toString();
3086 * End a sixel string for display one row's worth of bitmap data.
3088 * @return the string to emit to an ANSI / ECMA-style terminal
3090 private String
endSixel() {
3091 assert (sixel
== true);
3098 * Create a sixel string representing a row of several cells containing
3101 * @param x column coordinate. 0 is the left-most column.
3102 * @param y row coordinate. 0 is the top-most row.
3103 * @param cells the cells containing the bitmap data
3104 * @return the string to emit to an ANSI / ECMA-style terminal
3106 private String
toSixel(final int x
, final int y
,
3107 final ArrayList
<Cell
> cells
) {
3109 StringBuilder sb
= new StringBuilder();
3111 assert (cells
!= null);
3112 assert (cells
.size() > 0);
3113 assert (cells
.get(0).getImage() != null);
3115 if (sixel
== false) {
3116 sb
.append(normal());
3117 sb
.append(gotoXY(x
, y
));
3118 for (int i
= 0; i
< cells
.size(); i
++) {
3121 return sb
.toString();
3124 if (y
== height
- 1) {
3125 // We are on the bottom row. If scrolling mode is enabled
3126 // (default), then VT320/xterm will scroll the entire screen if
3127 // we draw any pixels here. Do not draw the image, bail out
3129 sb
.append(normal());
3130 sb
.append(gotoXY(x
, y
));
3131 for (int j
= 0; j
< cells
.size(); j
++) {
3134 return sb
.toString();
3137 if (sixelCache
== null) {
3138 sixelCache
= new ImageCache(height
* 10);
3141 // Save and get rows to/from the cache that do NOT have inverted
3143 boolean saveInCache
= true;
3144 for (Cell cell
: cells
) {
3145 if (cell
.isInvertedImage()) {
3146 saveInCache
= false;
3150 String cachedResult
= sixelCache
.get(cells
);
3151 if (cachedResult
!= null) {
3152 // System.err.println("CACHE HIT");
3153 sb
.append(startSixel(x
, y
));
3154 sb
.append(cachedResult
);
3155 sb
.append(endSixel());
3156 return sb
.toString();
3158 // System.err.println("CACHE MISS");
3161 int imageWidth
= cells
.get(0).getImage().getWidth();
3162 int imageHeight
= cells
.get(0).getImage().getHeight();
3164 // cells.get(x).getImage() has a dithered bitmap containing indexes
3165 // into the color palette. Piece these together into one larger
3166 // image for final rendering.
3168 int fullWidth
= cells
.size() * getTextWidth();
3169 int fullHeight
= getTextHeight();
3170 for (int i
= 0; i
< cells
.size(); i
++) {
3171 totalWidth
+= cells
.get(i
).getImage().getWidth();
3174 BufferedImage image
= new BufferedImage(fullWidth
,
3175 fullHeight
, BufferedImage
.TYPE_INT_ARGB
);
3178 for (int i
= 0; i
< cells
.size() - 1; i
++) {
3179 int tileWidth
= Math
.min(cells
.get(i
).getImage().getWidth(),
3181 int tileHeight
= Math
.min(cells
.get(i
).getImage().getHeight(),
3184 if (false && cells
.get(i
).isInvertedImage()) {
3185 // I used to put an all-white cell over the cursor, don't do
3187 rgbArray
= new int[imageWidth
* imageHeight
];
3188 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3189 rgbArray
[j
] = 0xFFFFFF;
3193 rgbArray
= cells
.get(i
).getImage().getRGB(0, 0,
3194 tileWidth
, tileHeight
, null, 0, tileWidth
);
3195 } catch (Exception e
) {
3196 throw new RuntimeException("image " + imageWidth
+ "x" +
3198 "tile " + tileWidth
+ "x" +
3200 " cells.get(i).getImage() " +
3201 cells
.get(i
).getImage() +
3203 " fullWidth " + fullWidth
+
3204 " fullHeight " + fullHeight
, e
);
3209 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
3210 i * imageWidth, 0, imageWidth, imageHeight,
3212 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
3213 fullWidth, fullHeight, cells.size(), getTextWidth());
3216 image
.setRGB(i
* imageWidth
, 0, tileWidth
, tileHeight
,
3217 rgbArray
, 0, tileWidth
);
3218 if (tileHeight
< fullHeight
) {
3219 int backgroundColor
= cells
.get(i
).getBackground().getRGB();
3220 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3221 for (int imageY
= imageHeight
; imageY
< fullHeight
;
3224 image
.setRGB(imageX
, imageY
, backgroundColor
);
3229 totalWidth
-= ((cells
.size() - 1) * imageWidth
);
3230 if (false && cells
.get(cells
.size() - 1).isInvertedImage()) {
3231 // I used to put an all-white cell over the cursor, don't do that
3233 rgbArray
= new int[totalWidth
* imageHeight
];
3234 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3235 rgbArray
[j
] = 0xFFFFFF;
3239 rgbArray
= cells
.get(cells
.size() - 1).getImage().getRGB(0, 0,
3240 totalWidth
, imageHeight
, null, 0, totalWidth
);
3241 } catch (Exception e
) {
3242 throw new RuntimeException("image " + imageWidth
+ "x" +
3243 imageHeight
+ " cells.get(cells.size() - 1).getImage() " +
3244 cells
.get(cells
.size() - 1).getImage(), e
);
3247 image
.setRGB((cells
.size() - 1) * imageWidth
, 0, totalWidth
,
3248 imageHeight
, rgbArray
, 0, totalWidth
);
3250 if (totalWidth
< getTextWidth()) {
3251 int backgroundColor
= cells
.get(cells
.size() - 1).getBackground().getRGB();
3253 for (int imageX
= image
.getWidth() - totalWidth
;
3254 imageX
< image
.getWidth(); imageX
++) {
3256 for (int imageY
= 0; imageY
< fullHeight
; imageY
++) {
3257 image
.setRGB(imageX
, imageY
, backgroundColor
);
3262 // Dither the image. It is ok to lose the original here.
3263 if (palette
== null) {
3264 palette
= new SixelPalette();
3265 if (sixelSharedPalette
== true) {
3266 palette
.emitPalette(sb
, null);
3269 image
= palette
.ditherImage(image
);
3271 // Collect the raster information
3272 int rasterHeight
= 0;
3273 int rasterWidth
= image
.getWidth();
3275 if (sixelSharedPalette
== false) {
3276 // Emit the palette, but only for the colors actually used by
3278 boolean [] usedColors
= new boolean[sixelPaletteSize
];
3279 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3280 for (int imageY
= 0; imageY
< image
.getHeight(); imageY
++) {
3281 usedColors
[image
.getRGB(imageX
, imageY
)] = true;
3284 palette
.emitPalette(sb
, usedColors
);
3287 // Render the entire row of cells.
3288 for (int currentRow
= 0; currentRow
< fullHeight
; currentRow
+= 6) {
3289 int [][] sixels
= new int[image
.getWidth()][6];
3291 // See which colors are actually used in this band of sixels.
3292 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3293 for (int imageY
= 0;
3294 (imageY
< 6) && (imageY
+ currentRow
< fullHeight
);
3297 int colorIdx
= image
.getRGB(imageX
, imageY
+ currentRow
);
3298 assert (colorIdx
>= 0);
3299 assert (colorIdx
< sixelPaletteSize
);
3301 sixels
[imageX
][imageY
] = colorIdx
;
3305 for (int i
= 0; i
< sixelPaletteSize
; i
++) {
3306 boolean isUsed
= false;
3307 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3308 for (int j
= 0; j
< 6; j
++) {
3309 if (sixels
[imageX
][j
] == i
) {
3314 if (isUsed
== false) {
3318 // Set to the beginning of scan line for the next set of
3319 // colored pixels, and select the color.
3320 sb
.append(String
.format("$#%d", i
));
3323 int oldDataCount
= 0;
3324 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3326 // Add up all the pixels that match this color.
3329 (j
< 6) && (currentRow
+ j
< fullHeight
);
3332 if (sixels
[imageX
][j
] == i
) {
3353 if ((currentRow
+ j
+ 1) > rasterHeight
) {
3354 rasterHeight
= currentRow
+ j
+ 1;
3362 if (data
== oldData
) {
3365 if (oldDataCount
== 1) {
3366 sb
.append((char) oldData
);
3367 } else if (oldDataCount
> 1) {
3368 sb
.append(String
.format("!%d", oldDataCount
));
3369 sb
.append((char) oldData
);
3375 } // for (int imageX = 0; imageX < image.getWidth(); imageX++)
3377 // Emit the last sequence.
3378 if (oldDataCount
== 1) {
3379 sb
.append((char) oldData
);
3380 } else if (oldDataCount
> 1) {
3381 sb
.append(String
.format("!%d", oldDataCount
));
3382 sb
.append((char) oldData
);
3385 } // for (int i = 0; i < sixelPaletteSize; i++)
3387 // Advance to the next scan line.
3390 } // for (int currentRow = 0; currentRow < imageHeight; currentRow += 6)
3392 // Kill the very last "-", because it is unnecessary.
3393 sb
.deleteCharAt(sb
.length() - 1);
3395 // Add the raster information
3396 sb
.insert(0, String
.format("\"1;1;%d;%d", rasterWidth
, rasterHeight
));
3399 // This row is OK to save into the cache.
3400 sixelCache
.put(cells
, sb
.toString());
3403 return (startSixel(x
, y
) + sb
.toString() + endSixel());
3407 * Get the sixel support flag.
3409 * @return true if this terminal is emitting sixel
3411 public boolean hasSixel() {
3415 // ------------------------------------------------------------------------
3416 // End sixel output support -----------------------------------------------
3417 // ------------------------------------------------------------------------
3419 // ------------------------------------------------------------------------
3420 // iTerm2 image output support --------------------------------------------
3421 // ------------------------------------------------------------------------
3424 * Create an iTerm2 images string representing a row of several cells
3425 * containing bitmap data.
3427 * @param x column coordinate. 0 is the left-most column.
3428 * @param y row coordinate. 0 is the top-most row.
3429 * @param cells the cells containing the bitmap data
3430 * @return the string to emit to an ANSI / ECMA-style terminal
3432 private String
toIterm2Image(final int x
, final int y
,
3433 final ArrayList
<Cell
> cells
) {
3435 StringBuilder sb
= new StringBuilder();
3437 assert (cells
!= null);
3438 assert (cells
.size() > 0);
3439 assert (cells
.get(0).getImage() != null);
3441 if (iterm2Images
== false) {
3442 sb
.append(normal());
3443 sb
.append(gotoXY(x
, y
));
3444 for (int i
= 0; i
< cells
.size(); i
++) {
3447 return sb
.toString();
3450 if (iterm2Cache
== null) {
3451 iterm2Cache
= new ImageCache(height
* 10);
3454 // Save and get rows to/from the cache that do NOT have inverted
3456 boolean saveInCache
= true;
3457 for (Cell cell
: cells
) {
3458 if (cell
.isInvertedImage()) {
3459 saveInCache
= false;
3463 String cachedResult
= iterm2Cache
.get(cells
);
3464 if (cachedResult
!= null) {
3465 // System.err.println("CACHE HIT");
3466 sb
.append(gotoXY(x
, y
));
3467 sb
.append(cachedResult
);
3468 return sb
.toString();
3470 // System.err.println("CACHE MISS");
3473 int imageWidth
= cells
.get(0).getImage().getWidth();
3474 int imageHeight
= cells
.get(0).getImage().getHeight();
3476 // Piece cells.get(x).getImage() pieces together into one larger
3477 // image for final rendering.
3479 int fullWidth
= cells
.size() * getTextWidth();
3480 int fullHeight
= getTextHeight();
3481 for (int i
= 0; i
< cells
.size(); i
++) {
3482 totalWidth
+= cells
.get(i
).getImage().getWidth();
3485 BufferedImage image
= new BufferedImage(fullWidth
,
3486 fullHeight
, BufferedImage
.TYPE_INT_ARGB
);
3489 for (int i
= 0; i
< cells
.size() - 1; i
++) {
3490 int tileWidth
= Math
.min(cells
.get(i
).getImage().getWidth(),
3492 int tileHeight
= Math
.min(cells
.get(i
).getImage().getHeight(),
3494 if (false && cells
.get(i
).isInvertedImage()) {
3495 // I used to put an all-white cell over the cursor, don't do
3497 rgbArray
= new int[imageWidth
* imageHeight
];
3498 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3499 rgbArray
[j
] = 0xFFFFFF;
3503 rgbArray
= cells
.get(i
).getImage().getRGB(0, 0,
3504 tileWidth
, tileHeight
, null, 0, tileWidth
);
3505 } catch (Exception e
) {
3506 throw new RuntimeException("image " + imageWidth
+ "x" +
3508 "tile " + tileWidth
+ "x" +
3510 " cells.get(i).getImage() " +
3511 cells
.get(i
).getImage() +
3513 " fullWidth " + fullWidth
+
3514 " fullHeight " + fullHeight
, e
);
3519 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
3520 i * imageWidth, 0, imageWidth, imageHeight,
3522 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
3523 fullWidth, fullHeight, cells.size(), getTextWidth());
3526 image
.setRGB(i
* imageWidth
, 0, tileWidth
, tileHeight
,
3527 rgbArray
, 0, tileWidth
);
3528 if (tileHeight
< fullHeight
) {
3529 int backgroundColor
= cells
.get(i
).getBackground().getRGB();
3530 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3531 for (int imageY
= imageHeight
; imageY
< fullHeight
;
3534 image
.setRGB(imageX
, imageY
, backgroundColor
);
3539 totalWidth
-= ((cells
.size() - 1) * imageWidth
);
3540 if (false && cells
.get(cells
.size() - 1).isInvertedImage()) {
3541 // I used to put an all-white cell over the cursor, don't do that
3543 rgbArray
= new int[totalWidth
* imageHeight
];
3544 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3545 rgbArray
[j
] = 0xFFFFFF;
3549 rgbArray
= cells
.get(cells
.size() - 1).getImage().getRGB(0, 0,
3550 totalWidth
, imageHeight
, null, 0, totalWidth
);
3551 } catch (Exception e
) {
3552 throw new RuntimeException("image " + imageWidth
+ "x" +
3553 imageHeight
+ " cells.get(cells.size() - 1).getImage() " +
3554 cells
.get(cells
.size() - 1).getImage(), e
);
3557 image
.setRGB((cells
.size() - 1) * imageWidth
, 0, totalWidth
,
3558 imageHeight
, rgbArray
, 0, totalWidth
);
3560 if (totalWidth
< getTextWidth()) {
3561 int backgroundColor
= cells
.get(cells
.size() - 1).getBackground().getRGB();
3563 for (int imageX
= image
.getWidth() - totalWidth
;
3564 imageX
< image
.getWidth(); imageX
++) {
3566 for (int imageY
= 0; imageY
< fullHeight
; imageY
++) {
3567 image
.setRGB(imageX
, imageY
, backgroundColor
);
3573 * From https://iterm2.com/documentation-images.html:
3577 * iTerm2 extends the xterm protocol with a set of proprietary escape
3578 * sequences. In general, the pattern is:
3580 * ESC ] 1337 ; key = value ^G
3582 * Whitespace is shown here for ease of reading: in practice, no
3583 * spaces should be used.
3585 * For file transfer and inline images, the code is:
3587 * ESC ] 1337 ; File = [optional arguments] : base-64 encoded file contents ^G
3589 * The optional arguments are formatted as key=value with a semicolon
3590 * between each key-value pair. They are described below:
3592 * Key Description of value
3593 * name base-64 encoded filename. Defaults to "Unnamed file".
3594 * size File size in bytes. Optional; this is only used by the
3595 * progress indicator.
3596 * width Width to render. See notes below.
3597 * height Height to render. See notes below.
3598 * preserveAspectRatio If set to 0, then the image's inherent aspect
3599 * ratio will not be respected; otherwise, it
3600 * will fill the specified width and height as
3601 * much as possible without stretching. Defaults
3603 * inline If set to 1, the file will be displayed inline. Otherwise,
3604 * it will be downloaded with no visual representation in the
3605 * terminal session. Defaults to 0.
3607 * The width and height are given as a number followed by a unit, or
3610 * N: N character cells.
3612 * N%: N percent of the session's width or height.
3613 * auto: The image's inherent size will be used to determine an
3614 * appropriate dimension.
3618 // File contents can be several image formats. We will use PNG.
3619 ByteArrayOutputStream pngOutputStream
= new ByteArrayOutputStream(1024);
3621 if (!ImageIO
.write(image
.getSubimage(0, 0, image
.getWidth(),
3622 Math
.min(image
.getHeight(), fullHeight
)),
3623 "PNG", pngOutputStream
)
3625 // We failed to render image, bail out.
3628 } catch (IOException e
) {
3629 // We failed to render image, bail out.
3633 sb
.append("\033]1337;File=");
3635 sb.append(String.format("width=$d;height=1;preserveAspectRatio=1;",
3639 sb.append(String.format("width=$dpx;height=%dpx;preserveAspectRatio=1;",
3640 image.getWidth(), Math.min(image.getHeight(),
3643 sb
.append("inline=1:");
3644 sb
.append(StringUtils
.toBase64(pngOutputStream
.toByteArray()));
3648 // This row is OK to save into the cache.
3649 iterm2Cache
.put(cells
, sb
.toString());
3652 return (gotoXY(x
, y
) + sb
.toString());
3656 * Get the iTerm2 images support flag.
3658 * @return true if this terminal is emitting iTerm2 images
3660 public boolean hasIterm2Images() {
3661 return iterm2Images
;
3664 // ------------------------------------------------------------------------
3665 // End iTerm2 image output support ----------------------------------------
3666 // ------------------------------------------------------------------------
3668 // ------------------------------------------------------------------------
3669 // Jexer image output support ---------------------------------------------
3670 // ------------------------------------------------------------------------
3673 * Create a Jexer images string representing a row of several cells
3674 * containing bitmap data.
3676 * @param x column coordinate. 0 is the left-most column.
3677 * @param y row coordinate. 0 is the top-most row.
3678 * @param cells the cells containing the bitmap data
3679 * @return the string to emit to an ANSI / ECMA-style terminal
3681 private String
toJexerImage(final int x
, final int y
,
3682 final ArrayList
<Cell
> cells
) {
3684 StringBuilder sb
= new StringBuilder();
3686 assert (cells
!= null);
3687 assert (cells
.size() > 0);
3688 assert (cells
.get(0).getImage() != null);
3690 if (jexerImageOption
== JexerImageOption
.DISABLED
) {
3691 sb
.append(normal());
3692 sb
.append(gotoXY(x
, y
));
3693 for (int i
= 0; i
< cells
.size(); i
++) {
3696 return sb
.toString();
3699 if (jexerCache
== null) {
3700 jexerCache
= new ImageCache(height
* 10);
3703 // Save and get rows to/from the cache that do NOT have inverted
3705 boolean saveInCache
= true;
3706 for (Cell cell
: cells
) {
3707 if (cell
.isInvertedImage()) {
3708 saveInCache
= false;
3712 String cachedResult
= jexerCache
.get(cells
);
3713 if (cachedResult
!= null) {
3714 // System.err.println("CACHE HIT");
3715 sb
.append(gotoXY(x
, y
));
3716 sb
.append(cachedResult
);
3717 return sb
.toString();
3719 // System.err.println("CACHE MISS");
3722 int imageWidth
= cells
.get(0).getImage().getWidth();
3723 int imageHeight
= cells
.get(0).getImage().getHeight();
3725 // Piece cells.get(x).getImage() pieces together into one larger
3726 // image for final rendering.
3728 int fullWidth
= cells
.size() * getTextWidth();
3729 int fullHeight
= getTextHeight();
3730 for (int i
= 0; i
< cells
.size(); i
++) {
3731 totalWidth
+= cells
.get(i
).getImage().getWidth();
3734 BufferedImage image
= new BufferedImage(fullWidth
,
3735 fullHeight
, BufferedImage
.TYPE_INT_ARGB
);
3738 for (int i
= 0; i
< cells
.size() - 1; i
++) {
3739 int tileWidth
= Math
.min(cells
.get(i
).getImage().getWidth(),
3741 int tileHeight
= Math
.min(cells
.get(i
).getImage().getHeight(),
3743 if (false && cells
.get(i
).isInvertedImage()) {
3744 // I used to put an all-white cell over the cursor, don't do
3746 rgbArray
= new int[imageWidth
* imageHeight
];
3747 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3748 rgbArray
[j
] = 0xFFFFFF;
3752 rgbArray
= cells
.get(i
).getImage().getRGB(0, 0,
3753 tileWidth
, tileHeight
, null, 0, tileWidth
);
3754 } catch (Exception e
) {
3755 throw new RuntimeException("image " + imageWidth
+ "x" +
3757 "tile " + tileWidth
+ "x" +
3759 " cells.get(i).getImage() " +
3760 cells
.get(i
).getImage() +
3762 " fullWidth " + fullWidth
+
3763 " fullHeight " + fullHeight
, e
);
3768 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
3769 i * imageWidth, 0, imageWidth, imageHeight,
3771 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
3772 fullWidth, fullHeight, cells.size(), getTextWidth());
3775 image
.setRGB(i
* imageWidth
, 0, tileWidth
, tileHeight
,
3776 rgbArray
, 0, tileWidth
);
3777 if (tileHeight
< fullHeight
) {
3778 int backgroundColor
= cells
.get(i
).getBackground().getRGB();
3779 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
3780 for (int imageY
= imageHeight
; imageY
< fullHeight
;
3783 image
.setRGB(imageX
, imageY
, backgroundColor
);
3788 totalWidth
-= ((cells
.size() - 1) * imageWidth
);
3789 if (false && cells
.get(cells
.size() - 1).isInvertedImage()) {
3790 // I used to put an all-white cell over the cursor, don't do that
3792 rgbArray
= new int[totalWidth
* imageHeight
];
3793 for (int j
= 0; j
< rgbArray
.length
; j
++) {
3794 rgbArray
[j
] = 0xFFFFFF;
3798 rgbArray
= cells
.get(cells
.size() - 1).getImage().getRGB(0, 0,
3799 totalWidth
, imageHeight
, null, 0, totalWidth
);
3800 } catch (Exception e
) {
3801 throw new RuntimeException("image " + imageWidth
+ "x" +
3802 imageHeight
+ " cells.get(cells.size() - 1).getImage() " +
3803 cells
.get(cells
.size() - 1).getImage(), e
);
3806 image
.setRGB((cells
.size() - 1) * imageWidth
, 0, totalWidth
,
3807 imageHeight
, rgbArray
, 0, totalWidth
);
3809 if (totalWidth
< getTextWidth()) {
3810 int backgroundColor
= cells
.get(cells
.size() - 1).getBackground().getRGB();
3812 for (int imageX
= image
.getWidth() - totalWidth
;
3813 imageX
< image
.getWidth(); imageX
++) {
3815 for (int imageY
= 0; imageY
< fullHeight
; imageY
++) {
3816 image
.setRGB(imageX
, imageY
, backgroundColor
);
3821 if (jexerImageOption
== JexerImageOption
.PNG
) {
3823 ByteArrayOutputStream pngOutputStream
= new ByteArrayOutputStream(1024);
3825 if (!ImageIO
.write(image
.getSubimage(0, 0, image
.getWidth(),
3826 Math
.min(image
.getHeight(), fullHeight
)),
3827 "PNG", pngOutputStream
)
3829 // We failed to render image, bail out.
3832 } catch (IOException e
) {
3833 // We failed to render image, bail out.
3837 sb
.append("\033]444;1;0;");
3838 sb
.append(StringUtils
.toBase64(pngOutputStream
.toByteArray()));
3841 } else if (jexerImageOption
== JexerImageOption
.JPG
) {
3844 ByteArrayOutputStream jpgOutputStream
= new ByteArrayOutputStream(1024);
3846 // Convert from ARGB to RGB, otherwise the JPG encode will fail.
3847 BufferedImage jpgImage
= new BufferedImage(image
.getWidth(),
3848 image
.getHeight(), BufferedImage
.TYPE_INT_RGB
);
3849 int [] pixels
= new int[image
.getWidth() * image
.getHeight()];
3850 image
.getRGB(0, 0, image
.getWidth(), image
.getHeight(), pixels
,
3851 0, image
.getWidth());
3852 jpgImage
.setRGB(0, 0, image
.getWidth(), image
.getHeight(), pixels
,
3853 0, image
.getWidth());
3856 if (!ImageIO
.write(jpgImage
.getSubimage(0, 0,
3857 jpgImage
.getWidth(),
3858 Math
.min(jpgImage
.getHeight(), fullHeight
)),
3859 "JPG", jpgOutputStream
)
3861 // We failed to render image, bail out.
3864 } catch (IOException e
) {
3865 // We failed to render image, bail out.
3869 sb
.append("\033]444;2;0;");
3870 sb
.append(StringUtils
.toBase64(jpgOutputStream
.toByteArray()));
3873 } else if (jexerImageOption
== JexerImageOption
.RGB
) {
3876 sb
.append(String
.format("\033]444;0;%d;%d;0;", image
.getWidth(),
3877 Math
.min(image
.getHeight(), fullHeight
)));
3879 byte [] bytes
= new byte[image
.getWidth() * image
.getHeight() * 3];
3880 int stride
= image
.getWidth();
3881 for (int px
= 0; px
< stride
; px
++) {
3882 for (int py
= 0; py
< image
.getHeight(); py
++) {
3883 int rgb
= image
.getRGB(px
, py
);
3884 bytes
[(py
* stride
* 3) + (px
* 3)] = (byte) ((rgb
>>> 16) & 0xFF);
3885 bytes
[(py
* stride
* 3) + (px
* 3) + 1] = (byte) ((rgb
>>> 8) & 0xFF);
3886 bytes
[(py
* stride
* 3) + (px
* 3) + 2] = (byte) ( rgb
& 0xFF);
3889 sb
.append(StringUtils
.toBase64(bytes
));
3894 // This row is OK to save into the cache.
3895 jexerCache
.put(cells
, sb
.toString());
3898 return (gotoXY(x
, y
) + sb
.toString());
3902 * Get the Jexer images support flag.
3904 * @return true if this terminal is emitting Jexer images
3906 public boolean hasJexerImages() {
3907 return (jexerImageOption
!= JexerImageOption
.DISABLED
);
3910 // ------------------------------------------------------------------------
3911 // End Jexer image output support -----------------------------------------
3912 // ------------------------------------------------------------------------
3915 * Setup system colors to match DOS color palette.
3917 private void setDOSColors() {
3918 MYBLACK
= new java
.awt
.Color(0x00, 0x00, 0x00);
3919 MYRED
= new java
.awt
.Color(0xa8, 0x00, 0x00);
3920 MYGREEN
= new java
.awt
.Color(0x00, 0xa8, 0x00);
3921 MYYELLOW
= new java
.awt
.Color(0xa8, 0x54, 0x00);
3922 MYBLUE
= new java
.awt
.Color(0x00, 0x00, 0xa8);
3923 MYMAGENTA
= new java
.awt
.Color(0xa8, 0x00, 0xa8);
3924 MYCYAN
= new java
.awt
.Color(0x00, 0xa8, 0xa8);
3925 MYWHITE
= new java
.awt
.Color(0xa8, 0xa8, 0xa8);
3926 MYBOLD_BLACK
= new java
.awt
.Color(0x54, 0x54, 0x54);
3927 MYBOLD_RED
= new java
.awt
.Color(0xfc, 0x54, 0x54);
3928 MYBOLD_GREEN
= new java
.awt
.Color(0x54, 0xfc, 0x54);
3929 MYBOLD_YELLOW
= new java
.awt
.Color(0xfc, 0xfc, 0x54);
3930 MYBOLD_BLUE
= new java
.awt
.Color(0x54, 0x54, 0xfc);
3931 MYBOLD_MAGENTA
= new java
.awt
.Color(0xfc, 0x54, 0xfc);
3932 MYBOLD_CYAN
= new java
.awt
.Color(0x54, 0xfc, 0xfc);
3933 MYBOLD_WHITE
= new java
.awt
.Color(0xfc, 0xfc, 0xfc);
3937 * Setup ECMA48 colors to match those provided in system properties.
3939 private void setCustomSystemColors() {
3942 MYBLACK
= getCustomColor("jexer.ECMA48.color0", MYBLACK
);
3943 MYRED
= getCustomColor("jexer.ECMA48.color1", MYRED
);
3944 MYGREEN
= getCustomColor("jexer.ECMA48.color2", MYGREEN
);
3945 MYYELLOW
= getCustomColor("jexer.ECMA48.color3", MYYELLOW
);
3946 MYBLUE
= getCustomColor("jexer.ECMA48.color4", MYBLUE
);
3947 MYMAGENTA
= getCustomColor("jexer.ECMA48.color5", MYMAGENTA
);
3948 MYCYAN
= getCustomColor("jexer.ECMA48.color6", MYCYAN
);
3949 MYWHITE
= getCustomColor("jexer.ECMA48.color7", MYWHITE
);
3950 MYBOLD_BLACK
= getCustomColor("jexer.ECMA48.color8", MYBOLD_BLACK
);
3951 MYBOLD_RED
= getCustomColor("jexer.ECMA48.color9", MYBOLD_RED
);
3952 MYBOLD_GREEN
= getCustomColor("jexer.ECMA48.color10", MYBOLD_GREEN
);
3953 MYBOLD_YELLOW
= getCustomColor("jexer.ECMA48.color11", MYBOLD_YELLOW
);
3954 MYBOLD_BLUE
= getCustomColor("jexer.ECMA48.color12", MYBOLD_BLUE
);
3955 MYBOLD_MAGENTA
= getCustomColor("jexer.ECMA48.color13", MYBOLD_MAGENTA
);
3956 MYBOLD_CYAN
= getCustomColor("jexer.ECMA48.color14", MYBOLD_CYAN
);
3957 MYBOLD_WHITE
= getCustomColor("jexer.ECMA48.color15", MYBOLD_WHITE
);
3961 * Setup one system color to match the RGB value provided in system
3964 * @param key the system property key
3965 * @param defaultColor the default color to return if key is not set, or
3967 * @return a color from the RGB string, or defaultColor
3969 private java
.awt
.Color
getCustomColor(final String key
,
3970 final java
.awt
.Color defaultColor
) {
3972 String rgb
= System
.getProperty(key
);
3974 return defaultColor
;
3976 if (rgb
.startsWith("#")) {
3977 rgb
= rgb
.substring(1);
3981 rgbInt
= Integer
.parseInt(rgb
, 16);
3982 } catch (NumberFormatException e
) {
3983 return defaultColor
;
3985 java
.awt
.Color color
= new java
.awt
.Color((rgbInt
& 0xFF0000) >>> 16,
3986 (rgbInt
& 0x00FF00) >>> 8,
3987 (rgbInt
& 0x0000FF));
3993 * Create a T.416 RGB parameter sequence for a custom system color.
3995 * @param color one of the MYBLACK, MYBOLD_BLUE, etc. colors
3996 * @return the color portion of the string to emit to an ANSI /
3997 * ECMA-style terminal
3999 private String
systemColorRGB(final java
.awt
.Color color
) {
4000 return String
.format("%d;%d;%d", color
.getRed(), color
.getGreen(),
4005 * Create a SGR parameter sequence for a single color change.
4007 * @param bold if true, set bold
4008 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
4009 * @param foreground if true, this is a foreground color
4010 * @return the string to emit to an ANSI / ECMA-style terminal,
4013 private String
color(final boolean bold
, final Color color
,
4014 final boolean foreground
) {
4015 return color(color
, foreground
, true) +
4016 rgbColor(bold
, color
, foreground
);
4020 * Create a T.416 RGB parameter sequence for a single color change.
4022 * @param colorRGB a 24-bit RGB value for foreground color
4023 * @param foreground if true, this is a foreground color
4024 * @return the string to emit to an ANSI / ECMA-style terminal,
4027 private String
colorRGB(final int colorRGB
, final boolean foreground
) {
4029 int colorRed
= (colorRGB
>>> 16) & 0xFF;
4030 int colorGreen
= (colorRGB
>>> 8) & 0xFF;
4031 int colorBlue
= colorRGB
& 0xFF;
4033 StringBuilder sb
= new StringBuilder();
4035 sb
.append("\033[38;2;");
4037 sb
.append("\033[48;2;");
4039 sb
.append(String
.format("%d;%d;%dm", colorRed
, colorGreen
, colorBlue
));
4040 return sb
.toString();
4044 * Create a T.416 RGB parameter sequence for both foreground and
4045 * background color change.
4047 * @param foreColorRGB a 24-bit RGB value for foreground color
4048 * @param backColorRGB a 24-bit RGB value for foreground color
4049 * @return the string to emit to an ANSI / ECMA-style terminal,
4052 private String
colorRGB(final int foreColorRGB
, final int backColorRGB
) {
4053 int foreColorRed
= (foreColorRGB
>>> 16) & 0xFF;
4054 int foreColorGreen
= (foreColorRGB
>>> 8) & 0xFF;
4055 int foreColorBlue
= foreColorRGB
& 0xFF;
4056 int backColorRed
= (backColorRGB
>>> 16) & 0xFF;
4057 int backColorGreen
= (backColorRGB
>>> 8) & 0xFF;
4058 int backColorBlue
= backColorRGB
& 0xFF;
4060 StringBuilder sb
= new StringBuilder();
4061 sb
.append(String
.format("\033[38;2;%d;%d;%dm",
4062 foreColorRed
, foreColorGreen
, foreColorBlue
));
4063 sb
.append(String
.format("\033[48;2;%d;%d;%dm",
4064 backColorRed
, backColorGreen
, backColorBlue
));
4065 return sb
.toString();
4069 * Create a T.416 RGB parameter sequence for a single color change.
4071 * @param bold if true, set bold
4072 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
4073 * @param foreground if true, this is a foreground color
4074 * @return the string to emit to an xterm terminal with RGB support,
4075 * e.g. "\033[38;2;RR;GG;BBm"
4077 private String
rgbColor(final boolean bold
, final Color color
,
4078 final boolean foreground
) {
4079 if (doRgbColor
== false) {
4082 StringBuilder sb
= new StringBuilder("\033[");
4084 // Bold implies foreground only
4086 if (color
.equals(Color
.BLACK
)) {
4087 sb
.append(systemColorRGB(MYBOLD_BLACK
));
4088 } else if (color
.equals(Color
.RED
)) {
4089 sb
.append(systemColorRGB(MYBOLD_RED
));
4090 } else if (color
.equals(Color
.GREEN
)) {
4091 sb
.append(systemColorRGB(MYBOLD_GREEN
));
4092 } else if (color
.equals(Color
.YELLOW
)) {
4093 sb
.append(systemColorRGB(MYBOLD_YELLOW
));
4094 } else if (color
.equals(Color
.BLUE
)) {
4095 sb
.append(systemColorRGB(MYBOLD_BLUE
));
4096 } else if (color
.equals(Color
.MAGENTA
)) {
4097 sb
.append(systemColorRGB(MYBOLD_MAGENTA
));
4098 } else if (color
.equals(Color
.CYAN
)) {
4099 sb
.append(systemColorRGB(MYBOLD_CYAN
));
4100 } else if (color
.equals(Color
.WHITE
)) {
4101 sb
.append(systemColorRGB(MYBOLD_WHITE
));
4109 if (color
.equals(Color
.BLACK
)) {
4110 sb
.append(systemColorRGB(MYBLACK
));
4111 } else if (color
.equals(Color
.RED
)) {
4112 sb
.append(systemColorRGB(MYRED
));
4113 } else if (color
.equals(Color
.GREEN
)) {
4114 sb
.append(systemColorRGB(MYGREEN
));
4115 } else if (color
.equals(Color
.YELLOW
)) {
4116 sb
.append(systemColorRGB(MYYELLOW
));
4117 } else if (color
.equals(Color
.BLUE
)) {
4118 sb
.append(systemColorRGB(MYBLUE
));
4119 } else if (color
.equals(Color
.MAGENTA
)) {
4120 sb
.append(systemColorRGB(MYMAGENTA
));
4121 } else if (color
.equals(Color
.CYAN
)) {
4122 sb
.append(systemColorRGB(MYCYAN
));
4123 } else if (color
.equals(Color
.WHITE
)) {
4124 sb
.append(systemColorRGB(MYWHITE
));
4128 return sb
.toString();
4132 * Create a T.416 RGB parameter sequence for both foreground and
4133 * background color change.
4135 * @param bold if true, set bold
4136 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4137 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4138 * @return the string to emit to an xterm terminal with RGB support,
4139 * e.g. "\033[38;2;RR;GG;BB;48;2;RR;GG;BBm"
4141 private String
rgbColor(final boolean bold
, final Color foreColor
,
4142 final Color backColor
) {
4143 if (doRgbColor
== false) {
4147 return rgbColor(bold
, foreColor
, true) +
4148 rgbColor(false, backColor
, false);
4152 * Create a SGR parameter sequence for a single color change.
4154 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
4155 * @param foreground if true, this is a foreground color
4156 * @param header if true, make the full header, otherwise just emit the
4157 * color parameter e.g. "42;"
4158 * @return the string to emit to an ANSI / ECMA-style terminal,
4161 private String
color(final Color color
, final boolean foreground
,
4162 final boolean header
) {
4164 int ecmaColor
= color
.getValue();
4166 // Convert Color.* values to SGR numerics
4174 return String
.format("\033[%dm", ecmaColor
);
4176 return String
.format("%d;", ecmaColor
);
4181 * Create a SGR parameter sequence for both foreground and background
4184 * @param bold if true, set bold
4185 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4186 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4187 * @return the string to emit to an ANSI / ECMA-style terminal,
4188 * e.g. "\033[31;42m"
4190 private String
color(final boolean bold
, final Color foreColor
,
4191 final Color backColor
) {
4192 return color(foreColor
, backColor
, true) +
4193 rgbColor(bold
, foreColor
, backColor
);
4197 * Create a SGR parameter sequence for both foreground and
4198 * background color change.
4200 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4201 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4202 * @param header if true, make the full header, otherwise just emit the
4203 * color parameter e.g. "31;42;"
4204 * @return the string to emit to an ANSI / ECMA-style terminal,
4205 * e.g. "\033[31;42m"
4207 private String
color(final Color foreColor
, final Color backColor
,
4208 final boolean header
) {
4210 int ecmaForeColor
= foreColor
.getValue();
4211 int ecmaBackColor
= backColor
.getValue();
4213 // Convert Color.* values to SGR numerics
4214 ecmaBackColor
+= 40;
4215 ecmaForeColor
+= 30;
4218 return String
.format("\033[%d;%dm", ecmaForeColor
, ecmaBackColor
);
4220 return String
.format("%d;%d;", ecmaForeColor
, ecmaBackColor
);
4225 * Create a SGR parameter sequence for foreground, background, and
4226 * several attributes. This sequence first resets all attributes to
4227 * default, then sets attributes as per the parameters.
4229 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4230 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4231 * @param bold if true, set bold
4232 * @param reverse if true, set reverse
4233 * @param blink if true, set blink
4234 * @param underline if true, set underline
4235 * @return the string to emit to an ANSI / ECMA-style terminal,
4236 * e.g. "\033[0;1;31;42m"
4238 private String
color(final Color foreColor
, final Color backColor
,
4239 final boolean bold
, final boolean reverse
, final boolean blink
,
4240 final boolean underline
) {
4242 int ecmaForeColor
= foreColor
.getValue();
4243 int ecmaBackColor
= backColor
.getValue();
4245 // Convert Color.* values to SGR numerics
4246 ecmaBackColor
+= 40;
4247 ecmaForeColor
+= 30;
4249 StringBuilder sb
= new StringBuilder();
4250 if ( bold
&& reverse
&& blink
&& !underline
) {
4251 sb
.append("\033[0;1;7;5;");
4252 } else if ( bold
&& reverse
&& !blink
&& !underline
) {
4253 sb
.append("\033[0;1;7;");
4254 } else if ( !bold
&& reverse
&& blink
&& !underline
) {
4255 sb
.append("\033[0;7;5;");
4256 } else if ( bold
&& !reverse
&& blink
&& !underline
) {
4257 sb
.append("\033[0;1;5;");
4258 } else if ( bold
&& !reverse
&& !blink
&& !underline
) {
4259 sb
.append("\033[0;1;");
4260 } else if ( !bold
&& reverse
&& !blink
&& !underline
) {
4261 sb
.append("\033[0;7;");
4262 } else if ( !bold
&& !reverse
&& blink
&& !underline
) {
4263 sb
.append("\033[0;5;");
4264 } else if ( bold
&& reverse
&& blink
&& underline
) {
4265 sb
.append("\033[0;1;7;5;4;");
4266 } else if ( bold
&& reverse
&& !blink
&& underline
) {
4267 sb
.append("\033[0;1;7;4;");
4268 } else if ( !bold
&& reverse
&& blink
&& underline
) {
4269 sb
.append("\033[0;7;5;4;");
4270 } else if ( bold
&& !reverse
&& blink
&& underline
) {
4271 sb
.append("\033[0;1;5;4;");
4272 } else if ( bold
&& !reverse
&& !blink
&& underline
) {
4273 sb
.append("\033[0;1;4;");
4274 } else if ( !bold
&& reverse
&& !blink
&& underline
) {
4275 sb
.append("\033[0;7;4;");
4276 } else if ( !bold
&& !reverse
&& blink
&& underline
) {
4277 sb
.append("\033[0;5;4;");
4278 } else if ( !bold
&& !reverse
&& !blink
&& underline
) {
4279 sb
.append("\033[0;4;");
4281 assert (!bold
&& !reverse
&& !blink
&& !underline
);
4282 sb
.append("\033[0;");
4284 sb
.append(String
.format("%d;%dm", ecmaForeColor
, ecmaBackColor
));
4285 sb
.append(rgbColor(bold
, foreColor
, backColor
));
4286 return sb
.toString();
4290 * Create a SGR parameter sequence for foreground, background, and
4291 * several attributes. This sequence first resets all attributes to
4292 * default, then sets attributes as per the parameters.
4294 * @param foreColorRGB a 24-bit RGB value for foreground color
4295 * @param backColorRGB a 24-bit RGB value for foreground color
4296 * @param bold if true, set bold
4297 * @param reverse if true, set reverse
4298 * @param blink if true, set blink
4299 * @param underline if true, set underline
4300 * @return the string to emit to an ANSI / ECMA-style terminal,
4301 * e.g. "\033[0;1;31;42m"
4303 private String
colorRGB(final int foreColorRGB
, final int backColorRGB
,
4304 final boolean bold
, final boolean reverse
, final boolean blink
,
4305 final boolean underline
) {
4307 int foreColorRed
= (foreColorRGB
>>> 16) & 0xFF;
4308 int foreColorGreen
= (foreColorRGB
>>> 8) & 0xFF;
4309 int foreColorBlue
= foreColorRGB
& 0xFF;
4310 int backColorRed
= (backColorRGB
>>> 16) & 0xFF;
4311 int backColorGreen
= (backColorRGB
>>> 8) & 0xFF;
4312 int backColorBlue
= backColorRGB
& 0xFF;
4314 StringBuilder sb
= new StringBuilder();
4315 if ( bold
&& reverse
&& blink
&& !underline
) {
4316 sb
.append("\033[0;1;7;5;");
4317 } else if ( bold
&& reverse
&& !blink
&& !underline
) {
4318 sb
.append("\033[0;1;7;");
4319 } else if ( !bold
&& reverse
&& blink
&& !underline
) {
4320 sb
.append("\033[0;7;5;");
4321 } else if ( bold
&& !reverse
&& blink
&& !underline
) {
4322 sb
.append("\033[0;1;5;");
4323 } else if ( bold
&& !reverse
&& !blink
&& !underline
) {
4324 sb
.append("\033[0;1;");
4325 } else if ( !bold
&& reverse
&& !blink
&& !underline
) {
4326 sb
.append("\033[0;7;");
4327 } else if ( !bold
&& !reverse
&& blink
&& !underline
) {
4328 sb
.append("\033[0;5;");
4329 } else if ( bold
&& reverse
&& blink
&& underline
) {
4330 sb
.append("\033[0;1;7;5;4;");
4331 } else if ( bold
&& reverse
&& !blink
&& underline
) {
4332 sb
.append("\033[0;1;7;4;");
4333 } else if ( !bold
&& reverse
&& blink
&& underline
) {
4334 sb
.append("\033[0;7;5;4;");
4335 } else if ( bold
&& !reverse
&& blink
&& underline
) {
4336 sb
.append("\033[0;1;5;4;");
4337 } else if ( bold
&& !reverse
&& !blink
&& underline
) {
4338 sb
.append("\033[0;1;4;");
4339 } else if ( !bold
&& reverse
&& !blink
&& underline
) {
4340 sb
.append("\033[0;7;4;");
4341 } else if ( !bold
&& !reverse
&& blink
&& underline
) {
4342 sb
.append("\033[0;5;4;");
4343 } else if ( !bold
&& !reverse
&& !blink
&& underline
) {
4344 sb
.append("\033[0;4;");
4346 assert (!bold
&& !reverse
&& !blink
&& !underline
);
4347 sb
.append("\033[0;");
4350 sb
.append("m\033[38;2;");
4351 sb
.append(String
.format("%d;%d;%d", foreColorRed
, foreColorGreen
,
4353 sb
.append("m\033[48;2;");
4354 sb
.append(String
.format("%d;%d;%d", backColorRed
, backColorGreen
,
4357 return sb
.toString();
4361 * Create a SGR parameter sequence to reset to VT100 defaults.
4363 * @return the string to emit to an ANSI / ECMA-style terminal,
4366 private String
normal() {
4367 return normal(true) + rgbColor(false, Color
.WHITE
, Color
.BLACK
);
4371 * Create a SGR parameter sequence to reset to ECMA-48 default
4372 * foreground/background.
4374 * @return the string to emit to an ANSI / ECMA-style terminal,
4377 private String
defaultColor() {
4380 * Normal (neither bold nor faint).
4383 * Steady (not blinking).
4384 * Positive (not inverse).
4385 * Visible (not hidden).
4387 * Default foreground color.
4388 * Default background color.
4390 return "\033[0;22;23;24;25;27;28;29;39;49m";
4394 * Create a SGR parameter sequence to reset to defaults.
4396 * @param header if true, make the full header, otherwise just emit the
4397 * bare parameter e.g. "0;"
4398 * @return the string to emit to an ANSI / ECMA-style terminal,
4401 private String
normal(final boolean header
) {
4403 return "\033[0;37;40m";
4409 * Create a SGR parameter sequence for enabling the visible cursor.
4411 * @param on if true, turn on cursor
4412 * @return the string to emit to an ANSI / ECMA-style terminal
4414 private String
cursor(final boolean on
) {
4415 if (on
&& !cursorOn
) {
4419 if (!on
&& cursorOn
) {
4427 * Clear the entire screen. Because some terminals use back-color-erase,
4428 * set the color to white-on-black beforehand.
4430 * @return the string to emit to an ANSI / ECMA-style terminal
4432 private String
clearAll() {
4433 return "\033[0;37;40m\033[2J";
4437 * Clear the line from the cursor (inclusive) to the end of the screen.
4438 * Because some terminals use back-color-erase, set the color to
4439 * white-on-black beforehand.
4441 * @return the string to emit to an ANSI / ECMA-style terminal
4443 private String
clearRemainingLine() {
4444 return "\033[0;37;40m\033[K";
4448 * Move the cursor to (x, y).
4450 * @param x column coordinate. 0 is the left-most column.
4451 * @param y row coordinate. 0 is the top-most row.
4452 * @return the string to emit to an ANSI / ECMA-style terminal
4454 private String
gotoXY(final int x
, final int y
) {
4455 return String
.format("\033[%d;%dH", y
+ 1, x
+ 1);
4459 * Tell (u)xterm that we want to receive mouse events based on "Any event
4460 * tracking", UTF-8 coordinates, and then SGR coordinates. Ideally we
4461 * will end up with SGR coordinates with UTF-8 coordinates as a fallback.
4463 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
4465 * Note that this also sets the alternate/primary screen buffer.
4467 * Finally, also emit a Privacy Message sequence that Jexer recognizes to
4468 * mean "hide the mouse pointer." We have to use our own sequence to do
4469 * this because there is no standard in xterm for unilaterally hiding the
4470 * pointer all the time (regardless of typing).
4472 * @param on If true, enable mouse report and use the alternate screen
4473 * buffer. If false disable mouse reporting and use the primary screen
4475 * @return the string to emit to xterm
4477 private String
mouse(final boolean on
) {
4479 return "\033[?1002;1003;1005;1006h\033[?1049h\033^hideMousePointer\033\\";
4481 return "\033[?1002;1003;1006;1005l\033[?1049l\033^showMousePointer\033\\";