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