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
;
47 import java
.util
.LinkedList
;
50 import jexer
.bits
.Cell
;
51 import jexer
.bits
.CellAttributes
;
52 import jexer
.bits
.Color
;
53 import jexer
.event
.TInputEvent
;
54 import jexer
.event
.TKeypressEvent
;
55 import jexer
.event
.TMouseEvent
;
56 import jexer
.event
.TResizeEvent
;
57 import static jexer
.TKeypress
.*;
60 * This class reads keystrokes and mouse events and emits output to ANSI
61 * X3.64 / ECMA-48 type terminals e.g. xterm, linux, vt100, ansi.sys, etc.
63 public class ECMA48Terminal
extends LogicalScreen
64 implements TerminalReader
, Runnable
{
66 // ------------------------------------------------------------------------
67 // Constants --------------------------------------------------------------
68 // ------------------------------------------------------------------------
71 * States in the input parser.
73 private enum ParseState
{
84 * Number of colors in the sixel palette. Xterm 335 defines the max as
87 private static final int MAX_COLOR_REGISTERS
= 1024;
89 // ------------------------------------------------------------------------
90 // Variables --------------------------------------------------------------
91 // ------------------------------------------------------------------------
94 * Emit debugging to stderr.
96 private boolean debugToStderr
= false;
99 * If true, emit T.416-style RGB colors for normal system colors. This
100 * is a) expensive in bandwidth, and b) potentially terrible looking for
103 private static boolean doRgbColor
= false;
106 * The session information.
108 private SessionInfo sessionInfo
;
111 * The event queue, filled up by a thread reading on input.
113 private List
<TInputEvent
> eventQueue
;
116 * If true, we want the reader thread to exit gracefully.
118 private boolean stopReaderThread
;
123 private Thread readerThread
;
126 * Parameters being collected. E.g. if the string is \033[1;3m, then
127 * params[0] will be 1 and params[1] will be 3.
129 private List
<String
> params
;
132 * Current parsing state.
134 private ParseState state
;
137 * The time we entered ESCAPE. If we get a bare escape without a code
138 * following it, this is used to return that bare escape.
140 private long escapeTime
;
143 * The time we last checked the window size. We try not to spawn stty
144 * more than once per second.
146 private long windowSizeTime
;
149 * true if mouse1 was down. Used to report mouse1 on the release event.
151 private boolean mouse1
;
154 * true if mouse2 was down. Used to report mouse2 on the release event.
156 private boolean mouse2
;
159 * true if mouse3 was down. Used to report mouse3 on the release event.
161 private boolean mouse3
;
164 * Cache the cursor visibility value so we only emit the sequence when we
167 private boolean cursorOn
= true;
170 * Cache the last window size to figure out if a TResizeEvent needs to be
173 private TResizeEvent windowResize
= null;
176 * Window width in pixels. Used for sixel support.
178 private int widthPixels
= 640;
181 * Window height in pixels. Used for sixel support.
183 private int heightPixels
= 400;
186 * If true, emit image data via sixel.
188 private boolean sixel
= true;
191 * The sixel palette handler.
193 private SixelPalette palette
= null;
196 * The sixel post-rendered string cache.
198 private SixelCache sixelCache
= null;
201 * If true, then we changed System.in and need to change it back.
203 private boolean setRawMode
;
206 * The terminal's input. If an InputStream is not specified in the
207 * constructor, then this InputStreamReader will be bound to System.in
208 * with UTF-8 encoding.
210 private Reader input
;
213 * The terminal's raw InputStream. If an InputStream is not specified in
214 * the constructor, then this InputReader will be bound to System.in.
215 * This is used by run() to see if bytes are available() before calling
216 * (Reader)input.read().
218 private InputStream inputStream
;
221 * The terminal's output. If an OutputStream is not specified in the
222 * constructor, then this PrintWriter will be bound to System.out with
225 private PrintWriter output
;
228 * The listening object that run() wakes up on new input.
230 private Object listener
;
233 * SixelPalette is used to manage the conversion of images between 24-bit
234 * RGB color and a palette of MAX_COLOR_REGISTERS colors.
236 private class SixelPalette
{
239 * Color palette for sixel output, sorted low to high.
241 private List
<Integer
> rgbColors
= new ArrayList
<Integer
>();
244 * Map of color palette index for sixel output, from the order it was
245 * generated by makePalette() to rgbColors.
247 private int [] rgbSortedIndex
= new int[MAX_COLOR_REGISTERS
];
250 * The color palette, organized by hue, saturation, and luminance.
251 * This is used for a fast color match.
253 private ArrayList
<ArrayList
<ArrayList
<ColorIdx
>>> hslColors
;
256 * Number of bits for hue.
258 private int hueBits
= -1;
261 * Number of bits for saturation.
263 private int satBits
= -1;
266 * Number of bits for luminance.
268 private int lumBits
= -1;
271 * Step size for hue bins.
273 private int hueStep
= -1;
276 * Step size for saturation bins.
278 private int satStep
= -1;
281 * Cached RGB to HSL result.
283 private int hsl
[] = new int[3];
286 * ColorIdx records a RGB color and its palette index.
288 private class ColorIdx
{
290 * The 24-bit RGB color.
295 * The palette index for this color.
300 * Public constructor.
302 * @param color the 24-bit RGB color
303 * @param index the palette index for this color
305 public ColorIdx(final int color
, final int index
) {
312 * Public constructor.
314 public SixelPalette() {
319 * Find the nearest match for a color in the palette.
321 * @param color the RGB color
322 * @return the index in rgbColors that is closest to color
324 public int matchColor(final int color
) {
329 * matchColor() is a critical performance bottleneck. To make it
330 * decent, we do the following:
332 * 1. Find the nearest two hues that bracket this color.
334 * 2. Find the nearest two saturations that bracket this color.
336 * 3. Iterate within these four bands of luminance values,
337 * returning the closest color by Euclidean distance.
339 * This strategy reduces the search space by about 97%.
341 int red
= (color
>>> 16) & 0xFF;
342 int green
= (color
>>> 8) & 0xFF;
343 int blue
= color
& 0xFF;
345 rgbToHsl(red
, green
, blue
, hsl
);
349 // System.err.printf("%d %d %d\n", hue, sat, lum);
351 double diff
= Double
.MAX_VALUE
;
354 int hue1
= hue
/ (360/hueStep
);
356 if (hue1
>= hslColors
.size() - 1) {
357 // Bracket pure red from above.
358 hue1
= hslColors
.size() - 1;
360 } else if (hue1
== 0) {
361 // Bracket pure red from below.
362 hue2
= hslColors
.size() - 1;
365 for (int hI
= hue1
; hI
!= -1;) {
366 ArrayList
<ArrayList
<ColorIdx
>> sats
= hslColors
.get(hI
);
369 } else if (hI
== hue2
) {
373 int sMin
= (sat
/ satStep
) - 1;
378 } else if (sMin
== sats
.size() - 1) {
383 assert (sMax
- sMin
== 1);
386 // int sMax = sats.size() - 1;
388 for (int sI
= sMin
; sI
<= sMax
; sI
++) {
389 ArrayList
<ColorIdx
> lums
= sats
.get(sI
);
391 // True 3D colorspace match for the remaining values
392 for (ColorIdx c
: lums
) {
393 int rgbColor
= c
.color
;
395 int red2
= (rgbColor
>>> 16) & 0xFF;
396 int green2
= (rgbColor
>>> 8) & 0xFF;
397 int blue2
= rgbColor
& 0xFF;
398 newDiff
+= Math
.pow(red2
- red
, 2);
399 newDiff
+= Math
.pow(green2
- green
, 2);
400 newDiff
+= Math
.pow(blue2
- blue
, 2);
401 if (newDiff
< diff
) {
402 idx
= rgbSortedIndex
[c
.index
];
409 if (((red
* red
) + (green
* green
) + (blue
* blue
)) < diff
) {
410 // Black is a closer match.
412 } else if ((((255 - red
) * (255 - red
)) +
413 ((255 - green
) * (255 - green
)) +
414 ((255 - blue
) * (255 - blue
))) < diff
) {
416 // White is a closer match.
417 idx
= MAX_COLOR_REGISTERS
- 1;
424 * Clamp an int value to [0, 255].
426 * @param x the int value
427 * @return an int between 0 and 255.
429 private int clamp(final int x
) {
440 * Dither an image to a MAX_COLOR_REGISTERS palette. The dithered
441 * image cells will contain indexes into the palette.
443 * @param image the image to dither
444 * @return the dithered image. Every pixel is an index into the
447 public BufferedImage
ditherImage(final BufferedImage image
) {
449 BufferedImage ditheredImage
= new BufferedImage(image
.getWidth(),
450 image
.getHeight(), BufferedImage
.TYPE_INT_ARGB
);
452 int [] rgbArray
= image
.getRGB(0, 0, image
.getWidth(),
453 image
.getHeight(), null, 0, image
.getWidth());
454 ditheredImage
.setRGB(0, 0, image
.getWidth(), image
.getHeight(),
455 rgbArray
, 0, image
.getWidth());
457 for (int imageY
= 0; imageY
< image
.getHeight(); imageY
++) {
458 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
459 int oldPixel
= ditheredImage
.getRGB(imageX
,
461 int colorIdx
= matchColor(oldPixel
);
462 assert (colorIdx
>= 0);
463 assert (colorIdx
< MAX_COLOR_REGISTERS
);
464 int newPixel
= rgbColors
.get(colorIdx
);
465 ditheredImage
.setRGB(imageX
, imageY
, colorIdx
);
467 int oldRed
= (oldPixel
>>> 16) & 0xFF;
468 int oldGreen
= (oldPixel
>>> 8) & 0xFF;
469 int oldBlue
= oldPixel
& 0xFF;
471 int newRed
= (newPixel
>>> 16) & 0xFF;
472 int newGreen
= (newPixel
>>> 8) & 0xFF;
473 int newBlue
= newPixel
& 0xFF;
475 int redError
= (oldRed
- newRed
) / 16;
476 int greenError
= (oldGreen
- newGreen
) / 16;
477 int blueError
= (oldBlue
- newBlue
) / 16;
479 int red
, green
, blue
;
480 if (imageX
< image
.getWidth() - 1) {
481 int pXpY
= ditheredImage
.getRGB(imageX
+ 1, imageY
);
482 red
= ((pXpY
>>> 16) & 0xFF) + (7 * redError
);
483 green
= ((pXpY
>>> 8) & 0xFF) + (7 * greenError
);
484 blue
= ( pXpY
& 0xFF) + (7 * blueError
);
486 green
= clamp(green
);
488 pXpY
= ((red
& 0xFF) << 16);
489 pXpY
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
490 ditheredImage
.setRGB(imageX
+ 1, imageY
, pXpY
);
492 if (imageY
< image
.getHeight() - 1) {
493 int pXpYp
= ditheredImage
.getRGB(imageX
+ 1,
495 red
= ((pXpYp
>>> 16) & 0xFF) + redError
;
496 green
= ((pXpYp
>>> 8) & 0xFF) + greenError
;
497 blue
= ( pXpYp
& 0xFF) + blueError
;
499 green
= clamp(green
);
501 pXpYp
= ((red
& 0xFF) << 16);
502 pXpYp
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
503 ditheredImage
.setRGB(imageX
+ 1, imageY
+ 1, pXpYp
);
505 } else if (imageY
< image
.getHeight() - 1) {
506 int pXmYp
= ditheredImage
.getRGB(imageX
- 1,
508 int pXYp
= ditheredImage
.getRGB(imageX
,
511 red
= ((pXmYp
>>> 16) & 0xFF) + (3 * redError
);
512 green
= ((pXmYp
>>> 8) & 0xFF) + (3 * greenError
);
513 blue
= ( pXmYp
& 0xFF) + (3 * blueError
);
515 green
= clamp(green
);
517 pXmYp
= ((red
& 0xFF) << 16);
518 pXmYp
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
519 ditheredImage
.setRGB(imageX
- 1, imageY
+ 1, pXmYp
);
521 red
= ((pXYp
>>> 16) & 0xFF) + (5 * redError
);
522 green
= ((pXYp
>>> 8) & 0xFF) + (5 * greenError
);
523 blue
= ( pXYp
& 0xFF) + (5 * blueError
);
525 green
= clamp(green
);
527 pXYp
= ((red
& 0xFF) << 16);
528 pXYp
|= ((green
& 0xFF) << 8) | (blue
& 0xFF);
529 ditheredImage
.setRGB(imageX
, imageY
+ 1, pXYp
);
531 } // for (int imageY = 0; imageY < image.getHeight(); imageY++)
532 } // for (int imageX = 0; imageX < image.getWidth(); imageX++)
534 return ditheredImage
;
538 * Convert an RGB color to HSL.
540 * @param red red color, between 0 and 255
541 * @param green green color, between 0 and 255
542 * @param blue blue color, between 0 and 255
543 * @param hsl the hsl color as [hue, saturation, luminance]
545 private void rgbToHsl(final int red
, final int green
,
546 final int blue
, final int [] hsl
) {
548 assert ((red
>= 0) && (red
<= 255));
549 assert ((green
>= 0) && (green
<= 255));
550 assert ((blue
>= 0) && (blue
<= 255));
552 double R
= red
/ 255.0;
553 double G
= green
/ 255.0;
554 double B
= blue
/ 255.0;
555 boolean Rmax
= false;
556 boolean Gmax
= false;
557 boolean Bmax
= false;
558 double min
= (R
< G ? R
: G
);
559 min
= (min
< B ? min
: B
);
561 if ((R
>= G
) && (R
>= B
)) {
564 } else if ((G
>= R
) && (G
>= B
)) {
567 } else if ((B
>= G
) && (B
>= R
)) {
572 double L
= (min
+ max
) / 2.0;
577 S
= (max
- min
) / (max
+ min
);
579 S
= (max
- min
) / (2.0 - max
- min
);
583 assert (Gmax
== false);
584 assert (Bmax
== false);
585 H
= (G
- B
) / (max
- min
);
587 assert (Rmax
== false);
588 assert (Bmax
== false);
589 H
= 2.0 + (B
- R
) / (max
- min
);
591 assert (Rmax
== false);
592 assert (Gmax
== false);
593 H
= 4.0 + (R
- G
) / (max
- min
);
598 hsl
[0] = (int) (H
* 60.0);
599 hsl
[1] = (int) (S
* 100.0);
600 hsl
[2] = (int) (L
* 100.0);
602 assert ((hsl
[0] >= 0) && (hsl
[0] <= 360));
603 assert ((hsl
[1] >= 0) && (hsl
[1] <= 100));
604 assert ((hsl
[2] >= 0) && (hsl
[2] <= 100));
608 * Convert a HSL color to RGB.
610 * @param hue hue, between 0 and 359
611 * @param sat saturation, between 0 and 100
612 * @param lum luminance, between 0 and 100
613 * @return the rgb color as 0x00RRGGBB
615 private int hslToRgb(final int hue
, final int sat
, final int lum
) {
616 assert ((hue
>= 0) && (hue
<= 360));
617 assert ((sat
>= 0) && (sat
<= 100));
618 assert ((lum
>= 0) && (lum
<= 100));
620 double S
= sat
/ 100.0;
621 double L
= lum
/ 100.0;
622 double C
= (1.0 - Math
.abs((2.0 * L
) - 1.0)) * S
;
623 double Hp
= hue
/ 60.0;
624 double X
= C
* (1.0 - Math
.abs((Hp
% 2) - 1.0));
631 } else if (Hp
<= 2.0) {
634 } else if (Hp
<= 3.0) {
637 } else if (Hp
<= 4.0) {
640 } else if (Hp
<= 5.0) {
643 } else if (Hp
<= 6.0) {
647 double m
= L
- (C
/ 2.0);
648 int red
= ((int) ((Rp
+ m
) * 255.0)) << 16;
649 int green
= ((int) ((Gp
+ m
) * 255.0)) << 8;
650 int blue
= (int) ((Bp
+ m
) * 255.0);
652 return (red
| green
| blue
);
656 * Create the sixel palette.
658 private void makePalette() {
659 // Generate the sixel palette. Because we have no idea at this
660 // layer which image(s) will be shown, we have to use a common
661 // palette with MAX_COLOR_REGISTERS colors for everything, and
662 // map the BufferedImage colors to their nearest neighbor in RGB
665 // We build a palette using the Hue-Saturation-Luminence model,
666 // with 5+ bits for Hue, 2+ bits for Saturation, and 1+ bit for
667 // Luminance. We convert these colors to 24-bit RGB, sort them
668 // ascending, and steal the first index for pure black and the
669 // last for pure white. The 8-bit final palette favors bright
670 // colors, somewhere between pastel and classic television
671 // technicolor. 9- and 10-bit palettes are more uniform.
673 // Default at 256 colors.
678 assert (MAX_COLOR_REGISTERS
>= 256);
679 assert ((MAX_COLOR_REGISTERS
== 256)
680 || (MAX_COLOR_REGISTERS
== 512)
681 || (MAX_COLOR_REGISTERS
== 1024)
682 || (MAX_COLOR_REGISTERS
== 2048));
684 switch (MAX_COLOR_REGISTERS
) {
701 hueStep
= (int) (Math
.pow(2, hueBits
));
702 satStep
= (int) (100 / Math
.pow(2, satBits
));
703 // 1 bit for luminance: 40 and 70.
708 // 2 bits: 20, 40, 60, 80
713 // 3 bits: 8, 20, 32, 44, 56, 68, 80, 92
719 // System.err.printf("<html><body>\n");
720 // Hue is evenly spaced around the wheel.
721 hslColors
= new ArrayList
<ArrayList
<ArrayList
<ColorIdx
>>>();
723 final boolean DEBUG
= false;
724 ArrayList
<Integer
> rawRgbList
= new ArrayList
<Integer
>();
726 for (int hue
= 0; hue
< (360 - (360 % hueStep
));
727 hue
+= (360/hueStep
)) {
729 ArrayList
<ArrayList
<ColorIdx
>> satList
= null;
730 satList
= new ArrayList
<ArrayList
<ColorIdx
>>();
731 hslColors
.add(satList
);
733 // Saturation is linearly spaced between pastel and pure.
734 for (int sat
= satStep
; sat
<= 100; sat
+= satStep
) {
736 ArrayList
<ColorIdx
> lumList
= new ArrayList
<ColorIdx
>();
737 satList
.add(lumList
);
739 // Luminance brackets the pure color, but leaning toward
741 for (int lum
= lumBegin
; lum
< 100; lum
+= lumStep
) {
743 System.err.printf("<font style = \"color:");
744 System.err.printf("hsl(%d, %d%%, %d%%)",
746 System.err.printf(";\">=</font>\n");
748 int rgbColor
= hslToRgb(hue
, sat
, lum
);
749 rgbColors
.add(rgbColor
);
750 ColorIdx colorIdx
= new ColorIdx(rgbColor
,
751 rgbColors
.size() - 1);
752 lumList
.add(colorIdx
);
754 rawRgbList
.add(rgbColor
);
756 int red
= (rgbColor
>>> 16) & 0xFF;
757 int green
= (rgbColor
>>> 8) & 0xFF;
758 int blue
= rgbColor
& 0xFF;
759 int [] backToHsl
= new int[3];
760 rgbToHsl(red
, green
, blue
, backToHsl
);
761 System
.err
.printf("%d [%d] %d [%d] %d [%d]\n",
762 hue
, backToHsl
[0], sat
, backToHsl
[1],
768 // System.err.printf("\n</body></html>\n");
770 assert (rgbColors
.size() == MAX_COLOR_REGISTERS
);
773 * We need to sort rgbColors, so that toSixel() can know where
774 * BLACK and WHITE are in it. But we also need to be able to
775 * find the sorted values using the old unsorted indexes. So we
776 * will sort it, put all the indexes into a HashMap, and then
777 * build rgbSortedIndex[].
779 Collections
.sort(rgbColors
);
780 HashMap
<Integer
, Integer
> rgbColorIndices
= null;
781 rgbColorIndices
= new HashMap
<Integer
, Integer
>();
782 for (int i
= 0; i
< MAX_COLOR_REGISTERS
; i
++) {
783 rgbColorIndices
.put(rgbColors
.get(i
), i
);
785 for (int i
= 0; i
< MAX_COLOR_REGISTERS
; i
++) {
786 int rawColor
= rawRgbList
.get(i
);
787 rgbSortedIndex
[i
] = rgbColorIndices
.get(rawColor
);
790 for (int i
= 0; i
< MAX_COLOR_REGISTERS
; i
++) {
791 assert (rawRgbList
!= null);
792 int idx
= rgbSortedIndex
[i
];
793 int rgbColor
= rgbColors
.get(idx
);
794 if ((idx
!= 0) && (idx
!= MAX_COLOR_REGISTERS
- 1)) {
796 System.err.printf("%d %06x --> %d %06x\n",
797 i, rawRgbList.get(i), idx, rgbColors.get(idx));
799 assert (rgbColor
== rawRgbList
.get(i
));
804 // Set the dimmest color as true black, and the brightest as true
807 rgbColors
.set(MAX_COLOR_REGISTERS
- 1, 0xFFFFFF);
810 System.err.printf("<html><body>\n");
811 for (Integer rgb: rgbColors) {
812 System.err.printf("<font style = \"color:");
813 System.err.printf("#%06x", rgb);
814 System.err.printf(";\">=</font>\n");
816 System.err.printf("\n</body></html>\n");
822 * Emit the sixel palette.
824 * @param sb the StringBuilder to append to
825 * @param used array of booleans set to true for each color actually
826 * used in this cell, or null to emit the entire palette
827 * @return the string to emit to an ANSI / ECMA-style terminal
829 public String
emitPalette(final StringBuilder sb
,
830 final boolean [] used
) {
832 for (int i
= 0; i
< MAX_COLOR_REGISTERS
; i
++) {
833 if (((used
!= null) && (used
[i
] == true)) || (used
== null)) {
834 int rgbColor
= rgbColors
.get(i
);
835 sb
.append(String
.format("#%d;2;%d;%d;%d", i
,
836 ((rgbColor
>>> 16) & 0xFF) * 100 / 255,
837 ((rgbColor
>>> 8) & 0xFF) * 100 / 255,
838 ( rgbColor
& 0xFF) * 100 / 255));
841 return sb
.toString();
846 * SixelCache is a least-recently-used cache that hangs on to the
847 * post-rendered sixel string for a particular set of cells.
849 private class SixelCache
{
852 * Maximum size of the cache.
854 private int maxSize
= 100;
857 * The entries stored in the cache.
859 private HashMap
<String
, CacheEntry
> cache
= null;
862 * CacheEntry is one entry in the cache.
864 private class CacheEntry
{
876 * The last time this entry was used.
878 public long millis
= 0;
881 * Public constructor.
883 * @param key the cache entry key
884 * @param data the cache entry data
886 public CacheEntry(final String key
, final String data
) {
889 this.millis
= System
.currentTimeMillis();
894 * Public constructor.
896 * @param maxSize the maximum size of the cache
898 public SixelCache(final int maxSize
) {
899 this.maxSize
= maxSize
;
900 cache
= new HashMap
<String
, CacheEntry
>();
904 * Make a unique key for a list of cells.
906 * @param cells the cells
909 private String
makeKey(final ArrayList
<Cell
> cells
) {
910 StringBuilder sb
= new StringBuilder();
911 for (Cell cell
: cells
) {
912 sb
.append(cell
.hashCode());
914 return sb
.toString();
918 * Get an entry from the cache.
920 * @param cells the list of cells that are the cache key
921 * @return the sixel string representing these cells, or null if this
922 * list of cells is not in the cache
924 public String
get(final ArrayList
<Cell
> cells
) {
925 CacheEntry entry
= cache
.get(makeKey(cells
));
929 entry
.millis
= System
.currentTimeMillis();
934 * Put an entry into the cache.
936 * @param cells the list of cells that are the cache key
937 * @param data the sixel string representing these cells
939 public void put(final ArrayList
<Cell
> cells
, final String data
) {
940 String key
= makeKey(cells
);
942 // System.err.println("put() " + key + " size " + cache.size());
944 assert (!cache
.containsKey(key
));
946 assert (cache
.size() <= maxSize
);
947 if (cache
.size() == maxSize
) {
948 // Cache is at limit, evict oldest entry.
949 long oldestTime
= Long
.MAX_VALUE
;
950 String keyToRemove
= null;
951 for (CacheEntry entry
: cache
.values()) {
952 if ((entry
.millis
< oldestTime
) || (keyToRemove
== null)) {
953 keyToRemove
= entry
.key
;
954 oldestTime
= entry
.millis
;
958 System.err.println("put() remove key = " + keyToRemove +
959 " size " + cache.size());
961 assert (keyToRemove
!= null);
962 cache
.remove(keyToRemove
);
964 System.err.println("put() removed, size " + cache.size());
967 assert (cache
.size() <= maxSize
);
968 CacheEntry entry
= new CacheEntry(key
, data
);
969 assert (key
.equals(entry
.key
));
970 cache
.put(key
, entry
);
972 System.err.println("put() added key " + key + " " +
973 " size " + cache.size());
979 // ------------------------------------------------------------------------
980 // Constructors -----------------------------------------------------------
981 // ------------------------------------------------------------------------
984 * Constructor sets up state for getEvent().
986 * @param listener the object this backend needs to wake up when new
988 * @param input an InputStream connected to the remote user, or null for
989 * System.in. If System.in is used, then on non-Windows systems it will
990 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
991 * mode. input is always converted to a Reader with UTF-8 encoding.
992 * @param output an OutputStream connected to the remote user, or null
993 * for System.out. output is always converted to a Writer with UTF-8
995 * @param windowWidth the number of text columns to start with
996 * @param windowHeight the number of text rows to start with
997 * @throws UnsupportedEncodingException if an exception is thrown when
998 * creating the InputStreamReader
1000 public ECMA48Terminal(final Object listener
, final InputStream input
,
1001 final OutputStream output
, final int windowWidth
,
1002 final int windowHeight
) throws UnsupportedEncodingException
{
1004 this(listener
, input
, output
);
1006 // Send dtterm/xterm sequences, which will probably not work because
1007 // allowWindowOps is defaulted to false.
1008 String resizeString
= String
.format("\033[8;%d;%dt", windowHeight
,
1010 this.output
.write(resizeString
);
1011 this.output
.flush();
1015 * Constructor sets up state for getEvent().
1017 * @param listener the object this backend needs to wake up when new
1019 * @param input an InputStream connected to the remote user, or null for
1020 * System.in. If System.in is used, then on non-Windows systems it will
1021 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
1022 * mode. input is always converted to a Reader with UTF-8 encoding.
1023 * @param output an OutputStream connected to the remote user, or null
1024 * for System.out. output is always converted to a Writer with UTF-8
1026 * @throws UnsupportedEncodingException if an exception is thrown when
1027 * creating the InputStreamReader
1029 public ECMA48Terminal(final Object listener
, final InputStream input
,
1030 final OutputStream output
) throws UnsupportedEncodingException
{
1036 stopReaderThread
= false;
1037 this.listener
= listener
;
1039 if (input
== null) {
1040 // inputStream = System.in;
1041 inputStream
= new FileInputStream(FileDescriptor
.in
);
1045 inputStream
= input
;
1047 this.input
= new InputStreamReader(inputStream
, "UTF-8");
1049 if (input
instanceof SessionInfo
) {
1050 // This is a TelnetInputStream that exposes window size and
1051 // environment variables from the telnet layer.
1052 sessionInfo
= (SessionInfo
) input
;
1054 if (sessionInfo
== null) {
1055 if (input
== null) {
1056 // Reading right off the tty
1057 sessionInfo
= new TTYSessionInfo();
1059 sessionInfo
= new TSessionInfo();
1063 if (output
== null) {
1064 this.output
= new PrintWriter(new OutputStreamWriter(System
.out
,
1067 this.output
= new PrintWriter(new OutputStreamWriter(output
,
1071 // Request xterm report window dimensions in pixels
1072 this.output
.printf("%s", xtermReportWindowPixelDimensions());
1074 // Enable mouse reporting and metaSendsEscape
1075 this.output
.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
1076 this.output
.flush();
1078 // Query the screen size
1079 sessionInfo
.queryWindowSize();
1080 setDimensions(sessionInfo
.getWindowWidth(),
1081 sessionInfo
.getWindowHeight());
1083 // Hang onto the window size
1084 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
1085 sessionInfo
.getWindowWidth(), sessionInfo
.getWindowHeight());
1089 // Spin up the input reader
1090 eventQueue
= new LinkedList
<TInputEvent
>();
1091 readerThread
= new Thread(this);
1092 readerThread
.start();
1095 this.output
.write(clearAll());
1096 this.output
.flush();
1100 * Constructor sets up state for getEvent().
1102 * @param listener the object this backend needs to wake up when new
1104 * @param input the InputStream underlying 'reader'. Its available()
1105 * method is used to determine if reader.read() will block or not.
1106 * @param reader a Reader connected to the remote user.
1107 * @param writer a PrintWriter connected to the remote user.
1108 * @param setRawMode if true, set System.in into raw mode with stty.
1109 * This should in general not be used. It is here solely for Demo3,
1110 * which uses System.in.
1111 * @throws IllegalArgumentException if input, reader, or writer are null.
1113 public ECMA48Terminal(final Object listener
, final InputStream input
,
1114 final Reader reader
, final PrintWriter writer
,
1115 final boolean setRawMode
) {
1117 if (input
== null) {
1118 throw new IllegalArgumentException("InputStream must be specified");
1120 if (reader
== null) {
1121 throw new IllegalArgumentException("Reader must be specified");
1123 if (writer
== null) {
1124 throw new IllegalArgumentException("Writer must be specified");
1130 stopReaderThread
= false;
1131 this.listener
= listener
;
1133 inputStream
= input
;
1134 this.input
= reader
;
1136 if (setRawMode
== true) {
1139 this.setRawMode
= setRawMode
;
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 (setRawMode
== true) {
1148 // Reading right off the tty
1149 sessionInfo
= new TTYSessionInfo();
1151 sessionInfo
= new TSessionInfo();
1155 this.output
= writer
;
1157 // Request xterm report window dimensions in pixels
1158 this.output
.printf("%s", xtermReportWindowPixelDimensions());
1160 // Enable mouse reporting and metaSendsEscape
1161 this.output
.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
1162 this.output
.flush();
1164 // Query the screen size
1165 sessionInfo
.queryWindowSize();
1166 setDimensions(sessionInfo
.getWindowWidth(),
1167 sessionInfo
.getWindowHeight());
1169 // Hang onto the window size
1170 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
1171 sessionInfo
.getWindowWidth(), sessionInfo
.getWindowHeight());
1175 // Spin up the input reader
1176 eventQueue
= new LinkedList
<TInputEvent
>();
1177 readerThread
= new Thread(this);
1178 readerThread
.start();
1181 this.output
.write(clearAll());
1182 this.output
.flush();
1186 * Constructor sets up state for getEvent().
1188 * @param listener the object this backend needs to wake up when new
1190 * @param input the InputStream underlying 'reader'. Its available()
1191 * method is used to determine if reader.read() will block or not.
1192 * @param reader a Reader connected to the remote user.
1193 * @param writer a PrintWriter connected to the remote user.
1194 * @throws IllegalArgumentException if input, reader, or writer are null.
1196 public ECMA48Terminal(final Object listener
, final InputStream input
,
1197 final Reader reader
, final PrintWriter writer
) {
1199 this(listener
, input
, reader
, writer
, false);
1202 // ------------------------------------------------------------------------
1203 // LogicalScreen ----------------------------------------------------------
1204 // ------------------------------------------------------------------------
1207 * Set the window title.
1209 * @param title the new title
1212 public void setTitle(final String title
) {
1213 output
.write(getSetTitleString(title
));
1218 * Push the logical screen to the physical device.
1221 public void flushPhysical() {
1222 StringBuilder sb
= new StringBuilder();
1226 && (cursorY
<= height
- 1)
1227 && (cursorX
<= width
- 1)
1230 sb
.append(cursor(true));
1231 sb
.append(gotoXY(cursorX
, cursorY
));
1233 sb
.append(cursor(false));
1236 output
.write(sb
.toString());
1241 * Resize the physical screen to match the logical screen dimensions.
1244 public void resizeToScreen() {
1245 // Send dtterm/xterm sequences, which will probably not work because
1246 // allowWindowOps is defaulted to false.
1247 String resizeString
= String
.format("\033[8;%d;%dt", getHeight(),
1249 this.output
.write(resizeString
);
1250 this.output
.flush();
1253 // ------------------------------------------------------------------------
1254 // TerminalReader ---------------------------------------------------------
1255 // ------------------------------------------------------------------------
1258 * Check if there are events in the queue.
1260 * @return if true, getEvents() has something to return to the backend
1262 public boolean hasEvents() {
1263 synchronized (eventQueue
) {
1264 return (eventQueue
.size() > 0);
1269 * Return any events in the IO queue.
1271 * @param queue list to append new events to
1273 public void getEvents(final List
<TInputEvent
> queue
) {
1274 synchronized (eventQueue
) {
1275 if (eventQueue
.size() > 0) {
1276 synchronized (queue
) {
1277 queue
.addAll(eventQueue
);
1285 * Restore terminal to normal state.
1287 public void closeTerminal() {
1289 // System.err.println("=== shutdown() ==="); System.err.flush();
1291 // Tell the reader thread to stop looking at input
1292 stopReaderThread
= true;
1294 readerThread
.join();
1295 } catch (InterruptedException e
) {
1296 if (debugToStderr
) {
1297 e
.printStackTrace();
1301 // Disable mouse reporting and show cursor. Defensive null check
1302 // here in case closeTerminal() is called twice.
1303 if (output
!= null) {
1304 output
.printf("%s%s%s", mouse(false), cursor(true), normal());
1311 // We don't close System.in/out
1313 // Shut down the streams, this should wake up the reader thread
1314 // and make it exit.
1315 if (input
!= null) {
1318 } catch (IOException e
) {
1323 if (output
!= null) {
1331 * Set listener to a different Object.
1333 * @param listener the new listening object that run() wakes up on new
1336 public void setListener(final Object listener
) {
1337 this.listener
= listener
;
1341 * Reload options from System properties.
1343 public void reloadOptions() {
1344 // Permit RGB colors only if externally requested.
1345 if (System
.getProperty("jexer.ECMA48.rgbColor",
1346 "false").equals("true")
1353 // Pull the system properties for sixel output.
1354 if (System
.getProperty("jexer.ECMA48.sixel", "true").equals("true")) {
1361 // ------------------------------------------------------------------------
1362 // Runnable ---------------------------------------------------------------
1363 // ------------------------------------------------------------------------
1366 * Read function runs on a separate thread.
1369 boolean done
= false;
1370 // available() will often return > 1, so we need to read in chunks to
1372 char [] readBuffer
= new char[128];
1373 List
<TInputEvent
> events
= new LinkedList
<TInputEvent
>();
1375 while (!done
&& !stopReaderThread
) {
1377 // We assume that if inputStream has bytes available, then
1378 // input won't block on read().
1379 int n
= inputStream
.available();
1382 System.err.printf("inputStream.available(): %d\n", n);
1387 if (readBuffer
.length
< n
) {
1388 // The buffer wasn't big enough, make it huger
1389 readBuffer
= new char[readBuffer
.length
* 2];
1392 // System.err.printf("BEFORE read()\n"); System.err.flush();
1394 int rc
= input
.read(readBuffer
, 0, readBuffer
.length
);
1397 System.err.printf("AFTER read() %d\n", rc);
1405 for (int i
= 0; i
< rc
; i
++) {
1406 int ch
= readBuffer
[i
];
1407 processChar(events
, (char)ch
);
1409 getIdleEvents(events
);
1410 if (events
.size() > 0) {
1411 // Add to the queue for the backend thread to
1412 // be able to obtain.
1413 synchronized (eventQueue
) {
1414 eventQueue
.addAll(events
);
1416 if (listener
!= null) {
1417 synchronized (listener
) {
1418 listener
.notifyAll();
1425 getIdleEvents(events
);
1426 if (events
.size() > 0) {
1427 synchronized (eventQueue
) {
1428 eventQueue
.addAll(events
);
1430 if (listener
!= null) {
1431 synchronized (listener
) {
1432 listener
.notifyAll();
1438 // Wait 20 millis for more data
1441 // System.err.println("end while loop"); System.err.flush();
1442 } catch (InterruptedException e
) {
1444 } catch (IOException e
) {
1445 e
.printStackTrace();
1448 } // while ((done == false) && (stopReaderThread == false))
1449 // System.err.println("*** run() exiting..."); System.err.flush();
1452 // ------------------------------------------------------------------------
1453 // ECMA48Terminal ---------------------------------------------------------
1454 // ------------------------------------------------------------------------
1457 * Get the width of a character cell in pixels.
1459 * @return the width in pixels of a character cell
1461 public int getTextWidth() {
1462 return (widthPixels
/ sessionInfo
.getWindowWidth());
1466 * Get the height of a character cell in pixels.
1468 * @return the height in pixels of a character cell
1470 public int getTextHeight() {
1471 return (heightPixels
/ sessionInfo
.getWindowHeight());
1475 * Getter for sessionInfo.
1477 * @return the SessionInfo
1479 public SessionInfo
getSessionInfo() {
1484 * Get the output writer.
1486 * @return the Writer
1488 public PrintWriter
getOutput() {
1493 * Call 'stty' to set cooked mode.
1495 * <p>Actually executes '/bin/sh -c stty sane cooked < /dev/tty'
1497 private void sttyCooked() {
1502 * Call 'stty' to set raw mode.
1504 * <p>Actually executes '/bin/sh -c stty -ignbrk -brkint -parmrk -istrip
1505 * -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten
1506 * -parenb cs8 min 1 < /dev/tty'
1508 private void sttyRaw() {
1513 * Call 'stty' to set raw or cooked mode.
1515 * @param mode if true, set raw mode, otherwise set cooked mode
1517 private void doStty(final boolean mode
) {
1518 String
[] cmdRaw
= {
1519 "/bin/sh", "-c", "stty -ignbrk -brkint -parmrk -istrip -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten -parenb cs8 min 1 < /dev/tty"
1521 String
[] cmdCooked
= {
1522 "/bin/sh", "-c", "stty sane cooked < /dev/tty"
1527 process
= Runtime
.getRuntime().exec(cmdRaw
);
1529 process
= Runtime
.getRuntime().exec(cmdCooked
);
1531 BufferedReader in
= new BufferedReader(new InputStreamReader(process
.getInputStream(), "UTF-8"));
1532 String line
= in
.readLine();
1533 if ((line
!= null) && (line
.length() > 0)) {
1534 System
.err
.println("WEIRD?! Normal output from stty: " + line
);
1537 BufferedReader err
= new BufferedReader(new InputStreamReader(process
.getErrorStream(), "UTF-8"));
1538 line
= err
.readLine();
1539 if ((line
!= null) && (line
.length() > 0)) {
1540 System
.err
.println("Error output from stty: " + line
);
1545 } catch (InterruptedException e
) {
1546 if (debugToStderr
) {
1547 e
.printStackTrace();
1551 int rc
= process
.exitValue();
1553 System
.err
.println("stty returned error code: " + rc
);
1555 } catch (IOException e
) {
1556 e
.printStackTrace();
1563 public void flush() {
1568 * Perform a somewhat-optimal rendering of a line.
1570 * @param y row coordinate. 0 is the top-most row.
1571 * @param sb StringBuilder to write escape sequences to
1572 * @param lastAttr cell attributes from the last call to flushLine
1574 private void flushLine(final int y
, final StringBuilder sb
,
1575 CellAttributes lastAttr
) {
1579 for (int x
= 0; x
< width
; x
++) {
1580 Cell lCell
= logical
[x
][y
];
1581 if (!lCell
.isBlank()) {
1585 // Push textEnd to first column beyond the text area
1589 // reallyCleared = true;
1591 boolean hasImage
= false;
1593 for (int x
= 0; x
< width
; x
++) {
1594 Cell lCell
= logical
[x
][y
];
1595 Cell pCell
= physical
[x
][y
];
1597 if (!lCell
.equals(pCell
) || reallyCleared
) {
1599 if (debugToStderr
) {
1600 System
.err
.printf("\n--\n");
1601 System
.err
.printf(" Y: %d X: %d\n", y
, x
);
1602 System
.err
.printf(" lCell: %s\n", lCell
);
1603 System
.err
.printf(" pCell: %s\n", pCell
);
1604 System
.err
.printf(" ==== \n");
1607 if (lastAttr
== null) {
1608 lastAttr
= new CellAttributes();
1609 sb
.append(normal());
1613 if ((lastX
!= (x
- 1)) || (lastX
== -1)) {
1614 // Advancing at least one cell, or the first gotoXY
1615 sb
.append(gotoXY(x
, y
));
1618 assert (lastAttr
!= null);
1620 if ((x
== textEnd
) && (textEnd
< width
- 1)) {
1621 assert (lCell
.isBlank());
1623 for (int i
= x
; i
< width
; i
++) {
1624 assert (logical
[i
][y
].isBlank());
1625 // Physical is always updated
1626 physical
[i
][y
].reset();
1629 // Clear remaining line
1630 sb
.append(clearRemainingLine());
1635 // Image cell: bypass the rest of the loop, it is not
1637 if (lCell
.isImage()) {
1640 // Save the last rendered cell
1643 // Physical is always updated
1644 physical
[x
][y
].setTo(lCell
);
1648 assert (!lCell
.isImage());
1651 sb
.append(gotoXY(x
, y
));
1654 // Now emit only the modified attributes
1655 if ((lCell
.getForeColor() != lastAttr
.getForeColor())
1656 && (lCell
.getBackColor() != lastAttr
.getBackColor())
1658 && (lCell
.isBold() == lastAttr
.isBold())
1659 && (lCell
.isReverse() == lastAttr
.isReverse())
1660 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1661 && (lCell
.isBlink() == lastAttr
.isBlink())
1663 // Both colors changed, attributes the same
1664 sb
.append(color(lCell
.isBold(),
1665 lCell
.getForeColor(), lCell
.getBackColor()));
1667 if (debugToStderr
) {
1668 System
.err
.printf("1 Change only fore/back colors\n");
1671 } else if (lCell
.isRGB()
1672 && (lCell
.getForeColorRGB() != lastAttr
.getForeColorRGB())
1673 && (lCell
.getBackColorRGB() != lastAttr
.getBackColorRGB())
1674 && (lCell
.isBold() == lastAttr
.isBold())
1675 && (lCell
.isReverse() == lastAttr
.isReverse())
1676 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1677 && (lCell
.isBlink() == lastAttr
.isBlink())
1679 // Both colors changed, attributes the same
1680 sb
.append(colorRGB(lCell
.getForeColorRGB(),
1681 lCell
.getBackColorRGB()));
1683 if (debugToStderr
) {
1684 System
.err
.printf("1 Change only fore/back colors (RGB)\n");
1686 } else if ((lCell
.getForeColor() != lastAttr
.getForeColor())
1687 && (lCell
.getBackColor() != lastAttr
.getBackColor())
1689 && (lCell
.isBold() != lastAttr
.isBold())
1690 && (lCell
.isReverse() != lastAttr
.isReverse())
1691 && (lCell
.isUnderline() != lastAttr
.isUnderline())
1692 && (lCell
.isBlink() != lastAttr
.isBlink())
1694 // Everything is different
1695 sb
.append(color(lCell
.getForeColor(),
1696 lCell
.getBackColor(),
1697 lCell
.isBold(), lCell
.isReverse(),
1699 lCell
.isUnderline()));
1701 if (debugToStderr
) {
1702 System
.err
.printf("2 Set all attributes\n");
1704 } else if ((lCell
.getForeColor() != lastAttr
.getForeColor())
1705 && (lCell
.getBackColor() == lastAttr
.getBackColor())
1707 && (lCell
.isBold() == lastAttr
.isBold())
1708 && (lCell
.isReverse() == lastAttr
.isReverse())
1709 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1710 && (lCell
.isBlink() == lastAttr
.isBlink())
1713 // Attributes same, foreColor different
1714 sb
.append(color(lCell
.isBold(),
1715 lCell
.getForeColor(), true));
1717 if (debugToStderr
) {
1718 System
.err
.printf("3 Change foreColor\n");
1720 } else if (lCell
.isRGB()
1721 && (lCell
.getForeColorRGB() != lastAttr
.getForeColorRGB())
1722 && (lCell
.getBackColorRGB() == lastAttr
.getBackColorRGB())
1723 && (lCell
.getForeColorRGB() >= 0)
1724 && (lCell
.getBackColorRGB() >= 0)
1725 && (lCell
.isBold() == lastAttr
.isBold())
1726 && (lCell
.isReverse() == lastAttr
.isReverse())
1727 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1728 && (lCell
.isBlink() == lastAttr
.isBlink())
1730 // Attributes same, foreColor different
1731 sb
.append(colorRGB(lCell
.getForeColorRGB(), true));
1733 if (debugToStderr
) {
1734 System
.err
.printf("3 Change foreColor (RGB)\n");
1736 } else if ((lCell
.getForeColor() == lastAttr
.getForeColor())
1737 && (lCell
.getBackColor() != lastAttr
.getBackColor())
1739 && (lCell
.isBold() == lastAttr
.isBold())
1740 && (lCell
.isReverse() == lastAttr
.isReverse())
1741 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1742 && (lCell
.isBlink() == lastAttr
.isBlink())
1744 // Attributes same, backColor different
1745 sb
.append(color(lCell
.isBold(),
1746 lCell
.getBackColor(), false));
1748 if (debugToStderr
) {
1749 System
.err
.printf("4 Change backColor\n");
1751 } else if (lCell
.isRGB()
1752 && (lCell
.getForeColorRGB() == lastAttr
.getForeColorRGB())
1753 && (lCell
.getBackColorRGB() != lastAttr
.getBackColorRGB())
1754 && (lCell
.isBold() == lastAttr
.isBold())
1755 && (lCell
.isReverse() == lastAttr
.isReverse())
1756 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1757 && (lCell
.isBlink() == lastAttr
.isBlink())
1759 // Attributes same, foreColor different
1760 sb
.append(colorRGB(lCell
.getBackColorRGB(), false));
1762 if (debugToStderr
) {
1763 System
.err
.printf("4 Change backColor (RGB)\n");
1765 } else if ((lCell
.getForeColor() == lastAttr
.getForeColor())
1766 && (lCell
.getBackColor() == lastAttr
.getBackColor())
1767 && (lCell
.getForeColorRGB() == lastAttr
.getForeColorRGB())
1768 && (lCell
.getBackColorRGB() == lastAttr
.getBackColorRGB())
1769 && (lCell
.isBold() == lastAttr
.isBold())
1770 && (lCell
.isReverse() == lastAttr
.isReverse())
1771 && (lCell
.isUnderline() == lastAttr
.isUnderline())
1772 && (lCell
.isBlink() == lastAttr
.isBlink())
1775 // All attributes the same, just print the char
1778 if (debugToStderr
) {
1779 System
.err
.printf("5 Only emit character\n");
1782 // Just reset everything again
1783 if (!lCell
.isRGB()) {
1784 sb
.append(color(lCell
.getForeColor(),
1785 lCell
.getBackColor(),
1789 lCell
.isUnderline()));
1791 if (debugToStderr
) {
1792 System
.err
.printf("6 Change all attributes\n");
1795 sb
.append(colorRGB(lCell
.getForeColorRGB(),
1796 lCell
.getBackColorRGB(),
1800 lCell
.isUnderline()));
1801 if (debugToStderr
) {
1802 System
.err
.printf("6 Change all attributes (RGB)\n");
1807 // Emit the character
1808 sb
.append(lCell
.getChar());
1810 // Save the last rendered cell
1812 lastAttr
.setTo(lCell
);
1814 // Physical is always updated
1815 physical
[x
][y
].setTo(lCell
);
1817 } // if (!lCell.equals(pCell) || (reallyCleared == true))
1819 } // for (int x = 0; x < width; x++)
1823 * Render the screen to a string that can be emitted to something that
1824 * knows how to process ECMA-48/ANSI X3.64 escape sequences.
1826 * @param sb StringBuilder to write escape sequences to
1827 * @return escape sequences string that provides the updates to the
1830 private String
flushString(final StringBuilder sb
) {
1831 CellAttributes attr
= null;
1833 if (reallyCleared
) {
1834 attr
= new CellAttributes();
1835 sb
.append(clearAll());
1839 * For sixel support, draw all of the sixel output first, and then
1840 * draw everything else afterwards. This works OK, but performance
1841 * is still a drag on larger pictures.
1843 for (int y
= 0; y
< height
; y
++) {
1844 for (int x
= 0; x
< width
; x
++) {
1845 // If physical had non-image data that is now image data, the
1846 // entire row must be redrawn.
1847 Cell lCell
= logical
[x
][y
];
1848 Cell pCell
= physical
[x
][y
];
1849 if (lCell
.isImage() && !pCell
.isImage()) {
1855 for (int y
= 0; y
< height
; y
++) {
1856 for (int x
= 0; x
< width
; x
++) {
1857 Cell lCell
= logical
[x
][y
];
1858 Cell pCell
= physical
[x
][y
];
1860 if (!lCell
.isImage()) {
1866 while ((right
< width
)
1867 && (logical
[right
][y
].isImage())
1868 && (!logical
[right
][y
].equals(physical
[right
][y
])
1873 ArrayList
<Cell
> cellsToDraw
= new ArrayList
<Cell
>();
1874 for (int i
= 0; i
< (right
- x
); i
++) {
1875 assert (logical
[x
+ i
][y
].isImage());
1876 cellsToDraw
.add(logical
[x
+ i
][y
]);
1878 // Physical is always updated.
1879 physical
[x
+ i
][y
].setTo(lCell
);
1881 if (cellsToDraw
.size() > 0) {
1882 sb
.append(toSixel(x
, y
, cellsToDraw
));
1889 // Draw the text part now.
1890 for (int y
= 0; y
< height
; y
++) {
1891 flushLine(y
, sb
, attr
);
1894 reallyCleared
= false;
1896 String result
= sb
.toString();
1897 if (debugToStderr
) {
1898 System
.err
.printf("flushString(): %s\n", result
);
1904 * Reset keyboard/mouse input parser.
1906 private void resetParser() {
1907 state
= ParseState
.GROUND
;
1908 params
= new ArrayList
<String
>();
1914 * Produce a control character or one of the special ones (ENTER, TAB,
1917 * @param ch Unicode code point
1918 * @param alt if true, set alt on the TKeypress
1919 * @return one TKeypress event, either a control character (e.g. isKey ==
1920 * false, ch == 'A', ctrl == true), or a special key (e.g. isKey == true,
1923 private TKeypressEvent
controlChar(final char ch
, final boolean alt
) {
1924 // System.err.printf("controlChar: %02x\n", ch);
1928 // Carriage return --> ENTER
1929 return new TKeypressEvent(kbEnter
, alt
, false, false);
1931 // Linefeed --> ENTER
1932 return new TKeypressEvent(kbEnter
, alt
, false, false);
1935 return new TKeypressEvent(kbEsc
, alt
, false, false);
1938 return new TKeypressEvent(kbTab
, alt
, false, false);
1940 // Make all other control characters come back as the alphabetic
1941 // character with the ctrl field set. So SOH would be 'A' +
1943 return new TKeypressEvent(false, 0, (char)(ch
+ 0x40),
1949 * Produce special key from CSI Pn ; Pm ; ... ~
1951 * @return one KEYPRESS event representing a special key
1953 private TInputEvent
csiFnKey() {
1955 if (params
.size() > 0) {
1956 key
= Integer
.parseInt(params
.get(0));
1958 boolean alt
= false;
1959 boolean ctrl
= false;
1960 boolean shift
= false;
1961 if (params
.size() > 1) {
1962 shift
= csiIsShift(params
.get(1));
1963 alt
= csiIsAlt(params
.get(1));
1964 ctrl
= csiIsCtrl(params
.get(1));
1969 return new TKeypressEvent(kbHome
, alt
, ctrl
, shift
);
1971 return new TKeypressEvent(kbIns
, alt
, ctrl
, shift
);
1973 return new TKeypressEvent(kbDel
, alt
, ctrl
, shift
);
1975 return new TKeypressEvent(kbEnd
, alt
, ctrl
, shift
);
1977 return new TKeypressEvent(kbPgUp
, alt
, ctrl
, shift
);
1979 return new TKeypressEvent(kbPgDn
, alt
, ctrl
, shift
);
1981 return new TKeypressEvent(kbF5
, alt
, ctrl
, shift
);
1983 return new TKeypressEvent(kbF6
, alt
, ctrl
, shift
);
1985 return new TKeypressEvent(kbF7
, alt
, ctrl
, shift
);
1987 return new TKeypressEvent(kbF8
, alt
, ctrl
, shift
);
1989 return new TKeypressEvent(kbF9
, alt
, ctrl
, shift
);
1991 return new TKeypressEvent(kbF10
, alt
, ctrl
, shift
);
1993 return new TKeypressEvent(kbF11
, alt
, ctrl
, shift
);
1995 return new TKeypressEvent(kbF12
, alt
, ctrl
, shift
);
2003 * Produce mouse events based on "Any event tracking" and UTF-8
2005 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
2007 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
2009 private TInputEvent
parseMouse() {
2010 int buttons
= params
.get(0).charAt(0) - 32;
2011 int x
= params
.get(0).charAt(1) - 32 - 1;
2012 int y
= params
.get(0).charAt(2) - 32 - 1;
2014 // Clamp X and Y to the physical screen coordinates.
2015 if (x
>= windowResize
.getWidth()) {
2016 x
= windowResize
.getWidth() - 1;
2018 if (y
>= windowResize
.getHeight()) {
2019 y
= windowResize
.getHeight() - 1;
2022 TMouseEvent
.Type eventType
= TMouseEvent
.Type
.MOUSE_DOWN
;
2023 boolean eventMouse1
= false;
2024 boolean eventMouse2
= false;
2025 boolean eventMouse3
= false;
2026 boolean eventMouseWheelUp
= false;
2027 boolean eventMouseWheelDown
= false;
2029 // System.err.printf("buttons: %04x\r\n", buttons);
2046 if (!mouse1
&& !mouse2
&& !mouse3
) {
2047 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2049 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
2066 // Dragging with mouse1 down
2069 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2073 // Dragging with mouse2 down
2076 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2080 // Dragging with mouse3 down
2083 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2087 // Dragging with mouse2 down after wheelUp
2090 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2094 // Dragging with mouse2 down after wheelDown
2097 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2101 eventMouseWheelUp
= true;
2105 eventMouseWheelDown
= true;
2109 // Unknown, just make it motion
2110 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2113 return new TMouseEvent(eventType
, x
, y
, x
, y
,
2114 eventMouse1
, eventMouse2
, eventMouse3
,
2115 eventMouseWheelUp
, eventMouseWheelDown
);
2119 * Produce mouse events based on "Any event tracking" and SGR
2121 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
2123 * @param release if true, this was a release ('m')
2124 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
2126 private TInputEvent
parseMouseSGR(final boolean release
) {
2127 // SGR extended coordinates - mode 1006
2128 if (params
.size() < 3) {
2129 // Invalid position, bail out.
2132 int buttons
= Integer
.parseInt(params
.get(0));
2133 int x
= Integer
.parseInt(params
.get(1)) - 1;
2134 int y
= Integer
.parseInt(params
.get(2)) - 1;
2136 // Clamp X and Y to the physical screen coordinates.
2137 if (x
>= windowResize
.getWidth()) {
2138 x
= windowResize
.getWidth() - 1;
2140 if (y
>= windowResize
.getHeight()) {
2141 y
= windowResize
.getHeight() - 1;
2144 TMouseEvent
.Type eventType
= TMouseEvent
.Type
.MOUSE_DOWN
;
2145 boolean eventMouse1
= false;
2146 boolean eventMouse2
= false;
2147 boolean eventMouse3
= false;
2148 boolean eventMouseWheelUp
= false;
2149 boolean eventMouseWheelDown
= false;
2152 eventType
= TMouseEvent
.Type
.MOUSE_UP
;
2166 // Motion only, no buttons down
2167 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2171 // Dragging with mouse1 down
2173 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2177 // Dragging with mouse2 down
2179 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2183 // Dragging with mouse3 down
2185 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2189 // Dragging with mouse2 down after wheelUp
2191 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2195 // Dragging with mouse2 down after wheelDown
2197 eventType
= TMouseEvent
.Type
.MOUSE_MOTION
;
2201 eventMouseWheelUp
= true;
2205 eventMouseWheelDown
= true;
2209 // Unknown, bail out
2212 return new TMouseEvent(eventType
, x
, y
, x
, y
,
2213 eventMouse1
, eventMouse2
, eventMouse3
,
2214 eventMouseWheelUp
, eventMouseWheelDown
);
2218 * Return any events in the IO queue due to timeout.
2220 * @param queue list to append new events to
2222 private void getIdleEvents(final List
<TInputEvent
> queue
) {
2223 long nowTime
= System
.currentTimeMillis();
2225 // Check for new window size
2226 long windowSizeDelay
= nowTime
- windowSizeTime
;
2227 if (windowSizeDelay
> 1000) {
2228 int oldTextWidth
= getTextWidth();
2229 int oldTextHeight
= getTextHeight();
2231 sessionInfo
.queryWindowSize();
2232 int newWidth
= sessionInfo
.getWindowWidth();
2233 int newHeight
= sessionInfo
.getWindowHeight();
2235 if ((newWidth
!= windowResize
.getWidth())
2236 || (newHeight
!= windowResize
.getHeight())
2239 // Request xterm report window dimensions in pixels again.
2240 // Between now and then, ensure that the reported text cell
2241 // size is the same by setting widthPixels and heightPixels
2242 // to match the new dimensions.
2243 widthPixels
= oldTextWidth
* newWidth
;
2244 heightPixels
= oldTextHeight
* newHeight
;
2246 if (debugToStderr
) {
2247 System
.err
.println("Screen size changed, old size " +
2249 System
.err
.println(" new size " +
2250 newWidth
+ " x " + newHeight
);
2251 System
.err
.println(" old pixels " +
2252 oldTextWidth
+ " x " + oldTextHeight
);
2253 System
.err
.println(" new pixels " +
2254 getTextWidth() + " x " + getTextHeight());
2257 this.output
.printf("%s", xtermReportWindowPixelDimensions());
2258 this.output
.flush();
2260 TResizeEvent event
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
2261 newWidth
, newHeight
);
2262 windowResize
= new TResizeEvent(TResizeEvent
.Type
.SCREEN
,
2263 newWidth
, newHeight
);
2266 windowSizeTime
= nowTime
;
2269 // ESCDELAY type timeout
2270 if (state
== ParseState
.ESCAPE
) {
2271 long escDelay
= nowTime
- escapeTime
;
2272 if (escDelay
> 100) {
2273 // After 0.1 seconds, assume a true escape character
2274 queue
.add(controlChar((char)0x1B, false));
2281 * Returns true if the CSI parameter for a keyboard command means that
2284 private boolean csiIsShift(final String x
) {
2296 * Returns true if the CSI parameter for a keyboard command means that
2299 private boolean csiIsAlt(final String x
) {
2311 * Returns true if the CSI parameter for a keyboard command means that
2314 private boolean csiIsCtrl(final String x
) {
2326 * Parses the next character of input to see if an InputEvent is
2329 * @param events list to append new events to
2330 * @param ch Unicode code point
2332 private void processChar(final List
<TInputEvent
> events
, final char ch
) {
2334 // ESCDELAY type timeout
2335 long nowTime
= System
.currentTimeMillis();
2336 if (state
== ParseState
.ESCAPE
) {
2337 long escDelay
= nowTime
- escapeTime
;
2338 if (escDelay
> 250) {
2339 // After 0.25 seconds, assume a true escape character
2340 events
.add(controlChar((char)0x1B, false));
2346 boolean ctrl
= false;
2347 boolean alt
= false;
2348 boolean shift
= false;
2350 // System.err.printf("state: %s ch %c\r\n", state, ch);
2356 state
= ParseState
.ESCAPE
;
2357 escapeTime
= nowTime
;
2362 // Control character
2363 events
.add(controlChar(ch
, false));
2370 events
.add(new TKeypressEvent(false, 0, ch
,
2371 false, false, false));
2380 // ALT-Control character
2381 events
.add(controlChar(ch
, true));
2387 // This will be one of the function keys
2388 state
= ParseState
.ESCAPE_INTERMEDIATE
;
2392 // '[' goes to CSI_ENTRY
2394 state
= ParseState
.CSI_ENTRY
;
2398 // Everything else is assumed to be Alt-keystroke
2399 if ((ch
>= 'A') && (ch
<= 'Z')) {
2403 events
.add(new TKeypressEvent(false, 0, ch
, alt
, ctrl
, shift
));
2407 case ESCAPE_INTERMEDIATE
:
2408 if ((ch
>= 'P') && (ch
<= 'S')) {
2412 events
.add(new TKeypressEvent(kbF1
));
2415 events
.add(new TKeypressEvent(kbF2
));
2418 events
.add(new TKeypressEvent(kbF3
));
2421 events
.add(new TKeypressEvent(kbF4
));
2430 // Unknown keystroke, ignore
2435 // Numbers - parameter values
2436 if ((ch
>= '0') && (ch
<= '9')) {
2437 params
.set(params
.size() - 1,
2438 params
.get(params
.size() - 1) + ch
);
2439 state
= ParseState
.CSI_PARAM
;
2442 // Parameter separator
2448 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
2452 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
2457 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
2462 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
2467 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
2472 events
.add(new TKeypressEvent(kbHome
));
2477 events
.add(new TKeypressEvent(kbEnd
));
2481 // CBT - Cursor backward X tab stops (default 1)
2482 events
.add(new TKeypressEvent(kbBackTab
));
2487 state
= ParseState
.MOUSE
;
2490 // Mouse position, SGR (1006) coordinates
2491 state
= ParseState
.MOUSE_SGR
;
2498 // Unknown keystroke, ignore
2503 // Numbers - parameter values
2504 if ((ch
>= '0') && (ch
<= '9')) {
2505 params
.set(params
.size() - 1,
2506 params
.get(params
.size() - 1) + ch
);
2509 // Parameter separator
2517 // Generate a mouse press event
2518 TInputEvent event
= parseMouseSGR(false);
2519 if (event
!= null) {
2525 // Generate a mouse release event
2526 event
= parseMouseSGR(true);
2527 if (event
!= null) {
2536 // Unknown keystroke, ignore
2541 // Numbers - parameter values
2542 if ((ch
>= '0') && (ch
<= '9')) {
2543 params
.set(params
.size() - 1,
2544 params
.get(params
.size() - 1) + ch
);
2545 state
= ParseState
.CSI_PARAM
;
2548 // Parameter separator
2555 events
.add(csiFnKey());
2560 if ((ch
>= 0x30) && (ch
<= 0x7E)) {
2564 if (params
.size() > 1) {
2565 shift
= csiIsShift(params
.get(1));
2566 alt
= csiIsAlt(params
.get(1));
2567 ctrl
= csiIsCtrl(params
.get(1));
2569 events
.add(new TKeypressEvent(kbUp
, alt
, ctrl
, shift
));
2574 if (params
.size() > 1) {
2575 shift
= csiIsShift(params
.get(1));
2576 alt
= csiIsAlt(params
.get(1));
2577 ctrl
= csiIsCtrl(params
.get(1));
2579 events
.add(new TKeypressEvent(kbDown
, alt
, ctrl
, shift
));
2584 if (params
.size() > 1) {
2585 shift
= csiIsShift(params
.get(1));
2586 alt
= csiIsAlt(params
.get(1));
2587 ctrl
= csiIsCtrl(params
.get(1));
2589 events
.add(new TKeypressEvent(kbRight
, alt
, ctrl
, shift
));
2594 if (params
.size() > 1) {
2595 shift
= csiIsShift(params
.get(1));
2596 alt
= csiIsAlt(params
.get(1));
2597 ctrl
= csiIsCtrl(params
.get(1));
2599 events
.add(new TKeypressEvent(kbLeft
, alt
, ctrl
, shift
));
2604 if (params
.size() > 1) {
2605 shift
= csiIsShift(params
.get(1));
2606 alt
= csiIsAlt(params
.get(1));
2607 ctrl
= csiIsCtrl(params
.get(1));
2609 events
.add(new TKeypressEvent(kbHome
, alt
, ctrl
, shift
));
2614 if (params
.size() > 1) {
2615 shift
= csiIsShift(params
.get(1));
2616 alt
= csiIsAlt(params
.get(1));
2617 ctrl
= csiIsCtrl(params
.get(1));
2619 events
.add(new TKeypressEvent(kbEnd
, alt
, ctrl
, shift
));
2624 if ((params
.size() > 2) && (params
.get(0).equals("4"))) {
2625 if (debugToStderr
) {
2626 System
.err
.printf("windowOp pixels: " +
2627 "height %s width %s\n",
2628 params
.get(1), params
.get(2));
2631 widthPixels
= Integer
.parseInt(params
.get(2));
2632 heightPixels
= Integer
.parseInt(params
.get(1));
2633 } catch (NumberFormatException e
) {
2634 if (debugToStderr
) {
2635 e
.printStackTrace();
2638 if (widthPixels
<= 0) {
2641 if (heightPixels
<= 0) {
2652 // Unknown keystroke, ignore
2657 params
.set(0, params
.get(params
.size() - 1) + ch
);
2658 if (params
.get(0).length() == 3) {
2659 // We have enough to generate a mouse event
2660 events
.add(parseMouse());
2669 // This "should" be impossible to reach
2674 * Request (u)xterm to report the current window size dimensions.
2676 * @return the string to emit to xterm
2678 private String
xtermReportWindowPixelDimensions() {
2683 * Tell (u)xterm that we want alt- keystrokes to send escape + character
2684 * rather than set the 8th bit. Anyone who wants UTF8 should want this
2687 * @param on if true, enable metaSendsEscape
2688 * @return the string to emit to xterm
2690 private String
xtermMetaSendsEscape(final boolean on
) {
2692 return "\033[?1036h\033[?1034l";
2694 return "\033[?1036l";
2698 * Create an xterm OSC sequence to change the window title.
2700 * @param title the new title
2701 * @return the string to emit to xterm
2703 private String
getSetTitleString(final String title
) {
2704 return "\033]2;" + title
+ "\007";
2707 // ------------------------------------------------------------------------
2708 // Sixel output support ---------------------------------------------------
2709 // ------------------------------------------------------------------------
2712 * Start a sixel string for display one row's worth of bitmap data.
2714 * @param x column coordinate. 0 is the left-most column.
2715 * @param y row coordinate. 0 is the top-most row.
2716 * @return the string to emit to an ANSI / ECMA-style terminal
2718 private String
startSixel(final int x
, final int y
) {
2719 StringBuilder sb
= new StringBuilder();
2721 assert (sixel
== true);
2724 sb
.append(gotoXY(x
, y
));
2727 sb
.append("\033Pq");
2729 if (palette
== null) {
2730 palette
= new SixelPalette();
2733 return sb
.toString();
2737 * End a sixel string for display one row's worth of bitmap data.
2739 * @return the string to emit to an ANSI / ECMA-style terminal
2741 private String
endSixel() {
2742 assert (sixel
== true);
2749 * Create a sixel string representing a row of several cells containing
2752 * @param x column coordinate. 0 is the left-most column.
2753 * @param y row coordinate. 0 is the top-most row.
2754 * @param cells the cells containing the bitmap data
2755 * @return the string to emit to an ANSI / ECMA-style terminal
2757 private String
toSixel(final int x
, final int y
,
2758 final ArrayList
<Cell
> cells
) {
2760 StringBuilder sb
= new StringBuilder();
2762 assert (cells
!= null);
2763 assert (cells
.size() > 0);
2764 assert (cells
.get(0).getImage() != null);
2766 if (sixel
== false) {
2767 sb
.append(normal());
2768 sb
.append(gotoXY(x
, y
));
2769 for (int i
= 0; i
< cells
.size(); i
++) {
2772 return sb
.toString();
2775 if (sixelCache
== null) {
2776 sixelCache
= new SixelCache(height
* 10);
2779 // Save and get rows to/from the cache that do NOT have inverted
2781 boolean saveInCache
= true;
2782 for (Cell cell
: cells
) {
2783 if (cell
.isInvertedImage()) {
2784 saveInCache
= false;
2788 String cachedResult
= sixelCache
.get(cells
);
2789 if (cachedResult
!= null) {
2790 // System.err.println("CACHE HIT");
2791 sb
.append(startSixel(x
, y
));
2792 sb
.append(cachedResult
);
2793 sb
.append(endSixel());
2794 return sb
.toString();
2796 // System.err.println("CACHE MISS");
2799 int imageWidth
= cells
.get(0).getImage().getWidth();
2800 int imageHeight
= cells
.get(0).getImage().getHeight();
2802 // cells.get(x).getImage() has a dithered bitmap containing indexes
2803 // into the color palette. Piece these together into one larger
2804 // image for final rendering.
2806 int fullWidth
= cells
.size() * getTextWidth();
2807 int fullHeight
= getTextHeight();
2808 for (int i
= 0; i
< cells
.size(); i
++) {
2809 totalWidth
+= cells
.get(i
).getImage().getWidth();
2812 BufferedImage image
= new BufferedImage(fullWidth
,
2813 fullHeight
, BufferedImage
.TYPE_INT_ARGB
);
2816 for (int i
= 0; i
< cells
.size() - 1; i
++) {
2817 if (cells
.get(i
).isInvertedImage()) {
2818 rgbArray
= new int[imageWidth
* imageHeight
];
2819 for (int j
= 0; j
< rgbArray
.length
; j
++) {
2820 rgbArray
[j
] = 0xFFFFFF;
2823 rgbArray
= cells
.get(i
).getImage().getRGB(0, 0,
2824 imageWidth
, imageHeight
, null, 0, imageWidth
);
2828 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
2829 i * imageWidth, 0, imageWidth, imageHeight,
2831 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
2832 fullWidth, fullHeight, cells.size(), getTextWidth());
2835 image
.setRGB(i
* imageWidth
, 0, imageWidth
, imageHeight
,
2836 rgbArray
, 0, imageWidth
);
2837 if (imageHeight
< fullHeight
) {
2838 int backgroundColor
= cells
.get(i
).getBackground().getRGB();
2839 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
2840 for (int imageY
= imageHeight
; imageY
< fullHeight
;
2843 image
.setRGB(imageX
, imageY
, backgroundColor
);
2848 totalWidth
-= ((cells
.size() - 1) * imageWidth
);
2849 if (cells
.get(cells
.size() - 1).isInvertedImage()) {
2850 rgbArray
= new int[totalWidth
* imageHeight
];
2851 for (int j
= 0; j
< rgbArray
.length
; j
++) {
2852 rgbArray
[j
] = 0xFFFFFF;
2855 rgbArray
= cells
.get(cells
.size() - 1).getImage().getRGB(0, 0,
2856 totalWidth
, imageHeight
, null, 0, totalWidth
);
2858 image
.setRGB((cells
.size() - 1) * imageWidth
, 0, totalWidth
,
2859 imageHeight
, rgbArray
, 0, totalWidth
);
2861 if (totalWidth
< getTextWidth()) {
2862 int backgroundColor
= cells
.get(cells
.size() - 1).getBackground().getRGB();
2864 for (int imageX
= image
.getWidth() - totalWidth
;
2865 imageX
< image
.getWidth(); imageX
++) {
2867 for (int imageY
= 0; imageY
< fullHeight
; imageY
++) {
2868 image
.setRGB(imageX
, imageY
, backgroundColor
);
2873 // Dither the image. It is ok to lose the original here.
2874 if (palette
== null) {
2875 palette
= new SixelPalette();
2877 image
= palette
.ditherImage(image
);
2879 // Emit the palette, but only for the colors actually used by these
2881 boolean [] usedColors
= new boolean[MAX_COLOR_REGISTERS
];
2882 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
2883 for (int imageY
= 0; imageY
< image
.getHeight(); imageY
++) {
2884 usedColors
[image
.getRGB(imageX
, imageY
)] = true;
2887 palette
.emitPalette(sb
, usedColors
);
2889 // Render the entire row of cells.
2890 for (int currentRow
= 0; currentRow
< fullHeight
; currentRow
+= 6) {
2891 int [][] sixels
= new int[image
.getWidth()][6];
2893 // See which colors are actually used in this band of sixels.
2894 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
2895 for (int imageY
= 0;
2896 (imageY
< 6) && (imageY
+ currentRow
< fullHeight
);
2899 int colorIdx
= image
.getRGB(imageX
, imageY
+ currentRow
);
2900 assert (colorIdx
>= 0);
2901 assert (colorIdx
< MAX_COLOR_REGISTERS
);
2903 sixels
[imageX
][imageY
] = colorIdx
;
2907 for (int i
= 0; i
< MAX_COLOR_REGISTERS
; i
++) {
2908 boolean isUsed
= false;
2909 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
2910 for (int j
= 0; j
< 6; j
++) {
2911 if (sixels
[imageX
][j
] == i
) {
2916 if (isUsed
== false) {
2920 // Set to the beginning of scan line for the next set of
2921 // colored pixels, and select the color.
2922 sb
.append(String
.format("$#%d", i
));
2924 for (int imageX
= 0; imageX
< image
.getWidth(); imageX
++) {
2926 // Add up all the pixels that match this color.
2929 (j
< 6) && (currentRow
+ j
< fullHeight
);
2932 if (sixels
[imageX
][j
] == i
) {
2956 assert (data
< 127);
2958 sb
.append((char) data
);
2959 } // for (int imageX = 0; imageX < image.getWidth(); imageX++)
2960 } // for (int i = 0; i < MAX_COLOR_REGISTERS; i++)
2962 // Advance to the next scan line.
2965 } // for (int currentRow = 0; currentRow < imageHeight; currentRow += 6)
2967 // Kill the very last "-", because it is unnecessary.
2968 sb
.deleteCharAt(sb
.length() - 1);
2971 // This row is OK to save into the cache.
2972 sixelCache
.put(cells
, sb
.toString());
2975 return (startSixel(x
, y
) + sb
.toString() + endSixel());
2978 // ------------------------------------------------------------------------
2979 // End sixel output support -----------------------------------------------
2980 // ------------------------------------------------------------------------
2983 * Create a SGR parameter sequence for a single color change.
2985 * @param bold if true, set bold
2986 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
2987 * @param foreground if true, this is a foreground color
2988 * @return the string to emit to an ANSI / ECMA-style terminal,
2991 private String
color(final boolean bold
, final Color color
,
2992 final boolean foreground
) {
2993 return color(color
, foreground
, true) +
2994 rgbColor(bold
, color
, foreground
);
2998 * Create a T.416 RGB parameter sequence for a single color change.
3000 * @param colorRGB a 24-bit RGB value for foreground color
3001 * @param foreground if true, this is a foreground color
3002 * @return the string to emit to an ANSI / ECMA-style terminal,
3005 private String
colorRGB(final int colorRGB
, final boolean foreground
) {
3007 int colorRed
= (colorRGB
>>> 16) & 0xFF;
3008 int colorGreen
= (colorRGB
>>> 8) & 0xFF;
3009 int colorBlue
= colorRGB
& 0xFF;
3011 StringBuilder sb
= new StringBuilder();
3013 sb
.append("\033[38;2;");
3015 sb
.append("\033[48;2;");
3017 sb
.append(String
.format("%d;%d;%dm", colorRed
, colorGreen
, colorBlue
));
3018 return sb
.toString();
3022 * Create a T.416 RGB parameter sequence for both foreground and
3023 * background color change.
3025 * @param foreColorRGB a 24-bit RGB value for foreground color
3026 * @param backColorRGB a 24-bit RGB value for foreground color
3027 * @return the string to emit to an ANSI / ECMA-style terminal,
3030 private String
colorRGB(final int foreColorRGB
, final int backColorRGB
) {
3031 int foreColorRed
= (foreColorRGB
>>> 16) & 0xFF;
3032 int foreColorGreen
= (foreColorRGB
>>> 8) & 0xFF;
3033 int foreColorBlue
= foreColorRGB
& 0xFF;
3034 int backColorRed
= (backColorRGB
>>> 16) & 0xFF;
3035 int backColorGreen
= (backColorRGB
>>> 8) & 0xFF;
3036 int backColorBlue
= backColorRGB
& 0xFF;
3038 StringBuilder sb
= new StringBuilder();
3039 sb
.append(String
.format("\033[38;2;%d;%d;%dm",
3040 foreColorRed
, foreColorGreen
, foreColorBlue
));
3041 sb
.append(String
.format("\033[48;2;%d;%d;%dm",
3042 backColorRed
, backColorGreen
, backColorBlue
));
3043 return sb
.toString();
3047 * Create a T.416 RGB parameter sequence for a single color change.
3049 * @param bold if true, set bold
3050 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
3051 * @param foreground if true, this is a foreground color
3052 * @return the string to emit to an xterm terminal with RGB support,
3053 * e.g. "\033[38;2;RR;GG;BBm"
3055 private String
rgbColor(final boolean bold
, final Color color
,
3056 final boolean foreground
) {
3057 if (doRgbColor
== false) {
3060 StringBuilder sb
= new StringBuilder("\033[");
3062 // Bold implies foreground only
3064 if (color
.equals(Color
.BLACK
)) {
3065 sb
.append("84;84;84");
3066 } else if (color
.equals(Color
.RED
)) {
3067 sb
.append("252;84;84");
3068 } else if (color
.equals(Color
.GREEN
)) {
3069 sb
.append("84;252;84");
3070 } else if (color
.equals(Color
.YELLOW
)) {
3071 sb
.append("252;252;84");
3072 } else if (color
.equals(Color
.BLUE
)) {
3073 sb
.append("84;84;252");
3074 } else if (color
.equals(Color
.MAGENTA
)) {
3075 sb
.append("252;84;252");
3076 } else if (color
.equals(Color
.CYAN
)) {
3077 sb
.append("84;252;252");
3078 } else if (color
.equals(Color
.WHITE
)) {
3079 sb
.append("252;252;252");
3087 if (color
.equals(Color
.BLACK
)) {
3089 } else if (color
.equals(Color
.RED
)) {
3090 sb
.append("168;0;0");
3091 } else if (color
.equals(Color
.GREEN
)) {
3092 sb
.append("0;168;0");
3093 } else if (color
.equals(Color
.YELLOW
)) {
3094 sb
.append("168;84;0");
3095 } else if (color
.equals(Color
.BLUE
)) {
3096 sb
.append("0;0;168");
3097 } else if (color
.equals(Color
.MAGENTA
)) {
3098 sb
.append("168;0;168");
3099 } else if (color
.equals(Color
.CYAN
)) {
3100 sb
.append("0;168;168");
3101 } else if (color
.equals(Color
.WHITE
)) {
3102 sb
.append("168;168;168");
3106 return sb
.toString();
3110 * Create a T.416 RGB parameter sequence for both foreground and
3111 * background color change.
3113 * @param bold if true, set bold
3114 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3115 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3116 * @return the string to emit to an xterm terminal with RGB support,
3117 * e.g. "\033[38;2;RR;GG;BB;48;2;RR;GG;BBm"
3119 private String
rgbColor(final boolean bold
, final Color foreColor
,
3120 final Color backColor
) {
3121 if (doRgbColor
== false) {
3125 return rgbColor(bold
, foreColor
, true) +
3126 rgbColor(false, backColor
, false);
3130 * Create a SGR parameter sequence for a single color change.
3132 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
3133 * @param foreground if true, this is a foreground color
3134 * @param header if true, make the full header, otherwise just emit the
3135 * color parameter e.g. "42;"
3136 * @return the string to emit to an ANSI / ECMA-style terminal,
3139 private String
color(final Color color
, final boolean foreground
,
3140 final boolean header
) {
3142 int ecmaColor
= color
.getValue();
3144 // Convert Color.* values to SGR numerics
3152 return String
.format("\033[%dm", ecmaColor
);
3154 return String
.format("%d;", ecmaColor
);
3159 * Create a SGR parameter sequence for both foreground and background
3162 * @param bold if true, set bold
3163 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3164 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3165 * @return the string to emit to an ANSI / ECMA-style terminal,
3166 * e.g. "\033[31;42m"
3168 private String
color(final boolean bold
, final Color foreColor
,
3169 final Color backColor
) {
3170 return color(foreColor
, backColor
, true) +
3171 rgbColor(bold
, foreColor
, backColor
);
3175 * Create a SGR parameter sequence for both foreground and
3176 * background color change.
3178 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3179 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3180 * @param header if true, make the full header, otherwise just emit the
3181 * color parameter e.g. "31;42;"
3182 * @return the string to emit to an ANSI / ECMA-style terminal,
3183 * e.g. "\033[31;42m"
3185 private String
color(final Color foreColor
, final Color backColor
,
3186 final boolean header
) {
3188 int ecmaForeColor
= foreColor
.getValue();
3189 int ecmaBackColor
= backColor
.getValue();
3191 // Convert Color.* values to SGR numerics
3192 ecmaBackColor
+= 40;
3193 ecmaForeColor
+= 30;
3196 return String
.format("\033[%d;%dm", ecmaForeColor
, ecmaBackColor
);
3198 return String
.format("%d;%d;", ecmaForeColor
, ecmaBackColor
);
3203 * Create a SGR parameter sequence for foreground, background, and
3204 * several attributes. This sequence first resets all attributes to
3205 * default, then sets attributes as per the parameters.
3207 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3208 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3209 * @param bold if true, set bold
3210 * @param reverse if true, set reverse
3211 * @param blink if true, set blink
3212 * @param underline if true, set underline
3213 * @return the string to emit to an ANSI / ECMA-style terminal,
3214 * e.g. "\033[0;1;31;42m"
3216 private String
color(final Color foreColor
, final Color backColor
,
3217 final boolean bold
, final boolean reverse
, final boolean blink
,
3218 final boolean underline
) {
3220 int ecmaForeColor
= foreColor
.getValue();
3221 int ecmaBackColor
= backColor
.getValue();
3223 // Convert Color.* values to SGR numerics
3224 ecmaBackColor
+= 40;
3225 ecmaForeColor
+= 30;
3227 StringBuilder sb
= new StringBuilder();
3228 if ( bold
&& reverse
&& blink
&& !underline
) {
3229 sb
.append("\033[0;1;7;5;");
3230 } else if ( bold
&& reverse
&& !blink
&& !underline
) {
3231 sb
.append("\033[0;1;7;");
3232 } else if ( !bold
&& reverse
&& blink
&& !underline
) {
3233 sb
.append("\033[0;7;5;");
3234 } else if ( bold
&& !reverse
&& blink
&& !underline
) {
3235 sb
.append("\033[0;1;5;");
3236 } else if ( bold
&& !reverse
&& !blink
&& !underline
) {
3237 sb
.append("\033[0;1;");
3238 } else if ( !bold
&& reverse
&& !blink
&& !underline
) {
3239 sb
.append("\033[0;7;");
3240 } else if ( !bold
&& !reverse
&& blink
&& !underline
) {
3241 sb
.append("\033[0;5;");
3242 } else if ( bold
&& reverse
&& blink
&& underline
) {
3243 sb
.append("\033[0;1;7;5;4;");
3244 } else if ( bold
&& reverse
&& !blink
&& underline
) {
3245 sb
.append("\033[0;1;7;4;");
3246 } else if ( !bold
&& reverse
&& blink
&& underline
) {
3247 sb
.append("\033[0;7;5;4;");
3248 } else if ( bold
&& !reverse
&& blink
&& underline
) {
3249 sb
.append("\033[0;1;5;4;");
3250 } else if ( bold
&& !reverse
&& !blink
&& underline
) {
3251 sb
.append("\033[0;1;4;");
3252 } else if ( !bold
&& reverse
&& !blink
&& underline
) {
3253 sb
.append("\033[0;7;4;");
3254 } else if ( !bold
&& !reverse
&& blink
&& underline
) {
3255 sb
.append("\033[0;5;4;");
3256 } else if ( !bold
&& !reverse
&& !blink
&& underline
) {
3257 sb
.append("\033[0;4;");
3259 assert (!bold
&& !reverse
&& !blink
&& !underline
);
3260 sb
.append("\033[0;");
3262 sb
.append(String
.format("%d;%dm", ecmaForeColor
, ecmaBackColor
));
3263 sb
.append(rgbColor(bold
, foreColor
, backColor
));
3264 return sb
.toString();
3268 * Create a SGR parameter sequence for foreground, background, and
3269 * several attributes. This sequence first resets all attributes to
3270 * default, then sets attributes as per the parameters.
3272 * @param foreColorRGB a 24-bit RGB value for foreground color
3273 * @param backColorRGB a 24-bit RGB value for foreground color
3274 * @param bold if true, set bold
3275 * @param reverse if true, set reverse
3276 * @param blink if true, set blink
3277 * @param underline if true, set underline
3278 * @return the string to emit to an ANSI / ECMA-style terminal,
3279 * e.g. "\033[0;1;31;42m"
3281 private String
colorRGB(final int foreColorRGB
, final int backColorRGB
,
3282 final boolean bold
, final boolean reverse
, final boolean blink
,
3283 final boolean underline
) {
3285 int foreColorRed
= (foreColorRGB
>>> 16) & 0xFF;
3286 int foreColorGreen
= (foreColorRGB
>>> 8) & 0xFF;
3287 int foreColorBlue
= foreColorRGB
& 0xFF;
3288 int backColorRed
= (backColorRGB
>>> 16) & 0xFF;
3289 int backColorGreen
= (backColorRGB
>>> 8) & 0xFF;
3290 int backColorBlue
= backColorRGB
& 0xFF;
3292 StringBuilder sb
= new StringBuilder();
3293 if ( bold
&& reverse
&& blink
&& !underline
) {
3294 sb
.append("\033[0;1;7;5;");
3295 } else if ( bold
&& reverse
&& !blink
&& !underline
) {
3296 sb
.append("\033[0;1;7;");
3297 } else if ( !bold
&& reverse
&& blink
&& !underline
) {
3298 sb
.append("\033[0;7;5;");
3299 } else if ( bold
&& !reverse
&& blink
&& !underline
) {
3300 sb
.append("\033[0;1;5;");
3301 } else if ( bold
&& !reverse
&& !blink
&& !underline
) {
3302 sb
.append("\033[0;1;");
3303 } else if ( !bold
&& reverse
&& !blink
&& !underline
) {
3304 sb
.append("\033[0;7;");
3305 } else if ( !bold
&& !reverse
&& blink
&& !underline
) {
3306 sb
.append("\033[0;5;");
3307 } else if ( bold
&& reverse
&& blink
&& underline
) {
3308 sb
.append("\033[0;1;7;5;4;");
3309 } else if ( bold
&& reverse
&& !blink
&& underline
) {
3310 sb
.append("\033[0;1;7;4;");
3311 } else if ( !bold
&& reverse
&& blink
&& underline
) {
3312 sb
.append("\033[0;7;5;4;");
3313 } else if ( bold
&& !reverse
&& blink
&& underline
) {
3314 sb
.append("\033[0;1;5;4;");
3315 } else if ( bold
&& !reverse
&& !blink
&& underline
) {
3316 sb
.append("\033[0;1;4;");
3317 } else if ( !bold
&& reverse
&& !blink
&& underline
) {
3318 sb
.append("\033[0;7;4;");
3319 } else if ( !bold
&& !reverse
&& blink
&& underline
) {
3320 sb
.append("\033[0;5;4;");
3321 } else if ( !bold
&& !reverse
&& !blink
&& underline
) {
3322 sb
.append("\033[0;4;");
3324 assert (!bold
&& !reverse
&& !blink
&& !underline
);
3325 sb
.append("\033[0;");
3328 sb
.append("m\033[38;2;");
3329 sb
.append(String
.format("%d;%d;%d", foreColorRed
, foreColorGreen
,
3331 sb
.append("m\033[48;2;");
3332 sb
.append(String
.format("%d;%d;%d", backColorRed
, backColorGreen
,
3335 return sb
.toString();
3339 * Create a SGR parameter sequence to reset to defaults.
3341 * @return the string to emit to an ANSI / ECMA-style terminal,
3344 private String
normal() {
3345 return normal(true) + rgbColor(false, Color
.WHITE
, Color
.BLACK
);
3349 * Create a SGR parameter sequence to reset to defaults.
3351 * @param header if true, make the full header, otherwise just emit the
3352 * bare parameter e.g. "0;"
3353 * @return the string to emit to an ANSI / ECMA-style terminal,
3356 private String
normal(final boolean header
) {
3358 return "\033[0;37;40m";
3364 * Create a SGR parameter sequence for enabling the visible cursor.
3366 * @param on if true, turn on cursor
3367 * @return the string to emit to an ANSI / ECMA-style terminal
3369 private String
cursor(final boolean on
) {
3370 if (on
&& !cursorOn
) {
3374 if (!on
&& cursorOn
) {
3382 * Clear the entire screen. Because some terminals use back-color-erase,
3383 * set the color to white-on-black beforehand.
3385 * @return the string to emit to an ANSI / ECMA-style terminal
3387 private String
clearAll() {
3388 return "\033[0;37;40m\033[2J";
3392 * Clear the line from the cursor (inclusive) to the end of the screen.
3393 * Because some terminals use back-color-erase, set the color to
3394 * white-on-black beforehand.
3396 * @return the string to emit to an ANSI / ECMA-style terminal
3398 private String
clearRemainingLine() {
3399 return "\033[0;37;40m\033[K";
3403 * Move the cursor to (x, y).
3405 * @param x column coordinate. 0 is the left-most column.
3406 * @param y row coordinate. 0 is the top-most row.
3407 * @return the string to emit to an ANSI / ECMA-style terminal
3409 private String
gotoXY(final int x
, final int y
) {
3410 return String
.format("\033[%d;%dH", y
+ 1, x
+ 1);
3414 * Tell (u)xterm that we want to receive mouse events based on "Any event
3415 * tracking", UTF-8 coordinates, and then SGR coordinates. Ideally we
3416 * will end up with SGR coordinates with UTF-8 coordinates as a fallback.
3418 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
3420 * Note that this also sets the alternate/primary screen buffer.
3422 * Finally, also emit a Privacy Message sequence that Jexer recognizes to
3423 * mean "hide the mouse pointer." We have to use our own sequence to do
3424 * this because there is no standard in xterm for unilaterally hiding the
3425 * pointer all the time (regardless of typing).
3427 * @param on If true, enable mouse report and use the alternate screen
3428 * buffer. If false disable mouse reporting and use the primary screen
3430 * @return the string to emit to xterm
3432 private String
mouse(final boolean on
) {
3434 return "\033[?1002;1003;1005;1006h\033[?1049h\033^hideMousePointer\033\\";
3436 return "\033[?1002;1003;1006;1005l\033[?1049l\033^showMousePointer\033\\";