sixelSharedPalette
[fanfix.git] / src / jexer / backend / ECMA48Terminal.java
1 /*
2 * Jexer - Java Text User Interface
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (C) 2019 Kevin Lamonte
7 *
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:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
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.
25 *
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
27 * @version 1
28 */
29 package jexer.backend;
30
31 import java.awt.image.BufferedImage;
32 import java.io.BufferedReader;
33 import java.io.ByteArrayOutputStream;
34 import java.io.FileDescriptor;
35 import java.io.FileInputStream;
36 import java.io.InputStream;
37 import java.io.InputStreamReader;
38 import java.io.IOException;
39 import java.io.OutputStream;
40 import java.io.OutputStreamWriter;
41 import java.io.PrintWriter;
42 import java.io.Reader;
43 import java.io.UnsupportedEncodingException;
44 import java.util.ArrayList;
45 import java.util.Collections;
46 import java.util.HashMap;
47 import java.util.List;
48 import javax.imageio.ImageIO;
49
50 import jexer.TImage;
51 import jexer.bits.Cell;
52 import jexer.bits.CellAttributes;
53 import jexer.bits.Color;
54 import jexer.event.TCommandEvent;
55 import jexer.event.TInputEvent;
56 import jexer.event.TKeypressEvent;
57 import jexer.event.TMouseEvent;
58 import jexer.event.TResizeEvent;
59 import static jexer.TCommand.*;
60 import static jexer.TKeypress.*;
61
62 /**
63 * This class reads keystrokes and mouse events and emits output to ANSI
64 * X3.64 / ECMA-48 type terminals e.g. xterm, linux, vt100, ansi.sys, etc.
65 */
66 public class ECMA48Terminal extends LogicalScreen
67 implements TerminalReader, Runnable {
68
69 // ------------------------------------------------------------------------
70 // Constants --------------------------------------------------------------
71 // ------------------------------------------------------------------------
72
73 /**
74 * States in the input parser.
75 */
76 private enum ParseState {
77 GROUND,
78 ESCAPE,
79 ESCAPE_INTERMEDIATE,
80 CSI_ENTRY,
81 CSI_PARAM,
82 MOUSE,
83 MOUSE_SGR,
84 }
85
86 /**
87 * Available Jexer images support.
88 */
89 private enum JexerImageOption {
90 DISABLED,
91 JPG,
92 PNG,
93 RGB,
94 }
95
96 // ------------------------------------------------------------------------
97 // Variables --------------------------------------------------------------
98 // ------------------------------------------------------------------------
99
100 /**
101 * Emit debugging to stderr.
102 */
103 private boolean debugToStderr = false;
104
105 /**
106 * If true, emit T.416-style RGB colors for normal system colors. This
107 * is a) expensive in bandwidth, and b) potentially terrible looking for
108 * non-xterms.
109 */
110 private static boolean doRgbColor = false;
111
112 /**
113 * The session information.
114 */
115 private SessionInfo sessionInfo;
116
117 /**
118 * The event queue, filled up by a thread reading on input.
119 */
120 private List<TInputEvent> eventQueue;
121
122 /**
123 * If true, we want the reader thread to exit gracefully.
124 */
125 private boolean stopReaderThread;
126
127 /**
128 * The reader thread.
129 */
130 private Thread readerThread;
131
132 /**
133 * Parameters being collected. E.g. if the string is \033[1;3m, then
134 * params[0] will be 1 and params[1] will be 3.
135 */
136 private List<String> params;
137
138 /**
139 * Current parsing state.
140 */
141 private ParseState state;
142
143 /**
144 * The time we entered ESCAPE. If we get a bare escape without a code
145 * following it, this is used to return that bare escape.
146 */
147 private long escapeTime;
148
149 /**
150 * The time we last checked the window size. We try not to spawn stty
151 * more than once per second.
152 */
153 private long windowSizeTime;
154
155 /**
156 * true if mouse1 was down. Used to report mouse1 on the release event.
157 */
158 private boolean mouse1;
159
160 /**
161 * true if mouse2 was down. Used to report mouse2 on the release event.
162 */
163 private boolean mouse2;
164
165 /**
166 * true if mouse3 was down. Used to report mouse3 on the release event.
167 */
168 private boolean mouse3;
169
170 /**
171 * Cache the cursor visibility value so we only emit the sequence when we
172 * need to.
173 */
174 private boolean cursorOn = true;
175
176 /**
177 * Cache the last window size to figure out if a TResizeEvent needs to be
178 * generated.
179 */
180 private TResizeEvent windowResize = null;
181
182 /**
183 * If true, emit wide-char (CJK/Emoji) characters as sixel images.
184 */
185 private boolean wideCharImages = true;
186
187 /**
188 * Window width in pixels. Used for sixel support.
189 */
190 private int widthPixels = 640;
191
192 /**
193 * Window height in pixels. Used for sixel support.
194 */
195 private int heightPixels = 400;
196
197 /**
198 * If true, emit image data via sixel.
199 */
200 private boolean sixel = true;
201
202 /**
203 * If true, use a single shared palette for sixel.
204 */
205 private boolean sixelSharedPalette = true;
206
207 /**
208 * The sixel palette handler.
209 */
210 private SixelPalette palette = null;
211
212 /**
213 * The sixel post-rendered string cache.
214 */
215 private ImageCache sixelCache = null;
216
217 /**
218 * Number of colors in the sixel palette. Xterm 335 defines the max as
219 * 1024. Valid values are: 2 (black and white), 256, 512, 1024, and
220 * 2048.
221 */
222 private int sixelPaletteSize = 1024;
223
224 /**
225 * If true, emit image data via iTerm2 image protocol.
226 */
227 private boolean iterm2Images = false;
228
229 /**
230 * The iTerm2 post-rendered string cache.
231 */
232 private ImageCache iterm2Cache = null;
233
234 /**
235 * If not DISABLED, emit image data via Jexer image protocol if the
236 * terminal supports it.
237 */
238 private JexerImageOption jexerImageOption = JexerImageOption.JPG;
239
240 /**
241 * The Jexer post-rendered string cache.
242 */
243 private ImageCache jexerCache = null;
244
245 /**
246 * Base64 encoder used by iTerm2 and Jexer images.
247 */
248 private java.util.Base64.Encoder base64 = null;
249
250 /**
251 * If true, then we changed System.in and need to change it back.
252 */
253 private boolean setRawMode = false;
254
255 /**
256 * If true, '?' was seen in terminal response.
257 */
258 private boolean decPrivateModeFlag = false;
259
260 /**
261 * The terminal's input. If an InputStream is not specified in the
262 * constructor, then this InputStreamReader will be bound to System.in
263 * with UTF-8 encoding.
264 */
265 private Reader input;
266
267 /**
268 * The terminal's raw InputStream. If an InputStream is not specified in
269 * the constructor, then this InputReader will be bound to System.in.
270 * This is used by run() to see if bytes are available() before calling
271 * (Reader)input.read().
272 */
273 private InputStream inputStream;
274
275 /**
276 * The terminal's output. If an OutputStream is not specified in the
277 * constructor, then this PrintWriter will be bound to System.out with
278 * UTF-8 encoding.
279 */
280 private PrintWriter output;
281
282 /**
283 * The listening object that run() wakes up on new input.
284 */
285 private Object listener;
286
287 // Colors to map DOS colors to AWT colors.
288 private static java.awt.Color MYBLACK;
289 private static java.awt.Color MYRED;
290 private static java.awt.Color MYGREEN;
291 private static java.awt.Color MYYELLOW;
292 private static java.awt.Color MYBLUE;
293 private static java.awt.Color MYMAGENTA;
294 private static java.awt.Color MYCYAN;
295 private static java.awt.Color MYWHITE;
296 private static java.awt.Color MYBOLD_BLACK;
297 private static java.awt.Color MYBOLD_RED;
298 private static java.awt.Color MYBOLD_GREEN;
299 private static java.awt.Color MYBOLD_YELLOW;
300 private static java.awt.Color MYBOLD_BLUE;
301 private static java.awt.Color MYBOLD_MAGENTA;
302 private static java.awt.Color MYBOLD_CYAN;
303 private static java.awt.Color MYBOLD_WHITE;
304
305 /**
306 * SixelPalette is used to manage the conversion of images between 24-bit
307 * RGB color and a palette of sixelPaletteSize colors.
308 */
309 private class SixelPalette {
310
311 /**
312 * Color palette for sixel output, sorted low to high.
313 */
314 private List<Integer> rgbColors = new ArrayList<Integer>();
315
316 /**
317 * Map of color palette index for sixel output, from the order it was
318 * generated by makePalette() to rgbColors.
319 */
320 private int [] rgbSortedIndex = new int[sixelPaletteSize];
321
322 /**
323 * The color palette, organized by hue, saturation, and luminance.
324 * This is used for a fast color match.
325 */
326 private ArrayList<ArrayList<ArrayList<ColorIdx>>> hslColors;
327
328 /**
329 * Number of bits for hue.
330 */
331 private int hueBits = -1;
332
333 /**
334 * Number of bits for saturation.
335 */
336 private int satBits = -1;
337
338 /**
339 * Number of bits for luminance.
340 */
341 private int lumBits = -1;
342
343 /**
344 * Step size for hue bins.
345 */
346 private int hueStep = -1;
347
348 /**
349 * Step size for saturation bins.
350 */
351 private int satStep = -1;
352
353 /**
354 * Cached RGB to HSL result.
355 */
356 private int hsl[] = new int[3];
357
358 /**
359 * ColorIdx records a RGB color and its palette index.
360 */
361 private class ColorIdx {
362 /**
363 * The 24-bit RGB color.
364 */
365 public int color;
366
367 /**
368 * The palette index for this color.
369 */
370 public int index;
371
372 /**
373 * Public constructor.
374 *
375 * @param color the 24-bit RGB color
376 * @param index the palette index for this color
377 */
378 public ColorIdx(final int color, final int index) {
379 this.color = color;
380 this.index = index;
381 }
382 }
383
384 /**
385 * Public constructor.
386 */
387 public SixelPalette() {
388 makePalette();
389 }
390
391 /**
392 * Find the nearest match for a color in the palette.
393 *
394 * @param color the RGB color
395 * @return the index in rgbColors that is closest to color
396 */
397 public int matchColor(final int color) {
398
399 assert (color >= 0);
400
401 /*
402 * matchColor() is a critical performance bottleneck. To make it
403 * decent, we do the following:
404 *
405 * 1. Find the nearest two hues that bracket this color.
406 *
407 * 2. Find the nearest two saturations that bracket this color.
408 *
409 * 3. Iterate within these four bands of luminance values,
410 * returning the closest color by Euclidean distance.
411 *
412 * This strategy reduces the search space by about 97%.
413 */
414 int red = (color >>> 16) & 0xFF;
415 int green = (color >>> 8) & 0xFF;
416 int blue = color & 0xFF;
417
418 if (sixelPaletteSize == 2) {
419 if (((red * red) + (green * green) + (blue * blue)) < 35568) {
420 // Black
421 return 0;
422 }
423 // White
424 return 1;
425 }
426
427
428 rgbToHsl(red, green, blue, hsl);
429 int hue = hsl[0];
430 int sat = hsl[1];
431 int lum = hsl[2];
432 // System.err.printf("%d %d %d\n", hue, sat, lum);
433
434 double diff = Double.MAX_VALUE;
435 int idx = -1;
436
437 int hue1 = hue / (360/hueStep);
438 int hue2 = hue1 + 1;
439 if (hue1 >= hslColors.size() - 1) {
440 // Bracket pure red from above.
441 hue1 = hslColors.size() - 1;
442 hue2 = 0;
443 } else if (hue1 == 0) {
444 // Bracket pure red from below.
445 hue2 = hslColors.size() - 1;
446 }
447
448 for (int hI = hue1; hI != -1;) {
449 ArrayList<ArrayList<ColorIdx>> sats = hslColors.get(hI);
450 if (hI == hue1) {
451 hI = hue2;
452 } else if (hI == hue2) {
453 hI = -1;
454 }
455
456 int sMin = (sat / satStep) - 1;
457 int sMax = sMin + 1;
458 if (sMin < 0) {
459 sMin = 0;
460 sMax = 1;
461 } else if (sMin == sats.size() - 1) {
462 sMax = sMin;
463 sMin--;
464 }
465 assert (sMin >= 0);
466 assert (sMax - sMin == 1);
467
468 // int sMin = 0;
469 // int sMax = sats.size() - 1;
470
471 for (int sI = sMin; sI <= sMax; sI++) {
472 ArrayList<ColorIdx> lums = sats.get(sI);
473
474 // True 3D colorspace match for the remaining values
475 for (ColorIdx c: lums) {
476 int rgbColor = c.color;
477 double newDiff = 0;
478 int red2 = (rgbColor >>> 16) & 0xFF;
479 int green2 = (rgbColor >>> 8) & 0xFF;
480 int blue2 = rgbColor & 0xFF;
481 newDiff += Math.pow(red2 - red, 2);
482 newDiff += Math.pow(green2 - green, 2);
483 newDiff += Math.pow(blue2 - blue, 2);
484 if (newDiff < diff) {
485 idx = rgbSortedIndex[c.index];
486 diff = newDiff;
487 }
488 }
489 }
490 }
491
492 if (((red * red) + (green * green) + (blue * blue)) < diff) {
493 // Black is a closer match.
494 idx = 0;
495 } else if ((((255 - red) * (255 - red)) +
496 ((255 - green) * (255 - green)) +
497 ((255 - blue) * (255 - blue))) < diff) {
498
499 // White is a closer match.
500 idx = sixelPaletteSize - 1;
501 }
502 assert (idx != -1);
503 return idx;
504 }
505
506 /**
507 * Clamp an int value to [0, 255].
508 *
509 * @param x the int value
510 * @return an int between 0 and 255.
511 */
512 private int clamp(final int x) {
513 if (x < 0) {
514 return 0;
515 }
516 if (x > 255) {
517 return 255;
518 }
519 return x;
520 }
521
522 /**
523 * Dither an image to a sixelPaletteSize palette. The dithered
524 * image cells will contain indexes into the palette.
525 *
526 * @param image the image to dither
527 * @return the dithered image. Every pixel is an index into the
528 * palette.
529 */
530 public BufferedImage ditherImage(final BufferedImage image) {
531
532 BufferedImage ditheredImage = new BufferedImage(image.getWidth(),
533 image.getHeight(), BufferedImage.TYPE_INT_ARGB);
534
535 int [] rgbArray = image.getRGB(0, 0, image.getWidth(),
536 image.getHeight(), null, 0, image.getWidth());
537 ditheredImage.setRGB(0, 0, image.getWidth(), image.getHeight(),
538 rgbArray, 0, image.getWidth());
539
540 for (int imageY = 0; imageY < image.getHeight(); imageY++) {
541 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
542 int oldPixel = ditheredImage.getRGB(imageX,
543 imageY) & 0xFFFFFF;
544 int colorIdx = matchColor(oldPixel);
545 assert (colorIdx >= 0);
546 assert (colorIdx < sixelPaletteSize);
547 int newPixel = rgbColors.get(colorIdx);
548 ditheredImage.setRGB(imageX, imageY, colorIdx);
549
550 int oldRed = (oldPixel >>> 16) & 0xFF;
551 int oldGreen = (oldPixel >>> 8) & 0xFF;
552 int oldBlue = oldPixel & 0xFF;
553
554 int newRed = (newPixel >>> 16) & 0xFF;
555 int newGreen = (newPixel >>> 8) & 0xFF;
556 int newBlue = newPixel & 0xFF;
557
558 int redError = (oldRed - newRed) / 16;
559 int greenError = (oldGreen - newGreen) / 16;
560 int blueError = (oldBlue - newBlue) / 16;
561
562 int red, green, blue;
563 if (imageX < image.getWidth() - 1) {
564 int pXpY = ditheredImage.getRGB(imageX + 1, imageY);
565 red = ((pXpY >>> 16) & 0xFF) + (7 * redError);
566 green = ((pXpY >>> 8) & 0xFF) + (7 * greenError);
567 blue = ( pXpY & 0xFF) + (7 * blueError);
568 red = clamp(red);
569 green = clamp(green);
570 blue = clamp(blue);
571 pXpY = ((red & 0xFF) << 16);
572 pXpY |= ((green & 0xFF) << 8) | (blue & 0xFF);
573 ditheredImage.setRGB(imageX + 1, imageY, pXpY);
574
575 if (imageY < image.getHeight() - 1) {
576 int pXpYp = ditheredImage.getRGB(imageX + 1,
577 imageY + 1);
578 red = ((pXpYp >>> 16) & 0xFF) + redError;
579 green = ((pXpYp >>> 8) & 0xFF) + greenError;
580 blue = ( pXpYp & 0xFF) + blueError;
581 red = clamp(red);
582 green = clamp(green);
583 blue = clamp(blue);
584 pXpYp = ((red & 0xFF) << 16);
585 pXpYp |= ((green & 0xFF) << 8) | (blue & 0xFF);
586 ditheredImage.setRGB(imageX + 1, imageY + 1, pXpYp);
587 }
588 } else if (imageY < image.getHeight() - 1) {
589 int pXmYp = ditheredImage.getRGB(imageX - 1,
590 imageY + 1);
591 int pXYp = ditheredImage.getRGB(imageX,
592 imageY + 1);
593
594 red = ((pXmYp >>> 16) & 0xFF) + (3 * redError);
595 green = ((pXmYp >>> 8) & 0xFF) + (3 * greenError);
596 blue = ( pXmYp & 0xFF) + (3 * blueError);
597 red = clamp(red);
598 green = clamp(green);
599 blue = clamp(blue);
600 pXmYp = ((red & 0xFF) << 16);
601 pXmYp |= ((green & 0xFF) << 8) | (blue & 0xFF);
602 ditheredImage.setRGB(imageX - 1, imageY + 1, pXmYp);
603
604 red = ((pXYp >>> 16) & 0xFF) + (5 * redError);
605 green = ((pXYp >>> 8) & 0xFF) + (5 * greenError);
606 blue = ( pXYp & 0xFF) + (5 * blueError);
607 red = clamp(red);
608 green = clamp(green);
609 blue = clamp(blue);
610 pXYp = ((red & 0xFF) << 16);
611 pXYp |= ((green & 0xFF) << 8) | (blue & 0xFF);
612 ditheredImage.setRGB(imageX, imageY + 1, pXYp);
613 }
614 } // for (int imageY = 0; imageY < image.getHeight(); imageY++)
615 } // for (int imageX = 0; imageX < image.getWidth(); imageX++)
616
617 return ditheredImage;
618 }
619
620 /**
621 * Convert an RGB color to HSL.
622 *
623 * @param red red color, between 0 and 255
624 * @param green green color, between 0 and 255
625 * @param blue blue color, between 0 and 255
626 * @param hsl the hsl color as [hue, saturation, luminance]
627 */
628 private void rgbToHsl(final int red, final int green,
629 final int blue, final int [] hsl) {
630
631 assert ((red >= 0) && (red <= 255));
632 assert ((green >= 0) && (green <= 255));
633 assert ((blue >= 0) && (blue <= 255));
634
635 double R = red / 255.0;
636 double G = green / 255.0;
637 double B = blue / 255.0;
638 boolean Rmax = false;
639 boolean Gmax = false;
640 boolean Bmax = false;
641 double min = (R < G ? R : G);
642 min = (min < B ? min : B);
643 double max = 0;
644 if ((R >= G) && (R >= B)) {
645 max = R;
646 Rmax = true;
647 } else if ((G >= R) && (G >= B)) {
648 max = G;
649 Gmax = true;
650 } else if ((B >= G) && (B >= R)) {
651 max = B;
652 Bmax = true;
653 }
654
655 double L = (min + max) / 2.0;
656 double H = 0.0;
657 double S = 0.0;
658 if (min != max) {
659 if (L < 0.5) {
660 S = (max - min) / (max + min);
661 } else {
662 S = (max - min) / (2.0 - max - min);
663 }
664 }
665 if (Rmax) {
666 assert (Gmax == false);
667 assert (Bmax == false);
668 H = (G - B) / (max - min);
669 } else if (Gmax) {
670 assert (Rmax == false);
671 assert (Bmax == false);
672 H = 2.0 + (B - R) / (max - min);
673 } else if (Bmax) {
674 assert (Rmax == false);
675 assert (Gmax == false);
676 H = 4.0 + (R - G) / (max - min);
677 }
678 if (H < 0.0) {
679 H += 6.0;
680 }
681 hsl[0] = (int) (H * 60.0);
682 hsl[1] = (int) (S * 100.0);
683 hsl[2] = (int) (L * 100.0);
684
685 assert ((hsl[0] >= 0) && (hsl[0] <= 360));
686 assert ((hsl[1] >= 0) && (hsl[1] <= 100));
687 assert ((hsl[2] >= 0) && (hsl[2] <= 100));
688 }
689
690 /**
691 * Convert a HSL color to RGB.
692 *
693 * @param hue hue, between 0 and 359
694 * @param sat saturation, between 0 and 100
695 * @param lum luminance, between 0 and 100
696 * @return the rgb color as 0x00RRGGBB
697 */
698 private int hslToRgb(final int hue, final int sat, final int lum) {
699 assert ((hue >= 0) && (hue <= 360));
700 assert ((sat >= 0) && (sat <= 100));
701 assert ((lum >= 0) && (lum <= 100));
702
703 double S = sat / 100.0;
704 double L = lum / 100.0;
705 double C = (1.0 - Math.abs((2.0 * L) - 1.0)) * S;
706 double Hp = hue / 60.0;
707 double X = C * (1.0 - Math.abs((Hp % 2) - 1.0));
708 double Rp = 0.0;
709 double Gp = 0.0;
710 double Bp = 0.0;
711 if (Hp <= 1.0) {
712 Rp = C;
713 Gp = X;
714 } else if (Hp <= 2.0) {
715 Rp = X;
716 Gp = C;
717 } else if (Hp <= 3.0) {
718 Gp = C;
719 Bp = X;
720 } else if (Hp <= 4.0) {
721 Gp = X;
722 Bp = C;
723 } else if (Hp <= 5.0) {
724 Rp = X;
725 Bp = C;
726 } else if (Hp <= 6.0) {
727 Rp = C;
728 Bp = X;
729 }
730 double m = L - (C / 2.0);
731 int red = ((int) ((Rp + m) * 255.0)) << 16;
732 int green = ((int) ((Gp + m) * 255.0)) << 8;
733 int blue = (int) ((Bp + m) * 255.0);
734
735 return (red | green | blue);
736 }
737
738 /**
739 * Create the sixel palette.
740 */
741 private void makePalette() {
742 // Generate the sixel palette. Because we have no idea at this
743 // layer which image(s) will be shown, we have to use a common
744 // palette with sixelPaletteSize colors for everything, and
745 // map the BufferedImage colors to their nearest neighbor in RGB
746 // space.
747
748 if (sixelPaletteSize == 2) {
749 rgbColors.add(0);
750 rgbColors.add(0xFFFFFF);
751 rgbSortedIndex[0] = 0;
752 rgbSortedIndex[1] = 1;
753 return;
754 }
755
756 // We build a palette using the Hue-Saturation-Luminence model,
757 // with 5+ bits for Hue, 2+ bits for Saturation, and 1+ bit for
758 // Luminance. We convert these colors to 24-bit RGB, sort them
759 // ascending, and steal the first index for pure black and the
760 // last for pure white. The 8-bit final palette favors bright
761 // colors, somewhere between pastel and classic television
762 // technicolor. 9- and 10-bit palettes are more uniform.
763
764 // Default at 256 colors.
765 hueBits = 5;
766 satBits = 2;
767 lumBits = 1;
768
769 assert (sixelPaletteSize >= 256);
770 assert ((sixelPaletteSize == 256)
771 || (sixelPaletteSize == 512)
772 || (sixelPaletteSize == 1024)
773 || (sixelPaletteSize == 2048));
774
775 switch (sixelPaletteSize) {
776 case 512:
777 hueBits = 5;
778 satBits = 2;
779 lumBits = 2;
780 break;
781 case 1024:
782 hueBits = 5;
783 satBits = 2;
784 lumBits = 3;
785 break;
786 case 2048:
787 hueBits = 5;
788 satBits = 3;
789 lumBits = 3;
790 break;
791 }
792 hueStep = (int) (Math.pow(2, hueBits));
793 satStep = (int) (100 / Math.pow(2, satBits));
794 // 1 bit for luminance: 40 and 70.
795 int lumBegin = 40;
796 int lumStep = 30;
797 switch (lumBits) {
798 case 2:
799 // 2 bits: 20, 40, 60, 80
800 lumBegin = 20;
801 lumStep = 20;
802 break;
803 case 3:
804 // 3 bits: 8, 20, 32, 44, 56, 68, 80, 92
805 lumBegin = 8;
806 lumStep = 12;
807 break;
808 }
809
810 // System.err.printf("<html><body>\n");
811 // Hue is evenly spaced around the wheel.
812 hslColors = new ArrayList<ArrayList<ArrayList<ColorIdx>>>();
813
814 final boolean DEBUG = false;
815 ArrayList<Integer> rawRgbList = new ArrayList<Integer>();
816
817 for (int hue = 0; hue < (360 - (360 % hueStep));
818 hue += (360/hueStep)) {
819
820 ArrayList<ArrayList<ColorIdx>> satList = null;
821 satList = new ArrayList<ArrayList<ColorIdx>>();
822 hslColors.add(satList);
823
824 // Saturation is linearly spaced between pastel and pure.
825 for (int sat = satStep; sat <= 100; sat += satStep) {
826
827 ArrayList<ColorIdx> lumList = new ArrayList<ColorIdx>();
828 satList.add(lumList);
829
830 // Luminance brackets the pure color, but leaning toward
831 // lighter.
832 for (int lum = lumBegin; lum < 100; lum += lumStep) {
833 /*
834 System.err.printf("<font style = \"color:");
835 System.err.printf("hsl(%d, %d%%, %d%%)",
836 hue, sat, lum);
837 System.err.printf(";\">=</font>\n");
838 */
839 int rgbColor = hslToRgb(hue, sat, lum);
840 rgbColors.add(rgbColor);
841 ColorIdx colorIdx = new ColorIdx(rgbColor,
842 rgbColors.size() - 1);
843 lumList.add(colorIdx);
844
845 rawRgbList.add(rgbColor);
846 if (DEBUG) {
847 int red = (rgbColor >>> 16) & 0xFF;
848 int green = (rgbColor >>> 8) & 0xFF;
849 int blue = rgbColor & 0xFF;
850 int [] backToHsl = new int[3];
851 rgbToHsl(red, green, blue, backToHsl);
852 System.err.printf("%d [%d] %d [%d] %d [%d]\n",
853 hue, backToHsl[0], sat, backToHsl[1],
854 lum, backToHsl[2]);
855 }
856 }
857 }
858 }
859 // System.err.printf("\n</body></html>\n");
860
861 assert (rgbColors.size() == sixelPaletteSize);
862
863 /*
864 * We need to sort rgbColors, so that toSixel() can know where
865 * BLACK and WHITE are in it. But we also need to be able to
866 * find the sorted values using the old unsorted indexes. So we
867 * will sort it, put all the indexes into a HashMap, and then
868 * build rgbSortedIndex[].
869 */
870 Collections.sort(rgbColors);
871 HashMap<Integer, Integer> rgbColorIndices = null;
872 rgbColorIndices = new HashMap<Integer, Integer>();
873 for (int i = 0; i < sixelPaletteSize; i++) {
874 rgbColorIndices.put(rgbColors.get(i), i);
875 }
876 for (int i = 0; i < sixelPaletteSize; i++) {
877 int rawColor = rawRgbList.get(i);
878 rgbSortedIndex[i] = rgbColorIndices.get(rawColor);
879 }
880 if (DEBUG) {
881 for (int i = 0; i < sixelPaletteSize; i++) {
882 assert (rawRgbList != null);
883 int idx = rgbSortedIndex[i];
884 int rgbColor = rgbColors.get(idx);
885 if ((idx != 0) && (idx != sixelPaletteSize - 1)) {
886 /*
887 System.err.printf("%d %06x --> %d %06x\n",
888 i, rawRgbList.get(i), idx, rgbColors.get(idx));
889 */
890 assert (rgbColor == rawRgbList.get(i));
891 }
892 }
893 }
894
895 // Set the dimmest color as true black, and the brightest as true
896 // white.
897 rgbColors.set(0, 0);
898 rgbColors.set(sixelPaletteSize - 1, 0xFFFFFF);
899
900 /*
901 System.err.printf("<html><body>\n");
902 for (Integer rgb: rgbColors) {
903 System.err.printf("<font style = \"color:");
904 System.err.printf("#%06x", rgb);
905 System.err.printf(";\">=</font>\n");
906 }
907 System.err.printf("\n</body></html>\n");
908 */
909
910 }
911
912 /**
913 * Emit the sixel palette.
914 *
915 * @param sb the StringBuilder to append to
916 * @param used array of booleans set to true for each color actually
917 * used in this cell, or null to emit the entire palette
918 * @return the string to emit to an ANSI / ECMA-style terminal
919 */
920 public String emitPalette(final StringBuilder sb,
921 final boolean [] used) {
922
923 for (int i = 0; i < sixelPaletteSize; i++) {
924 if (((used != null) && (used[i] == true)) || (used == null)) {
925 int rgbColor = rgbColors.get(i);
926 sb.append(String.format("#%d;2;%d;%d;%d", i,
927 ((rgbColor >>> 16) & 0xFF) * 100 / 255,
928 ((rgbColor >>> 8) & 0xFF) * 100 / 255,
929 ( rgbColor & 0xFF) * 100 / 255));
930 }
931 }
932 return sb.toString();
933 }
934 }
935
936 /**
937 * ImageCache is a least-recently-used cache that hangs on to the
938 * post-rendered sixel or iTerm2 string for a particular set of cells.
939 */
940 private class ImageCache {
941
942 /**
943 * Maximum size of the cache.
944 */
945 private int maxSize = 100;
946
947 /**
948 * The entries stored in the cache.
949 */
950 private HashMap<String, CacheEntry> cache = null;
951
952 /**
953 * CacheEntry is one entry in the cache.
954 */
955 private class CacheEntry {
956 /**
957 * The cache key.
958 */
959 public String key;
960
961 /**
962 * The cache data.
963 */
964 public String data;
965
966 /**
967 * The last time this entry was used.
968 */
969 public long millis = 0;
970
971 /**
972 * Public constructor.
973 *
974 * @param key the cache entry key
975 * @param data the cache entry data
976 */
977 public CacheEntry(final String key, final String data) {
978 this.key = key;
979 this.data = data;
980 this.millis = System.currentTimeMillis();
981 }
982 }
983
984 /**
985 * Public constructor.
986 *
987 * @param maxSize the maximum size of the cache
988 */
989 public ImageCache(final int maxSize) {
990 this.maxSize = maxSize;
991 cache = new HashMap<String, CacheEntry>();
992 }
993
994 /**
995 * Make a unique key for a list of cells.
996 *
997 * @param cells the cells
998 * @return the key
999 */
1000 private String makeKey(final ArrayList<Cell> cells) {
1001 StringBuilder sb = new StringBuilder();
1002 for (Cell cell: cells) {
1003 sb.append(cell.hashCode());
1004 }
1005 return sb.toString();
1006 }
1007
1008 /**
1009 * Get an entry from the cache.
1010 *
1011 * @param cells the list of cells that are the cache key
1012 * @return the sixel string representing these cells, or null if this
1013 * list of cells is not in the cache
1014 */
1015 public String get(final ArrayList<Cell> cells) {
1016 CacheEntry entry = cache.get(makeKey(cells));
1017 if (entry == null) {
1018 return null;
1019 }
1020 entry.millis = System.currentTimeMillis();
1021 return entry.data;
1022 }
1023
1024 /**
1025 * Put an entry into the cache.
1026 *
1027 * @param cells the list of cells that are the cache key
1028 * @param data the sixel string representing these cells
1029 */
1030 public void put(final ArrayList<Cell> cells, final String data) {
1031 String key = makeKey(cells);
1032
1033 // System.err.println("put() " + key + " size " + cache.size());
1034
1035 assert (!cache.containsKey(key));
1036
1037 assert (cache.size() <= maxSize);
1038 if (cache.size() == maxSize) {
1039 // Cache is at limit, evict oldest entry.
1040 long oldestTime = Long.MAX_VALUE;
1041 String keyToRemove = null;
1042 for (CacheEntry entry: cache.values()) {
1043 if ((entry.millis < oldestTime) || (keyToRemove == null)) {
1044 keyToRemove = entry.key;
1045 oldestTime = entry.millis;
1046 }
1047 }
1048 /*
1049 System.err.println("put() remove key = " + keyToRemove +
1050 " size " + cache.size());
1051 */
1052 assert (keyToRemove != null);
1053 cache.remove(keyToRemove);
1054 /*
1055 System.err.println("put() removed, size " + cache.size());
1056 */
1057 }
1058 assert (cache.size() <= maxSize);
1059 CacheEntry entry = new CacheEntry(key, data);
1060 assert (key.equals(entry.key));
1061 cache.put(key, entry);
1062 /*
1063 System.err.println("put() added key " + key + " " +
1064 " size " + cache.size());
1065 */
1066 }
1067
1068 }
1069
1070 // ------------------------------------------------------------------------
1071 // Constructors -----------------------------------------------------------
1072 // ------------------------------------------------------------------------
1073
1074 /**
1075 * Constructor sets up state for getEvent(). If either windowWidth or
1076 * windowHeight are less than 1, the terminal is not resized.
1077 *
1078 * @param listener the object this backend needs to wake up when new
1079 * input comes in
1080 * @param input an InputStream connected to the remote user, or null for
1081 * System.in. If System.in is used, then on non-Windows systems it will
1082 * be put in raw mode; closeTerminal() will (blindly!) put System.in in
1083 * cooked mode. input is always converted to a Reader with UTF-8
1084 * encoding.
1085 * @param output an OutputStream connected to the remote user, or null
1086 * for System.out. output is always converted to a Writer with UTF-8
1087 * encoding.
1088 * @param windowWidth the number of text columns to start with
1089 * @param windowHeight the number of text rows to start with
1090 * @throws UnsupportedEncodingException if an exception is thrown when
1091 * creating the InputStreamReader
1092 */
1093 public ECMA48Terminal(final Object listener, final InputStream input,
1094 final OutputStream output, final int windowWidth,
1095 final int windowHeight) throws UnsupportedEncodingException {
1096
1097 this(listener, input, output);
1098
1099 // Send dtterm/xterm sequences, which will probably not work because
1100 // allowWindowOps is defaulted to false.
1101 if ((windowWidth > 0) && (windowHeight > 0)) {
1102 String resizeString = String.format("\033[8;%d;%dt", windowHeight,
1103 windowWidth);
1104 this.output.write(resizeString);
1105 this.output.flush();
1106 }
1107 }
1108
1109 /**
1110 * Constructor sets up state for getEvent().
1111 *
1112 * @param listener the object this backend needs to wake up when new
1113 * input comes in
1114 * @param input an InputStream connected to the remote user, or null for
1115 * System.in. If System.in is used, then on non-Windows systems it will
1116 * be put in raw mode; closeTerminal() will (blindly!) put System.in in
1117 * cooked mode. input is always converted to a Reader with UTF-8
1118 * encoding.
1119 * @param output an OutputStream connected to the remote user, or null
1120 * for System.out. output is always converted to a Writer with UTF-8
1121 * encoding.
1122 * @throws UnsupportedEncodingException if an exception is thrown when
1123 * creating the InputStreamReader
1124 */
1125 public ECMA48Terminal(final Object listener, final InputStream input,
1126 final OutputStream output) throws UnsupportedEncodingException {
1127
1128 resetParser();
1129 mouse1 = false;
1130 mouse2 = false;
1131 mouse3 = false;
1132 stopReaderThread = false;
1133 this.listener = listener;
1134
1135 if (input == null) {
1136 // inputStream = System.in;
1137 inputStream = new FileInputStream(FileDescriptor.in);
1138 sttyRaw();
1139 setRawMode = true;
1140 } else {
1141 inputStream = input;
1142 }
1143 this.input = new InputStreamReader(inputStream, "UTF-8");
1144
1145 if (input instanceof SessionInfo) {
1146 // This is a TelnetInputStream that exposes window size and
1147 // environment variables from the telnet layer.
1148 sessionInfo = (SessionInfo) input;
1149 }
1150 if (sessionInfo == null) {
1151 if (input == null) {
1152 // Reading right off the tty
1153 sessionInfo = new TTYSessionInfo();
1154 } else {
1155 sessionInfo = new TSessionInfo();
1156 }
1157 }
1158
1159 if (output == null) {
1160 this.output = new PrintWriter(new OutputStreamWriter(System.out,
1161 "UTF-8"));
1162 } else {
1163 this.output = new PrintWriter(new OutputStreamWriter(output,
1164 "UTF-8"));
1165 }
1166
1167 // Request Device Attributes
1168 this.output.printf("\033[c");
1169
1170 // Request xterm report window/cell dimensions in pixels
1171 this.output.printf("%s", xtermReportPixelDimensions());
1172
1173 // Enable mouse reporting and metaSendsEscape
1174 this.output.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
1175 this.output.flush();
1176
1177 // Request xterm use the sixel settings we want
1178 this.output.printf("%s", xtermSetSixelSettings());
1179
1180 // Query the screen size
1181 sessionInfo.queryWindowSize();
1182 setDimensions(sessionInfo.getWindowWidth(),
1183 sessionInfo.getWindowHeight());
1184
1185 // Hang onto the window size
1186 windowResize = new TResizeEvent(TResizeEvent.Type.SCREEN,
1187 sessionInfo.getWindowWidth(), sessionInfo.getWindowHeight());
1188
1189 reloadOptions();
1190
1191 // Spin up the input reader
1192 eventQueue = new ArrayList<TInputEvent>();
1193 readerThread = new Thread(this);
1194 readerThread.start();
1195
1196 // Clear the screen
1197 this.output.write(clearAll());
1198 this.output.flush();
1199 }
1200
1201 /**
1202 * Constructor sets up state for getEvent().
1203 *
1204 * @param listener the object this backend needs to wake up when new
1205 * input comes in
1206 * @param input the InputStream underlying 'reader'. Its available()
1207 * method is used to determine if reader.read() will block or not.
1208 * @param reader a Reader connected to the remote user.
1209 * @param writer a PrintWriter connected to the remote user.
1210 * @param setRawMode if true, set System.in into raw mode with stty.
1211 * This should in general not be used. It is here solely for Demo3,
1212 * which uses System.in.
1213 * @throws IllegalArgumentException if input, reader, or writer are null.
1214 */
1215 public ECMA48Terminal(final Object listener, final InputStream input,
1216 final Reader reader, final PrintWriter writer,
1217 final boolean setRawMode) {
1218
1219 if (input == null) {
1220 throw new IllegalArgumentException("InputStream must be specified");
1221 }
1222 if (reader == null) {
1223 throw new IllegalArgumentException("Reader must be specified");
1224 }
1225 if (writer == null) {
1226 throw new IllegalArgumentException("Writer must be specified");
1227 }
1228 resetParser();
1229 mouse1 = false;
1230 mouse2 = false;
1231 mouse3 = false;
1232 stopReaderThread = false;
1233 this.listener = listener;
1234
1235 inputStream = input;
1236 this.input = reader;
1237
1238 if (setRawMode == true) {
1239 sttyRaw();
1240 }
1241 this.setRawMode = setRawMode;
1242
1243 if (input instanceof SessionInfo) {
1244 // This is a TelnetInputStream that exposes window size and
1245 // environment variables from the telnet layer.
1246 sessionInfo = (SessionInfo) input;
1247 }
1248 if (sessionInfo == null) {
1249 if (setRawMode == true) {
1250 // Reading right off the tty
1251 sessionInfo = new TTYSessionInfo();
1252 } else {
1253 sessionInfo = new TSessionInfo();
1254 }
1255 }
1256
1257 this.output = writer;
1258
1259 // Request Device Attributes
1260 this.output.printf("\033[c");
1261
1262 // Request xterm report window/cell dimensions in pixels
1263 this.output.printf("%s", xtermReportPixelDimensions());
1264
1265 // Enable mouse reporting and metaSendsEscape
1266 this.output.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
1267 this.output.flush();
1268
1269 // Request xterm use the sixel settings we want
1270 this.output.printf("%s", xtermSetSixelSettings());
1271
1272 // Query the screen size
1273 sessionInfo.queryWindowSize();
1274 setDimensions(sessionInfo.getWindowWidth(),
1275 sessionInfo.getWindowHeight());
1276
1277 // Hang onto the window size
1278 windowResize = new TResizeEvent(TResizeEvent.Type.SCREEN,
1279 sessionInfo.getWindowWidth(), sessionInfo.getWindowHeight());
1280
1281 reloadOptions();
1282
1283 // Spin up the input reader
1284 eventQueue = new ArrayList<TInputEvent>();
1285 readerThread = new Thread(this);
1286 readerThread.start();
1287
1288 // Clear the screen
1289 this.output.write(clearAll());
1290 this.output.flush();
1291 }
1292
1293 /**
1294 * Constructor sets up state for getEvent().
1295 *
1296 * @param listener the object this backend needs to wake up when new
1297 * input comes in
1298 * @param input the InputStream underlying 'reader'. Its available()
1299 * method is used to determine if reader.read() will block or not.
1300 * @param reader a Reader connected to the remote user.
1301 * @param writer a PrintWriter connected to the remote user.
1302 * @throws IllegalArgumentException if input, reader, or writer are null.
1303 */
1304 public ECMA48Terminal(final Object listener, final InputStream input,
1305 final Reader reader, final PrintWriter writer) {
1306
1307 this(listener, input, reader, writer, false);
1308 }
1309
1310 // ------------------------------------------------------------------------
1311 // LogicalScreen ----------------------------------------------------------
1312 // ------------------------------------------------------------------------
1313
1314 /**
1315 * Set the window title.
1316 *
1317 * @param title the new title
1318 */
1319 @Override
1320 public void setTitle(final String title) {
1321 output.write(getSetTitleString(title));
1322 flush();
1323 }
1324
1325 /**
1326 * Push the logical screen to the physical device.
1327 */
1328 @Override
1329 public void flushPhysical() {
1330 StringBuilder sb = new StringBuilder();
1331 if ((cursorVisible)
1332 && (cursorY >= 0)
1333 && (cursorX >= 0)
1334 && (cursorY <= height - 1)
1335 && (cursorX <= width - 1)
1336 ) {
1337 flushString(sb);
1338 sb.append(cursor(true));
1339 sb.append(gotoXY(cursorX, cursorY));
1340 } else {
1341 sb.append(cursor(false));
1342 flushString(sb);
1343 }
1344 output.write(sb.toString());
1345 flush();
1346 }
1347
1348 /**
1349 * Resize the physical screen to match the logical screen dimensions.
1350 */
1351 @Override
1352 public void resizeToScreen() {
1353 // Send dtterm/xterm sequences, which will probably not work because
1354 // allowWindowOps is defaulted to false.
1355 String resizeString = String.format("\033[8;%d;%dt", getHeight(),
1356 getWidth());
1357 this.output.write(resizeString);
1358 this.output.flush();
1359 }
1360
1361 // ------------------------------------------------------------------------
1362 // TerminalReader ---------------------------------------------------------
1363 // ------------------------------------------------------------------------
1364
1365 /**
1366 * Check if there are events in the queue.
1367 *
1368 * @return if true, getEvents() has something to return to the backend
1369 */
1370 public boolean hasEvents() {
1371 synchronized (eventQueue) {
1372 return (eventQueue.size() > 0);
1373 }
1374 }
1375
1376 /**
1377 * Return any events in the IO queue.
1378 *
1379 * @param queue list to append new events to
1380 */
1381 public void getEvents(final List<TInputEvent> queue) {
1382 synchronized (eventQueue) {
1383 if (eventQueue.size() > 0) {
1384 synchronized (queue) {
1385 queue.addAll(eventQueue);
1386 }
1387 eventQueue.clear();
1388 }
1389 }
1390 }
1391
1392 /**
1393 * Restore terminal to normal state.
1394 */
1395 public void closeTerminal() {
1396
1397 // System.err.println("=== closeTerminal() ==="); System.err.flush();
1398
1399 // Tell the reader thread to stop looking at input
1400 stopReaderThread = true;
1401 try {
1402 readerThread.join();
1403 } catch (InterruptedException e) {
1404 if (debugToStderr) {
1405 e.printStackTrace();
1406 }
1407 }
1408
1409 // Disable mouse reporting and show cursor. Defensive null check
1410 // here in case closeTerminal() is called twice.
1411 if (output != null) {
1412 output.printf("%s%s%s%s", mouse(false), cursor(true),
1413 defaultColor(), xtermResetSixelSettings());
1414 output.flush();
1415 }
1416
1417 if (setRawMode) {
1418 sttyCooked();
1419 setRawMode = false;
1420 // We don't close System.in/out
1421 } else {
1422 // Shut down the streams, this should wake up the reader thread
1423 // and make it exit.
1424 if (input != null) {
1425 try {
1426 input.close();
1427 } catch (IOException e) {
1428 // SQUASH
1429 }
1430 input = null;
1431 }
1432 if (output != null) {
1433 output.close();
1434 output = null;
1435 }
1436 }
1437 }
1438
1439 /**
1440 * Set listener to a different Object.
1441 *
1442 * @param listener the new listening object that run() wakes up on new
1443 * input
1444 */
1445 public void setListener(final Object listener) {
1446 this.listener = listener;
1447 }
1448
1449 /**
1450 * Reload options from System properties.
1451 */
1452 public void reloadOptions() {
1453 // Permit RGB colors only if externally requested.
1454 if (System.getProperty("jexer.ECMA48.rgbColor",
1455 "false").equals("true")
1456 ) {
1457 doRgbColor = true;
1458 } else {
1459 doRgbColor = false;
1460 }
1461
1462 // Default to using images for full-width characters.
1463 if (System.getProperty("jexer.ECMA48.wideCharImages",
1464 "true").equals("true")) {
1465 wideCharImages = true;
1466 } else {
1467 wideCharImages = false;
1468 }
1469
1470 // Pull the system properties for sixel output.
1471 if (System.getProperty("jexer.ECMA48.sixel", "true").equals("true")) {
1472 sixel = true;
1473 } else {
1474 sixel = false;
1475 }
1476
1477 // Palette size
1478 int paletteSize = 1024;
1479 try {
1480 paletteSize = Integer.parseInt(System.getProperty(
1481 "jexer.ECMA48.sixelPaletteSize", "1024"));
1482 switch (paletteSize) {
1483 case 2:
1484 case 256:
1485 case 512:
1486 case 1024:
1487 case 2048:
1488 sixelPaletteSize = paletteSize;
1489 break;
1490 default:
1491 // Ignore value
1492 break;
1493 }
1494 } catch (NumberFormatException e) {
1495 // SQUASH
1496 }
1497
1498 // Shared palette
1499 if (System.getProperty("jexer.ECMA48.sixelSharedPalette",
1500 "true").equals("false")) {
1501 sixelSharedPalette = false;
1502 } else {
1503 sixelSharedPalette = true;
1504 }
1505
1506 // Default to not supporting iTerm2 images.
1507 if (System.getProperty("jexer.ECMA48.iTerm2Images",
1508 "false").equals("true")) {
1509 iterm2Images = true;
1510 } else {
1511 iterm2Images = false;
1512 }
1513
1514 // Default to using JPG Jexer images if terminal supports it.
1515 String jexerImageStr = System.getProperty("jexer.ECMA48.jexerImages",
1516 "jpg").toLowerCase();
1517 if (jexerImageStr.equals("false")) {
1518 jexerImageOption = JexerImageOption.DISABLED;
1519 } else if (jexerImageStr.equals("jpg")) {
1520 jexerImageOption = JexerImageOption.JPG;
1521 } else if (jexerImageStr.equals("png")) {
1522 jexerImageOption = JexerImageOption.PNG;
1523 } else if (jexerImageStr.equals("rgb")) {
1524 jexerImageOption = JexerImageOption.RGB;
1525 }
1526
1527 // Set custom colors
1528 setCustomSystemColors();
1529 }
1530
1531 // ------------------------------------------------------------------------
1532 // Runnable ---------------------------------------------------------------
1533 // ------------------------------------------------------------------------
1534
1535 /**
1536 * Read function runs on a separate thread.
1537 */
1538 public void run() {
1539 boolean done = false;
1540 // available() will often return > 1, so we need to read in chunks to
1541 // stay caught up.
1542 char [] readBuffer = new char[128];
1543 List<TInputEvent> events = new ArrayList<TInputEvent>();
1544
1545 while (!done && !stopReaderThread) {
1546 try {
1547 // We assume that if inputStream has bytes available, then
1548 // input won't block on read().
1549 int n = inputStream.available();
1550
1551 /*
1552 System.err.printf("inputStream.available(): %d\n", n);
1553 System.err.flush();
1554 */
1555
1556 if (n > 0) {
1557 if (readBuffer.length < n) {
1558 // The buffer wasn't big enough, make it huger
1559 readBuffer = new char[readBuffer.length * 2];
1560 }
1561
1562 // System.err.printf("BEFORE read()\n"); System.err.flush();
1563
1564 int rc = input.read(readBuffer, 0, readBuffer.length);
1565
1566 /*
1567 System.err.printf("AFTER read() %d\n", rc);
1568 System.err.flush();
1569 */
1570
1571 if (rc == -1) {
1572 // This is EOF
1573 done = true;
1574 } else {
1575 for (int i = 0; i < rc; i++) {
1576 int ch = readBuffer[i];
1577 processChar(events, (char)ch);
1578 }
1579 getIdleEvents(events);
1580 if (events.size() > 0) {
1581 // Add to the queue for the backend thread to
1582 // be able to obtain.
1583 synchronized (eventQueue) {
1584 eventQueue.addAll(events);
1585 }
1586 if (listener != null) {
1587 synchronized (listener) {
1588 listener.notifyAll();
1589 }
1590 }
1591 events.clear();
1592 }
1593 }
1594 } else {
1595 getIdleEvents(events);
1596 if (events.size() > 0) {
1597 synchronized (eventQueue) {
1598 eventQueue.addAll(events);
1599 }
1600 if (listener != null) {
1601 synchronized (listener) {
1602 listener.notifyAll();
1603 }
1604 }
1605 events.clear();
1606 }
1607
1608 if (output.checkError()) {
1609 // This is EOF.
1610 done = true;
1611 }
1612
1613 // Wait 20 millis for more data
1614 Thread.sleep(20);
1615 }
1616 // System.err.println("end while loop"); System.err.flush();
1617 } catch (InterruptedException e) {
1618 // SQUASH
1619 } catch (IOException e) {
1620 e.printStackTrace();
1621 done = true;
1622 }
1623 } // while ((done == false) && (stopReaderThread == false))
1624
1625 // Pass an event up to TApplication to tell it this Backend is done.
1626 synchronized (eventQueue) {
1627 eventQueue.add(new TCommandEvent(cmBackendDisconnect));
1628 }
1629 if (listener != null) {
1630 synchronized (listener) {
1631 listener.notifyAll();
1632 }
1633 }
1634
1635 // System.err.println("*** run() exiting..."); System.err.flush();
1636 }
1637
1638 // ------------------------------------------------------------------------
1639 // ECMA48Terminal ---------------------------------------------------------
1640 // ------------------------------------------------------------------------
1641
1642 /**
1643 * Get the width of a character cell in pixels.
1644 *
1645 * @return the width in pixels of a character cell
1646 */
1647 public int getTextWidth() {
1648 return (widthPixels / sessionInfo.getWindowWidth());
1649 }
1650
1651 /**
1652 * Get the height of a character cell in pixels.
1653 *
1654 * @return the height in pixels of a character cell
1655 */
1656 public int getTextHeight() {
1657 return (heightPixels / sessionInfo.getWindowHeight());
1658 }
1659
1660 /**
1661 * Getter for sessionInfo.
1662 *
1663 * @return the SessionInfo
1664 */
1665 public SessionInfo getSessionInfo() {
1666 return sessionInfo;
1667 }
1668
1669 /**
1670 * Get the output writer.
1671 *
1672 * @return the Writer
1673 */
1674 public PrintWriter getOutput() {
1675 return output;
1676 }
1677
1678 /**
1679 * Call 'stty' to set cooked mode.
1680 *
1681 * <p>Actually executes '/bin/sh -c stty sane cooked &lt; /dev/tty'
1682 */
1683 private void sttyCooked() {
1684 doStty(false);
1685 }
1686
1687 /**
1688 * Call 'stty' to set raw mode.
1689 *
1690 * <p>Actually executes '/bin/sh -c stty -ignbrk -brkint -parmrk -istrip
1691 * -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten
1692 * -parenb cs8 min 1 &lt; /dev/tty'
1693 */
1694 private void sttyRaw() {
1695 doStty(true);
1696 }
1697
1698 /**
1699 * Call 'stty' to set raw or cooked mode.
1700 *
1701 * @param mode if true, set raw mode, otherwise set cooked mode
1702 */
1703 private void doStty(final boolean mode) {
1704 String [] cmdRaw = {
1705 "/bin/sh", "-c", "stty -ignbrk -brkint -parmrk -istrip -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten -parenb cs8 min 1 < /dev/tty"
1706 };
1707 String [] cmdCooked = {
1708 "/bin/sh", "-c", "stty sane cooked < /dev/tty"
1709 };
1710 try {
1711 Process process;
1712 if (mode) {
1713 process = Runtime.getRuntime().exec(cmdRaw);
1714 } else {
1715 process = Runtime.getRuntime().exec(cmdCooked);
1716 }
1717 BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
1718 String line = in.readLine();
1719 if ((line != null) && (line.length() > 0)) {
1720 System.err.println("WEIRD?! Normal output from stty: " + line);
1721 }
1722 while (true) {
1723 BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
1724 line = err.readLine();
1725 if ((line != null) && (line.length() > 0)) {
1726 System.err.println("Error output from stty: " + line);
1727 }
1728 try {
1729 process.waitFor();
1730 break;
1731 } catch (InterruptedException e) {
1732 if (debugToStderr) {
1733 e.printStackTrace();
1734 }
1735 }
1736 }
1737 int rc = process.exitValue();
1738 if (rc != 0) {
1739 System.err.println("stty returned error code: " + rc);
1740 }
1741 } catch (IOException e) {
1742 e.printStackTrace();
1743 }
1744 }
1745
1746 /**
1747 * Flush output.
1748 */
1749 public void flush() {
1750 output.flush();
1751 }
1752
1753 /**
1754 * Perform a somewhat-optimal rendering of a line.
1755 *
1756 * @param y row coordinate. 0 is the top-most row.
1757 * @param sb StringBuilder to write escape sequences to
1758 * @param lastAttr cell attributes from the last call to flushLine
1759 */
1760 private void flushLine(final int y, final StringBuilder sb,
1761 CellAttributes lastAttr) {
1762
1763 int lastX = -1;
1764 int textEnd = 0;
1765 for (int x = 0; x < width; x++) {
1766 Cell lCell = logical[x][y];
1767 if (!lCell.isBlank()) {
1768 textEnd = x;
1769 }
1770 }
1771 // Push textEnd to first column beyond the text area
1772 textEnd++;
1773
1774 // DEBUG
1775 // reallyCleared = true;
1776
1777 boolean hasImage = false;
1778
1779 for (int x = 0; x < width; x++) {
1780 Cell lCell = logical[x][y];
1781 Cell pCell = physical[x][y];
1782
1783 if (!lCell.equals(pCell) || reallyCleared) {
1784
1785 if (debugToStderr) {
1786 System.err.printf("\n--\n");
1787 System.err.printf(" Y: %d X: %d\n", y, x);
1788 System.err.printf(" lCell: %s\n", lCell);
1789 System.err.printf(" pCell: %s\n", pCell);
1790 System.err.printf(" ==== \n");
1791 }
1792
1793 if (lastAttr == null) {
1794 lastAttr = new CellAttributes();
1795 sb.append(normal());
1796 }
1797
1798 // Place the cell
1799 if ((lastX != (x - 1)) || (lastX == -1)) {
1800 // Advancing at least one cell, or the first gotoXY
1801 sb.append(gotoXY(x, y));
1802 }
1803
1804 assert (lastAttr != null);
1805
1806 if ((x == textEnd) && (textEnd < width - 1)) {
1807 assert (lCell.isBlank());
1808
1809 for (int i = x; i < width; i++) {
1810 assert (logical[i][y].isBlank());
1811 // Physical is always updated
1812 physical[i][y].reset();
1813 }
1814
1815 // Clear remaining line
1816 sb.append(clearRemainingLine());
1817 lastAttr.reset();
1818 return;
1819 }
1820
1821 // Image cell: bypass the rest of the loop, it is not
1822 // rendered here.
1823 if ((wideCharImages && lCell.isImage())
1824 || (!wideCharImages
1825 && lCell.isImage()
1826 && (lCell.getWidth() == Cell.Width.SINGLE))
1827 ) {
1828 hasImage = true;
1829
1830 // Save the last rendered cell
1831 lastX = x;
1832
1833 // Physical is always updated
1834 physical[x][y].setTo(lCell);
1835 continue;
1836 }
1837
1838 assert ((wideCharImages && !lCell.isImage())
1839 || (!wideCharImages
1840 && (!lCell.isImage()
1841 || (lCell.isImage()
1842 && (lCell.getWidth() != Cell.Width.SINGLE)))));
1843
1844 if (!wideCharImages && (lCell.getWidth() == Cell.Width.RIGHT)) {
1845 continue;
1846 }
1847
1848 if (hasImage) {
1849 hasImage = false;
1850 sb.append(gotoXY(x, y));
1851 }
1852
1853 // Now emit only the modified attributes
1854 if ((lCell.getForeColor() != lastAttr.getForeColor())
1855 && (lCell.getBackColor() != lastAttr.getBackColor())
1856 && (!lCell.isRGB())
1857 && (lCell.isBold() == lastAttr.isBold())
1858 && (lCell.isReverse() == lastAttr.isReverse())
1859 && (lCell.isUnderline() == lastAttr.isUnderline())
1860 && (lCell.isBlink() == lastAttr.isBlink())
1861 ) {
1862 // Both colors changed, attributes the same
1863 sb.append(color(lCell.isBold(),
1864 lCell.getForeColor(), lCell.getBackColor()));
1865
1866 if (debugToStderr) {
1867 System.err.printf("1 Change only fore/back colors\n");
1868 }
1869
1870 } else if (lCell.isRGB()
1871 && (lCell.getForeColorRGB() != lastAttr.getForeColorRGB())
1872 && (lCell.getBackColorRGB() != lastAttr.getBackColorRGB())
1873 && (lCell.isBold() == lastAttr.isBold())
1874 && (lCell.isReverse() == lastAttr.isReverse())
1875 && (lCell.isUnderline() == lastAttr.isUnderline())
1876 && (lCell.isBlink() == lastAttr.isBlink())
1877 ) {
1878 // Both colors changed, attributes the same
1879 sb.append(colorRGB(lCell.getForeColorRGB(),
1880 lCell.getBackColorRGB()));
1881
1882 if (debugToStderr) {
1883 System.err.printf("1 Change only fore/back colors (RGB)\n");
1884 }
1885 } else if ((lCell.getForeColor() != lastAttr.getForeColor())
1886 && (lCell.getBackColor() != lastAttr.getBackColor())
1887 && (!lCell.isRGB())
1888 && (lCell.isBold() != lastAttr.isBold())
1889 && (lCell.isReverse() != lastAttr.isReverse())
1890 && (lCell.isUnderline() != lastAttr.isUnderline())
1891 && (lCell.isBlink() != lastAttr.isBlink())
1892 ) {
1893 // Everything is different
1894 sb.append(color(lCell.getForeColor(),
1895 lCell.getBackColor(),
1896 lCell.isBold(), lCell.isReverse(),
1897 lCell.isBlink(),
1898 lCell.isUnderline()));
1899
1900 if (debugToStderr) {
1901 System.err.printf("2 Set all attributes\n");
1902 }
1903 } else if ((lCell.getForeColor() != lastAttr.getForeColor())
1904 && (lCell.getBackColor() == lastAttr.getBackColor())
1905 && (!lCell.isRGB())
1906 && (lCell.isBold() == lastAttr.isBold())
1907 && (lCell.isReverse() == lastAttr.isReverse())
1908 && (lCell.isUnderline() == lastAttr.isUnderline())
1909 && (lCell.isBlink() == lastAttr.isBlink())
1910 ) {
1911
1912 // Attributes same, foreColor different
1913 sb.append(color(lCell.isBold(),
1914 lCell.getForeColor(), true));
1915
1916 if (debugToStderr) {
1917 System.err.printf("3 Change foreColor\n");
1918 }
1919 } else if (lCell.isRGB()
1920 && (lCell.getForeColorRGB() != lastAttr.getForeColorRGB())
1921 && (lCell.getBackColorRGB() == lastAttr.getBackColorRGB())
1922 && (lCell.getForeColorRGB() >= 0)
1923 && (lCell.getBackColorRGB() >= 0)
1924 && (lCell.isBold() == lastAttr.isBold())
1925 && (lCell.isReverse() == lastAttr.isReverse())
1926 && (lCell.isUnderline() == lastAttr.isUnderline())
1927 && (lCell.isBlink() == lastAttr.isBlink())
1928 ) {
1929 // Attributes same, foreColor different
1930 sb.append(colorRGB(lCell.getForeColorRGB(), true));
1931
1932 if (debugToStderr) {
1933 System.err.printf("3 Change foreColor (RGB)\n");
1934 }
1935 } else if ((lCell.getForeColor() == lastAttr.getForeColor())
1936 && (lCell.getBackColor() != lastAttr.getBackColor())
1937 && (!lCell.isRGB())
1938 && (lCell.isBold() == lastAttr.isBold())
1939 && (lCell.isReverse() == lastAttr.isReverse())
1940 && (lCell.isUnderline() == lastAttr.isUnderline())
1941 && (lCell.isBlink() == lastAttr.isBlink())
1942 ) {
1943 // Attributes same, backColor different
1944 sb.append(color(lCell.isBold(),
1945 lCell.getBackColor(), false));
1946
1947 if (debugToStderr) {
1948 System.err.printf("4 Change backColor\n");
1949 }
1950 } else if (lCell.isRGB()
1951 && (lCell.getForeColorRGB() == lastAttr.getForeColorRGB())
1952 && (lCell.getBackColorRGB() != lastAttr.getBackColorRGB())
1953 && (lCell.isBold() == lastAttr.isBold())
1954 && (lCell.isReverse() == lastAttr.isReverse())
1955 && (lCell.isUnderline() == lastAttr.isUnderline())
1956 && (lCell.isBlink() == lastAttr.isBlink())
1957 ) {
1958 // Attributes same, foreColor different
1959 sb.append(colorRGB(lCell.getBackColorRGB(), false));
1960
1961 if (debugToStderr) {
1962 System.err.printf("4 Change backColor (RGB)\n");
1963 }
1964 } else if ((lCell.getForeColor() == lastAttr.getForeColor())
1965 && (lCell.getBackColor() == lastAttr.getBackColor())
1966 && (lCell.getForeColorRGB() == lastAttr.getForeColorRGB())
1967 && (lCell.getBackColorRGB() == lastAttr.getBackColorRGB())
1968 && (lCell.isBold() == lastAttr.isBold())
1969 && (lCell.isReverse() == lastAttr.isReverse())
1970 && (lCell.isUnderline() == lastAttr.isUnderline())
1971 && (lCell.isBlink() == lastAttr.isBlink())
1972 ) {
1973
1974 // All attributes the same, just print the char
1975 // NOP
1976
1977 if (debugToStderr) {
1978 System.err.printf("5 Only emit character\n");
1979 }
1980 } else {
1981 // Just reset everything again
1982 if (!lCell.isRGB()) {
1983 sb.append(color(lCell.getForeColor(),
1984 lCell.getBackColor(),
1985 lCell.isBold(),
1986 lCell.isReverse(),
1987 lCell.isBlink(),
1988 lCell.isUnderline()));
1989
1990 if (debugToStderr) {
1991 System.err.printf("6 Change all attributes\n");
1992 }
1993 } else {
1994 sb.append(colorRGB(lCell.getForeColorRGB(),
1995 lCell.getBackColorRGB(),
1996 lCell.isBold(),
1997 lCell.isReverse(),
1998 lCell.isBlink(),
1999 lCell.isUnderline()));
2000 if (debugToStderr) {
2001 System.err.printf("6 Change all attributes (RGB)\n");
2002 }
2003 }
2004
2005 }
2006 // Emit the character
2007 if (wideCharImages
2008 // Don't emit the right-half of full-width chars.
2009 || (!wideCharImages
2010 && (lCell.getWidth() != Cell.Width.RIGHT))
2011 ) {
2012 sb.append(Character.toChars(lCell.getChar()));
2013 }
2014
2015 // Save the last rendered cell
2016 lastX = x;
2017 lastAttr.setTo(lCell);
2018
2019 // Physical is always updated
2020 physical[x][y].setTo(lCell);
2021
2022 } // if (!lCell.equals(pCell) || (reallyCleared == true))
2023
2024 } // for (int x = 0; x < width; x++)
2025 }
2026
2027 /**
2028 * Render the screen to a string that can be emitted to something that
2029 * knows how to process ECMA-48/ANSI X3.64 escape sequences.
2030 *
2031 * @param sb StringBuilder to write escape sequences to
2032 * @return escape sequences string that provides the updates to the
2033 * physical screen
2034 */
2035 private String flushString(final StringBuilder sb) {
2036 CellAttributes attr = null;
2037
2038 if (reallyCleared) {
2039 attr = new CellAttributes();
2040 sb.append(clearAll());
2041 }
2042
2043 /*
2044 * For images support, draw all of the image output first, and then
2045 * draw everything else afterwards. This works OK, but performance
2046 * is still a drag on larger pictures.
2047 */
2048 for (int y = 0; y < height; y++) {
2049 for (int x = 0; x < width; x++) {
2050 // If physical had non-image data that is now image data, the
2051 // entire row must be redrawn.
2052 Cell lCell = logical[x][y];
2053 Cell pCell = physical[x][y];
2054 if (lCell.isImage() && !pCell.isImage()) {
2055 unsetImageRow(y);
2056 break;
2057 }
2058 }
2059 }
2060 for (int y = 0; y < height; y++) {
2061 for (int x = 0; x < width; x++) {
2062 Cell lCell = logical[x][y];
2063 Cell pCell = physical[x][y];
2064
2065 if (!lCell.isImage()
2066 || (!wideCharImages
2067 && (lCell.getWidth() != Cell.Width.SINGLE))
2068 ) {
2069 continue;
2070 }
2071
2072 int left = x;
2073 int right = x;
2074 while ((right < width)
2075 && (logical[right][y].isImage())
2076 && (!logical[right][y].equals(physical[right][y])
2077 || reallyCleared)
2078 ) {
2079 right++;
2080 }
2081 ArrayList<Cell> cellsToDraw = new ArrayList<Cell>();
2082 for (int i = 0; i < (right - x); i++) {
2083 assert (logical[x + i][y].isImage());
2084 cellsToDraw.add(logical[x + i][y]);
2085
2086 // Physical is always updated.
2087 physical[x + i][y].setTo(lCell);
2088 }
2089 if (cellsToDraw.size() > 0) {
2090 if (iterm2Images) {
2091 sb.append(toIterm2Image(x, y, cellsToDraw));
2092 } else if (jexerImageOption != JexerImageOption.DISABLED) {
2093 sb.append(toJexerImage(x, y, cellsToDraw));
2094 } else {
2095 sb.append(toSixel(x, y, cellsToDraw));
2096 }
2097 }
2098
2099 x = right;
2100 }
2101 }
2102
2103 // Draw the text part now.
2104 for (int y = 0; y < height; y++) {
2105 flushLine(y, sb, attr);
2106 }
2107
2108 reallyCleared = false;
2109
2110 String result = sb.toString();
2111 if (debugToStderr) {
2112 System.err.printf("flushString(): %s\n", result);
2113 }
2114 return result;
2115 }
2116
2117 /**
2118 * Reset keyboard/mouse input parser.
2119 */
2120 private void resetParser() {
2121 state = ParseState.GROUND;
2122 params = new ArrayList<String>();
2123 params.clear();
2124 params.add("");
2125 decPrivateModeFlag = false;
2126 }
2127
2128 /**
2129 * Produce a control character or one of the special ones (ENTER, TAB,
2130 * etc.).
2131 *
2132 * @param ch Unicode code point
2133 * @param alt if true, set alt on the TKeypress
2134 * @return one TKeypress event, either a control character (e.g. isKey ==
2135 * false, ch == 'A', ctrl == true), or a special key (e.g. isKey == true,
2136 * fnKey == ESC)
2137 */
2138 private TKeypressEvent controlChar(final char ch, final boolean alt) {
2139 // System.err.printf("controlChar: %02x\n", ch);
2140
2141 switch (ch) {
2142 case 0x0D:
2143 // Carriage return --> ENTER
2144 return new TKeypressEvent(kbEnter, alt, false, false);
2145 case 0x0A:
2146 // Linefeed --> ENTER
2147 return new TKeypressEvent(kbEnter, alt, false, false);
2148 case 0x1B:
2149 // ESC
2150 return new TKeypressEvent(kbEsc, alt, false, false);
2151 case '\t':
2152 // TAB
2153 return new TKeypressEvent(kbTab, alt, false, false);
2154 default:
2155 // Make all other control characters come back as the alphabetic
2156 // character with the ctrl field set. So SOH would be 'A' +
2157 // ctrl.
2158 return new TKeypressEvent(false, 0, (char)(ch + 0x40),
2159 alt, true, false);
2160 }
2161 }
2162
2163 /**
2164 * Produce special key from CSI Pn ; Pm ; ... ~
2165 *
2166 * @return one KEYPRESS event representing a special key
2167 */
2168 private TInputEvent csiFnKey() {
2169 int key = 0;
2170 if (params.size() > 0) {
2171 key = Integer.parseInt(params.get(0));
2172 }
2173 boolean alt = false;
2174 boolean ctrl = false;
2175 boolean shift = false;
2176 if (params.size() > 1) {
2177 shift = csiIsShift(params.get(1));
2178 alt = csiIsAlt(params.get(1));
2179 ctrl = csiIsCtrl(params.get(1));
2180 }
2181
2182 switch (key) {
2183 case 1:
2184 return new TKeypressEvent(kbHome, alt, ctrl, shift);
2185 case 2:
2186 return new TKeypressEvent(kbIns, alt, ctrl, shift);
2187 case 3:
2188 return new TKeypressEvent(kbDel, alt, ctrl, shift);
2189 case 4:
2190 return new TKeypressEvent(kbEnd, alt, ctrl, shift);
2191 case 5:
2192 return new TKeypressEvent(kbPgUp, alt, ctrl, shift);
2193 case 6:
2194 return new TKeypressEvent(kbPgDn, alt, ctrl, shift);
2195 case 15:
2196 return new TKeypressEvent(kbF5, alt, ctrl, shift);
2197 case 17:
2198 return new TKeypressEvent(kbF6, alt, ctrl, shift);
2199 case 18:
2200 return new TKeypressEvent(kbF7, alt, ctrl, shift);
2201 case 19:
2202 return new TKeypressEvent(kbF8, alt, ctrl, shift);
2203 case 20:
2204 return new TKeypressEvent(kbF9, alt, ctrl, shift);
2205 case 21:
2206 return new TKeypressEvent(kbF10, alt, ctrl, shift);
2207 case 23:
2208 return new TKeypressEvent(kbF11, alt, ctrl, shift);
2209 case 24:
2210 return new TKeypressEvent(kbF12, alt, ctrl, shift);
2211 default:
2212 // Unknown
2213 return null;
2214 }
2215 }
2216
2217 /**
2218 * Produce mouse events based on "Any event tracking" and UTF-8
2219 * coordinates. See
2220 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
2221 *
2222 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
2223 */
2224 private TInputEvent parseMouse() {
2225 int buttons = params.get(0).charAt(0) - 32;
2226 int x = params.get(0).charAt(1) - 32 - 1;
2227 int y = params.get(0).charAt(2) - 32 - 1;
2228
2229 // Clamp X and Y to the physical screen coordinates.
2230 if (x >= windowResize.getWidth()) {
2231 x = windowResize.getWidth() - 1;
2232 }
2233 if (y >= windowResize.getHeight()) {
2234 y = windowResize.getHeight() - 1;
2235 }
2236
2237 TMouseEvent.Type eventType = TMouseEvent.Type.MOUSE_DOWN;
2238 boolean eventMouse1 = false;
2239 boolean eventMouse2 = false;
2240 boolean eventMouse3 = false;
2241 boolean eventMouseWheelUp = false;
2242 boolean eventMouseWheelDown = false;
2243
2244 // System.err.printf("buttons: %04x\r\n", buttons);
2245
2246 switch (buttons) {
2247 case 0:
2248 eventMouse1 = true;
2249 mouse1 = true;
2250 break;
2251 case 1:
2252 eventMouse2 = true;
2253 mouse2 = true;
2254 break;
2255 case 2:
2256 eventMouse3 = true;
2257 mouse3 = true;
2258 break;
2259 case 3:
2260 // Release or Move
2261 if (!mouse1 && !mouse2 && !mouse3) {
2262 eventType = TMouseEvent.Type.MOUSE_MOTION;
2263 } else {
2264 eventType = TMouseEvent.Type.MOUSE_UP;
2265 }
2266 if (mouse1) {
2267 mouse1 = false;
2268 eventMouse1 = true;
2269 }
2270 if (mouse2) {
2271 mouse2 = false;
2272 eventMouse2 = true;
2273 }
2274 if (mouse3) {
2275 mouse3 = false;
2276 eventMouse3 = true;
2277 }
2278 break;
2279
2280 case 32:
2281 // Dragging with mouse1 down
2282 eventMouse1 = true;
2283 mouse1 = true;
2284 eventType = TMouseEvent.Type.MOUSE_MOTION;
2285 break;
2286
2287 case 33:
2288 // Dragging with mouse2 down
2289 eventMouse2 = true;
2290 mouse2 = true;
2291 eventType = TMouseEvent.Type.MOUSE_MOTION;
2292 break;
2293
2294 case 34:
2295 // Dragging with mouse3 down
2296 eventMouse3 = true;
2297 mouse3 = true;
2298 eventType = TMouseEvent.Type.MOUSE_MOTION;
2299 break;
2300
2301 case 96:
2302 // Dragging with mouse2 down after wheelUp
2303 eventMouse2 = true;
2304 mouse2 = true;
2305 eventType = TMouseEvent.Type.MOUSE_MOTION;
2306 break;
2307
2308 case 97:
2309 // Dragging with mouse2 down after wheelDown
2310 eventMouse2 = true;
2311 mouse2 = true;
2312 eventType = TMouseEvent.Type.MOUSE_MOTION;
2313 break;
2314
2315 case 64:
2316 eventMouseWheelUp = true;
2317 break;
2318
2319 case 65:
2320 eventMouseWheelDown = true;
2321 break;
2322
2323 default:
2324 // Unknown, just make it motion
2325 eventType = TMouseEvent.Type.MOUSE_MOTION;
2326 break;
2327 }
2328 return new TMouseEvent(eventType, x, y, x, y,
2329 eventMouse1, eventMouse2, eventMouse3,
2330 eventMouseWheelUp, eventMouseWheelDown);
2331 }
2332
2333 /**
2334 * Produce mouse events based on "Any event tracking" and SGR
2335 * coordinates. See
2336 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
2337 *
2338 * @param release if true, this was a release ('m')
2339 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
2340 */
2341 private TInputEvent parseMouseSGR(final boolean release) {
2342 // SGR extended coordinates - mode 1006
2343 if (params.size() < 3) {
2344 // Invalid position, bail out.
2345 return null;
2346 }
2347 int buttons = Integer.parseInt(params.get(0));
2348 int x = Integer.parseInt(params.get(1)) - 1;
2349 int y = Integer.parseInt(params.get(2)) - 1;
2350
2351 // Clamp X and Y to the physical screen coordinates.
2352 if (x >= windowResize.getWidth()) {
2353 x = windowResize.getWidth() - 1;
2354 }
2355 if (y >= windowResize.getHeight()) {
2356 y = windowResize.getHeight() - 1;
2357 }
2358
2359 TMouseEvent.Type eventType = TMouseEvent.Type.MOUSE_DOWN;
2360 boolean eventMouse1 = false;
2361 boolean eventMouse2 = false;
2362 boolean eventMouse3 = false;
2363 boolean eventMouseWheelUp = false;
2364 boolean eventMouseWheelDown = false;
2365
2366 if (release) {
2367 eventType = TMouseEvent.Type.MOUSE_UP;
2368 }
2369
2370 switch (buttons) {
2371 case 0:
2372 eventMouse1 = true;
2373 break;
2374 case 1:
2375 eventMouse2 = true;
2376 break;
2377 case 2:
2378 eventMouse3 = true;
2379 break;
2380 case 35:
2381 // Motion only, no buttons down
2382 eventType = TMouseEvent.Type.MOUSE_MOTION;
2383 break;
2384
2385 case 32:
2386 // Dragging with mouse1 down
2387 eventMouse1 = true;
2388 eventType = TMouseEvent.Type.MOUSE_MOTION;
2389 break;
2390
2391 case 33:
2392 // Dragging with mouse2 down
2393 eventMouse2 = true;
2394 eventType = TMouseEvent.Type.MOUSE_MOTION;
2395 break;
2396
2397 case 34:
2398 // Dragging with mouse3 down
2399 eventMouse3 = true;
2400 eventType = TMouseEvent.Type.MOUSE_MOTION;
2401 break;
2402
2403 case 96:
2404 // Dragging with mouse2 down after wheelUp
2405 eventMouse2 = true;
2406 eventType = TMouseEvent.Type.MOUSE_MOTION;
2407 break;
2408
2409 case 97:
2410 // Dragging with mouse2 down after wheelDown
2411 eventMouse2 = true;
2412 eventType = TMouseEvent.Type.MOUSE_MOTION;
2413 break;
2414
2415 case 64:
2416 eventMouseWheelUp = true;
2417 break;
2418
2419 case 65:
2420 eventMouseWheelDown = true;
2421 break;
2422
2423 default:
2424 // Unknown, bail out
2425 return null;
2426 }
2427 return new TMouseEvent(eventType, x, y, x, y,
2428 eventMouse1, eventMouse2, eventMouse3,
2429 eventMouseWheelUp, eventMouseWheelDown);
2430 }
2431
2432 /**
2433 * Return any events in the IO queue due to timeout.
2434 *
2435 * @param queue list to append new events to
2436 */
2437 private void getIdleEvents(final List<TInputEvent> queue) {
2438 long nowTime = System.currentTimeMillis();
2439
2440 // Check for new window size
2441 long windowSizeDelay = nowTime - windowSizeTime;
2442 if (windowSizeDelay > 1000) {
2443 int oldTextWidth = getTextWidth();
2444 int oldTextHeight = getTextHeight();
2445
2446 sessionInfo.queryWindowSize();
2447 int newWidth = sessionInfo.getWindowWidth();
2448 int newHeight = sessionInfo.getWindowHeight();
2449
2450 if ((newWidth != windowResize.getWidth())
2451 || (newHeight != windowResize.getHeight())
2452 ) {
2453
2454 // Request xterm report window dimensions in pixels again.
2455 // Between now and then, ensure that the reported text cell
2456 // size is the same by setting widthPixels and heightPixels
2457 // to match the new dimensions.
2458 widthPixels = oldTextWidth * newWidth;
2459 heightPixels = oldTextHeight * newHeight;
2460
2461 if (debugToStderr) {
2462 System.err.println("Screen size changed, old size " +
2463 windowResize);
2464 System.err.println(" new size " +
2465 newWidth + " x " + newHeight);
2466 System.err.println(" old pixels " +
2467 oldTextWidth + " x " + oldTextHeight);
2468 System.err.println(" new pixels " +
2469 getTextWidth() + " x " + getTextHeight());
2470 }
2471
2472 this.output.printf("%s", xtermReportPixelDimensions());
2473 this.output.flush();
2474
2475 TResizeEvent event = new TResizeEvent(TResizeEvent.Type.SCREEN,
2476 newWidth, newHeight);
2477 windowResize = new TResizeEvent(TResizeEvent.Type.SCREEN,
2478 newWidth, newHeight);
2479 queue.add(event);
2480 }
2481 windowSizeTime = nowTime;
2482 }
2483
2484 // ESCDELAY type timeout
2485 if (state == ParseState.ESCAPE) {
2486 long escDelay = nowTime - escapeTime;
2487 if (escDelay > 100) {
2488 // After 0.1 seconds, assume a true escape character
2489 queue.add(controlChar((char)0x1B, false));
2490 resetParser();
2491 }
2492 }
2493 }
2494
2495 /**
2496 * Returns true if the CSI parameter for a keyboard command means that
2497 * shift was down.
2498 */
2499 private boolean csiIsShift(final String x) {
2500 if ((x.equals("2"))
2501 || (x.equals("4"))
2502 || (x.equals("6"))
2503 || (x.equals("8"))
2504 ) {
2505 return true;
2506 }
2507 return false;
2508 }
2509
2510 /**
2511 * Returns true if the CSI parameter for a keyboard command means that
2512 * alt was down.
2513 */
2514 private boolean csiIsAlt(final String x) {
2515 if ((x.equals("3"))
2516 || (x.equals("4"))
2517 || (x.equals("7"))
2518 || (x.equals("8"))
2519 ) {
2520 return true;
2521 }
2522 return false;
2523 }
2524
2525 /**
2526 * Returns true if the CSI parameter for a keyboard command means that
2527 * ctrl was down.
2528 */
2529 private boolean csiIsCtrl(final String x) {
2530 if ((x.equals("5"))
2531 || (x.equals("6"))
2532 || (x.equals("7"))
2533 || (x.equals("8"))
2534 ) {
2535 return true;
2536 }
2537 return false;
2538 }
2539
2540 /**
2541 * Parses the next character of input to see if an InputEvent is
2542 * fully here.
2543 *
2544 * @param events list to append new events to
2545 * @param ch Unicode code point
2546 */
2547 private void processChar(final List<TInputEvent> events, final char ch) {
2548
2549 // ESCDELAY type timeout
2550 long nowTime = System.currentTimeMillis();
2551 if (state == ParseState.ESCAPE) {
2552 long escDelay = nowTime - escapeTime;
2553 if (escDelay > 250) {
2554 // After 0.25 seconds, assume a true escape character
2555 events.add(controlChar((char)0x1B, false));
2556 resetParser();
2557 }
2558 }
2559
2560 // TKeypress fields
2561 boolean ctrl = false;
2562 boolean alt = false;
2563 boolean shift = false;
2564
2565 // System.err.printf("state: %s ch %c\r\n", state, ch);
2566
2567 switch (state) {
2568 case GROUND:
2569
2570 if (ch == 0x1B) {
2571 state = ParseState.ESCAPE;
2572 escapeTime = nowTime;
2573 return;
2574 }
2575
2576 if (ch <= 0x1F) {
2577 // Control character
2578 events.add(controlChar(ch, false));
2579 resetParser();
2580 return;
2581 }
2582
2583 if (ch >= 0x20) {
2584 // Normal character
2585 events.add(new TKeypressEvent(false, 0, ch,
2586 false, false, false));
2587 resetParser();
2588 return;
2589 }
2590
2591 break;
2592
2593 case ESCAPE:
2594 if (ch <= 0x1F) {
2595 // ALT-Control character
2596 events.add(controlChar(ch, true));
2597 resetParser();
2598 return;
2599 }
2600
2601 if (ch == 'O') {
2602 // This will be one of the function keys
2603 state = ParseState.ESCAPE_INTERMEDIATE;
2604 return;
2605 }
2606
2607 // '[' goes to CSI_ENTRY
2608 if (ch == '[') {
2609 state = ParseState.CSI_ENTRY;
2610 return;
2611 }
2612
2613 // Everything else is assumed to be Alt-keystroke
2614 if ((ch >= 'A') && (ch <= 'Z')) {
2615 shift = true;
2616 }
2617 alt = true;
2618 events.add(new TKeypressEvent(false, 0, ch, alt, ctrl, shift));
2619 resetParser();
2620 return;
2621
2622 case ESCAPE_INTERMEDIATE:
2623 if ((ch >= 'P') && (ch <= 'S')) {
2624 // Function key
2625 switch (ch) {
2626 case 'P':
2627 events.add(new TKeypressEvent(kbF1));
2628 break;
2629 case 'Q':
2630 events.add(new TKeypressEvent(kbF2));
2631 break;
2632 case 'R':
2633 events.add(new TKeypressEvent(kbF3));
2634 break;
2635 case 'S':
2636 events.add(new TKeypressEvent(kbF4));
2637 break;
2638 default:
2639 break;
2640 }
2641 resetParser();
2642 return;
2643 }
2644
2645 // Unknown keystroke, ignore
2646 resetParser();
2647 return;
2648
2649 case CSI_ENTRY:
2650 // Numbers - parameter values
2651 if ((ch >= '0') && (ch <= '9')) {
2652 params.set(params.size() - 1,
2653 params.get(params.size() - 1) + ch);
2654 state = ParseState.CSI_PARAM;
2655 return;
2656 }
2657 // Parameter separator
2658 if (ch == ';') {
2659 params.add("");
2660 return;
2661 }
2662
2663 if ((ch >= 0x30) && (ch <= 0x7E)) {
2664 switch (ch) {
2665 case 'A':
2666 // Up
2667 events.add(new TKeypressEvent(kbUp, alt, ctrl, shift));
2668 resetParser();
2669 return;
2670 case 'B':
2671 // Down
2672 events.add(new TKeypressEvent(kbDown, alt, ctrl, shift));
2673 resetParser();
2674 return;
2675 case 'C':
2676 // Right
2677 events.add(new TKeypressEvent(kbRight, alt, ctrl, shift));
2678 resetParser();
2679 return;
2680 case 'D':
2681 // Left
2682 events.add(new TKeypressEvent(kbLeft, alt, ctrl, shift));
2683 resetParser();
2684 return;
2685 case 'H':
2686 // Home
2687 events.add(new TKeypressEvent(kbHome));
2688 resetParser();
2689 return;
2690 case 'F':
2691 // End
2692 events.add(new TKeypressEvent(kbEnd));
2693 resetParser();
2694 return;
2695 case 'Z':
2696 // CBT - Cursor backward X tab stops (default 1)
2697 events.add(new TKeypressEvent(kbBackTab));
2698 resetParser();
2699 return;
2700 case 'M':
2701 // Mouse position
2702 state = ParseState.MOUSE;
2703 return;
2704 case '<':
2705 // Mouse position, SGR (1006) coordinates
2706 state = ParseState.MOUSE_SGR;
2707 return;
2708 case '?':
2709 // DEC private mode flag
2710 decPrivateModeFlag = true;
2711 return;
2712 default:
2713 break;
2714 }
2715 }
2716
2717 // Unknown keystroke, ignore
2718 resetParser();
2719 return;
2720
2721 case MOUSE_SGR:
2722 // Numbers - parameter values
2723 if ((ch >= '0') && (ch <= '9')) {
2724 params.set(params.size() - 1,
2725 params.get(params.size() - 1) + ch);
2726 return;
2727 }
2728 // Parameter separator
2729 if (ch == ';') {
2730 params.add("");
2731 return;
2732 }
2733
2734 switch (ch) {
2735 case 'M':
2736 // Generate a mouse press event
2737 TInputEvent event = parseMouseSGR(false);
2738 if (event != null) {
2739 events.add(event);
2740 }
2741 resetParser();
2742 return;
2743 case 'm':
2744 // Generate a mouse release event
2745 event = parseMouseSGR(true);
2746 if (event != null) {
2747 events.add(event);
2748 }
2749 resetParser();
2750 return;
2751 default:
2752 break;
2753 }
2754
2755 // Unknown keystroke, ignore
2756 resetParser();
2757 return;
2758
2759 case CSI_PARAM:
2760 // Numbers - parameter values
2761 if ((ch >= '0') && (ch <= '9')) {
2762 params.set(params.size() - 1,
2763 params.get(params.size() - 1) + ch);
2764 state = ParseState.CSI_PARAM;
2765 return;
2766 }
2767 // Parameter separator
2768 if (ch == ';') {
2769 params.add("");
2770 return;
2771 }
2772
2773 if (ch == '~') {
2774 events.add(csiFnKey());
2775 resetParser();
2776 return;
2777 }
2778
2779 if ((ch >= 0x30) && (ch <= 0x7E)) {
2780 switch (ch) {
2781 case 'A':
2782 // Up
2783 if (params.size() > 1) {
2784 shift = csiIsShift(params.get(1));
2785 alt = csiIsAlt(params.get(1));
2786 ctrl = csiIsCtrl(params.get(1));
2787 }
2788 events.add(new TKeypressEvent(kbUp, alt, ctrl, shift));
2789 resetParser();
2790 return;
2791 case 'B':
2792 // Down
2793 if (params.size() > 1) {
2794 shift = csiIsShift(params.get(1));
2795 alt = csiIsAlt(params.get(1));
2796 ctrl = csiIsCtrl(params.get(1));
2797 }
2798 events.add(new TKeypressEvent(kbDown, alt, ctrl, shift));
2799 resetParser();
2800 return;
2801 case 'C':
2802 // Right
2803 if (params.size() > 1) {
2804 shift = csiIsShift(params.get(1));
2805 alt = csiIsAlt(params.get(1));
2806 ctrl = csiIsCtrl(params.get(1));
2807 }
2808 events.add(new TKeypressEvent(kbRight, alt, ctrl, shift));
2809 resetParser();
2810 return;
2811 case 'D':
2812 // Left
2813 if (params.size() > 1) {
2814 shift = csiIsShift(params.get(1));
2815 alt = csiIsAlt(params.get(1));
2816 ctrl = csiIsCtrl(params.get(1));
2817 }
2818 events.add(new TKeypressEvent(kbLeft, alt, ctrl, shift));
2819 resetParser();
2820 return;
2821 case 'H':
2822 // Home
2823 if (params.size() > 1) {
2824 shift = csiIsShift(params.get(1));
2825 alt = csiIsAlt(params.get(1));
2826 ctrl = csiIsCtrl(params.get(1));
2827 }
2828 events.add(new TKeypressEvent(kbHome, alt, ctrl, shift));
2829 resetParser();
2830 return;
2831 case 'F':
2832 // End
2833 if (params.size() > 1) {
2834 shift = csiIsShift(params.get(1));
2835 alt = csiIsAlt(params.get(1));
2836 ctrl = csiIsCtrl(params.get(1));
2837 }
2838 events.add(new TKeypressEvent(kbEnd, alt, ctrl, shift));
2839 resetParser();
2840 return;
2841 case 'c':
2842 // Device Attributes
2843 if (decPrivateModeFlag == false) {
2844 break;
2845 }
2846 boolean jexerImages = false;
2847 for (String x: params) {
2848 if (x.equals("4")) {
2849 // Terminal reports sixel support
2850 if (debugToStderr) {
2851 System.err.println("Device Attributes: sixel");
2852 }
2853 }
2854 if (x.equals("444")) {
2855 // Terminal reports Jexer images support
2856 if (debugToStderr) {
2857 System.err.println("Device Attributes: Jexer images");
2858 }
2859 jexerImages = true;
2860 }
2861 }
2862 if (jexerImages == false) {
2863 // Terminal does not support Jexer images, disable
2864 // them.
2865 jexerImageOption = JexerImageOption.DISABLED;
2866 }
2867 return;
2868 case 't':
2869 // windowOps
2870 if ((params.size() > 2) && (params.get(0).equals("4"))) {
2871 if (debugToStderr) {
2872 System.err.printf("windowOp pixels: " +
2873 "height %s width %s\n",
2874 params.get(1), params.get(2));
2875 }
2876 try {
2877 widthPixels = Integer.parseInt(params.get(2));
2878 heightPixels = Integer.parseInt(params.get(1));
2879 } catch (NumberFormatException e) {
2880 if (debugToStderr) {
2881 e.printStackTrace();
2882 }
2883 }
2884 if (widthPixels <= 0) {
2885 widthPixels = 640;
2886 }
2887 if (heightPixels <= 0) {
2888 heightPixels = 400;
2889 }
2890 }
2891 if ((params.size() > 2) && (params.get(0).equals("6"))) {
2892 if (debugToStderr) {
2893 System.err.printf("windowOp text cell pixels: " +
2894 "height %s width %s\n",
2895 params.get(1), params.get(2));
2896 }
2897 try {
2898 widthPixels = width * Integer.parseInt(params.get(2));
2899 heightPixels = height * Integer.parseInt(params.get(1));
2900 } catch (NumberFormatException e) {
2901 if (debugToStderr) {
2902 e.printStackTrace();
2903 }
2904 }
2905 if (widthPixels <= 0) {
2906 widthPixels = 640;
2907 }
2908 if (heightPixels <= 0) {
2909 heightPixels = 400;
2910 }
2911 }
2912 resetParser();
2913 return;
2914 default:
2915 break;
2916 }
2917 }
2918
2919 // Unknown keystroke, ignore
2920 resetParser();
2921 return;
2922
2923 case MOUSE:
2924 params.set(0, params.get(params.size() - 1) + ch);
2925 if (params.get(0).length() == 3) {
2926 // We have enough to generate a mouse event
2927 events.add(parseMouse());
2928 resetParser();
2929 }
2930 return;
2931
2932 default:
2933 break;
2934 }
2935
2936 // This "should" be impossible to reach
2937 return;
2938 }
2939
2940 /**
2941 * Request (u)xterm to use the sixel settings we need:
2942 *
2943 * - enable sixel scrolling
2944 *
2945 * - disable private color registers (so that we can use one common
2946 * palette) if sixelSharedPalette is set
2947 *
2948 * @return the string to emit to xterm
2949 */
2950 private String xtermSetSixelSettings() {
2951 if (sixelSharedPalette == true) {
2952 return "\033[?80h\033[?1070l";
2953 } else {
2954 return "\033[?80h\033[?1070h";
2955 }
2956 }
2957
2958 /**
2959 * Restore (u)xterm its default sixel settings:
2960 *
2961 * - enable sixel scrolling
2962 *
2963 * - enable private color registers
2964 *
2965 * @return the string to emit to xterm
2966 */
2967 private String xtermResetSixelSettings() {
2968 return "\033[?80h\033[?1070h";
2969 }
2970
2971 /**
2972 * Request (u)xterm to report the current window and cell size dimensions
2973 * in pixels.
2974 *
2975 * @return the string to emit to xterm
2976 */
2977 private String xtermReportPixelDimensions() {
2978 // We will ask for both window and text cell dimensions, and
2979 // hopefully one of them will work.
2980 return "\033[14t\033[16t";
2981 }
2982
2983 /**
2984 * Tell (u)xterm that we want alt- keystrokes to send escape + character
2985 * rather than set the 8th bit. Anyone who wants UTF8 should want this
2986 * enabled.
2987 *
2988 * @param on if true, enable metaSendsEscape
2989 * @return the string to emit to xterm
2990 */
2991 private String xtermMetaSendsEscape(final boolean on) {
2992 if (on) {
2993 return "\033[?1036h\033[?1034l";
2994 }
2995 return "\033[?1036l";
2996 }
2997
2998 /**
2999 * Create an xterm OSC sequence to change the window title.
3000 *
3001 * @param title the new title
3002 * @return the string to emit to xterm
3003 */
3004 private String getSetTitleString(final String title) {
3005 return "\033]2;" + title + "\007";
3006 }
3007
3008 // ------------------------------------------------------------------------
3009 // Sixel output support ---------------------------------------------------
3010 // ------------------------------------------------------------------------
3011
3012 /**
3013 * Get the number of colors in the sixel palette.
3014 *
3015 * @return the palette size
3016 */
3017 public int getSixelPaletteSize() {
3018 return sixelPaletteSize;
3019 }
3020
3021 /**
3022 * Set the number of colors in the sixel palette.
3023 *
3024 * @param paletteSize the new palette size
3025 */
3026 public void setSixelPaletteSize(final int paletteSize) {
3027 if (paletteSize == sixelPaletteSize) {
3028 return;
3029 }
3030
3031 switch (paletteSize) {
3032 case 2:
3033 case 256:
3034 case 512:
3035 case 1024:
3036 case 2048:
3037 break;
3038 default:
3039 throw new IllegalArgumentException("Unsupported sixel palette " +
3040 " size: " + paletteSize);
3041 }
3042
3043 // Don't step on the screen refresh thread.
3044 synchronized (this) {
3045 sixelPaletteSize = paletteSize;
3046 palette = null;
3047 sixelCache = null;
3048 clearPhysical();
3049 }
3050 }
3051
3052 /**
3053 * Start a sixel string for display one row's worth of bitmap data.
3054 *
3055 * @param x column coordinate. 0 is the left-most column.
3056 * @param y row coordinate. 0 is the top-most row.
3057 * @return the string to emit to an ANSI / ECMA-style terminal
3058 */
3059 private String startSixel(final int x, final int y) {
3060 StringBuilder sb = new StringBuilder();
3061
3062 assert (sixel == true);
3063
3064 // Place the cursor
3065 sb.append(gotoXY(x, y));
3066
3067 // DCS
3068 sb.append("\033Pq");
3069
3070 if (palette == null) {
3071 palette = new SixelPalette();
3072 if (sixelSharedPalette == true) {
3073 palette.emitPalette(sb, null);
3074 }
3075 }
3076
3077 return sb.toString();
3078 }
3079
3080 /**
3081 * End a sixel string for display one row's worth of bitmap data.
3082 *
3083 * @return the string to emit to an ANSI / ECMA-style terminal
3084 */
3085 private String endSixel() {
3086 assert (sixel == true);
3087
3088 // ST
3089 return ("\033\\");
3090 }
3091
3092 /**
3093 * Create a sixel string representing a row of several cells containing
3094 * bitmap data.
3095 *
3096 * @param x column coordinate. 0 is the left-most column.
3097 * @param y row coordinate. 0 is the top-most row.
3098 * @param cells the cells containing the bitmap data
3099 * @return the string to emit to an ANSI / ECMA-style terminal
3100 */
3101 private String toSixel(final int x, final int y,
3102 final ArrayList<Cell> cells) {
3103
3104 StringBuilder sb = new StringBuilder();
3105
3106 assert (cells != null);
3107 assert (cells.size() > 0);
3108 assert (cells.get(0).getImage() != null);
3109
3110 if (sixel == false) {
3111 sb.append(normal());
3112 sb.append(gotoXY(x, y));
3113 for (int i = 0; i < cells.size(); i++) {
3114 sb.append(' ');
3115 }
3116 return sb.toString();
3117 }
3118
3119 if (y == height - 1) {
3120 // We are on the bottom row. If scrolling mode is enabled
3121 // (default), then VT320/xterm will scroll the entire screen if
3122 // we draw any pixels here. Do not draw the image, bail out
3123 // instead.
3124 sb.append(normal());
3125 sb.append(gotoXY(x, y));
3126 for (int j = 0; j < cells.size(); j++) {
3127 sb.append(' ');
3128 }
3129 return sb.toString();
3130 }
3131
3132 if (sixelCache == null) {
3133 sixelCache = new ImageCache(height * 10);
3134 }
3135
3136 // Save and get rows to/from the cache that do NOT have inverted
3137 // cells.
3138 boolean saveInCache = true;
3139 for (Cell cell: cells) {
3140 if (cell.isInvertedImage()) {
3141 saveInCache = false;
3142 }
3143 }
3144 if (saveInCache) {
3145 String cachedResult = sixelCache.get(cells);
3146 if (cachedResult != null) {
3147 // System.err.println("CACHE HIT");
3148 sb.append(startSixel(x, y));
3149 sb.append(cachedResult);
3150 sb.append(endSixel());
3151 return sb.toString();
3152 }
3153 // System.err.println("CACHE MISS");
3154 }
3155
3156 int imageWidth = cells.get(0).getImage().getWidth();
3157 int imageHeight = cells.get(0).getImage().getHeight();
3158
3159 // cells.get(x).getImage() has a dithered bitmap containing indexes
3160 // into the color palette. Piece these together into one larger
3161 // image for final rendering.
3162 int totalWidth = 0;
3163 int fullWidth = cells.size() * getTextWidth();
3164 int fullHeight = getTextHeight();
3165 for (int i = 0; i < cells.size(); i++) {
3166 totalWidth += cells.get(i).getImage().getWidth();
3167 }
3168
3169 BufferedImage image = new BufferedImage(fullWidth,
3170 fullHeight, BufferedImage.TYPE_INT_ARGB);
3171
3172 int [] rgbArray;
3173 for (int i = 0; i < cells.size() - 1; i++) {
3174 int tileWidth = Math.min(cells.get(i).getImage().getWidth(),
3175 imageWidth);
3176 int tileHeight = Math.min(cells.get(i).getImage().getHeight(),
3177 imageHeight);
3178
3179 if (false && cells.get(i).isInvertedImage()) {
3180 // I used to put an all-white cell over the cursor, don't do
3181 // that anymore.
3182 rgbArray = new int[imageWidth * imageHeight];
3183 for (int j = 0; j < rgbArray.length; j++) {
3184 rgbArray[j] = 0xFFFFFF;
3185 }
3186 } else {
3187 try {
3188 rgbArray = cells.get(i).getImage().getRGB(0, 0,
3189 tileWidth, tileHeight, null, 0, tileWidth);
3190 } catch (Exception e) {
3191 throw new RuntimeException("image " + imageWidth + "x" +
3192 imageHeight +
3193 "tile " + tileWidth + "x" +
3194 tileHeight +
3195 " cells.get(i).getImage() " +
3196 cells.get(i).getImage() +
3197 " i " + i +
3198 " fullWidth " + fullWidth +
3199 " fullHeight " + fullHeight, e);
3200 }
3201 }
3202
3203 /*
3204 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
3205 i * imageWidth, 0, imageWidth, imageHeight,
3206 0, imageWidth);
3207 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
3208 fullWidth, fullHeight, cells.size(), getTextWidth());
3209 */
3210
3211 image.setRGB(i * imageWidth, 0, tileWidth, tileHeight,
3212 rgbArray, 0, tileWidth);
3213 if (tileHeight < fullHeight) {
3214 int backgroundColor = cells.get(i).getBackground().getRGB();
3215 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
3216 for (int imageY = imageHeight; imageY < fullHeight;
3217 imageY++) {
3218
3219 image.setRGB(imageX, imageY, backgroundColor);
3220 }
3221 }
3222 }
3223 }
3224 totalWidth -= ((cells.size() - 1) * imageWidth);
3225 if (false && cells.get(cells.size() - 1).isInvertedImage()) {
3226 // I used to put an all-white cell over the cursor, don't do that
3227 // anymore.
3228 rgbArray = new int[totalWidth * imageHeight];
3229 for (int j = 0; j < rgbArray.length; j++) {
3230 rgbArray[j] = 0xFFFFFF;
3231 }
3232 } else {
3233 try {
3234 rgbArray = cells.get(cells.size() - 1).getImage().getRGB(0, 0,
3235 totalWidth, imageHeight, null, 0, totalWidth);
3236 } catch (Exception e) {
3237 throw new RuntimeException("image " + imageWidth + "x" +
3238 imageHeight + " cells.get(cells.size() - 1).getImage() " +
3239 cells.get(cells.size() - 1).getImage(), e);
3240 }
3241 }
3242 image.setRGB((cells.size() - 1) * imageWidth, 0, totalWidth,
3243 imageHeight, rgbArray, 0, totalWidth);
3244
3245 if (totalWidth < getTextWidth()) {
3246 int backgroundColor = cells.get(cells.size() - 1).getBackground().getRGB();
3247
3248 for (int imageX = image.getWidth() - totalWidth;
3249 imageX < image.getWidth(); imageX++) {
3250
3251 for (int imageY = 0; imageY < fullHeight; imageY++) {
3252 image.setRGB(imageX, imageY, backgroundColor);
3253 }
3254 }
3255 }
3256
3257 // Dither the image. It is ok to lose the original here.
3258 if (palette == null) {
3259 palette = new SixelPalette();
3260 if (sixelSharedPalette == true) {
3261 palette.emitPalette(sb, null);
3262 }
3263 }
3264 image = palette.ditherImage(image);
3265
3266 // Collect the raster information
3267 int rasterHeight = 0;
3268 int rasterWidth = image.getWidth();
3269
3270 if (sixelSharedPalette == false) {
3271 // Emit the palette, but only for the colors actually used by
3272 // these cells.
3273 boolean [] usedColors = new boolean[sixelPaletteSize];
3274 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
3275 for (int imageY = 0; imageY < image.getHeight(); imageY++) {
3276 usedColors[image.getRGB(imageX, imageY)] = true;
3277 }
3278 }
3279 palette.emitPalette(sb, usedColors);
3280 }
3281
3282 // Render the entire row of cells.
3283 for (int currentRow = 0; currentRow < fullHeight; currentRow += 6) {
3284 int [][] sixels = new int[image.getWidth()][6];
3285
3286 // See which colors are actually used in this band of sixels.
3287 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
3288 for (int imageY = 0;
3289 (imageY < 6) && (imageY + currentRow < fullHeight);
3290 imageY++) {
3291
3292 int colorIdx = image.getRGB(imageX, imageY + currentRow);
3293 assert (colorIdx >= 0);
3294 assert (colorIdx < sixelPaletteSize);
3295
3296 sixels[imageX][imageY] = colorIdx;
3297 }
3298 }
3299
3300 for (int i = 0; i < sixelPaletteSize; i++) {
3301 boolean isUsed = false;
3302 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
3303 for (int j = 0; j < 6; j++) {
3304 if (sixels[imageX][j] == i) {
3305 isUsed = true;
3306 }
3307 }
3308 }
3309 if (isUsed == false) {
3310 continue;
3311 }
3312
3313 // Set to the beginning of scan line for the next set of
3314 // colored pixels, and select the color.
3315 sb.append(String.format("$#%d", i));
3316
3317 int oldData = -1;
3318 int oldDataCount = 0;
3319 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
3320
3321 // Add up all the pixels that match this color.
3322 int data = 0;
3323 for (int j = 0;
3324 (j < 6) && (currentRow + j < fullHeight);
3325 j++) {
3326
3327 if (sixels[imageX][j] == i) {
3328 switch (j) {
3329 case 0:
3330 data += 1;
3331 break;
3332 case 1:
3333 data += 2;
3334 break;
3335 case 2:
3336 data += 4;
3337 break;
3338 case 3:
3339 data += 8;
3340 break;
3341 case 4:
3342 data += 16;
3343 break;
3344 case 5:
3345 data += 32;
3346 break;
3347 }
3348 if ((currentRow + j + 1) > rasterHeight) {
3349 rasterHeight = currentRow + j + 1;
3350 }
3351 }
3352 }
3353 assert (data >= 0);
3354 assert (data < 64);
3355 data += 63;
3356
3357 if (data == oldData) {
3358 oldDataCount++;
3359 } else {
3360 if (oldDataCount == 1) {
3361 sb.append((char) oldData);
3362 } else if (oldDataCount > 1) {
3363 sb.append(String.format("!%d", oldDataCount));
3364 sb.append((char) oldData);
3365 }
3366 oldDataCount = 1;
3367 oldData = data;
3368 }
3369
3370 } // for (int imageX = 0; imageX < image.getWidth(); imageX++)
3371
3372 // Emit the last sequence.
3373 if (oldDataCount == 1) {
3374 sb.append((char) oldData);
3375 } else if (oldDataCount > 1) {
3376 sb.append(String.format("!%d", oldDataCount));
3377 sb.append((char) oldData);
3378 }
3379
3380 } // for (int i = 0; i < sixelPaletteSize; i++)
3381
3382 // Advance to the next scan line.
3383 sb.append("-");
3384
3385 } // for (int currentRow = 0; currentRow < imageHeight; currentRow += 6)
3386
3387 // Kill the very last "-", because it is unnecessary.
3388 sb.deleteCharAt(sb.length() - 1);
3389
3390 // Add the raster information
3391 sb.insert(0, String.format("\"1;1;%d;%d", rasterWidth, rasterHeight));
3392
3393 if (saveInCache) {
3394 // This row is OK to save into the cache.
3395 sixelCache.put(cells, sb.toString());
3396 }
3397
3398 return (startSixel(x, y) + sb.toString() + endSixel());
3399 }
3400
3401 /**
3402 * Get the sixel support flag.
3403 *
3404 * @return true if this terminal is emitting sixel
3405 */
3406 public boolean hasSixel() {
3407 return sixel;
3408 }
3409
3410 // ------------------------------------------------------------------------
3411 // End sixel output support -----------------------------------------------
3412 // ------------------------------------------------------------------------
3413
3414 // ------------------------------------------------------------------------
3415 // iTerm2 image output support --------------------------------------------
3416 // ------------------------------------------------------------------------
3417
3418 /**
3419 * Create an iTerm2 images string representing a row of several cells
3420 * containing bitmap data.
3421 *
3422 * @param x column coordinate. 0 is the left-most column.
3423 * @param y row coordinate. 0 is the top-most row.
3424 * @param cells the cells containing the bitmap data
3425 * @return the string to emit to an ANSI / ECMA-style terminal
3426 */
3427 private String toIterm2Image(final int x, final int y,
3428 final ArrayList<Cell> cells) {
3429
3430 StringBuilder sb = new StringBuilder();
3431
3432 assert (cells != null);
3433 assert (cells.size() > 0);
3434 assert (cells.get(0).getImage() != null);
3435
3436 if (iterm2Images == false) {
3437 sb.append(normal());
3438 sb.append(gotoXY(x, y));
3439 for (int i = 0; i < cells.size(); i++) {
3440 sb.append(' ');
3441 }
3442 return sb.toString();
3443 }
3444
3445 if (iterm2Cache == null) {
3446 iterm2Cache = new ImageCache(height * 10);
3447 base64 = java.util.Base64.getEncoder();
3448 }
3449
3450 // Save and get rows to/from the cache that do NOT have inverted
3451 // cells.
3452 boolean saveInCache = true;
3453 for (Cell cell: cells) {
3454 if (cell.isInvertedImage()) {
3455 saveInCache = false;
3456 }
3457 }
3458 if (saveInCache) {
3459 String cachedResult = iterm2Cache.get(cells);
3460 if (cachedResult != null) {
3461 // System.err.println("CACHE HIT");
3462 sb.append(gotoXY(x, y));
3463 sb.append(cachedResult);
3464 return sb.toString();
3465 }
3466 // System.err.println("CACHE MISS");
3467 }
3468
3469 int imageWidth = cells.get(0).getImage().getWidth();
3470 int imageHeight = cells.get(0).getImage().getHeight();
3471
3472 // Piece cells.get(x).getImage() pieces together into one larger
3473 // image for final rendering.
3474 int totalWidth = 0;
3475 int fullWidth = cells.size() * getTextWidth();
3476 int fullHeight = getTextHeight();
3477 for (int i = 0; i < cells.size(); i++) {
3478 totalWidth += cells.get(i).getImage().getWidth();
3479 }
3480
3481 BufferedImage image = new BufferedImage(fullWidth,
3482 fullHeight, BufferedImage.TYPE_INT_ARGB);
3483
3484 int [] rgbArray;
3485 for (int i = 0; i < cells.size() - 1; i++) {
3486 int tileWidth = Math.min(cells.get(i).getImage().getWidth(),
3487 imageWidth);
3488 int tileHeight = Math.min(cells.get(i).getImage().getHeight(),
3489 imageHeight);
3490 if (false && cells.get(i).isInvertedImage()) {
3491 // I used to put an all-white cell over the cursor, don't do
3492 // that anymore.
3493 rgbArray = new int[imageWidth * imageHeight];
3494 for (int j = 0; j < rgbArray.length; j++) {
3495 rgbArray[j] = 0xFFFFFF;
3496 }
3497 } else {
3498 try {
3499 rgbArray = cells.get(i).getImage().getRGB(0, 0,
3500 tileWidth, tileHeight, null, 0, tileWidth);
3501 } catch (Exception e) {
3502 throw new RuntimeException("image " + imageWidth + "x" +
3503 imageHeight +
3504 "tile " + tileWidth + "x" +
3505 tileHeight +
3506 " cells.get(i).getImage() " +
3507 cells.get(i).getImage() +
3508 " i " + i +
3509 " fullWidth " + fullWidth +
3510 " fullHeight " + fullHeight, e);
3511 }
3512 }
3513
3514 /*
3515 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
3516 i * imageWidth, 0, imageWidth, imageHeight,
3517 0, imageWidth);
3518 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
3519 fullWidth, fullHeight, cells.size(), getTextWidth());
3520 */
3521
3522 image.setRGB(i * imageWidth, 0, tileWidth, tileHeight,
3523 rgbArray, 0, tileWidth);
3524 if (tileHeight < fullHeight) {
3525 int backgroundColor = cells.get(i).getBackground().getRGB();
3526 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
3527 for (int imageY = imageHeight; imageY < fullHeight;
3528 imageY++) {
3529
3530 image.setRGB(imageX, imageY, backgroundColor);
3531 }
3532 }
3533 }
3534 }
3535 totalWidth -= ((cells.size() - 1) * imageWidth);
3536 if (false && cells.get(cells.size() - 1).isInvertedImage()) {
3537 // I used to put an all-white cell over the cursor, don't do that
3538 // anymore.
3539 rgbArray = new int[totalWidth * imageHeight];
3540 for (int j = 0; j < rgbArray.length; j++) {
3541 rgbArray[j] = 0xFFFFFF;
3542 }
3543 } else {
3544 try {
3545 rgbArray = cells.get(cells.size() - 1).getImage().getRGB(0, 0,
3546 totalWidth, imageHeight, null, 0, totalWidth);
3547 } catch (Exception e) {
3548 throw new RuntimeException("image " + imageWidth + "x" +
3549 imageHeight + " cells.get(cells.size() - 1).getImage() " +
3550 cells.get(cells.size() - 1).getImage(), e);
3551 }
3552 }
3553 image.setRGB((cells.size() - 1) * imageWidth, 0, totalWidth,
3554 imageHeight, rgbArray, 0, totalWidth);
3555
3556 if (totalWidth < getTextWidth()) {
3557 int backgroundColor = cells.get(cells.size() - 1).getBackground().getRGB();
3558
3559 for (int imageX = image.getWidth() - totalWidth;
3560 imageX < image.getWidth(); imageX++) {
3561
3562 for (int imageY = 0; imageY < fullHeight; imageY++) {
3563 image.setRGB(imageX, imageY, backgroundColor);
3564 }
3565 }
3566 }
3567
3568 /*
3569 * From https://iterm2.com/documentation-images.html:
3570 *
3571 * Protocol
3572 *
3573 * iTerm2 extends the xterm protocol with a set of proprietary escape
3574 * sequences. In general, the pattern is:
3575 *
3576 * ESC ] 1337 ; key = value ^G
3577 *
3578 * Whitespace is shown here for ease of reading: in practice, no
3579 * spaces should be used.
3580 *
3581 * For file transfer and inline images, the code is:
3582 *
3583 * ESC ] 1337 ; File = [optional arguments] : base-64 encoded file contents ^G
3584 *
3585 * The optional arguments are formatted as key=value with a semicolon
3586 * between each key-value pair. They are described below:
3587 *
3588 * Key Description of value
3589 * name base-64 encoded filename. Defaults to "Unnamed file".
3590 * size File size in bytes. Optional; this is only used by the
3591 * progress indicator.
3592 * width Width to render. See notes below.
3593 * height Height to render. See notes below.
3594 * preserveAspectRatio If set to 0, then the image's inherent aspect
3595 * ratio will not be respected; otherwise, it
3596 * will fill the specified width and height as
3597 * much as possible without stretching. Defaults
3598 * to 1.
3599 * inline If set to 1, the file will be displayed inline. Otherwise,
3600 * it will be downloaded with no visual representation in the
3601 * terminal session. Defaults to 0.
3602 *
3603 * The width and height are given as a number followed by a unit, or
3604 * the word "auto".
3605 *
3606 * N: N character cells.
3607 * Npx: N pixels.
3608 * N%: N percent of the session's width or height.
3609 * auto: The image's inherent size will be used to determine an
3610 * appropriate dimension.
3611 *
3612 */
3613
3614 // File contents can be several image formats. We will use PNG.
3615 ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream(1024);
3616 try {
3617 if (!ImageIO.write(image.getSubimage(0, 0, image.getWidth(),
3618 Math.min(image.getHeight(), fullHeight)),
3619 "PNG", pngOutputStream)
3620 ) {
3621 // We failed to render image, bail out.
3622 return "";
3623 }
3624 } catch (IOException e) {
3625 // We failed to render image, bail out.
3626 return "";
3627 }
3628
3629 sb.append("\033]1337;File=");
3630 /*
3631 sb.append(String.format("width=$d;height=1;preserveAspectRatio=1;",
3632 cells.size()));
3633 */
3634 /*
3635 sb.append(String.format("width=$dpx;height=%dpx;preserveAspectRatio=1;",
3636 image.getWidth(), Math.min(image.getHeight(),
3637 getTextHeight())));
3638 */
3639 sb.append("inline=1:");
3640 sb.append(base64.encodeToString(pngOutputStream.toByteArray()));
3641 sb.append("\007");
3642
3643 if (saveInCache) {
3644 // This row is OK to save into the cache.
3645 iterm2Cache.put(cells, sb.toString());
3646 }
3647
3648 return (gotoXY(x, y) + sb.toString());
3649 }
3650
3651 /**
3652 * Get the iTerm2 images support flag.
3653 *
3654 * @return true if this terminal is emitting iTerm2 images
3655 */
3656 public boolean hasIterm2Images() {
3657 return iterm2Images;
3658 }
3659
3660 // ------------------------------------------------------------------------
3661 // End iTerm2 image output support ----------------------------------------
3662 // ------------------------------------------------------------------------
3663
3664 // ------------------------------------------------------------------------
3665 // Jexer image output support ---------------------------------------------
3666 // ------------------------------------------------------------------------
3667
3668 /**
3669 * Create a Jexer images string representing a row of several cells
3670 * containing bitmap data.
3671 *
3672 * @param x column coordinate. 0 is the left-most column.
3673 * @param y row coordinate. 0 is the top-most row.
3674 * @param cells the cells containing the bitmap data
3675 * @return the string to emit to an ANSI / ECMA-style terminal
3676 */
3677 private String toJexerImage(final int x, final int y,
3678 final ArrayList<Cell> cells) {
3679
3680 StringBuilder sb = new StringBuilder();
3681
3682 assert (cells != null);
3683 assert (cells.size() > 0);
3684 assert (cells.get(0).getImage() != null);
3685
3686 if (jexerImageOption == JexerImageOption.DISABLED) {
3687 sb.append(normal());
3688 sb.append(gotoXY(x, y));
3689 for (int i = 0; i < cells.size(); i++) {
3690 sb.append(' ');
3691 }
3692 return sb.toString();
3693 }
3694
3695 if (jexerCache == null) {
3696 jexerCache = new ImageCache(height * 10);
3697 base64 = java.util.Base64.getEncoder();
3698 }
3699
3700 // Save and get rows to/from the cache that do NOT have inverted
3701 // cells.
3702 boolean saveInCache = true;
3703 for (Cell cell: cells) {
3704 if (cell.isInvertedImage()) {
3705 saveInCache = false;
3706 }
3707 }
3708 if (saveInCache) {
3709 String cachedResult = jexerCache.get(cells);
3710 if (cachedResult != null) {
3711 // System.err.println("CACHE HIT");
3712 sb.append(gotoXY(x, y));
3713 sb.append(cachedResult);
3714 return sb.toString();
3715 }
3716 // System.err.println("CACHE MISS");
3717 }
3718
3719 int imageWidth = cells.get(0).getImage().getWidth();
3720 int imageHeight = cells.get(0).getImage().getHeight();
3721
3722 // Piece cells.get(x).getImage() pieces together into one larger
3723 // image for final rendering.
3724 int totalWidth = 0;
3725 int fullWidth = cells.size() * getTextWidth();
3726 int fullHeight = getTextHeight();
3727 for (int i = 0; i < cells.size(); i++) {
3728 totalWidth += cells.get(i).getImage().getWidth();
3729 }
3730
3731 BufferedImage image = new BufferedImage(fullWidth,
3732 fullHeight, BufferedImage.TYPE_INT_ARGB);
3733
3734 int [] rgbArray;
3735 for (int i = 0; i < cells.size() - 1; i++) {
3736 int tileWidth = Math.min(cells.get(i).getImage().getWidth(),
3737 imageWidth);
3738 int tileHeight = Math.min(cells.get(i).getImage().getHeight(),
3739 imageHeight);
3740 if (false && cells.get(i).isInvertedImage()) {
3741 // I used to put an all-white cell over the cursor, don't do
3742 // that anymore.
3743 rgbArray = new int[imageWidth * imageHeight];
3744 for (int j = 0; j < rgbArray.length; j++) {
3745 rgbArray[j] = 0xFFFFFF;
3746 }
3747 } else {
3748 try {
3749 rgbArray = cells.get(i).getImage().getRGB(0, 0,
3750 tileWidth, tileHeight, null, 0, tileWidth);
3751 } catch (Exception e) {
3752 throw new RuntimeException("image " + imageWidth + "x" +
3753 imageHeight +
3754 "tile " + tileWidth + "x" +
3755 tileHeight +
3756 " cells.get(i).getImage() " +
3757 cells.get(i).getImage() +
3758 " i " + i +
3759 " fullWidth " + fullWidth +
3760 " fullHeight " + fullHeight, e);
3761 }
3762 }
3763
3764 /*
3765 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
3766 i * imageWidth, 0, imageWidth, imageHeight,
3767 0, imageWidth);
3768 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
3769 fullWidth, fullHeight, cells.size(), getTextWidth());
3770 */
3771
3772 image.setRGB(i * imageWidth, 0, tileWidth, tileHeight,
3773 rgbArray, 0, tileWidth);
3774 if (tileHeight < fullHeight) {
3775 int backgroundColor = cells.get(i).getBackground().getRGB();
3776 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
3777 for (int imageY = imageHeight; imageY < fullHeight;
3778 imageY++) {
3779
3780 image.setRGB(imageX, imageY, backgroundColor);
3781 }
3782 }
3783 }
3784 }
3785 totalWidth -= ((cells.size() - 1) * imageWidth);
3786 if (false && cells.get(cells.size() - 1).isInvertedImage()) {
3787 // I used to put an all-white cell over the cursor, don't do that
3788 // anymore.
3789 rgbArray = new int[totalWidth * imageHeight];
3790 for (int j = 0; j < rgbArray.length; j++) {
3791 rgbArray[j] = 0xFFFFFF;
3792 }
3793 } else {
3794 try {
3795 rgbArray = cells.get(cells.size() - 1).getImage().getRGB(0, 0,
3796 totalWidth, imageHeight, null, 0, totalWidth);
3797 } catch (Exception e) {
3798 throw new RuntimeException("image " + imageWidth + "x" +
3799 imageHeight + " cells.get(cells.size() - 1).getImage() " +
3800 cells.get(cells.size() - 1).getImage(), e);
3801 }
3802 }
3803 image.setRGB((cells.size() - 1) * imageWidth, 0, totalWidth,
3804 imageHeight, rgbArray, 0, totalWidth);
3805
3806 if (totalWidth < getTextWidth()) {
3807 int backgroundColor = cells.get(cells.size() - 1).getBackground().getRGB();
3808
3809 for (int imageX = image.getWidth() - totalWidth;
3810 imageX < image.getWidth(); imageX++) {
3811
3812 for (int imageY = 0; imageY < fullHeight; imageY++) {
3813 image.setRGB(imageX, imageY, backgroundColor);
3814 }
3815 }
3816 }
3817
3818 if (jexerImageOption == JexerImageOption.PNG) {
3819 // Encode as PNG
3820 ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream(1024);
3821 try {
3822 if (!ImageIO.write(image.getSubimage(0, 0, image.getWidth(),
3823 Math.min(image.getHeight(), fullHeight)),
3824 "PNG", pngOutputStream)
3825 ) {
3826 // We failed to render image, bail out.
3827 return "";
3828 }
3829 } catch (IOException e) {
3830 // We failed to render image, bail out.
3831 return "";
3832 }
3833
3834 sb.append("\033]444;1;0;");
3835 sb.append(base64.encodeToString(pngOutputStream.toByteArray()));
3836 sb.append("\007");
3837
3838 } else if (jexerImageOption == JexerImageOption.JPG) {
3839
3840 // Encode as JPG
3841 ByteArrayOutputStream jpgOutputStream = new ByteArrayOutputStream(1024);
3842
3843 // Convert from ARGB to RGB, otherwise the JPG encode will fail.
3844 BufferedImage jpgImage = new BufferedImage(image.getWidth(),
3845 image.getHeight(), BufferedImage.TYPE_INT_RGB);
3846 int [] pixels = new int[image.getWidth() * image.getHeight()];
3847 image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels,
3848 0, image.getWidth());
3849 jpgImage.setRGB(0, 0, image.getWidth(), image.getHeight(), pixels,
3850 0, image.getWidth());
3851
3852 try {
3853 if (!ImageIO.write(jpgImage.getSubimage(0, 0,
3854 jpgImage.getWidth(),
3855 Math.min(jpgImage.getHeight(), fullHeight)),
3856 "JPG", jpgOutputStream)
3857 ) {
3858 // We failed to render image, bail out.
3859 return "";
3860 }
3861 } catch (IOException e) {
3862 // We failed to render image, bail out.
3863 return "";
3864 }
3865
3866 sb.append("\033]444;2;0;");
3867 sb.append(base64.encodeToString(jpgOutputStream.toByteArray()));
3868 sb.append("\007");
3869
3870 } else if (jexerImageOption == JexerImageOption.RGB) {
3871
3872 // RGB
3873 sb.append(String.format("\033]444;0;%d;%d;0;", image.getWidth(),
3874 Math.min(image.getHeight(), fullHeight)));
3875
3876 byte [] bytes = new byte[image.getWidth() * image.getHeight() * 3];
3877 int stride = image.getWidth();
3878 for (int px = 0; px < stride; px++) {
3879 for (int py = 0; py < image.getHeight(); py++) {
3880 int rgb = image.getRGB(px, py);
3881 bytes[(py * stride * 3) + (px * 3)] = (byte) ((rgb >>> 16) & 0xFF);
3882 bytes[(py * stride * 3) + (px * 3) + 1] = (byte) ((rgb >>> 8) & 0xFF);
3883 bytes[(py * stride * 3) + (px * 3) + 2] = (byte) ( rgb & 0xFF);
3884 }
3885 }
3886 sb.append(base64.encodeToString(bytes));
3887 sb.append("\007");
3888 }
3889
3890 if (saveInCache) {
3891 // This row is OK to save into the cache.
3892 jexerCache.put(cells, sb.toString());
3893 }
3894
3895 return (gotoXY(x, y) + sb.toString());
3896 }
3897
3898 /**
3899 * Get the Jexer images support flag.
3900 *
3901 * @return true if this terminal is emitting Jexer images
3902 */
3903 public boolean hasJexerImages() {
3904 return (jexerImageOption != JexerImageOption.DISABLED);
3905 }
3906
3907 // ------------------------------------------------------------------------
3908 // End Jexer image output support -----------------------------------------
3909 // ------------------------------------------------------------------------
3910
3911 /**
3912 * Setup system colors to match DOS color palette.
3913 */
3914 private void setDOSColors() {
3915 MYBLACK = new java.awt.Color(0x00, 0x00, 0x00);
3916 MYRED = new java.awt.Color(0xa8, 0x00, 0x00);
3917 MYGREEN = new java.awt.Color(0x00, 0xa8, 0x00);
3918 MYYELLOW = new java.awt.Color(0xa8, 0x54, 0x00);
3919 MYBLUE = new java.awt.Color(0x00, 0x00, 0xa8);
3920 MYMAGENTA = new java.awt.Color(0xa8, 0x00, 0xa8);
3921 MYCYAN = new java.awt.Color(0x00, 0xa8, 0xa8);
3922 MYWHITE = new java.awt.Color(0xa8, 0xa8, 0xa8);
3923 MYBOLD_BLACK = new java.awt.Color(0x54, 0x54, 0x54);
3924 MYBOLD_RED = new java.awt.Color(0xfc, 0x54, 0x54);
3925 MYBOLD_GREEN = new java.awt.Color(0x54, 0xfc, 0x54);
3926 MYBOLD_YELLOW = new java.awt.Color(0xfc, 0xfc, 0x54);
3927 MYBOLD_BLUE = new java.awt.Color(0x54, 0x54, 0xfc);
3928 MYBOLD_MAGENTA = new java.awt.Color(0xfc, 0x54, 0xfc);
3929 MYBOLD_CYAN = new java.awt.Color(0x54, 0xfc, 0xfc);
3930 MYBOLD_WHITE = new java.awt.Color(0xfc, 0xfc, 0xfc);
3931 }
3932
3933 /**
3934 * Setup ECMA48 colors to match those provided in system properties.
3935 */
3936 private void setCustomSystemColors() {
3937 setDOSColors();
3938
3939 MYBLACK = getCustomColor("jexer.ECMA48.color0", MYBLACK);
3940 MYRED = getCustomColor("jexer.ECMA48.color1", MYRED);
3941 MYGREEN = getCustomColor("jexer.ECMA48.color2", MYGREEN);
3942 MYYELLOW = getCustomColor("jexer.ECMA48.color3", MYYELLOW);
3943 MYBLUE = getCustomColor("jexer.ECMA48.color4", MYBLUE);
3944 MYMAGENTA = getCustomColor("jexer.ECMA48.color5", MYMAGENTA);
3945 MYCYAN = getCustomColor("jexer.ECMA48.color6", MYCYAN);
3946 MYWHITE = getCustomColor("jexer.ECMA48.color7", MYWHITE);
3947 MYBOLD_BLACK = getCustomColor("jexer.ECMA48.color8", MYBOLD_BLACK);
3948 MYBOLD_RED = getCustomColor("jexer.ECMA48.color9", MYBOLD_RED);
3949 MYBOLD_GREEN = getCustomColor("jexer.ECMA48.color10", MYBOLD_GREEN);
3950 MYBOLD_YELLOW = getCustomColor("jexer.ECMA48.color11", MYBOLD_YELLOW);
3951 MYBOLD_BLUE = getCustomColor("jexer.ECMA48.color12", MYBOLD_BLUE);
3952 MYBOLD_MAGENTA = getCustomColor("jexer.ECMA48.color13", MYBOLD_MAGENTA);
3953 MYBOLD_CYAN = getCustomColor("jexer.ECMA48.color14", MYBOLD_CYAN);
3954 MYBOLD_WHITE = getCustomColor("jexer.ECMA48.color15", MYBOLD_WHITE);
3955 }
3956
3957 /**
3958 * Setup one system color to match the RGB value provided in system
3959 * properties.
3960 *
3961 * @param key the system property key
3962 * @param defaultColor the default color to return if key is not set, or
3963 * incorrect
3964 * @return a color from the RGB string, or defaultColor
3965 */
3966 private java.awt.Color getCustomColor(final String key,
3967 final java.awt.Color defaultColor) {
3968
3969 String rgb = System.getProperty(key);
3970 if (rgb == null) {
3971 return defaultColor;
3972 }
3973 if (rgb.startsWith("#")) {
3974 rgb = rgb.substring(1);
3975 }
3976 int rgbInt = 0;
3977 try {
3978 rgbInt = Integer.parseInt(rgb, 16);
3979 } catch (NumberFormatException e) {
3980 return defaultColor;
3981 }
3982 java.awt.Color color = new java.awt.Color((rgbInt & 0xFF0000) >>> 16,
3983 (rgbInt & 0x00FF00) >>> 8,
3984 (rgbInt & 0x0000FF));
3985
3986 return color;
3987 }
3988
3989 /**
3990 * Create a T.416 RGB parameter sequence for a custom system color.
3991 *
3992 * @param color one of the MYBLACK, MYBOLD_BLUE, etc. colors
3993 * @return the color portion of the string to emit to an ANSI /
3994 * ECMA-style terminal
3995 */
3996 private String systemColorRGB(final java.awt.Color color) {
3997 return String.format("%d;%d;%d", color.getRed(), color.getGreen(),
3998 color.getBlue());
3999 }
4000
4001 /**
4002 * Create a SGR parameter sequence for a single color change.
4003 *
4004 * @param bold if true, set bold
4005 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
4006 * @param foreground if true, this is a foreground color
4007 * @return the string to emit to an ANSI / ECMA-style terminal,
4008 * e.g. "\033[42m"
4009 */
4010 private String color(final boolean bold, final Color color,
4011 final boolean foreground) {
4012 return color(color, foreground, true) +
4013 rgbColor(bold, color, foreground);
4014 }
4015
4016 /**
4017 * Create a T.416 RGB parameter sequence for a single color change.
4018 *
4019 * @param colorRGB a 24-bit RGB value for foreground color
4020 * @param foreground if true, this is a foreground color
4021 * @return the string to emit to an ANSI / ECMA-style terminal,
4022 * e.g. "\033[42m"
4023 */
4024 private String colorRGB(final int colorRGB, final boolean foreground) {
4025
4026 int colorRed = (colorRGB >>> 16) & 0xFF;
4027 int colorGreen = (colorRGB >>> 8) & 0xFF;
4028 int colorBlue = colorRGB & 0xFF;
4029
4030 StringBuilder sb = new StringBuilder();
4031 if (foreground) {
4032 sb.append("\033[38;2;");
4033 } else {
4034 sb.append("\033[48;2;");
4035 }
4036 sb.append(String.format("%d;%d;%dm", colorRed, colorGreen, colorBlue));
4037 return sb.toString();
4038 }
4039
4040 /**
4041 * Create a T.416 RGB parameter sequence for both foreground and
4042 * background color change.
4043 *
4044 * @param foreColorRGB a 24-bit RGB value for foreground color
4045 * @param backColorRGB a 24-bit RGB value for foreground color
4046 * @return the string to emit to an ANSI / ECMA-style terminal,
4047 * e.g. "\033[42m"
4048 */
4049 private String colorRGB(final int foreColorRGB, final int backColorRGB) {
4050 int foreColorRed = (foreColorRGB >>> 16) & 0xFF;
4051 int foreColorGreen = (foreColorRGB >>> 8) & 0xFF;
4052 int foreColorBlue = foreColorRGB & 0xFF;
4053 int backColorRed = (backColorRGB >>> 16) & 0xFF;
4054 int backColorGreen = (backColorRGB >>> 8) & 0xFF;
4055 int backColorBlue = backColorRGB & 0xFF;
4056
4057 StringBuilder sb = new StringBuilder();
4058 sb.append(String.format("\033[38;2;%d;%d;%dm",
4059 foreColorRed, foreColorGreen, foreColorBlue));
4060 sb.append(String.format("\033[48;2;%d;%d;%dm",
4061 backColorRed, backColorGreen, backColorBlue));
4062 return sb.toString();
4063 }
4064
4065 /**
4066 * Create a T.416 RGB parameter sequence for a single color change.
4067 *
4068 * @param bold if true, set bold
4069 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
4070 * @param foreground if true, this is a foreground color
4071 * @return the string to emit to an xterm terminal with RGB support,
4072 * e.g. "\033[38;2;RR;GG;BBm"
4073 */
4074 private String rgbColor(final boolean bold, final Color color,
4075 final boolean foreground) {
4076 if (doRgbColor == false) {
4077 return "";
4078 }
4079 StringBuilder sb = new StringBuilder("\033[");
4080 if (bold) {
4081 // Bold implies foreground only
4082 sb.append("38;2;");
4083 if (color.equals(Color.BLACK)) {
4084 sb.append(systemColorRGB(MYBOLD_BLACK));
4085 } else if (color.equals(Color.RED)) {
4086 sb.append(systemColorRGB(MYBOLD_RED));
4087 } else if (color.equals(Color.GREEN)) {
4088 sb.append(systemColorRGB(MYBOLD_GREEN));
4089 } else if (color.equals(Color.YELLOW)) {
4090 sb.append(systemColorRGB(MYBOLD_YELLOW));
4091 } else if (color.equals(Color.BLUE)) {
4092 sb.append(systemColorRGB(MYBOLD_BLUE));
4093 } else if (color.equals(Color.MAGENTA)) {
4094 sb.append(systemColorRGB(MYBOLD_MAGENTA));
4095 } else if (color.equals(Color.CYAN)) {
4096 sb.append(systemColorRGB(MYBOLD_CYAN));
4097 } else if (color.equals(Color.WHITE)) {
4098 sb.append(systemColorRGB(MYBOLD_WHITE));
4099 }
4100 } else {
4101 if (foreground) {
4102 sb.append("38;2;");
4103 } else {
4104 sb.append("48;2;");
4105 }
4106 if (color.equals(Color.BLACK)) {
4107 sb.append(systemColorRGB(MYBLACK));
4108 } else if (color.equals(Color.RED)) {
4109 sb.append(systemColorRGB(MYRED));
4110 } else if (color.equals(Color.GREEN)) {
4111 sb.append(systemColorRGB(MYGREEN));
4112 } else if (color.equals(Color.YELLOW)) {
4113 sb.append(systemColorRGB(MYYELLOW));
4114 } else if (color.equals(Color.BLUE)) {
4115 sb.append(systemColorRGB(MYBLUE));
4116 } else if (color.equals(Color.MAGENTA)) {
4117 sb.append(systemColorRGB(MYMAGENTA));
4118 } else if (color.equals(Color.CYAN)) {
4119 sb.append(systemColorRGB(MYCYAN));
4120 } else if (color.equals(Color.WHITE)) {
4121 sb.append(systemColorRGB(MYWHITE));
4122 }
4123 }
4124 sb.append("m");
4125 return sb.toString();
4126 }
4127
4128 /**
4129 * Create a T.416 RGB parameter sequence for both foreground and
4130 * background color change.
4131 *
4132 * @param bold if true, set bold
4133 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4134 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4135 * @return the string to emit to an xterm terminal with RGB support,
4136 * e.g. "\033[38;2;RR;GG;BB;48;2;RR;GG;BBm"
4137 */
4138 private String rgbColor(final boolean bold, final Color foreColor,
4139 final Color backColor) {
4140 if (doRgbColor == false) {
4141 return "";
4142 }
4143
4144 return rgbColor(bold, foreColor, true) +
4145 rgbColor(false, backColor, false);
4146 }
4147
4148 /**
4149 * Create a SGR parameter sequence for a single color change.
4150 *
4151 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
4152 * @param foreground if true, this is a foreground color
4153 * @param header if true, make the full header, otherwise just emit the
4154 * color parameter e.g. "42;"
4155 * @return the string to emit to an ANSI / ECMA-style terminal,
4156 * e.g. "\033[42m"
4157 */
4158 private String color(final Color color, final boolean foreground,
4159 final boolean header) {
4160
4161 int ecmaColor = color.getValue();
4162
4163 // Convert Color.* values to SGR numerics
4164 if (foreground) {
4165 ecmaColor += 30;
4166 } else {
4167 ecmaColor += 40;
4168 }
4169
4170 if (header) {
4171 return String.format("\033[%dm", ecmaColor);
4172 } else {
4173 return String.format("%d;", ecmaColor);
4174 }
4175 }
4176
4177 /**
4178 * Create a SGR parameter sequence for both foreground and background
4179 * color change.
4180 *
4181 * @param bold if true, set bold
4182 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4183 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4184 * @return the string to emit to an ANSI / ECMA-style terminal,
4185 * e.g. "\033[31;42m"
4186 */
4187 private String color(final boolean bold, final Color foreColor,
4188 final Color backColor) {
4189 return color(foreColor, backColor, true) +
4190 rgbColor(bold, foreColor, backColor);
4191 }
4192
4193 /**
4194 * Create a SGR parameter sequence for both foreground and
4195 * background color change.
4196 *
4197 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4198 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4199 * @param header if true, make the full header, otherwise just emit the
4200 * color parameter e.g. "31;42;"
4201 * @return the string to emit to an ANSI / ECMA-style terminal,
4202 * e.g. "\033[31;42m"
4203 */
4204 private String color(final Color foreColor, final Color backColor,
4205 final boolean header) {
4206
4207 int ecmaForeColor = foreColor.getValue();
4208 int ecmaBackColor = backColor.getValue();
4209
4210 // Convert Color.* values to SGR numerics
4211 ecmaBackColor += 40;
4212 ecmaForeColor += 30;
4213
4214 if (header) {
4215 return String.format("\033[%d;%dm", ecmaForeColor, ecmaBackColor);
4216 } else {
4217 return String.format("%d;%d;", ecmaForeColor, ecmaBackColor);
4218 }
4219 }
4220
4221 /**
4222 * Create a SGR parameter sequence for foreground, background, and
4223 * several attributes. This sequence first resets all attributes to
4224 * default, then sets attributes as per the parameters.
4225 *
4226 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4227 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4228 * @param bold if true, set bold
4229 * @param reverse if true, set reverse
4230 * @param blink if true, set blink
4231 * @param underline if true, set underline
4232 * @return the string to emit to an ANSI / ECMA-style terminal,
4233 * e.g. "\033[0;1;31;42m"
4234 */
4235 private String color(final Color foreColor, final Color backColor,
4236 final boolean bold, final boolean reverse, final boolean blink,
4237 final boolean underline) {
4238
4239 int ecmaForeColor = foreColor.getValue();
4240 int ecmaBackColor = backColor.getValue();
4241
4242 // Convert Color.* values to SGR numerics
4243 ecmaBackColor += 40;
4244 ecmaForeColor += 30;
4245
4246 StringBuilder sb = new StringBuilder();
4247 if ( bold && reverse && blink && !underline ) {
4248 sb.append("\033[0;1;7;5;");
4249 } else if ( bold && reverse && !blink && !underline ) {
4250 sb.append("\033[0;1;7;");
4251 } else if ( !bold && reverse && blink && !underline ) {
4252 sb.append("\033[0;7;5;");
4253 } else if ( bold && !reverse && blink && !underline ) {
4254 sb.append("\033[0;1;5;");
4255 } else if ( bold && !reverse && !blink && !underline ) {
4256 sb.append("\033[0;1;");
4257 } else if ( !bold && reverse && !blink && !underline ) {
4258 sb.append("\033[0;7;");
4259 } else if ( !bold && !reverse && blink && !underline) {
4260 sb.append("\033[0;5;");
4261 } else if ( bold && reverse && blink && underline ) {
4262 sb.append("\033[0;1;7;5;4;");
4263 } else if ( bold && reverse && !blink && underline ) {
4264 sb.append("\033[0;1;7;4;");
4265 } else if ( !bold && reverse && blink && underline ) {
4266 sb.append("\033[0;7;5;4;");
4267 } else if ( bold && !reverse && blink && underline ) {
4268 sb.append("\033[0;1;5;4;");
4269 } else if ( bold && !reverse && !blink && underline ) {
4270 sb.append("\033[0;1;4;");
4271 } else if ( !bold && reverse && !blink && underline ) {
4272 sb.append("\033[0;7;4;");
4273 } else if ( !bold && !reverse && blink && underline) {
4274 sb.append("\033[0;5;4;");
4275 } else if ( !bold && !reverse && !blink && underline) {
4276 sb.append("\033[0;4;");
4277 } else {
4278 assert (!bold && !reverse && !blink && !underline);
4279 sb.append("\033[0;");
4280 }
4281 sb.append(String.format("%d;%dm", ecmaForeColor, ecmaBackColor));
4282 sb.append(rgbColor(bold, foreColor, backColor));
4283 return sb.toString();
4284 }
4285
4286 /**
4287 * Create a SGR parameter sequence for foreground, background, and
4288 * several attributes. This sequence first resets all attributes to
4289 * default, then sets attributes as per the parameters.
4290 *
4291 * @param foreColorRGB a 24-bit RGB value for foreground color
4292 * @param backColorRGB a 24-bit RGB value for foreground color
4293 * @param bold if true, set bold
4294 * @param reverse if true, set reverse
4295 * @param blink if true, set blink
4296 * @param underline if true, set underline
4297 * @return the string to emit to an ANSI / ECMA-style terminal,
4298 * e.g. "\033[0;1;31;42m"
4299 */
4300 private String colorRGB(final int foreColorRGB, final int backColorRGB,
4301 final boolean bold, final boolean reverse, final boolean blink,
4302 final boolean underline) {
4303
4304 int foreColorRed = (foreColorRGB >>> 16) & 0xFF;
4305 int foreColorGreen = (foreColorRGB >>> 8) & 0xFF;
4306 int foreColorBlue = foreColorRGB & 0xFF;
4307 int backColorRed = (backColorRGB >>> 16) & 0xFF;
4308 int backColorGreen = (backColorRGB >>> 8) & 0xFF;
4309 int backColorBlue = backColorRGB & 0xFF;
4310
4311 StringBuilder sb = new StringBuilder();
4312 if ( bold && reverse && blink && !underline ) {
4313 sb.append("\033[0;1;7;5;");
4314 } else if ( bold && reverse && !blink && !underline ) {
4315 sb.append("\033[0;1;7;");
4316 } else if ( !bold && reverse && blink && !underline ) {
4317 sb.append("\033[0;7;5;");
4318 } else if ( bold && !reverse && blink && !underline ) {
4319 sb.append("\033[0;1;5;");
4320 } else if ( bold && !reverse && !blink && !underline ) {
4321 sb.append("\033[0;1;");
4322 } else if ( !bold && reverse && !blink && !underline ) {
4323 sb.append("\033[0;7;");
4324 } else if ( !bold && !reverse && blink && !underline) {
4325 sb.append("\033[0;5;");
4326 } else if ( bold && reverse && blink && underline ) {
4327 sb.append("\033[0;1;7;5;4;");
4328 } else if ( bold && reverse && !blink && underline ) {
4329 sb.append("\033[0;1;7;4;");
4330 } else if ( !bold && reverse && blink && underline ) {
4331 sb.append("\033[0;7;5;4;");
4332 } else if ( bold && !reverse && blink && underline ) {
4333 sb.append("\033[0;1;5;4;");
4334 } else if ( bold && !reverse && !blink && underline ) {
4335 sb.append("\033[0;1;4;");
4336 } else if ( !bold && reverse && !blink && underline ) {
4337 sb.append("\033[0;7;4;");
4338 } else if ( !bold && !reverse && blink && underline) {
4339 sb.append("\033[0;5;4;");
4340 } else if ( !bold && !reverse && !blink && underline) {
4341 sb.append("\033[0;4;");
4342 } else {
4343 assert (!bold && !reverse && !blink && !underline);
4344 sb.append("\033[0;");
4345 }
4346
4347 sb.append("m\033[38;2;");
4348 sb.append(String.format("%d;%d;%d", foreColorRed, foreColorGreen,
4349 foreColorBlue));
4350 sb.append("m\033[48;2;");
4351 sb.append(String.format("%d;%d;%d", backColorRed, backColorGreen,
4352 backColorBlue));
4353 sb.append("m");
4354 return sb.toString();
4355 }
4356
4357 /**
4358 * Create a SGR parameter sequence to reset to VT100 defaults.
4359 *
4360 * @return the string to emit to an ANSI / ECMA-style terminal,
4361 * e.g. "\033[0m"
4362 */
4363 private String normal() {
4364 return normal(true) + rgbColor(false, Color.WHITE, Color.BLACK);
4365 }
4366
4367 /**
4368 * Create a SGR parameter sequence to reset to ECMA-48 default
4369 * foreground/background.
4370 *
4371 * @return the string to emit to an ANSI / ECMA-style terminal,
4372 * e.g. "\033[0m"
4373 */
4374 private String defaultColor() {
4375 /*
4376 * VT100 normal.
4377 * Normal (neither bold nor faint).
4378 * Not italicized.
4379 * Not underlined.
4380 * Steady (not blinking).
4381 * Positive (not inverse).
4382 * Visible (not hidden).
4383 * Not crossed-out.
4384 * Default foreground color.
4385 * Default background color.
4386 */
4387 return "\033[0;22;23;24;25;27;28;29;39;49m";
4388 }
4389
4390 /**
4391 * Create a SGR parameter sequence to reset to defaults.
4392 *
4393 * @param header if true, make the full header, otherwise just emit the
4394 * bare parameter e.g. "0;"
4395 * @return the string to emit to an ANSI / ECMA-style terminal,
4396 * e.g. "\033[0m"
4397 */
4398 private String normal(final boolean header) {
4399 if (header) {
4400 return "\033[0;37;40m";
4401 }
4402 return "0;37;40";
4403 }
4404
4405 /**
4406 * Create a SGR parameter sequence for enabling the visible cursor.
4407 *
4408 * @param on if true, turn on cursor
4409 * @return the string to emit to an ANSI / ECMA-style terminal
4410 */
4411 private String cursor(final boolean on) {
4412 if (on && !cursorOn) {
4413 cursorOn = true;
4414 return "\033[?25h";
4415 }
4416 if (!on && cursorOn) {
4417 cursorOn = false;
4418 return "\033[?25l";
4419 }
4420 return "";
4421 }
4422
4423 /**
4424 * Clear the entire screen. Because some terminals use back-color-erase,
4425 * set the color to white-on-black beforehand.
4426 *
4427 * @return the string to emit to an ANSI / ECMA-style terminal
4428 */
4429 private String clearAll() {
4430 return "\033[0;37;40m\033[2J";
4431 }
4432
4433 /**
4434 * Clear the line from the cursor (inclusive) to the end of the screen.
4435 * Because some terminals use back-color-erase, set the color to
4436 * white-on-black beforehand.
4437 *
4438 * @return the string to emit to an ANSI / ECMA-style terminal
4439 */
4440 private String clearRemainingLine() {
4441 return "\033[0;37;40m\033[K";
4442 }
4443
4444 /**
4445 * Move the cursor to (x, y).
4446 *
4447 * @param x column coordinate. 0 is the left-most column.
4448 * @param y row coordinate. 0 is the top-most row.
4449 * @return the string to emit to an ANSI / ECMA-style terminal
4450 */
4451 private String gotoXY(final int x, final int y) {
4452 return String.format("\033[%d;%dH", y + 1, x + 1);
4453 }
4454
4455 /**
4456 * Tell (u)xterm that we want to receive mouse events based on "Any event
4457 * tracking", UTF-8 coordinates, and then SGR coordinates. Ideally we
4458 * will end up with SGR coordinates with UTF-8 coordinates as a fallback.
4459 * See
4460 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
4461 *
4462 * Note that this also sets the alternate/primary screen buffer.
4463 *
4464 * Finally, also emit a Privacy Message sequence that Jexer recognizes to
4465 * mean "hide the mouse pointer." We have to use our own sequence to do
4466 * this because there is no standard in xterm for unilaterally hiding the
4467 * pointer all the time (regardless of typing).
4468 *
4469 * @param on If true, enable mouse report and use the alternate screen
4470 * buffer. If false disable mouse reporting and use the primary screen
4471 * buffer.
4472 * @return the string to emit to xterm
4473 */
4474 private String mouse(final boolean on) {
4475 if (on) {
4476 return "\033[?1002;1003;1005;1006h\033[?1049h\033^hideMousePointer\033\\";
4477 }
4478 return "\033[?1002;1003;1006;1005l\033[?1049l\033^showMousePointer\033\\";
4479 }
4480
4481 }