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
.FileDescriptor
;
34 import java
.io
.FileInputStream
;
35 import java
.io
.InputStream
;
36 import java
.io
.InputStreamReader
;
37 import java
.io
.IOException
;
38 import java
.io
.OutputStream
;
39 import java
.io
.OutputStreamWriter
;
40 import java
.io
.PrintWriter
;
41 import java
.io
.Reader
;
42 import java
.io
.UnsupportedEncodingException
;
43 import java
.util
.ArrayList
;
44 import java
.util
.Collections
;
45 import java
.util
.HashMap
;
46 import java
.util
.List
;
49 import jexer
.bits
.Cell
;
50 import jexer
.bits
.CellAttributes
;
51 import jexer
.bits
.Color
;
52 import jexer
.event
.TCommandEvent
;
53 import jexer
.event
.TInputEvent
;
54 import jexer
.event
.TKeypressEvent
;
55 import jexer
.event
.TMouseEvent
;
56 import jexer
.event
.TResizeEvent
;
57 import static jexer
.TCommand
.*;
58 import static jexer
.TKeypress
.*;
61 * This class reads keystrokes and mouse events and emits output to ANSI
62 * X3.64 / ECMA-48 type terminals e.g. xterm, linux, vt100, ansi.sys, etc.
64 public class ECMA48Terminal
extends LogicalScreen
65 implements TerminalReader
, Runnable
{
67 // ------------------------------------------------------------------------
68 // Constants --------------------------------------------------------------
69 // ------------------------------------------------------------------------
72 * States in the input parser.
74 private enum ParseState
{
85 * Number of colors in the sixel palette. Xterm 335 defines the max as
88 private static final int MAX_COLOR_REGISTERS
= 1024;
89 // Black-and-white is possible too.
90 // private static final int MAX_COLOR_REGISTERS = 2;
92 // ------------------------------------------------------------------------
93 // Variables --------------------------------------------------------------
94 // ------------------------------------------------------------------------
97 * Emit debugging to stderr.
99 private boolean debugToStderr
= false;
102 * If true, emit T.416-style RGB colors for normal system colors. This
103 * is a) expensive in bandwidth, and b) potentially terrible looking for
106 private static boolean doRgbColor
= false;
109 * The session information.
111 private SessionInfo sessionInfo
;
114 * The event queue, filled up by a thread reading on input.
116 private List
<TInputEvent
> eventQueue
;
119 * If true, we want the reader thread to exit gracefully.
121 private boolean stopReaderThread
;
126 private Thread readerThread
;
129 * Parameters being collected. E.g. if the string is \033[1;3m, then
130 * params[0] will be 1 and params[1] will be 3.
132 private List
<String
> params
;
135 * Current parsing state.
137 private ParseState state
;
140 * The time we entered ESCAPE. If we get a bare escape without a code
141 * following it, this is used to return that bare escape.
143 private long escapeTime
;
146 * The time we last checked the window size. We try not to spawn stty
147 * more than once per second.
149 private long windowSizeTime
;
152 * true if mouse1 was down. Used to report mouse1 on the release event.
154 private boolean mouse1
;
157 * true if mouse2 was down. Used to report mouse2 on the release event.
159 private boolean mouse2
;
162 * true if mouse3 was down. Used to report mouse3 on the release event.
164 private boolean mouse3
;
167 * Cache the cursor visibility value so we only emit the sequence when we
170 private boolean cursorOn
= true;
173 * Cache the last window size to figure out if a TResizeEvent needs to be
176 private TResizeEvent windowResize
= null;
179 * Window width in pixels. Used for sixel support.
181 private int widthPixels
= 640;
184 * Window height in pixels. Used for sixel support.
186 private int heightPixels
= 400;
189 * If true, emit image data via sixel.
191 private boolean sixel
= true;
194 * The sixel palette handler.
196 private SixelPalette palette
= null;
199 * The sixel post-rendered string cache.
201 private SixelCache sixelCache
= null;
204 * If true, then we changed System.in and need to change it back.
206 private boolean setRawMode
;
209 * The terminal's input. If an InputStream is not specified in the
210 * constructor, then this InputStreamReader will be bound to System.in
211 * with UTF-8 encoding.
213 private Reader input
;
216 * The terminal's raw InputStream. If an InputStream is not specified in
217 * the constructor, then this InputReader will be bound to System.in.
218 * This is used by run() to see if bytes are available() before calling
219 * (Reader)input.read().
221 private InputStream inputStream
;
224 * The terminal's output. If an OutputStream is not specified in the
225 * constructor, then this PrintWriter will be bound to System.out with
228 private PrintWriter output
;
231 * The listening object that run() wakes up on new input.
233 private Object listener
;
236 * SixelPalette is used to manage the conversion of images between 24-bit
237 * RGB color and a palette of MAX_COLOR_REGISTERS colors.
239 private class SixelPalette
{
242 * Color palette for sixel output, sorted low to high.
244 private List
<Integer
> rgbColors
= new ArrayList
<Integer
>();
247 * Map of color palette index for sixel output, from the order it was
248 * generated by makePalette() to rgbColors.
250 private int [] rgbSortedIndex
= new int[MAX_COLOR_REGISTERS
];
253 * The color palette, organized by hue, saturation, and luminance.
254 * This is used for a fast color match.
256 private ArrayList
<ArrayList
<ArrayList
<ColorIdx
>>> hslColors
;
259 * Number of bits for hue.
261 private int hueBits
= -1;
264 * Number of bits for saturation.
266 private int satBits
= -1;
269 * Number of bits for luminance.
271 private int lumBits
= -1;
274 * Step size for hue bins.
276 private int hueStep
= -1;
279 * Step size for saturation bins.
281 private int satStep
= -1;
284 * Cached RGB to HSL result.
286 private int hsl
[] = new int[3];
289 * ColorIdx records a RGB color and its palette index.
291 private class ColorIdx
{
293 * The 24-bit RGB color.
298 * The palette index for this color.
303 * Public constructor.
305 * @param color the 24-bit RGB color
306 * @param index the palette index for this color
308 public ColorIdx(final int color
, final int index
) {
315 * Public constructor.
317 public SixelPalette() {
322 * Find the nearest match for a color in the palette.
324 * @param color the RGB color
325 * @return the index in rgbColors that is closest to color
327 public int matchColor(final int color
) {
332 * matchColor() is a critical performance bottleneck. To make it
333 * decent, we do the following:
335 * 1. Find the nearest two hues that bracket this color.
337 * 2. Find the nearest two saturations that bracket this color.
339 * 3. Iterate within these four bands of luminance values,
340 * returning the closest color by Euclidean distance.
342 * This strategy reduces the search space by about 97%.
344 int red
= (color
>>> 16) & 0xFF;
345 int green
= (color
>>> 8) & 0xFF;
346 int blue
= color
& 0xFF;
348 if (MAX_COLOR_REGISTERS
== 2) {
349 if (((red
* red
) + (green
* green
) + (blue
* blue
)) < 35568) {
358 rgbToHsl(red
, green
, blue
, hsl
);
362 // System.err.printf("%d %d %d\n", hue, sat, lum);
364 double diff
= Double
.MAX_VALUE
;
367 int hue1
= hue
/ (360/hueStep
);
369 if (hue1
>= hslColors
.size() - 1) {
370 // Bracket pure red from above.
371 hue1
= hslColors
.size() - 1;
373 } else if (hue1
== 0) {
374 // Bracket pure red from below.
375 hue2
= hslColors
.size() - 1;
378 for (int hI
= hue1
; hI
!= -1;) {
379 ArrayList
<ArrayList
<ColorIdx
>> sats
= hslColors
.get(hI
);
382 } else if (hI
== hue2
) {
386 int sMin
= (sat
/ satStep
) - 1;
391 } else if (sMin
== sats
.size() - 1) {
396 assert (sMax
- sMin
== 1);
399 // int sMax = sats.size() - 1;
401 for (int sI
= sMin
; sI
<= sMax
; sI
++) {
402 ArrayList
<ColorIdx
> lums
= sats
.get(sI
);
404 // True 3D colorspace match for the remaining values
405 for (ColorIdx c
: lums
) {
406 int rgbColor
= c
.color
;
408 int red2
= (rgbColor
>>> 16) & 0xFF;
409 int green2
= (rgbColor
>>> 8) & 0xFF;
410 int blue2
= rgbColor
& 0xFF;
411 newDiff
+= Math
.pow(red2
- red
, 2);
412 newDiff
+= Math
.pow(green2
- green
, 2);
413 newDiff
+= Math
.pow(blue2
- blue
, 2);
414 if (newDiff
< diff
) {
415 idx
= rgbSortedIndex
[c
.index
];
422 if (((red
* red
) + (green
* green
) + (blue
* blue
)) < diff
) {
423 // Black is a closer match.
425 } else if ((((255 - red
) * (255 - red
)) +
426 ((255 - green
) * (255 - green
)) +
427 ((255 - blue
) * (255 - blue
))) < diff
) {
429 // White is a closer match.
430 idx
= MAX_COLOR_REGISTERS
- 1;
437 * Clamp an int value to [0, 255].
439 * @param x the int value
440 * @return an int between 0 and 255.
442 private int clamp(final int x
) {
453 * Dither an image to a MAX_COLOR_REGISTERS palette. The dithered
454 * image cells will contain indexes into the palette.
456 * @param image the image to dither
457 * @return the dithered image. Every pixel is an index into the
460 public BufferedImage
ditherImage(final BufferedImage image
) {
462 BufferedImage ditheredImage
= new BufferedImage(image
.getWidth(),
463 image
.getHeight(), BufferedImage
.TYPE_INT_ARGB
);
465 int [] rgbArray
= image
.getRGB(0, 0, image
.getWidth(),
466 image
.getHeight(), null, 0, image
.getWidth());
467 ditheredImage
.setRGB(0, 0, image
.getWidth(), image
.getHeight(),
468 rgbArray
, 0, image
.getWidth());
470 for (int imageY
= 0; imageY
< image
.getHeight(); imageY
++) {
471 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
472 int oldPixel
= ditheredImage
.getRGB(imageX
,
474 int colorIdx
= matchColor(oldPixel
);
475 assert (colorIdx
>= 0);
476 assert (colorIdx
< MAX_COLOR_REGISTERS
);
477 int newPixel
= rgbColors
.get(colorIdx
);
478 ditheredImage
.setRGB(imageX
, imageY
, colorIdx
);
480 int oldRed
= (oldPixel
>>> 16) & 0xFF;
481 int oldGreen
= (oldPixel
>>> 8) & 0xFF;
482 int oldBlue
= oldPixel
& 0xFF;
484 int newRed
= (newPixel
>>> 16) & 0xFF;
485 int newGreen
= (newPixel
>>> 8) & 0xFF;
486 int newBlue
= newPixel
& 0xFF;
488 int redError
= (oldRed
- newRed
) / 16;
489 int greenError
= (oldGreen
- newGreen
) / 16;
490 int blueError
= (oldBlue
- newBlue
) / 16;
492 int red
, green
, blue
;
493 if (imageX
< image
.getWidth() - 1) {
494 int pXpY
= ditheredImage
.getRGB(imageX
+ 1, imageY
);
495 red
= ((pXpY
>>> 16) & 0xFF) + (7 * redError
);
496 green
= ((pXpY
>>> 8) & 0xFF) + (7 * greenError
);
497 blue
= ( pXpY
& 0xFF) + (7 * blueError
);
499 green
= clamp(green
);
501 pXpY
= ((red
& 0xFF) << 16);
502 pXpY
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
503 ditheredImage
.setRGB(imageX
+ 1, imageY
, pXpY
);
505 if (imageY
< image
.getHeight() - 1) {
506 int pXpYp
= ditheredImage
.getRGB(imageX
+ 1,
508 red
= ((pXpYp
>>> 16) & 0xFF) + redError
;
509 green
= ((pXpYp
>>> 8) & 0xFF) + greenError
;
510 blue
= ( pXpYp
& 0xFF) + blueError
;
512 green
= clamp(green
);
514 pXpYp
= ((red
& 0xFF) << 16);
515 pXpYp
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
516 ditheredImage
.setRGB(imageX
+ 1, imageY
+ 1, pXpYp
);
518 } else if (imageY
< image
.getHeight() - 1) {
519 int pXmYp
= ditheredImage
.getRGB(imageX
- 1,
521 int pXYp
= ditheredImage
.getRGB(imageX
,
524 red
= ((pXmYp
>>> 16) & 0xFF) + (3 * redError
);
525 green
= ((pXmYp
>>> 8) & 0xFF) + (3 * greenError
);
526 blue
= ( pXmYp
& 0xFF) + (3 * blueError
);
528 green
= clamp(green
);
530 pXmYp
= ((red
& 0xFF) << 16);
531 pXmYp
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
532 ditheredImage
.setRGB(imageX
- 1, imageY
+ 1, pXmYp
);
534 red
= ((pXYp
>>> 16) & 0xFF) + (5 * redError
);
535 green
= ((pXYp
>>> 8) & 0xFF) + (5 * greenError
);
536 blue
= ( pXYp
& 0xFF) + (5 * blueError
);
538 green
= clamp(green
);
540 pXYp
= ((red
& 0xFF) << 16);
541 pXYp
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
542 ditheredImage
.setRGB(imageX
, imageY
+ 1, pXYp
);
544 } // for (int imageY = 0; imageY < image.getHeight(); imageY++)
545 } // for (int imageX = 0; imageX < image.getWidth(); imageX++)
547 return ditheredImage
;
551 * Convert an RGB color to HSL.
553 * @param red red color, between 0 and 255
554 * @param green green color, between 0 and 255
555 * @param blue blue color, between 0 and 255
556 * @param hsl the hsl color as [hue, saturation, luminance]
558 private void rgbToHsl(final int red
, final int green
,
559 final int blue
, final int [] hsl
) {
561 assert ((red
>= 0) && (red
<= 255));
562 assert ((green
>= 0) && (green
<= 255));
563 assert ((blue
>= 0) && (blue
<= 255));
565 double R
= red
/ 255.0;
566 double G
= green
/ 255.0;
567 double B
= blue
/ 255.0;
568 boolean Rmax
= false;
569 boolean Gmax
= false;
570 boolean Bmax
= false;
571 double min
= (R
< G ? R
: G
);
572 min
= (min
< B ? min
: B
);
574 if ((R
>= G
) && (R
>= B
)) {
577 } else if ((G
>= R
) && (G
>= B
)) {
580 } else if ((B
>= G
) && (B
>= R
)) {
585 double L
= (min
+ max
) / 2.0;
590 S
= (max
- min
) / (max
+ min
);
592 S
= (max
- min
) / (2.0 - max
- min
);
596 assert (Gmax
== false);
597 assert (Bmax
== false);
598 H
= (G
- B
) / (max
- min
);
600 assert (Rmax
== false);
601 assert (Bmax
== false);
602 H
= 2.0 + (B
- R
) / (max
- min
);
604 assert (Rmax
== false);
605 assert (Gmax
== false);
606 H
= 4.0 + (R
- G
) / (max
- min
);
611 hsl
[0] = (int) (H
* 60.0);
612 hsl
[1] = (int) (S
* 100.0);
613 hsl
[2] = (int) (L
* 100.0);
615 assert ((hsl
[0] >= 0) && (hsl
[0] <= 360));
616 assert ((hsl
[1] >= 0) && (hsl
[1] <= 100));
617 assert ((hsl
[2] >= 0) && (hsl
[2] <= 100));
621 * Convert a HSL color to RGB.
623 * @param hue hue, between 0 and 359
624 * @param sat saturation, between 0 and 100
625 * @param lum luminance, between 0 and 100
626 * @return the rgb color as 0x00RRGGBB
628 private int hslToRgb(final int hue
, final int sat
, final int lum
) {
629 assert ((hue
>= 0) && (hue
<= 360));
630 assert ((sat
>= 0) && (sat
<= 100));
631 assert ((lum
>= 0) && (lum
<= 100));
633 double S
= sat
/ 100.0;
634 double L
= lum
/ 100.0;
635 double C
= (1.0 - Math
.abs((2.0 * L
) - 1.0)) * S
;
636 double Hp
= hue
/ 60.0;
637 double X
= C
* (1.0 - Math
.abs((Hp
% 2) - 1.0));
644 } else if (Hp
<= 2.0) {
647 } else if (Hp
<= 3.0) {
650 } else if (Hp
<= 4.0) {
653 } else if (Hp
<= 5.0) {
656 } else if (Hp
<= 6.0) {
660 double m
= L
- (C
/ 2.0);
661 int red
= ((int) ((Rp
+ m
) * 255.0)) << 16;
662 int green
= ((int) ((Gp
+ m
) * 255.0)) << 8;
663 int blue
= (int) ((Bp
+ m
) * 255.0);
665 return (red
| green
| blue
);
669 * Create the sixel palette.
671 private void makePalette() {
672 // Generate the sixel palette. Because we have no idea at this
673 // layer which image(s) will be shown, we have to use a common
674 // palette with MAX_COLOR_REGISTERS colors for everything, and
675 // map the BufferedImage colors to their nearest neighbor in RGB
678 if (MAX_COLOR_REGISTERS
== 2) {
680 rgbColors
.add(0xFFFFFF);
681 rgbSortedIndex
[0] = 0;
682 rgbSortedIndex
[1] = 1;
686 // We build a palette using the Hue-Saturation-Luminence model,
687 // with 5+ bits for Hue, 2+ bits for Saturation, and 1+ bit for
688 // Luminance. We convert these colors to 24-bit RGB, sort them
689 // ascending, and steal the first index for pure black and the
690 // last for pure white. The 8-bit final palette favors bright
691 // colors, somewhere between pastel and classic television
692 // technicolor. 9- and 10-bit palettes are more uniform.
694 // Default at 256 colors.
699 assert (MAX_COLOR_REGISTERS
>= 256);
700 assert ((MAX_COLOR_REGISTERS
== 256)
701 || (MAX_COLOR_REGISTERS
== 512)
702 || (MAX_COLOR_REGISTERS
== 1024)
703 || (MAX_COLOR_REGISTERS
== 2048));
705 switch (MAX_COLOR_REGISTERS
) {
722 hueStep
= (int) (Math
.pow(2, hueBits
));
723 satStep
= (int) (100 / Math
.pow(2, satBits
));
724 // 1 bit for luminance: 40 and 70.
729 // 2 bits: 20, 40, 60, 80
734 // 3 bits: 8, 20, 32, 44, 56, 68, 80, 92
740 // System.err.printf("<html><body>\n");
741 // Hue is evenly spaced around the wheel.
742 hslColors
= new ArrayList
<ArrayList
<ArrayList
<ColorIdx
>>>();
744 final boolean DEBUG
= false;
745 ArrayList
<Integer
> rawRgbList
= new ArrayList
<Integer
>();
747 for (int hue
= 0; hue
< (360 - (360 % hueStep
));
748 hue
+= (360/hueStep
)) {
750 ArrayList
<ArrayList
<ColorIdx
>> satList
= null;
751 satList
= new ArrayList
<ArrayList
<ColorIdx
>>();
752 hslColors
.add(satList
);
754 // Saturation is linearly spaced between pastel and pure.
755 for (int sat
= satStep
; sat
<= 100; sat
+= satStep
) {
757 ArrayList
<ColorIdx
> lumList
= new ArrayList
<ColorIdx
>();
758 satList
.add(lumList
);
760 // Luminance brackets the pure color, but leaning toward
762 for (int lum
= lumBegin
; lum
< 100; lum
+= lumStep
) {
764 System.err.printf("<font style = \"color:");
765 System.err.printf("hsl(%d, %d%%, %d%%)",
767 System.err.printf(";\">=</font>\n");
769 int rgbColor
= hslToRgb(hue
, sat
, lum
);
770 rgbColors
.add(rgbColor
);
771 ColorIdx colorIdx
= new ColorIdx(rgbColor
,
772 rgbColors
.size() - 1);
773 lumList
.add(colorIdx
);
775 rawRgbList
.add(rgbColor
);
777 int red
= (rgbColor
>>> 16) & 0xFF;
778 int green
= (rgbColor
>>> 8) & 0xFF;
779 int blue
= rgbColor
& 0xFF;
780 int [] backToHsl
= new int[3];
781 rgbToHsl(red
, green
, blue
, backToHsl
);
782 System
.err
.printf("%d [%d] %d [%d] %d [%d]\n",
783 hue
, backToHsl
[0], sat
, backToHsl
[1],
789 // System.err.printf("\n</body></html>\n");
791 assert (rgbColors
.size() == MAX_COLOR_REGISTERS
);
794 * We need to sort rgbColors, so that toSixel() can know where
795 * BLACK and WHITE are in it. But we also need to be able to
796 * find the sorted values using the old unsorted indexes. So we
797 * will sort it, put all the indexes into a HashMap, and then
798 * build rgbSortedIndex[].
800 Collections
.sort(rgbColors
);
801 HashMap
<Integer
, Integer
> rgbColorIndices
= null;
802 rgbColorIndices
= new HashMap
<Integer
, Integer
>();
803 for (int i
= 0; i
< MAX_COLOR_REGISTERS
; i
++) {
804 rgbColorIndices
.put(rgbColors
.get(i
), i
);
806 for (int i
= 0; i
< MAX_COLOR_REGISTERS
; i
++) {
807 int rawColor
= rawRgbList
.get(i
);
808 rgbSortedIndex
[i
] = rgbColorIndices
.get(rawColor
);
811 for (int i
= 0; i
< MAX_COLOR_REGISTERS
; i
++) {
812 assert (rawRgbList
!= null);
813 int idx
= rgbSortedIndex
[i
];
814 int rgbColor
= rgbColors
.get(idx
);
815 if ((idx
!= 0) && (idx
!= MAX_COLOR_REGISTERS
- 1)) {
817 System.err.printf("%d %06x --> %d %06x\n",
818 i, rawRgbList.get(i), idx, rgbColors.get(idx));
820 assert (rgbColor
== rawRgbList
.get(i
));
825 // Set the dimmest color as true black, and the brightest as true
828 rgbColors
.set(MAX_COLOR_REGISTERS
- 1, 0xFFFFFF);
831 System.err.printf("<html><body>\n");
832 for (Integer rgb: rgbColors) {
833 System.err.printf("<font style = \"color:");
834 System.err.printf("#%06x", rgb);
835 System.err.printf(";\">=</font>\n");
837 System.err.printf("\n</body></html>\n");
843 * Emit the sixel palette.
845 * @param sb the StringBuilder to append to
846 * @param used array of booleans set to true for each color actually
847 * used in this cell, or null to emit the entire palette
848 * @return the string to emit to an ANSI / ECMA-style terminal
850 public String
emitPalette(final StringBuilder sb
,
851 final boolean [] used
) {
853 for (int i
= 0; i
< MAX_COLOR_REGISTERS
; i
++) {
854 if (((used
!= null) && (used
[i
] == true)) || (used
== null)) {
855 int rgbColor
= rgbColors
.get(i
);
856 sb
.append(String
.format("#%d;2;%d;%d;%d", i
,
857 ((rgbColor
>>> 16) & 0xFF) * 100 / 255,
858 ((rgbColor
>>> 8) & 0xFF) * 100 / 255,
859 ( rgbColor
& 0xFF) * 100 / 255));
862 return sb
.toString();
867 * SixelCache is a least-recently-used cache that hangs on to the
868 * post-rendered sixel string for a particular set of cells.
870 private class SixelCache
{
873 * Maximum size of the cache.
875 private int maxSize
= 100;
878 * The entries stored in the cache.
880 private HashMap
<String
, CacheEntry
> cache
= null;
883 * CacheEntry is one entry in the cache.
885 private class CacheEntry
{
897 * The last time this entry was used.
899 public long millis
= 0;
902 * Public constructor.
904 * @param key the cache entry key
905 * @param data the cache entry data
907 public CacheEntry(final String key
, final String data
) {
910 this.millis
= System
.currentTimeMillis();
915 * Public constructor.
917 * @param maxSize the maximum size of the cache
919 public SixelCache(final int maxSize
) {
920 this.maxSize
= maxSize
;
921 cache
= new HashMap
<String
, CacheEntry
>();
925 * Make a unique key for a list of cells.
927 * @param cells the cells
930 private String
makeKey(final ArrayList
<Cell
> cells
) {
931 StringBuilder sb
= new StringBuilder();
932 for (Cell cell
: cells
) {
933 sb
.append(cell
.hashCode());
935 return sb
.toString();
939 * Get an entry from the cache.
941 * @param cells the list of cells that are the cache key
942 * @return the sixel string representing these cells, or null if this
943 * list of cells is not in the cache
945 public String
get(final ArrayList
<Cell
> cells
) {
946 CacheEntry entry
= cache
.get(makeKey(cells
));
950 entry
.millis
= System
.currentTimeMillis();
955 * Put an entry into the cache.
957 * @param cells the list of cells that are the cache key
958 * @param data the sixel string representing these cells
960 public void put(final ArrayList
<Cell
> cells
, final String data
) {
961 String key
= makeKey(cells
);
963 // System.err.println("put() " + key + " size " + cache.size());
965 assert (!cache
.containsKey(key
));
967 assert (cache
.size() <= maxSize
);
968 if (cache
.size() == maxSize
) {
969 // Cache is at limit, evict oldest entry.
970 long oldestTime
= Long
.MAX_VALUE
;
971 String keyToRemove
= null;
972 for (CacheEntry entry
: cache
.values()) {
973 if ((entry
.millis
< oldestTime
) || (keyToRemove
== null)) {
974 keyToRemove
= entry
.key
;
975 oldestTime
= entry
.millis
;
979 System.err.println("put() remove key = " + keyToRemove +
980 " size " + cache.size());
982 assert (keyToRemove
!= null);
983 cache
.remove(keyToRemove
);
985 System.err.println("put() removed, size " + cache.size());
988 assert (cache
.size() <= maxSize
);
989 CacheEntry entry
= new CacheEntry(key
, data
);
990 assert (key
.equals(entry
.key
));
991 cache
.put(key
, entry
);
993 System.err.println("put() added key " + key + " " +
994 " size " + cache.size());
1000 // ------------------------------------------------------------------------
1001 // Constructors -----------------------------------------------------------
1002 // ------------------------------------------------------------------------
1005 * Constructor sets up state for getEvent().
1007 * @param listener the object this backend needs to wake up when new
1009 * @param input an InputStream connected to the remote user, or null for
1010 * System.in. If System.in is used, then on non-Windows systems it will
1011 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
1012 * mode. input is always converted to a Reader with UTF-8 encoding.
1013 * @param output an OutputStream connected to the remote user, or null
1014 * for System.out. output is always converted to a Writer with UTF-8
1016 * @param windowWidth the number of text columns to start with
1017 * @param windowHeight the number of text rows to start with
1018 * @throws UnsupportedEncodingException if an exception is thrown when
1019 * creating the InputStreamReader
1021 public ECMA48Terminal(final Object listener
, final InputStream input
,
1022 final OutputStream output
, final int windowWidth
,
1023 final int windowHeight
) throws UnsupportedEncodingException
{
1025 this(listener
, input
, output
);
1027 // Send dtterm/xterm sequences, which will probably not work because
1028 // allowWindowOps is defaulted to false.
1029 String resizeString
= String
.format("\033[8;%d;%dt", windowHeight
,
1031 this.output
.write(resizeString
);
1032 this.output
.flush();
1036 * Constructor sets up state for getEvent().
1038 * @param listener the object this backend needs to wake up when new
1040 * @param input an InputStream connected to the remote user, or null for
1041 * System.in. If System.in is used, then on non-Windows systems it will
1042 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
1043 * mode. input is always converted to a Reader with UTF-8 encoding.
1044 * @param output an OutputStream connected to the remote user, or null
1045 * for System.out. output is always converted to a Writer with UTF-8
1047 * @throws UnsupportedEncodingException if an exception is thrown when
1048 * creating the InputStreamReader
1050 public ECMA48Terminal(final Object listener
, final InputStream input
,
1051 final OutputStream output
) throws UnsupportedEncodingException
{
1057 stopReaderThread
= false;
1058 this.listener
= listener
;
1060 if (input
== null) {
1061 // inputStream = System.in;
1062 inputStream
= new FileInputStream(FileDescriptor
.in
);
1066 inputStream
= input
;
1068 this.input
= new InputStreamReader(inputStream
, "UTF-8");
1070 if (input
instanceof SessionInfo
) {
1071 // This is a TelnetInputStream that exposes window size and
1072 // environment variables from the telnet layer.
1073 sessionInfo
= (SessionInfo
) input
;
1075 if (sessionInfo
== null) {
1076 if (input
== null) {
1077 // Reading right off the tty
1078 sessionInfo
= new TTYSessionInfo();
1080 sessionInfo
= new TSessionInfo();
1084 if (output
== null) {
1085 this.output
= new PrintWriter(new OutputStreamWriter(System
.out
,
1088 this.output
= new PrintWriter(new OutputStreamWriter(output
,
1092 // Request xterm report window dimensions in pixels
1093 this.output
.printf("%s", xtermReportWindowPixelDimensions());
1095 // Enable mouse reporting and metaSendsEscape
1096 this.output
.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
1097 this.output
.flush();
1099 // Query the screen size
1100 sessionInfo
.queryWindowSize();
1101 setDimensions(sessionInfo
.getWindowWidth(),
1102 sessionInfo
.getWindowHeight());
1104 // Hang onto the window size
1105 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
1106 sessionInfo
.getWindowWidth(), sessionInfo
.getWindowHeight());
1110 // Spin up the input reader
1111 eventQueue
= new ArrayList
<TInputEvent
>();
1112 readerThread
= new Thread(this);
1113 readerThread
.start();
1116 this.output
.write(clearAll());
1117 this.output
.flush();
1121 * Constructor sets up state for getEvent().
1123 * @param listener the object this backend needs to wake up when new
1125 * @param input the InputStream underlying 'reader'. Its available()
1126 * method is used to determine if reader.read() will block or not.
1127 * @param reader a Reader connected to the remote user.
1128 * @param writer a PrintWriter connected to the remote user.
1129 * @param setRawMode if true, set System.in into raw mode with stty.
1130 * This should in general not be used. It is here solely for Demo3,
1131 * which uses System.in.
1132 * @throws IllegalArgumentException if input, reader, or writer are null.
1134 public ECMA48Terminal(final Object listener
, final InputStream input
,
1135 final Reader reader
, final PrintWriter writer
,
1136 final boolean setRawMode
) {
1138 if (input
== null) {
1139 throw new IllegalArgumentException("InputStream must be specified");
1141 if (reader
== null) {
1142 throw new IllegalArgumentException("Reader must be specified");
1144 if (writer
== null) {
1145 throw new IllegalArgumentException("Writer must be specified");
1151 stopReaderThread
= false;
1152 this.listener
= listener
;
1154 inputStream
= input
;
1155 this.input
= reader
;
1157 if (setRawMode
== true) {
1160 this.setRawMode
= setRawMode
;
1162 if (input
instanceof SessionInfo
) {
1163 // This is a TelnetInputStream that exposes window size and
1164 // environment variables from the telnet layer.
1165 sessionInfo
= (SessionInfo
) input
;
1167 if (sessionInfo
== null) {
1168 if (setRawMode
== true) {
1169 // Reading right off the tty
1170 sessionInfo
= new TTYSessionInfo();
1172 sessionInfo
= new TSessionInfo();
1176 this.output
= writer
;
1178 // Request xterm report window dimensions in pixels
1179 this.output
.printf("%s", xtermReportWindowPixelDimensions());
1181 // Enable mouse reporting and metaSendsEscape
1182 this.output
.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
1183 this.output
.flush();
1185 // Query the screen size
1186 sessionInfo
.queryWindowSize();
1187 setDimensions(sessionInfo
.getWindowWidth(),
1188 sessionInfo
.getWindowHeight());
1190 // Hang onto the window size
1191 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
1192 sessionInfo
.getWindowWidth(), sessionInfo
.getWindowHeight());
1196 // Spin up the input reader
1197 eventQueue
= new ArrayList
<TInputEvent
>();
1198 readerThread
= new Thread(this);
1199 readerThread
.start();
1202 this.output
.write(clearAll());
1203 this.output
.flush();
1207 * Constructor sets up state for getEvent().
1209 * @param listener the object this backend needs to wake up when new
1211 * @param input the InputStream underlying 'reader'. Its available()
1212 * method is used to determine if reader.read() will block or not.
1213 * @param reader a Reader connected to the remote user.
1214 * @param writer a PrintWriter connected to the remote user.
1215 * @throws IllegalArgumentException if input, reader, or writer are null.
1217 public ECMA48Terminal(final Object listener
, final InputStream input
,
1218 final Reader reader
, final PrintWriter writer
) {
1220 this(listener
, input
, reader
, writer
, false);
1223 // ------------------------------------------------------------------------
1224 // LogicalScreen ----------------------------------------------------------
1225 // ------------------------------------------------------------------------
1228 * Set the window title.
1230 * @param title the new title
1233 public void setTitle(final String title
) {
1234 output
.write(getSetTitleString(title
));
1239 * Push the logical screen to the physical device.
1242 public void flushPhysical() {
1243 StringBuilder sb
= new StringBuilder();
1247 && (cursorY
<= height
- 1)
1248 && (cursorX
<= width
- 1)
1251 sb
.append(cursor(true));
1252 sb
.append(gotoXY(cursorX
, cursorY
));
1254 sb
.append(cursor(false));
1257 output
.write(sb
.toString());
1262 * Resize the physical screen to match the logical screen dimensions.
1265 public void resizeToScreen() {
1266 // Send dtterm/xterm sequences, which will probably not work because
1267 // allowWindowOps is defaulted to false.
1268 String resizeString
= String
.format("\033[8;%d;%dt", getHeight(),
1270 this.output
.write(resizeString
);
1271 this.output
.flush();
1274 // ------------------------------------------------------------------------
1275 // TerminalReader ---------------------------------------------------------
1276 // ------------------------------------------------------------------------
1279 * Check if there are events in the queue.
1281 * @return if true, getEvents() has something to return to the backend
1283 public boolean hasEvents() {
1284 synchronized (eventQueue
) {
1285 return (eventQueue
.size() > 0);
1290 * Return any events in the IO queue.
1292 * @param queue list to append new events to
1294 public void getEvents(final List
<TInputEvent
> queue
) {
1295 synchronized (eventQueue
) {
1296 if (eventQueue
.size() > 0) {
1297 synchronized (queue
) {
1298 queue
.addAll(eventQueue
);
1306 * Restore terminal to normal state.
1308 public void closeTerminal() {
1310 // System.err.println("=== shutdown() ==="); System.err.flush();
1312 // Tell the reader thread to stop looking at input
1313 stopReaderThread
= true;
1315 readerThread
.join();
1316 } catch (InterruptedException e
) {
1317 if (debugToStderr
) {
1318 e
.printStackTrace();
1322 // Disable mouse reporting and show cursor. Defensive null check
1323 // here in case closeTerminal() is called twice.
1324 if (output
!= null) {
1325 output
.printf("%s%s%s", mouse(false), cursor(true), normal());
1332 // We don't close System.in/out
1334 // Shut down the streams, this should wake up the reader thread
1335 // and make it exit.
1336 if (input
!= null) {
1339 } catch (IOException e
) {
1344 if (output
!= null) {
1352 * Set listener to a different Object.
1354 * @param listener the new listening object that run() wakes up on new
1357 public void setListener(final Object listener
) {
1358 this.listener
= listener
;
1362 * Reload options from System properties.
1364 public void reloadOptions() {
1365 // Permit RGB colors only if externally requested.
1366 if (System
.getProperty("jexer.ECMA48.rgbColor",
1367 "false").equals("true")
1374 // Pull the system properties for sixel output.
1375 if (System
.getProperty("jexer.ECMA48.sixel", "true").equals("true")) {
1382 // ------------------------------------------------------------------------
1383 // Runnable ---------------------------------------------------------------
1384 // ------------------------------------------------------------------------
1387 * Read function runs on a separate thread.
1390 boolean done
= false;
1391 // available() will often return > 1, so we need to read in chunks to
1393 char [] readBuffer
= new char[128];
1394 List
<TInputEvent
> events
= new ArrayList
<TInputEvent
>();
1396 while (!done
&& !stopReaderThread
) {
1398 // We assume that if inputStream has bytes available, then
1399 // input won't block on read().
1400 int n
= inputStream
.available();
1403 System.err.printf("inputStream.available(): %d\n", n);
1408 if (readBuffer
.length
< n
) {
1409 // The buffer wasn't big enough, make it huger
1410 readBuffer
= new char[readBuffer
.length
* 2];
1413 // System.err.printf("BEFORE read()\n"); System.err.flush();
1415 int rc
= input
.read(readBuffer
, 0, readBuffer
.length
);
1418 System.err.printf("AFTER read() %d\n", rc);
1426 for (int i
= 0; i
< rc
; i
++) {
1427 int ch
= readBuffer
[i
];
1428 processChar(events
, (char)ch
);
1430 getIdleEvents(events
);
1431 if (events
.size() > 0) {
1432 // Add to the queue for the backend thread to
1433 // be able to obtain.
1434 synchronized (eventQueue
) {
1435 eventQueue
.addAll(events
);
1437 if (listener
!= null) {
1438 synchronized (listener
) {
1439 listener
.notifyAll();
1446 getIdleEvents(events
);
1447 if (events
.size() > 0) {
1448 synchronized (eventQueue
) {
1449 eventQueue
.addAll(events
);
1451 if (listener
!= null) {
1452 synchronized (listener
) {
1453 listener
.notifyAll();
1459 if (output
.checkError()) {
1464 // Wait 20 millis for more data
1467 // System.err.println("end while loop"); System.err.flush();
1468 } catch (InterruptedException e
) {
1470 } catch (IOException e
) {
1471 e
.printStackTrace();
1474 } // while ((done == false) && (stopReaderThread == false))
1476 // Pass an event up to TApplication to tell it this Backend is done.
1477 synchronized (eventQueue
) {
1478 eventQueue
.add(new TCommandEvent(cmBackendDisconnect
));
1480 if (listener
!= null) {
1481 synchronized (listener
) {
1482 listener
.notifyAll();
1486 // System.err.println("*** run() exiting..."); System.err.flush();
1489 // ------------------------------------------------------------------------
1490 // ECMA48Terminal ---------------------------------------------------------
1491 // ------------------------------------------------------------------------
1494 * Get the width of a character cell in pixels.
1496 * @return the width in pixels of a character cell
1498 public int getTextWidth() {
1499 return (widthPixels
/ sessionInfo
.getWindowWidth());
1503 * Get the height of a character cell in pixels.
1505 * @return the height in pixels of a character cell
1507 public int getTextHeight() {
1508 return (heightPixels
/ sessionInfo
.getWindowHeight());
1512 * Getter for sessionInfo.
1514 * @return the SessionInfo
1516 public SessionInfo
getSessionInfo() {
1521 * Get the output writer.
1523 * @return the Writer
1525 public PrintWriter
getOutput() {
1530 * Call 'stty' to set cooked mode.
1532 * <p>Actually executes '/bin/sh -c stty sane cooked < /dev/tty'
1534 private void sttyCooked() {
1539 * Call 'stty' to set raw mode.
1541 * <p>Actually executes '/bin/sh -c stty -ignbrk -brkint -parmrk -istrip
1542 * -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten
1543 * -parenb cs8 min 1 < /dev/tty'
1545 private void sttyRaw() {
1550 * Call 'stty' to set raw or cooked mode.
1552 * @param mode if true, set raw mode, otherwise set cooked mode
1554 private void doStty(final boolean mode
) {
1555 String
[] cmdRaw
= {
1556 "/bin/sh", "-c", "stty -ignbrk -brkint -parmrk -istrip -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten -parenb cs8 min 1 < /dev/tty"
1558 String
[] cmdCooked
= {
1559 "/bin/sh", "-c", "stty sane cooked < /dev/tty"
1564 process
= Runtime
.getRuntime().exec(cmdRaw
);
1566 process
= Runtime
.getRuntime().exec(cmdCooked
);
1568 BufferedReader in
= new BufferedReader(new InputStreamReader(process
.getInputStream(), "UTF-8"));
1569 String line
= in
.readLine();
1570 if ((line
!= null) && (line
.length() > 0)) {
1571 System
.err
.println("WEIRD?! Normal output from stty: " + line
);
1574 BufferedReader err
= new BufferedReader(new InputStreamReader(process
.getErrorStream(), "UTF-8"));
1575 line
= err
.readLine();
1576 if ((line
!= null) && (line
.length() > 0)) {
1577 System
.err
.println("Error output from stty: " + line
);
1582 } catch (InterruptedException e
) {
1583 if (debugToStderr
) {
1584 e
.printStackTrace();
1588 int rc
= process
.exitValue();
1590 System
.err
.println("stty returned error code: " + rc
);
1592 } catch (IOException e
) {
1593 e
.printStackTrace();
1600 public void flush() {
1605 * Perform a somewhat-optimal rendering of a line.
1607 * @param y row coordinate. 0 is the top-most row.
1608 * @param sb StringBuilder to write escape sequences to
1609 * @param lastAttr cell attributes from the last call to flushLine
1611 private void flushLine(final int y
, final StringBuilder sb
,
1612 CellAttributes lastAttr
) {
1616 for (int x
= 0; x
< width
; x
++) {
1617 Cell lCell
= logical
[x
][y
];
1618 if (!lCell
.isBlank()) {
1622 // Push textEnd to first column beyond the text area
1626 // reallyCleared = true;
1628 boolean hasImage
= false;
1630 for (int x
= 0; x
< width
; x
++) {
1631 Cell lCell
= logical
[x
][y
];
1632 Cell pCell
= physical
[x
][y
];
1634 if (!lCell
.equals(pCell
) || reallyCleared
) {
1636 if (debugToStderr
) {
1637 System
.err
.printf("\n--\n");
1638 System
.err
.printf(" Y: %d X: %d\n", y
, x
);
1639 System
.err
.printf(" lCell: %s\n", lCell
);
1640 System
.err
.printf(" pCell: %s\n", pCell
);
1641 System
.err
.printf(" ==== \n");
1644 if (lastAttr
== null) {
1645 lastAttr
= new CellAttributes();
1646 sb
.append(normal());
1650 if ((lastX
!= (x
- 1)) || (lastX
== -1)) {
1651 // Advancing at least one cell, or the first gotoXY
1652 sb
.append(gotoXY(x
, y
));
1655 assert (lastAttr
!= null);
1657 if ((x
== textEnd
) && (textEnd
< width
- 1)) {
1658 assert (lCell
.isBlank());
1660 for (int i
= x
; i
< width
; i
++) {
1661 assert (logical
[i
][y
].isBlank());
1662 // Physical is always updated
1663 physical
[i
][y
].reset();
1666 // Clear remaining line
1667 sb
.append(clearRemainingLine());
1672 // Image cell: bypass the rest of the loop, it is not
1674 if (lCell
.isImage()) {
1677 // Save the last rendered cell
1680 // Physical is always updated
1681 physical
[x
][y
].setTo(lCell
);
1685 assert (!lCell
.isImage());
1688 sb
.append(gotoXY(x
, y
));
1691 // Now emit only the modified attributes
1692 if ((lCell
.getForeColor() != lastAttr
.getForeColor())
1693 && (lCell
.getBackColor() != lastAttr
.getBackColor())
1695 && (lCell
.isBold() == lastAttr
.isBold())
1696 && (lCell
.isReverse() == lastAttr
.isReverse())
1697 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1698 && (lCell
.isBlink() == lastAttr
.isBlink())
1700 // Both colors changed, attributes the same
1701 sb
.append(color(lCell
.isBold(),
1702 lCell
.getForeColor(), lCell
.getBackColor()));
1704 if (debugToStderr
) {
1705 System
.err
.printf("1 Change only fore/back colors\n");
1708 } else if (lCell
.isRGB()
1709 && (lCell
.getForeColorRGB() != lastAttr
.getForeColorRGB())
1710 && (lCell
.getBackColorRGB() != lastAttr
.getBackColorRGB())
1711 && (lCell
.isBold() == lastAttr
.isBold())
1712 && (lCell
.isReverse() == lastAttr
.isReverse())
1713 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1714 && (lCell
.isBlink() == lastAttr
.isBlink())
1716 // Both colors changed, attributes the same
1717 sb
.append(colorRGB(lCell
.getForeColorRGB(),
1718 lCell
.getBackColorRGB()));
1720 if (debugToStderr
) {
1721 System
.err
.printf("1 Change only fore/back colors (RGB)\n");
1723 } else if ((lCell
.getForeColor() != lastAttr
.getForeColor())
1724 && (lCell
.getBackColor() != lastAttr
.getBackColor())
1726 && (lCell
.isBold() != lastAttr
.isBold())
1727 && (lCell
.isReverse() != lastAttr
.isReverse())
1728 && (lCell
.isUnderline() != lastAttr
.isUnderline())
1729 && (lCell
.isBlink() != lastAttr
.isBlink())
1731 // Everything is different
1732 sb
.append(color(lCell
.getForeColor(),
1733 lCell
.getBackColor(),
1734 lCell
.isBold(), lCell
.isReverse(),
1736 lCell
.isUnderline()));
1738 if (debugToStderr
) {
1739 System
.err
.printf("2 Set all attributes\n");
1741 } else if ((lCell
.getForeColor() != lastAttr
.getForeColor())
1742 && (lCell
.getBackColor() == lastAttr
.getBackColor())
1744 && (lCell
.isBold() == lastAttr
.isBold())
1745 && (lCell
.isReverse() == lastAttr
.isReverse())
1746 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1747 && (lCell
.isBlink() == lastAttr
.isBlink())
1750 // Attributes same, foreColor different
1751 sb
.append(color(lCell
.isBold(),
1752 lCell
.getForeColor(), true));
1754 if (debugToStderr
) {
1755 System
.err
.printf("3 Change foreColor\n");
1757 } else if (lCell
.isRGB()
1758 && (lCell
.getForeColorRGB() != lastAttr
.getForeColorRGB())
1759 && (lCell
.getBackColorRGB() == lastAttr
.getBackColorRGB())
1760 && (lCell
.getForeColorRGB() >= 0)
1761 && (lCell
.getBackColorRGB() >= 0)
1762 && (lCell
.isBold() == lastAttr
.isBold())
1763 && (lCell
.isReverse() == lastAttr
.isReverse())
1764 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1765 && (lCell
.isBlink() == lastAttr
.isBlink())
1767 // Attributes same, foreColor different
1768 sb
.append(colorRGB(lCell
.getForeColorRGB(), true));
1770 if (debugToStderr
) {
1771 System
.err
.printf("3 Change foreColor (RGB)\n");
1773 } else if ((lCell
.getForeColor() == lastAttr
.getForeColor())
1774 && (lCell
.getBackColor() != lastAttr
.getBackColor())
1776 && (lCell
.isBold() == lastAttr
.isBold())
1777 && (lCell
.isReverse() == lastAttr
.isReverse())
1778 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1779 && (lCell
.isBlink() == lastAttr
.isBlink())
1781 // Attributes same, backColor different
1782 sb
.append(color(lCell
.isBold(),
1783 lCell
.getBackColor(), false));
1785 if (debugToStderr
) {
1786 System
.err
.printf("4 Change backColor\n");
1788 } else if (lCell
.isRGB()
1789 && (lCell
.getForeColorRGB() == lastAttr
.getForeColorRGB())
1790 && (lCell
.getBackColorRGB() != lastAttr
.getBackColorRGB())
1791 && (lCell
.isBold() == lastAttr
.isBold())
1792 && (lCell
.isReverse() == lastAttr
.isReverse())
1793 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1794 && (lCell
.isBlink() == lastAttr
.isBlink())
1796 // Attributes same, foreColor different
1797 sb
.append(colorRGB(lCell
.getBackColorRGB(), false));
1799 if (debugToStderr
) {
1800 System
.err
.printf("4 Change backColor (RGB)\n");
1802 } else if ((lCell
.getForeColor() == lastAttr
.getForeColor())
1803 && (lCell
.getBackColor() == lastAttr
.getBackColor())
1804 && (lCell
.getForeColorRGB() == lastAttr
.getForeColorRGB())
1805 && (lCell
.getBackColorRGB() == lastAttr
.getBackColorRGB())
1806 && (lCell
.isBold() == lastAttr
.isBold())
1807 && (lCell
.isReverse() == lastAttr
.isReverse())
1808 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1809 && (lCell
.isBlink() == lastAttr
.isBlink())
1812 // All attributes the same, just print the char
1815 if (debugToStderr
) {
1816 System
.err
.printf("5 Only emit character\n");
1819 // Just reset everything again
1820 if (!lCell
.isRGB()) {
1821 sb
.append(color(lCell
.getForeColor(),
1822 lCell
.getBackColor(),
1826 lCell
.isUnderline()));
1828 if (debugToStderr
) {
1829 System
.err
.printf("6 Change all attributes\n");
1832 sb
.append(colorRGB(lCell
.getForeColorRGB(),
1833 lCell
.getBackColorRGB(),
1837 lCell
.isUnderline()));
1838 if (debugToStderr
) {
1839 System
.err
.printf("6 Change all attributes (RGB)\n");
1844 // Emit the character
1845 sb
.append(lCell
.getChar());
1847 // Save the last rendered cell
1849 lastAttr
.setTo(lCell
);
1851 // Physical is always updated
1852 physical
[x
][y
].setTo(lCell
);
1854 } // if (!lCell.equals(pCell) || (reallyCleared == true))
1856 } // for (int x = 0; x < width; x++)
1860 * Render the screen to a string that can be emitted to something that
1861 * knows how to process ECMA-48/ANSI X3.64 escape sequences.
1863 * @param sb StringBuilder to write escape sequences to
1864 * @return escape sequences string that provides the updates to the
1867 private String
flushString(final StringBuilder sb
) {
1868 CellAttributes attr
= null;
1870 if (reallyCleared
) {
1871 attr
= new CellAttributes();
1872 sb
.append(clearAll());
1876 * For sixel support, draw all of the sixel output first, and then
1877 * draw everything else afterwards. This works OK, but performance
1878 * is still a drag on larger pictures.
1880 for (int y
= 0; y
< height
; y
++) {
1881 for (int x
= 0; x
< width
; x
++) {
1882 // If physical had non-image data that is now image data, the
1883 // entire row must be redrawn.
1884 Cell lCell
= logical
[x
][y
];
1885 Cell pCell
= physical
[x
][y
];
1886 if (lCell
.isImage() && !pCell
.isImage()) {
1892 for (int y
= 0; y
< height
; y
++) {
1893 for (int x
= 0; x
< width
; x
++) {
1894 Cell lCell
= logical
[x
][y
];
1895 Cell pCell
= physical
[x
][y
];
1897 if (!lCell
.isImage()) {
1903 while ((right
< width
)
1904 && (logical
[right
][y
].isImage())
1905 && (!logical
[right
][y
].equals(physical
[right
][y
])
1910 ArrayList
<Cell
> cellsToDraw
= new ArrayList
<Cell
>();
1911 for (int i
= 0; i
< (right
- x
); i
++) {
1912 assert (logical
[x
+ i
][y
].isImage());
1913 cellsToDraw
.add(logical
[x
+ i
][y
]);
1915 // Physical is always updated.
1916 physical
[x
+ i
][y
].setTo(lCell
);
1918 if (cellsToDraw
.size() > 0) {
1919 sb
.append(toSixel(x
, y
, cellsToDraw
));
1926 // Draw the text part now.
1927 for (int y
= 0; y
< height
; y
++) {
1928 flushLine(y
, sb
, attr
);
1931 reallyCleared
= false;
1933 String result
= sb
.toString();
1934 if (debugToStderr
) {
1935 System
.err
.printf("flushString(): %s\n", result
);
1941 * Reset keyboard/mouse input parser.
1943 private void resetParser() {
1944 state
= ParseState
.GROUND
;
1945 params
= new ArrayList
<String
>();
1951 * Produce a control character or one of the special ones (ENTER, TAB,
1954 * @param ch Unicode code point
1955 * @param alt if true, set alt on the TKeypress
1956 * @return one TKeypress event, either a control character (e.g. isKey ==
1957 * false, ch == 'A', ctrl == true), or a special key (e.g. isKey == true,
1960 private TKeypressEvent
controlChar(final char ch
, final boolean alt
) {
1961 // System.err.printf("controlChar: %02x\n", ch);
1965 // Carriage return --> ENTER
1966 return new TKeypressEvent(kbEnter
, alt
, false, false);
1968 // Linefeed --> ENTER
1969 return new TKeypressEvent(kbEnter
, alt
, false, false);
1972 return new TKeypressEvent(kbEsc
, alt
, false, false);
1975 return new TKeypressEvent(kbTab
, alt
, false, false);
1977 // Make all other control characters come back as the alphabetic
1978 // character with the ctrl field set. So SOH would be 'A' +
1980 return new TKeypressEvent(false, 0, (char)(ch
+ 0x40),
1986 * Produce special key from CSI Pn ; Pm ; ... ~
1988 * @return one KEYPRESS event representing a special key
1990 private TInputEvent
csiFnKey() {
1992 if (params
.size() > 0) {
1993 key
= Integer
.parseInt(params
.get(0));
1995 boolean alt
= false;
1996 boolean ctrl
= false;
1997 boolean shift
= false;
1998 if (params
.size() > 1) {
1999 shift
= csiIsShift(params
.get(1));
2000 alt
= csiIsAlt(params
.get(1));
2001 ctrl
= csiIsCtrl(params
.get(1));
2006 return new TKeypressEvent(kbHome
, alt
, ctrl
, shift
);
2008 return new TKeypressEvent(kbIns
, alt
, ctrl
, shift
);
2010 return new TKeypressEvent(kbDel
, alt
, ctrl
, shift
);
2012 return new TKeypressEvent(kbEnd
, alt
, ctrl
, shift
);
2014 return new TKeypressEvent(kbPgUp
, alt
, ctrl
, shift
);
2016 return new TKeypressEvent(kbPgDn
, alt
, ctrl
, shift
);
2018 return new TKeypressEvent(kbF5
, alt
, ctrl
, shift
);
2020 return new TKeypressEvent(kbF6
, alt
, ctrl
, shift
);
2022 return new TKeypressEvent(kbF7
, alt
, ctrl
, shift
);
2024 return new TKeypressEvent(kbF8
, alt
, ctrl
, shift
);
2026 return new TKeypressEvent(kbF9
, alt
, ctrl
, shift
);
2028 return new TKeypressEvent(kbF10
, alt
, ctrl
, shift
);
2030 return new TKeypressEvent(kbF11
, alt
, ctrl
, shift
);
2032 return new TKeypressEvent(kbF12
, alt
, ctrl
, shift
);
2040 * Produce mouse events based on "Any event tracking" and UTF-8
2042 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
2044 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
2046 private TInputEvent
parseMouse() {
2047 int buttons
= params
.get(0).charAt(0) - 32;
2048 int x
= params
.get(0).charAt(1) - 32 - 1;
2049 int y
= params
.get(0).charAt(2) - 32 - 1;
2051 // Clamp X and Y to the physical screen coordinates.
2052 if (x
>= windowResize
.getWidth()) {
2053 x
= windowResize
.getWidth() - 1;
2055 if (y
>= windowResize
.getHeight()) {
2056 y
= windowResize
.getHeight() - 1;
2059 TMouseEvent
.Type eventType
= TMouseEvent
.Type
.MOUSE_DOWN
;
2060 boolean eventMouse1
= false;
2061 boolean eventMouse2
= false;
2062 boolean eventMouse3
= false;
2063 boolean eventMouseWheelUp
= false;
2064 boolean eventMouseWheelDown
= false;
2066 // System.err.printf("buttons: %04x\r\n", buttons);
2083 if (!mouse1
&& !mouse2
&& !mouse3
) {
2084 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2086 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
2103 // Dragging with mouse1 down
2106 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2110 // Dragging with mouse2 down
2113 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2117 // Dragging with mouse3 down
2120 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2124 // Dragging with mouse2 down after wheelUp
2127 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2131 // Dragging with mouse2 down after wheelDown
2134 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2138 eventMouseWheelUp
= true;
2142 eventMouseWheelDown
= true;
2146 // Unknown, just make it motion
2147 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2150 return new TMouseEvent(eventType
, x
, y
, x
, y
,
2151 eventMouse1
, eventMouse2
, eventMouse3
,
2152 eventMouseWheelUp
, eventMouseWheelDown
);
2156 * Produce mouse events based on "Any event tracking" and SGR
2158 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
2160 * @param release if true, this was a release ('m')
2161 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
2163 private TInputEvent
parseMouseSGR(final boolean release
) {
2164 // SGR extended coordinates - mode 1006
2165 if (params
.size() < 3) {
2166 // Invalid position, bail out.
2169 int buttons
= Integer
.parseInt(params
.get(0));
2170 int x
= Integer
.parseInt(params
.get(1)) - 1;
2171 int y
= Integer
.parseInt(params
.get(2)) - 1;
2173 // Clamp X and Y to the physical screen coordinates.
2174 if (x
>= windowResize
.getWidth()) {
2175 x
= windowResize
.getWidth() - 1;
2177 if (y
>= windowResize
.getHeight()) {
2178 y
= windowResize
.getHeight() - 1;
2181 TMouseEvent
.Type eventType
= TMouseEvent
.Type
.MOUSE_DOWN
;
2182 boolean eventMouse1
= false;
2183 boolean eventMouse2
= false;
2184 boolean eventMouse3
= false;
2185 boolean eventMouseWheelUp
= false;
2186 boolean eventMouseWheelDown
= false;
2189 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
2203 // Motion only, no buttons down
2204 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2208 // Dragging with mouse1 down
2210 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2214 // Dragging with mouse2 down
2216 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2220 // Dragging with mouse3 down
2222 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2226 // Dragging with mouse2 down after wheelUp
2228 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2232 // Dragging with mouse2 down after wheelDown
2234 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2238 eventMouseWheelUp
= true;
2242 eventMouseWheelDown
= true;
2246 // Unknown, bail out
2249 return new TMouseEvent(eventType
, x
, y
, x
, y
,
2250 eventMouse1
, eventMouse2
, eventMouse3
,
2251 eventMouseWheelUp
, eventMouseWheelDown
);
2255 * Return any events in the IO queue due to timeout.
2257 * @param queue list to append new events to
2259 private void getIdleEvents(final List
<TInputEvent
> queue
) {
2260 long nowTime
= System
.currentTimeMillis();
2262 // Check for new window size
2263 long windowSizeDelay
= nowTime
- windowSizeTime
;
2264 if (windowSizeDelay
> 1000) {
2265 int oldTextWidth
= getTextWidth();
2266 int oldTextHeight
= getTextHeight();
2268 sessionInfo
.queryWindowSize();
2269 int newWidth
= sessionInfo
.getWindowWidth();
2270 int newHeight
= sessionInfo
.getWindowHeight();
2272 if ((newWidth
!= windowResize
.getWidth())
2273 || (newHeight
!= windowResize
.getHeight())
2276 // Request xterm report window dimensions in pixels again.
2277 // Between now and then, ensure that the reported text cell
2278 // size is the same by setting widthPixels and heightPixels
2279 // to match the new dimensions.
2280 widthPixels
= oldTextWidth
* newWidth
;
2281 heightPixels
= oldTextHeight
* newHeight
;
2283 if (debugToStderr
) {
2284 System
.err
.println("Screen size changed, old size " +
2286 System
.err
.println(" new size " +
2287 newWidth
+ " x " + newHeight
);
2288 System
.err
.println(" old pixels " +
2289 oldTextWidth
+ " x " + oldTextHeight
);
2290 System
.err
.println(" new pixels " +
2291 getTextWidth() + " x " + getTextHeight());
2294 this.output
.printf("%s", xtermReportWindowPixelDimensions());
2295 this.output
.flush();
2297 TResizeEvent event
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
2298 newWidth
, newHeight
);
2299 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
2300 newWidth
, newHeight
);
2303 windowSizeTime
= nowTime
;
2306 // ESCDELAY type timeout
2307 if (state
== ParseState
.ESCAPE
) {
2308 long escDelay
= nowTime
- escapeTime
;
2309 if (escDelay
> 100) {
2310 // After 0.1 seconds, assume a true escape character
2311 queue
.add(controlChar((char)0x1B, false));
2318 * Returns true if the CSI parameter for a keyboard command means that
2321 private boolean csiIsShift(final String x
) {
2333 * Returns true if the CSI parameter for a keyboard command means that
2336 private boolean csiIsAlt(final String x
) {
2348 * Returns true if the CSI parameter for a keyboard command means that
2351 private boolean csiIsCtrl(final String x
) {
2363 * Parses the next character of input to see if an InputEvent is
2366 * @param events list to append new events to
2367 * @param ch Unicode code point
2369 private void processChar(final List
<TInputEvent
> events
, final char ch
) {
2371 // ESCDELAY type timeout
2372 long nowTime
= System
.currentTimeMillis();
2373 if (state
== ParseState
.ESCAPE
) {
2374 long escDelay
= nowTime
- escapeTime
;
2375 if (escDelay
> 250) {
2376 // After 0.25 seconds, assume a true escape character
2377 events
.add(controlChar((char)0x1B, false));
2383 boolean ctrl
= false;
2384 boolean alt
= false;
2385 boolean shift
= false;
2387 // System.err.printf("state: %s ch %c\r\n", state, ch);
2393 state
= ParseState
.ESCAPE
;
2394 escapeTime
= nowTime
;
2399 // Control character
2400 events
.add(controlChar(ch
, false));
2407 events
.add(new TKeypressEvent(false, 0, ch
,
2408 false, false, false));
2417 // ALT-Control character
2418 events
.add(controlChar(ch
, true));
2424 // This will be one of the function keys
2425 state
= ParseState
.ESCAPE_INTERMEDIATE
;
2429 // '[' goes to CSI_ENTRY
2431 state
= ParseState
.CSI_ENTRY
;
2435 // Everything else is assumed to be Alt-keystroke
2436 if ((ch
>= 'A') && (ch
<= 'Z')) {
2440 events
.add(new TKeypressEvent(false, 0, ch
, alt
, ctrl
, shift
));
2444 case ESCAPE_INTERMEDIATE
:
2445 if ((ch
>= 'P') && (ch
<= 'S')) {
2449 events
.add(new TKeypressEvent(kbF1
));
2452 events
.add(new TKeypressEvent(kbF2
));
2455 events
.add(new TKeypressEvent(kbF3
));
2458 events
.add(new TKeypressEvent(kbF4
));
2467 // Unknown keystroke, ignore
2472 // Numbers - parameter values
2473 if ((ch
>= '0') && (ch
<= '9')) {
2474 params
.set(params
.size() - 1,
2475 params
.get(params
.size() - 1) + ch
);
2476 state
= ParseState
.CSI_PARAM
;
2479 // Parameter separator
2485 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
2489 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
2494 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
2499 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
2504 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
2509 events
.add(new TKeypressEvent(kbHome
));
2514 events
.add(new TKeypressEvent(kbEnd
));
2518 // CBT - Cursor backward X tab stops (default 1)
2519 events
.add(new TKeypressEvent(kbBackTab
));
2524 state
= ParseState
.MOUSE
;
2527 // Mouse position, SGR (1006) coordinates
2528 state
= ParseState
.MOUSE_SGR
;
2535 // Unknown keystroke, ignore
2540 // Numbers - parameter values
2541 if ((ch
>= '0') && (ch
<= '9')) {
2542 params
.set(params
.size() - 1,
2543 params
.get(params
.size() - 1) + ch
);
2546 // Parameter separator
2554 // Generate a mouse press event
2555 TInputEvent event
= parseMouseSGR(false);
2556 if (event
!= null) {
2562 // Generate a mouse release event
2563 event
= parseMouseSGR(true);
2564 if (event
!= null) {
2573 // Unknown keystroke, ignore
2578 // Numbers - parameter values
2579 if ((ch
>= '0') && (ch
<= '9')) {
2580 params
.set(params
.size() - 1,
2581 params
.get(params
.size() - 1) + ch
);
2582 state
= ParseState
.CSI_PARAM
;
2585 // Parameter separator
2592 events
.add(csiFnKey());
2597 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
2601 if (params
.size() > 1) {
2602 shift
= csiIsShift(params
.get(1));
2603 alt
= csiIsAlt(params
.get(1));
2604 ctrl
= csiIsCtrl(params
.get(1));
2606 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
2611 if (params
.size() > 1) {
2612 shift
= csiIsShift(params
.get(1));
2613 alt
= csiIsAlt(params
.get(1));
2614 ctrl
= csiIsCtrl(params
.get(1));
2616 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
2621 if (params
.size() > 1) {
2622 shift
= csiIsShift(params
.get(1));
2623 alt
= csiIsAlt(params
.get(1));
2624 ctrl
= csiIsCtrl(params
.get(1));
2626 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
2631 if (params
.size() > 1) {
2632 shift
= csiIsShift(params
.get(1));
2633 alt
= csiIsAlt(params
.get(1));
2634 ctrl
= csiIsCtrl(params
.get(1));
2636 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
2641 if (params
.size() > 1) {
2642 shift
= csiIsShift(params
.get(1));
2643 alt
= csiIsAlt(params
.get(1));
2644 ctrl
= csiIsCtrl(params
.get(1));
2646 events
.add(new TKeypressEvent(kbHome
, alt
, ctrl
, shift
));
2651 if (params
.size() > 1) {
2652 shift
= csiIsShift(params
.get(1));
2653 alt
= csiIsAlt(params
.get(1));
2654 ctrl
= csiIsCtrl(params
.get(1));
2656 events
.add(new TKeypressEvent(kbEnd
, alt
, ctrl
, shift
));
2661 if ((params
.size() > 2) && (params
.get(0).equals("4"))) {
2662 if (debugToStderr
) {
2663 System
.err
.printf("windowOp pixels: " +
2664 "height %s width %s\n",
2665 params
.get(1), params
.get(2));
2668 widthPixels
= Integer
.parseInt(params
.get(2));
2669 heightPixels
= Integer
.parseInt(params
.get(1));
2670 } catch (NumberFormatException e
) {
2671 if (debugToStderr
) {
2672 e
.printStackTrace();
2675 if (widthPixels
<= 0) {
2678 if (heightPixels
<= 0) {
2689 // Unknown keystroke, ignore
2694 params
.set(0, params
.get(params
.size() - 1) + ch
);
2695 if (params
.get(0).length() == 3) {
2696 // We have enough to generate a mouse event
2697 events
.add(parseMouse());
2706 // This "should" be impossible to reach
2711 * Request (u)xterm to report the current window size dimensions.
2713 * @return the string to emit to xterm
2715 private String
xtermReportWindowPixelDimensions() {
2720 * Tell (u)xterm that we want alt- keystrokes to send escape + character
2721 * rather than set the 8th bit. Anyone who wants UTF8 should want this
2724 * @param on if true, enable metaSendsEscape
2725 * @return the string to emit to xterm
2727 private String
xtermMetaSendsEscape(final boolean on
) {
2729 return "\033[?1036h\033[?1034l";
2731 return "\033[?1036l";
2735 * Create an xterm OSC sequence to change the window title.
2737 * @param title the new title
2738 * @return the string to emit to xterm
2740 private String
getSetTitleString(final String title
) {
2741 return "\033]2;" + title
+ "\007";
2744 // ------------------------------------------------------------------------
2745 // Sixel output support ---------------------------------------------------
2746 // ------------------------------------------------------------------------
2749 * Start a sixel string for display one row's worth of bitmap data.
2751 * @param x column coordinate. 0 is the left-most column.
2752 * @param y row coordinate. 0 is the top-most row.
2753 * @return the string to emit to an ANSI / ECMA-style terminal
2755 private String
startSixel(final int x
, final int y
) {
2756 StringBuilder sb
= new StringBuilder();
2758 assert (sixel
== true);
2761 sb
.append(gotoXY(x
, y
));
2764 sb
.append("\033Pq");
2766 if (palette
== null) {
2767 palette
= new SixelPalette();
2770 return sb
.toString();
2774 * End a sixel string for display one row's worth of bitmap data.
2776 * @return the string to emit to an ANSI / ECMA-style terminal
2778 private String
endSixel() {
2779 assert (sixel
== true);
2786 * Create a sixel string representing a row of several cells containing
2789 * @param x column coordinate. 0 is the left-most column.
2790 * @param y row coordinate. 0 is the top-most row.
2791 * @param cells the cells containing the bitmap data
2792 * @return the string to emit to an ANSI / ECMA-style terminal
2794 private String
toSixel(final int x
, final int y
,
2795 final ArrayList
<Cell
> cells
) {
2797 StringBuilder sb
= new StringBuilder();
2799 assert (cells
!= null);
2800 assert (cells
.size() > 0);
2801 assert (cells
.get(0).getImage() != null);
2803 if (sixel
== false) {
2804 sb
.append(normal());
2805 sb
.append(gotoXY(x
, y
));
2806 for (int i
= 0; i
< cells
.size(); i
++) {
2809 return sb
.toString();
2812 if (sixelCache
== null) {
2813 sixelCache
= new SixelCache(height
* 10);
2816 // Save and get rows to/from the cache that do NOT have inverted
2818 boolean saveInCache
= true;
2819 for (Cell cell
: cells
) {
2820 if (cell
.isInvertedImage()) {
2821 saveInCache
= false;
2825 String cachedResult
= sixelCache
.get(cells
);
2826 if (cachedResult
!= null) {
2827 // System.err.println("CACHE HIT");
2828 sb
.append(startSixel(x
, y
));
2829 sb
.append(cachedResult
);
2830 sb
.append(endSixel());
2831 return sb
.toString();
2833 // System.err.println("CACHE MISS");
2836 int imageWidth
= cells
.get(0).getImage().getWidth();
2837 int imageHeight
= cells
.get(0).getImage().getHeight();
2839 // cells.get(x).getImage() has a dithered bitmap containing indexes
2840 // into the color palette. Piece these together into one larger
2841 // image for final rendering.
2843 int fullWidth
= cells
.size() * getTextWidth();
2844 int fullHeight
= getTextHeight();
2845 for (int i
= 0; i
< cells
.size(); i
++) {
2846 totalWidth
+= cells
.get(i
).getImage().getWidth();
2849 BufferedImage image
= new BufferedImage(fullWidth
,
2850 fullHeight
, BufferedImage
.TYPE_INT_ARGB
);
2853 for (int i
= 0; i
< cells
.size() - 1; i
++) {
2854 if (cells
.get(i
).isInvertedImage()) {
2855 rgbArray
= new int[imageWidth
* imageHeight
];
2856 for (int j
= 0; j
< rgbArray
.length
; j
++) {
2857 rgbArray
[j
] = 0xFFFFFF;
2860 rgbArray
= cells
.get(i
).getImage().getRGB(0, 0,
2861 imageWidth
, imageHeight
, null, 0, imageWidth
);
2865 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
2866 i * imageWidth, 0, imageWidth, imageHeight,
2868 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
2869 fullWidth, fullHeight, cells.size(), getTextWidth());
2872 image
.setRGB(i
* imageWidth
, 0, imageWidth
, imageHeight
,
2873 rgbArray
, 0, imageWidth
);
2874 if (imageHeight
< fullHeight
) {
2875 int backgroundColor
= cells
.get(i
).getBackground().getRGB();
2876 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
2877 for (int imageY
= imageHeight
; imageY
< fullHeight
;
2880 image
.setRGB(imageX
, imageY
, backgroundColor
);
2885 totalWidth
-= ((cells
.size() - 1) * imageWidth
);
2886 if (cells
.get(cells
.size() - 1).isInvertedImage()) {
2887 rgbArray
= new int[totalWidth
* imageHeight
];
2888 for (int j
= 0; j
< rgbArray
.length
; j
++) {
2889 rgbArray
[j
] = 0xFFFFFF;
2892 rgbArray
= cells
.get(cells
.size() - 1).getImage().getRGB(0, 0,
2893 totalWidth
, imageHeight
, null, 0, totalWidth
);
2895 image
.setRGB((cells
.size() - 1) * imageWidth
, 0, totalWidth
,
2896 imageHeight
, rgbArray
, 0, totalWidth
);
2898 if (totalWidth
< getTextWidth()) {
2899 int backgroundColor
= cells
.get(cells
.size() - 1).getBackground().getRGB();
2901 for (int imageX
= image
.getWidth() - totalWidth
;
2902 imageX
< image
.getWidth(); imageX
++) {
2904 for (int imageY
= 0; imageY
< fullHeight
; imageY
++) {
2905 image
.setRGB(imageX
, imageY
, backgroundColor
);
2910 // Dither the image. It is ok to lose the original here.
2911 if (palette
== null) {
2912 palette
= new SixelPalette();
2914 image
= palette
.ditherImage(image
);
2916 // Emit the palette, but only for the colors actually used by these
2918 boolean [] usedColors
= new boolean[MAX_COLOR_REGISTERS
];
2919 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
2920 for (int imageY
= 0; imageY
< image
.getHeight(); imageY
++) {
2921 usedColors
[image
.getRGB(imageX
, imageY
)] = true;
2924 palette
.emitPalette(sb
, usedColors
);
2926 // Render the entire row of cells.
2927 for (int currentRow
= 0; currentRow
< fullHeight
; currentRow
+= 6) {
2928 int [][] sixels
= new int[image
.getWidth()][6];
2930 // See which colors are actually used in this band of sixels.
2931 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
2932 for (int imageY
= 0;
2933 (imageY
< 6) && (imageY
+ currentRow
< fullHeight
);
2936 int colorIdx
= image
.getRGB(imageX
, imageY
+ currentRow
);
2937 assert (colorIdx
>= 0);
2938 assert (colorIdx
< MAX_COLOR_REGISTERS
);
2940 sixels
[imageX
][imageY
] = colorIdx
;
2944 for (int i
= 0; i
< MAX_COLOR_REGISTERS
; i
++) {
2945 boolean isUsed
= false;
2946 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
2947 for (int j
= 0; j
< 6; j
++) {
2948 if (sixels
[imageX
][j
] == i
) {
2953 if (isUsed
== false) {
2957 // Set to the beginning of scan line for the next set of
2958 // colored pixels, and select the color.
2959 sb
.append(String
.format("$#%d", i
));
2962 int oldDataCount
= 0;
2963 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
2965 // Add up all the pixels that match this color.
2968 (j
< 6) && (currentRow
+ j
< fullHeight
);
2971 if (sixels
[imageX
][j
] == i
) {
2998 if (data
== oldData
) {
3001 if (oldDataCount
== 1) {
3002 sb
.append((char) oldData
);
3003 } else if (oldDataCount
> 1) {
3004 sb
.append(String
.format("!%d", oldDataCount
));
3005 sb
.append((char) oldData
);
3011 } // for (int imageX = 0; imageX < image.getWidth(); imageX++)
3013 // Emit the last sequence.
3014 if (oldDataCount
== 1) {
3015 sb
.append((char) oldData
);
3016 } else if (oldDataCount
> 1) {
3017 sb
.append(String
.format("!%d", oldDataCount
));
3018 sb
.append((char) oldData
);
3021 } // for (int i = 0; i < MAX_COLOR_REGISTERS; i++)
3023 // Advance to the next scan line.
3026 } // for (int currentRow = 0; currentRow < imageHeight; currentRow += 6)
3028 // Kill the very last "-", because it is unnecessary.
3029 sb
.deleteCharAt(sb
.length() - 1);
3032 // This row is OK to save into the cache.
3033 sixelCache
.put(cells
, sb
.toString());
3036 return (startSixel(x
, y
) + sb
.toString() + endSixel());
3040 * Get the sixel support flag.
3042 * @return true if this terminal is emitting sixel
3044 public boolean hasSixel() {
3048 // ------------------------------------------------------------------------
3049 // End sixel output support -----------------------------------------------
3050 // ------------------------------------------------------------------------
3053 * Create a SGR parameter sequence for a single color change.
3055 * @param bold if true, set bold
3056 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
3057 * @param foreground if true, this is a foreground color
3058 * @return the string to emit to an ANSI / ECMA-style terminal,
3061 private String
color(final boolean bold
, final Color color
,
3062 final boolean foreground
) {
3063 return color(color
, foreground
, true) +
3064 rgbColor(bold
, color
, foreground
);
3068 * Create a T.416 RGB parameter sequence for a single color change.
3070 * @param colorRGB a 24-bit RGB value for foreground color
3071 * @param foreground if true, this is a foreground color
3072 * @return the string to emit to an ANSI / ECMA-style terminal,
3075 private String
colorRGB(final int colorRGB
, final boolean foreground
) {
3077 int colorRed
= (colorRGB
>>> 16) & 0xFF;
3078 int colorGreen
= (colorRGB
>>> 8) & 0xFF;
3079 int colorBlue
= colorRGB
& 0xFF;
3081 StringBuilder sb
= new StringBuilder();
3083 sb
.append("\033[38;2;");
3085 sb
.append("\033[48;2;");
3087 sb
.append(String
.format("%d;%d;%dm", colorRed
, colorGreen
, colorBlue
));
3088 return sb
.toString();
3092 * Create a T.416 RGB parameter sequence for both foreground and
3093 * background color change.
3095 * @param foreColorRGB a 24-bit RGB value for foreground color
3096 * @param backColorRGB a 24-bit RGB value for foreground color
3097 * @return the string to emit to an ANSI / ECMA-style terminal,
3100 private String
colorRGB(final int foreColorRGB
, final int backColorRGB
) {
3101 int foreColorRed
= (foreColorRGB
>>> 16) & 0xFF;
3102 int foreColorGreen
= (foreColorRGB
>>> 8) & 0xFF;
3103 int foreColorBlue
= foreColorRGB
& 0xFF;
3104 int backColorRed
= (backColorRGB
>>> 16) & 0xFF;
3105 int backColorGreen
= (backColorRGB
>>> 8) & 0xFF;
3106 int backColorBlue
= backColorRGB
& 0xFF;
3108 StringBuilder sb
= new StringBuilder();
3109 sb
.append(String
.format("\033[38;2;%d;%d;%dm",
3110 foreColorRed
, foreColorGreen
, foreColorBlue
));
3111 sb
.append(String
.format("\033[48;2;%d;%d;%dm",
3112 backColorRed
, backColorGreen
, backColorBlue
));
3113 return sb
.toString();
3117 * Create a T.416 RGB parameter sequence for a single color change.
3119 * @param bold if true, set bold
3120 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
3121 * @param foreground if true, this is a foreground color
3122 * @return the string to emit to an xterm terminal with RGB support,
3123 * e.g. "\033[38;2;RR;GG;BBm"
3125 private String
rgbColor(final boolean bold
, final Color color
,
3126 final boolean foreground
) {
3127 if (doRgbColor
== false) {
3130 StringBuilder sb
= new StringBuilder("\033[");
3132 // Bold implies foreground only
3134 if (color
.equals(Color
.BLACK
)) {
3135 sb
.append("84;84;84");
3136 } else if (color
.equals(Color
.RED
)) {
3137 sb
.append("252;84;84");
3138 } else if (color
.equals(Color
.GREEN
)) {
3139 sb
.append("84;252;84");
3140 } else if (color
.equals(Color
.YELLOW
)) {
3141 sb
.append("252;252;84");
3142 } else if (color
.equals(Color
.BLUE
)) {
3143 sb
.append("84;84;252");
3144 } else if (color
.equals(Color
.MAGENTA
)) {
3145 sb
.append("252;84;252");
3146 } else if (color
.equals(Color
.CYAN
)) {
3147 sb
.append("84;252;252");
3148 } else if (color
.equals(Color
.WHITE
)) {
3149 sb
.append("252;252;252");
3157 if (color
.equals(Color
.BLACK
)) {
3159 } else if (color
.equals(Color
.RED
)) {
3160 sb
.append("168;0;0");
3161 } else if (color
.equals(Color
.GREEN
)) {
3162 sb
.append("0;168;0");
3163 } else if (color
.equals(Color
.YELLOW
)) {
3164 sb
.append("168;84;0");
3165 } else if (color
.equals(Color
.BLUE
)) {
3166 sb
.append("0;0;168");
3167 } else if (color
.equals(Color
.MAGENTA
)) {
3168 sb
.append("168;0;168");
3169 } else if (color
.equals(Color
.CYAN
)) {
3170 sb
.append("0;168;168");
3171 } else if (color
.equals(Color
.WHITE
)) {
3172 sb
.append("168;168;168");
3176 return sb
.toString();
3180 * Create a T.416 RGB parameter sequence for both foreground and
3181 * background color change.
3183 * @param bold if true, set bold
3184 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3185 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3186 * @return the string to emit to an xterm terminal with RGB support,
3187 * e.g. "\033[38;2;RR;GG;BB;48;2;RR;GG;BBm"
3189 private String
rgbColor(final boolean bold
, final Color foreColor
,
3190 final Color backColor
) {
3191 if (doRgbColor
== false) {
3195 return rgbColor(bold
, foreColor
, true) +
3196 rgbColor(false, backColor
, false);
3200 * Create a SGR parameter sequence for a single color change.
3202 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
3203 * @param foreground if true, this is a foreground color
3204 * @param header if true, make the full header, otherwise just emit the
3205 * color parameter e.g. "42;"
3206 * @return the string to emit to an ANSI / ECMA-style terminal,
3209 private String
color(final Color color
, final boolean foreground
,
3210 final boolean header
) {
3212 int ecmaColor
= color
.getValue();
3214 // Convert Color.* values to SGR numerics
3222 return String
.format("\033[%dm", ecmaColor
);
3224 return String
.format("%d;", ecmaColor
);
3229 * Create a SGR parameter sequence for both foreground and background
3232 * @param bold if true, set bold
3233 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3234 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3235 * @return the string to emit to an ANSI / ECMA-style terminal,
3236 * e.g. "\033[31;42m"
3238 private String
color(final boolean bold
, final Color foreColor
,
3239 final Color backColor
) {
3240 return color(foreColor
, backColor
, true) +
3241 rgbColor(bold
, foreColor
, backColor
);
3245 * Create a SGR parameter sequence for both foreground and
3246 * background color change.
3248 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3249 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3250 * @param header if true, make the full header, otherwise just emit the
3251 * color parameter e.g. "31;42;"
3252 * @return the string to emit to an ANSI / ECMA-style terminal,
3253 * e.g. "\033[31;42m"
3255 private String
color(final Color foreColor
, final Color backColor
,
3256 final boolean header
) {
3258 int ecmaForeColor
= foreColor
.getValue();
3259 int ecmaBackColor
= backColor
.getValue();
3261 // Convert Color.* values to SGR numerics
3262 ecmaBackColor
+= 40;
3263 ecmaForeColor
+= 30;
3266 return String
.format("\033[%d;%dm", ecmaForeColor
, ecmaBackColor
);
3268 return String
.format("%d;%d;", ecmaForeColor
, ecmaBackColor
);
3273 * Create a SGR parameter sequence for foreground, background, and
3274 * several attributes. This sequence first resets all attributes to
3275 * default, then sets attributes as per the parameters.
3277 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3278 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3279 * @param bold if true, set bold
3280 * @param reverse if true, set reverse
3281 * @param blink if true, set blink
3282 * @param underline if true, set underline
3283 * @return the string to emit to an ANSI / ECMA-style terminal,
3284 * e.g. "\033[0;1;31;42m"
3286 private String
color(final Color foreColor
, final Color backColor
,
3287 final boolean bold
, final boolean reverse
, final boolean blink
,
3288 final boolean underline
) {
3290 int ecmaForeColor
= foreColor
.getValue();
3291 int ecmaBackColor
= backColor
.getValue();
3293 // Convert Color.* values to SGR numerics
3294 ecmaBackColor
+= 40;
3295 ecmaForeColor
+= 30;
3297 StringBuilder sb
= new StringBuilder();
3298 if ( bold
&& reverse
&& blink
&& !underline
) {
3299 sb
.append("\033[0;1;7;5;");
3300 } else if ( bold
&& reverse
&& !blink
&& !underline
) {
3301 sb
.append("\033[0;1;7;");
3302 } else if ( !bold
&& reverse
&& blink
&& !underline
) {
3303 sb
.append("\033[0;7;5;");
3304 } else if ( bold
&& !reverse
&& blink
&& !underline
) {
3305 sb
.append("\033[0;1;5;");
3306 } else if ( bold
&& !reverse
&& !blink
&& !underline
) {
3307 sb
.append("\033[0;1;");
3308 } else if ( !bold
&& reverse
&& !blink
&& !underline
) {
3309 sb
.append("\033[0;7;");
3310 } else if ( !bold
&& !reverse
&& blink
&& !underline
) {
3311 sb
.append("\033[0;5;");
3312 } else if ( bold
&& reverse
&& blink
&& underline
) {
3313 sb
.append("\033[0;1;7;5;4;");
3314 } else if ( bold
&& reverse
&& !blink
&& underline
) {
3315 sb
.append("\033[0;1;7;4;");
3316 } else if ( !bold
&& reverse
&& blink
&& underline
) {
3317 sb
.append("\033[0;7;5;4;");
3318 } else if ( bold
&& !reverse
&& blink
&& underline
) {
3319 sb
.append("\033[0;1;5;4;");
3320 } else if ( bold
&& !reverse
&& !blink
&& underline
) {
3321 sb
.append("\033[0;1;4;");
3322 } else if ( !bold
&& reverse
&& !blink
&& underline
) {
3323 sb
.append("\033[0;7;4;");
3324 } else if ( !bold
&& !reverse
&& blink
&& underline
) {
3325 sb
.append("\033[0;5;4;");
3326 } else if ( !bold
&& !reverse
&& !blink
&& underline
) {
3327 sb
.append("\033[0;4;");
3329 assert (!bold
&& !reverse
&& !blink
&& !underline
);
3330 sb
.append("\033[0;");
3332 sb
.append(String
.format("%d;%dm", ecmaForeColor
, ecmaBackColor
));
3333 sb
.append(rgbColor(bold
, foreColor
, backColor
));
3334 return sb
.toString();
3338 * Create a SGR parameter sequence for foreground, background, and
3339 * several attributes. This sequence first resets all attributes to
3340 * default, then sets attributes as per the parameters.
3342 * @param foreColorRGB a 24-bit RGB value for foreground color
3343 * @param backColorRGB a 24-bit RGB value for foreground color
3344 * @param bold if true, set bold
3345 * @param reverse if true, set reverse
3346 * @param blink if true, set blink
3347 * @param underline if true, set underline
3348 * @return the string to emit to an ANSI / ECMA-style terminal,
3349 * e.g. "\033[0;1;31;42m"
3351 private String
colorRGB(final int foreColorRGB
, final int backColorRGB
,
3352 final boolean bold
, final boolean reverse
, final boolean blink
,
3353 final boolean underline
) {
3355 int foreColorRed
= (foreColorRGB
>>> 16) & 0xFF;
3356 int foreColorGreen
= (foreColorRGB
>>> 8) & 0xFF;
3357 int foreColorBlue
= foreColorRGB
& 0xFF;
3358 int backColorRed
= (backColorRGB
>>> 16) & 0xFF;
3359 int backColorGreen
= (backColorRGB
>>> 8) & 0xFF;
3360 int backColorBlue
= backColorRGB
& 0xFF;
3362 StringBuilder sb
= new StringBuilder();
3363 if ( bold
&& reverse
&& blink
&& !underline
) {
3364 sb
.append("\033[0;1;7;5;");
3365 } else if ( bold
&& reverse
&& !blink
&& !underline
) {
3366 sb
.append("\033[0;1;7;");
3367 } else if ( !bold
&& reverse
&& blink
&& !underline
) {
3368 sb
.append("\033[0;7;5;");
3369 } else if ( bold
&& !reverse
&& blink
&& !underline
) {
3370 sb
.append("\033[0;1;5;");
3371 } else if ( bold
&& !reverse
&& !blink
&& !underline
) {
3372 sb
.append("\033[0;1;");
3373 } else if ( !bold
&& reverse
&& !blink
&& !underline
) {
3374 sb
.append("\033[0;7;");
3375 } else if ( !bold
&& !reverse
&& blink
&& !underline
) {
3376 sb
.append("\033[0;5;");
3377 } else if ( bold
&& reverse
&& blink
&& underline
) {
3378 sb
.append("\033[0;1;7;5;4;");
3379 } else if ( bold
&& reverse
&& !blink
&& underline
) {
3380 sb
.append("\033[0;1;7;4;");
3381 } else if ( !bold
&& reverse
&& blink
&& underline
) {
3382 sb
.append("\033[0;7;5;4;");
3383 } else if ( bold
&& !reverse
&& blink
&& underline
) {
3384 sb
.append("\033[0;1;5;4;");
3385 } else if ( bold
&& !reverse
&& !blink
&& underline
) {
3386 sb
.append("\033[0;1;4;");
3387 } else if ( !bold
&& reverse
&& !blink
&& underline
) {
3388 sb
.append("\033[0;7;4;");
3389 } else if ( !bold
&& !reverse
&& blink
&& underline
) {
3390 sb
.append("\033[0;5;4;");
3391 } else if ( !bold
&& !reverse
&& !blink
&& underline
) {
3392 sb
.append("\033[0;4;");
3394 assert (!bold
&& !reverse
&& !blink
&& !underline
);
3395 sb
.append("\033[0;");
3398 sb
.append("m\033[38;2;");
3399 sb
.append(String
.format("%d;%d;%d", foreColorRed
, foreColorGreen
,
3401 sb
.append("m\033[48;2;");
3402 sb
.append(String
.format("%d;%d;%d", backColorRed
, backColorGreen
,
3405 return sb
.toString();
3409 * Create a SGR parameter sequence to reset to defaults.
3411 * @return the string to emit to an ANSI / ECMA-style terminal,
3414 private String
normal() {
3415 return normal(true) + rgbColor(false, Color
.WHITE
, Color
.BLACK
);
3419 * Create a SGR parameter sequence to reset to defaults.
3421 * @param header if true, make the full header, otherwise just emit the
3422 * bare parameter e.g. "0;"
3423 * @return the string to emit to an ANSI / ECMA-style terminal,
3426 private String
normal(final boolean header
) {
3428 return "\033[0;37;40m";
3434 * Create a SGR parameter sequence for enabling the visible cursor.
3436 * @param on if true, turn on cursor
3437 * @return the string to emit to an ANSI / ECMA-style terminal
3439 private String
cursor(final boolean on
) {
3440 if (on
&& !cursorOn
) {
3444 if (!on
&& cursorOn
) {
3452 * Clear the entire screen. Because some terminals use back-color-erase,
3453 * set the color to white-on-black beforehand.
3455 * @return the string to emit to an ANSI / ECMA-style terminal
3457 private String
clearAll() {
3458 return "\033[0;37;40m\033[2J";
3462 * Clear the line from the cursor (inclusive) to the end of the screen.
3463 * Because some terminals use back-color-erase, set the color to
3464 * white-on-black beforehand.
3466 * @return the string to emit to an ANSI / ECMA-style terminal
3468 private String
clearRemainingLine() {
3469 return "\033[0;37;40m\033[K";
3473 * Move the cursor to (x, y).
3475 * @param x column coordinate. 0 is the left-most column.
3476 * @param y row coordinate. 0 is the top-most row.
3477 * @return the string to emit to an ANSI / ECMA-style terminal
3479 private String
gotoXY(final int x
, final int y
) {
3480 return String
.format("\033[%d;%dH", y
+ 1, x
+ 1);
3484 * Tell (u)xterm that we want to receive mouse events based on "Any event
3485 * tracking", UTF-8 coordinates, and then SGR coordinates. Ideally we
3486 * will end up with SGR coordinates with UTF-8 coordinates as a fallback.
3488 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
3490 * Note that this also sets the alternate/primary screen buffer.
3492 * Finally, also emit a Privacy Message sequence that Jexer recognizes to
3493 * mean "hide the mouse pointer." We have to use our own sequence to do
3494 * this because there is no standard in xterm for unilaterally hiding the
3495 * pointer all the time (regardless of typing).
3497 * @param on If true, enable mouse report and use the alternate screen
3498 * buffer. If false disable mouse reporting and use the primary screen
3500 * @return the string to emit to xterm
3502 private String
mouse(final boolean on
) {
3504 return "\033[?1002;1003;1005;1006h\033[?1049h\033^hideMousePointer\033\\";
3506 return "\033[?1002;1003;1006;1005l\033[?1049l\033^showMousePointer\033\\";