ed2715c834bc3402062690cd270b4846c4dae618
[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 // Piece these together into one larger image for final rendering.
3196 int totalWidth = 0;
3197 int fullWidth = cells.size() * imageWidth;
3198 int fullHeight = imageHeight;
3199 for (int i = 0; i < cells.size(); i++) {
3200 totalWidth += cells.get(i).getImage().getWidth();
3201 }
3202
3203 BufferedImage image = new BufferedImage(fullWidth,
3204 fullHeight, BufferedImage.TYPE_INT_ARGB);
3205
3206 int [] rgbArray;
3207 for (int i = 0; i < cells.size() - 1; i++) {
3208 int tileWidth = imageWidth;
3209 int tileHeight = imageHeight;
3210
3211 if (false && cells.get(i).isInvertedImage()) {
3212 // I used to put an all-white cell over the cursor, don't do
3213 // that anymore.
3214 rgbArray = new int[imageWidth * imageHeight];
3215 for (int j = 0; j < rgbArray.length; j++) {
3216 rgbArray[j] = 0xFFFFFF;
3217 }
3218 } else {
3219 try {
3220 rgbArray = cells.get(i).getImage().getRGB(0, 0,
3221 tileWidth, tileHeight, null, 0, tileWidth);
3222 } catch (Exception e) {
3223 throw new RuntimeException("image " + imageWidth + "x" +
3224 imageHeight +
3225 "tile " + tileWidth + "x" +
3226 tileHeight +
3227 " cells.get(i).getImage() " +
3228 cells.get(i).getImage() +
3229 " i " + i +
3230 " fullWidth " + fullWidth +
3231 " fullHeight " + fullHeight, e);
3232 }
3233 }
3234
3235 /*
3236 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
3237 i * imageWidth, 0, imageWidth, imageHeight,
3238 0, imageWidth);
3239 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
3240 fullWidth, fullHeight, cells.size(), getTextWidth());
3241 */
3242
3243 image.setRGB(i * imageWidth, 0, tileWidth, tileHeight,
3244 rgbArray, 0, tileWidth);
3245 if (tileHeight < fullHeight) {
3246 int backgroundColor = cells.get(i).getBackground().getRGB();
3247 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
3248 for (int imageY = imageHeight; imageY < fullHeight;
3249 imageY++) {
3250
3251 image.setRGB(imageX, imageY, backgroundColor);
3252 }
3253 }
3254 }
3255 }
3256 totalWidth -= ((cells.size() - 1) * imageWidth);
3257 if (false && cells.get(cells.size() - 1).isInvertedImage()) {
3258 // I used to put an all-white cell over the cursor, don't do that
3259 // anymore.
3260 rgbArray = new int[totalWidth * imageHeight];
3261 for (int j = 0; j < rgbArray.length; j++) {
3262 rgbArray[j] = 0xFFFFFF;
3263 }
3264 } else {
3265 try {
3266 rgbArray = cells.get(cells.size() - 1).getImage().getRGB(0, 0,
3267 totalWidth, imageHeight, null, 0, totalWidth);
3268 } catch (Exception e) {
3269 throw new RuntimeException("image " + imageWidth + "x" +
3270 imageHeight + " cells.get(cells.size() - 1).getImage() " +
3271 cells.get(cells.size() - 1).getImage(), e);
3272 }
3273 }
3274 image.setRGB((cells.size() - 1) * imageWidth, 0, totalWidth,
3275 imageHeight, rgbArray, 0, totalWidth);
3276
3277 if (totalWidth < imageWidth) {
3278 int backgroundColor = cells.get(cells.size() - 1).getBackground().getRGB();
3279
3280 for (int imageX = image.getWidth() - totalWidth;
3281 imageX < image.getWidth(); imageX++) {
3282
3283 for (int imageY = 0; imageY < fullHeight; imageY++) {
3284 image.setRGB(imageX, imageY, backgroundColor);
3285 }
3286 }
3287 }
3288
3289 if ((image.getWidth() != cells.size() * getTextWidth())
3290 || (image.getHeight() != getTextHeight())
3291 ) {
3292 // Rescale the image to fit the text cells it is going into.
3293 BufferedImage newImage;
3294 newImage = new BufferedImage(cells.size() * getTextWidth(),
3295 getTextHeight(), BufferedImage.TYPE_INT_ARGB);
3296
3297 java.awt.Graphics gr = newImage.getGraphics();
3298 gr.drawImage(image, 0, 0, newImage.getWidth(),
3299 newImage.getHeight(), null, null);
3300 gr.dispose();
3301 image = newImage;
3302 fullHeight = image.getHeight();
3303 }
3304
3305 // Dither the image. It is ok to lose the original here.
3306 if (palette == null) {
3307 palette = new SixelPalette();
3308 if (sixelSharedPalette == true) {
3309 palette.emitPalette(sb, null);
3310 }
3311 }
3312 image = palette.ditherImage(image);
3313
3314 // Collect the raster information
3315 int rasterHeight = 0;
3316 int rasterWidth = image.getWidth();
3317
3318 if (sixelSharedPalette == false) {
3319 // Emit the palette, but only for the colors actually used by
3320 // these cells.
3321 boolean [] usedColors = new boolean[sixelPaletteSize];
3322 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
3323 for (int imageY = 0; imageY < image.getHeight(); imageY++) {
3324 usedColors[image.getRGB(imageX, imageY)] = true;
3325 }
3326 }
3327 palette.emitPalette(sb, usedColors);
3328 }
3329
3330 // Render the entire row of cells.
3331 for (int currentRow = 0; currentRow < fullHeight; currentRow += 6) {
3332 int [][] sixels = new int[image.getWidth()][6];
3333
3334 // See which colors are actually used in this band of sixels.
3335 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
3336 for (int imageY = 0;
3337 (imageY < 6) && (imageY + currentRow < fullHeight);
3338 imageY++) {
3339
3340 int colorIdx = image.getRGB(imageX, imageY + currentRow);
3341 assert (colorIdx >= 0);
3342 assert (colorIdx < sixelPaletteSize);
3343
3344 sixels[imageX][imageY] = colorIdx;
3345 }
3346 }
3347
3348 for (int i = 0; i < sixelPaletteSize; i++) {
3349 boolean isUsed = false;
3350 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
3351 for (int j = 0; j < 6; j++) {
3352 if (sixels[imageX][j] == i) {
3353 isUsed = true;
3354 }
3355 }
3356 }
3357 if (isUsed == false) {
3358 continue;
3359 }
3360
3361 // Set to the beginning of scan line for the next set of
3362 // colored pixels, and select the color.
3363 sb.append(String.format("$#%d", i));
3364
3365 int oldData = -1;
3366 int oldDataCount = 0;
3367 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
3368
3369 // Add up all the pixels that match this color.
3370 int data = 0;
3371 for (int j = 0;
3372 (j < 6) && (currentRow + j < fullHeight);
3373 j++) {
3374
3375 if (sixels[imageX][j] == i) {
3376 switch (j) {
3377 case 0:
3378 data += 1;
3379 break;
3380 case 1:
3381 data += 2;
3382 break;
3383 case 2:
3384 data += 4;
3385 break;
3386 case 3:
3387 data += 8;
3388 break;
3389 case 4:
3390 data += 16;
3391 break;
3392 case 5:
3393 data += 32;
3394 break;
3395 }
3396 if ((currentRow + j + 1) > rasterHeight) {
3397 rasterHeight = currentRow + j + 1;
3398 }
3399 }
3400 }
3401 assert (data >= 0);
3402 assert (data < 64);
3403 data += 63;
3404
3405 if (data == oldData) {
3406 oldDataCount++;
3407 } else {
3408 if (oldDataCount == 1) {
3409 sb.append((char) oldData);
3410 } else if (oldDataCount > 1) {
3411 sb.append(String.format("!%d", oldDataCount));
3412 sb.append((char) oldData);
3413 }
3414 oldDataCount = 1;
3415 oldData = data;
3416 }
3417
3418 } // for (int imageX = 0; imageX < image.getWidth(); imageX++)
3419
3420 // Emit the last sequence.
3421 if (oldDataCount == 1) {
3422 sb.append((char) oldData);
3423 } else if (oldDataCount > 1) {
3424 sb.append(String.format("!%d", oldDataCount));
3425 sb.append((char) oldData);
3426 }
3427
3428 } // for (int i = 0; i < sixelPaletteSize; i++)
3429
3430 // Advance to the next scan line.
3431 sb.append("-");
3432
3433 } // for (int currentRow = 0; currentRow < imageHeight; currentRow += 6)
3434
3435 // Kill the very last "-", because it is unnecessary.
3436 sb.deleteCharAt(sb.length() - 1);
3437
3438 // Add the raster information
3439 sb.insert(0, String.format("\"1;1;%d;%d", rasterWidth, rasterHeight));
3440
3441 if (saveInCache) {
3442 // This row is OK to save into the cache.
3443 sixelCache.put(cells, sb.toString());
3444 }
3445
3446 return (startSixel(x, y) + sb.toString() + endSixel());
3447 }
3448
3449 /**
3450 * Get the sixel support flag.
3451 *
3452 * @return true if this terminal is emitting sixel
3453 */
3454 public boolean hasSixel() {
3455 return sixel;
3456 }
3457
3458 // ------------------------------------------------------------------------
3459 // End sixel output support -----------------------------------------------
3460 // ------------------------------------------------------------------------
3461
3462 // ------------------------------------------------------------------------
3463 // iTerm2 image output support --------------------------------------------
3464 // ------------------------------------------------------------------------
3465
3466 /**
3467 * Create an iTerm2 images string representing a row of several cells
3468 * containing bitmap data.
3469 *
3470 * @param x column coordinate. 0 is the left-most column.
3471 * @param y row coordinate. 0 is the top-most row.
3472 * @param cells the cells containing the bitmap data
3473 * @return the string to emit to an ANSI / ECMA-style terminal
3474 */
3475 private String toIterm2Image(final int x, final int y,
3476 final ArrayList<Cell> cells) {
3477
3478 StringBuilder sb = new StringBuilder();
3479
3480 assert (cells != null);
3481 assert (cells.size() > 0);
3482 assert (cells.get(0).getImage() != null);
3483
3484 if (iterm2Images == false) {
3485 sb.append(normal());
3486 sb.append(gotoXY(x, y));
3487 for (int i = 0; i < cells.size(); i++) {
3488 sb.append(' ');
3489 }
3490 return sb.toString();
3491 }
3492
3493 if (iterm2Cache == null) {
3494 iterm2Cache = new ImageCache(height * 10);
3495 }
3496
3497 // Save and get rows to/from the cache that do NOT have inverted
3498 // cells.
3499 boolean saveInCache = true;
3500 for (Cell cell: cells) {
3501 if (cell.isInvertedImage()) {
3502 saveInCache = false;
3503 }
3504 }
3505 if (saveInCache) {
3506 String cachedResult = iterm2Cache.get(cells);
3507 if (cachedResult != null) {
3508 // System.err.println("CACHE HIT");
3509 sb.append(gotoXY(x, y));
3510 sb.append(cachedResult);
3511 return sb.toString();
3512 }
3513 // System.err.println("CACHE MISS");
3514 }
3515
3516 int imageWidth = cells.get(0).getImage().getWidth();
3517 int imageHeight = cells.get(0).getImage().getHeight();
3518
3519 // Piece cells.get(x).getImage() pieces together into one larger
3520 // image for final rendering.
3521 int totalWidth = 0;
3522 int fullWidth = cells.size() * imageWidth;
3523 int fullHeight = imageHeight;
3524 for (int i = 0; i < cells.size(); i++) {
3525 totalWidth += cells.get(i).getImage().getWidth();
3526 }
3527
3528 BufferedImage image = new BufferedImage(fullWidth,
3529 fullHeight, BufferedImage.TYPE_INT_ARGB);
3530
3531 int [] rgbArray;
3532 for (int i = 0; i < cells.size() - 1; i++) {
3533 int tileWidth = imageWidth;
3534 int tileHeight = imageHeight;
3535 if (false && cells.get(i).isInvertedImage()) {
3536 // I used to put an all-white cell over the cursor, don't do
3537 // that anymore.
3538 rgbArray = new int[imageWidth * imageHeight];
3539 for (int j = 0; j < rgbArray.length; j++) {
3540 rgbArray[j] = 0xFFFFFF;
3541 }
3542 } else {
3543 try {
3544 rgbArray = cells.get(i).getImage().getRGB(0, 0,
3545 tileWidth, tileHeight, null, 0, tileWidth);
3546 } catch (Exception e) {
3547 throw new RuntimeException("image " + imageWidth + "x" +
3548 imageHeight +
3549 "tile " + tileWidth + "x" +
3550 tileHeight +
3551 " cells.get(i).getImage() " +
3552 cells.get(i).getImage() +
3553 " i " + i +
3554 " fullWidth " + fullWidth +
3555 " fullHeight " + fullHeight, e);
3556 }
3557 }
3558
3559 /*
3560 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
3561 i * imageWidth, 0, imageWidth, imageHeight,
3562 0, imageWidth);
3563 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
3564 fullWidth, fullHeight, cells.size(), getTextWidth());
3565 */
3566
3567 image.setRGB(i * imageWidth, 0, tileWidth, tileHeight,
3568 rgbArray, 0, tileWidth);
3569 if (tileHeight < fullHeight) {
3570 int backgroundColor = cells.get(i).getBackground().getRGB();
3571 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
3572 for (int imageY = imageHeight; imageY < fullHeight;
3573 imageY++) {
3574
3575 image.setRGB(imageX, imageY, backgroundColor);
3576 }
3577 }
3578 }
3579 }
3580 totalWidth -= ((cells.size() - 1) * imageWidth);
3581 if (false && cells.get(cells.size() - 1).isInvertedImage()) {
3582 // I used to put an all-white cell over the cursor, don't do that
3583 // anymore.
3584 rgbArray = new int[totalWidth * imageHeight];
3585 for (int j = 0; j < rgbArray.length; j++) {
3586 rgbArray[j] = 0xFFFFFF;
3587 }
3588 } else {
3589 try {
3590 rgbArray = cells.get(cells.size() - 1).getImage().getRGB(0, 0,
3591 totalWidth, imageHeight, null, 0, totalWidth);
3592 } catch (Exception e) {
3593 throw new RuntimeException("image " + imageWidth + "x" +
3594 imageHeight + " cells.get(cells.size() - 1).getImage() " +
3595 cells.get(cells.size() - 1).getImage(), e);
3596 }
3597 }
3598 image.setRGB((cells.size() - 1) * imageWidth, 0, totalWidth,
3599 imageHeight, rgbArray, 0, totalWidth);
3600
3601 if (totalWidth < imageWidth) {
3602 int backgroundColor = cells.get(cells.size() - 1).getBackground().getRGB();
3603
3604 for (int imageX = image.getWidth() - totalWidth;
3605 imageX < image.getWidth(); imageX++) {
3606
3607 for (int imageY = 0; imageY < fullHeight; imageY++) {
3608 image.setRGB(imageX, imageY, backgroundColor);
3609 }
3610 }
3611 }
3612
3613 if ((image.getWidth() != cells.size() * getTextWidth())
3614 || (image.getHeight() != getTextHeight())
3615 ) {
3616 // Rescale the image to fit the text cells it is going into.
3617 BufferedImage newImage;
3618 newImage = new BufferedImage(cells.size() * getTextWidth(),
3619 getTextHeight(), BufferedImage.TYPE_INT_ARGB);
3620
3621 java.awt.Graphics gr = newImage.getGraphics();
3622 gr.drawImage(image, 0, 0, newImage.getWidth(),
3623 newImage.getHeight(), null, null);
3624 gr.dispose();
3625 image = newImage;
3626 fullHeight = image.getHeight();
3627 }
3628
3629 /*
3630 * From https://iterm2.com/documentation-images.html:
3631 *
3632 * Protocol
3633 *
3634 * iTerm2 extends the xterm protocol with a set of proprietary escape
3635 * sequences. In general, the pattern is:
3636 *
3637 * ESC ] 1337 ; key = value ^G
3638 *
3639 * Whitespace is shown here for ease of reading: in practice, no
3640 * spaces should be used.
3641 *
3642 * For file transfer and inline images, the code is:
3643 *
3644 * ESC ] 1337 ; File = [optional arguments] : base-64 encoded file contents ^G
3645 *
3646 * The optional arguments are formatted as key=value with a semicolon
3647 * between each key-value pair. They are described below:
3648 *
3649 * Key Description of value
3650 * name base-64 encoded filename. Defaults to "Unnamed file".
3651 * size File size in bytes. Optional; this is only used by the
3652 * progress indicator.
3653 * width Width to render. See notes below.
3654 * height Height to render. See notes below.
3655 * preserveAspectRatio If set to 0, then the image's inherent aspect
3656 * ratio will not be respected; otherwise, it
3657 * will fill the specified width and height as
3658 * much as possible without stretching. Defaults
3659 * to 1.
3660 * inline If set to 1, the file will be displayed inline. Otherwise,
3661 * it will be downloaded with no visual representation in the
3662 * terminal session. Defaults to 0.
3663 *
3664 * The width and height are given as a number followed by a unit, or
3665 * the word "auto".
3666 *
3667 * N: N character cells.
3668 * Npx: N pixels.
3669 * N%: N percent of the session's width or height.
3670 * auto: The image's inherent size will be used to determine an
3671 * appropriate dimension.
3672 *
3673 */
3674
3675 // File contents can be several image formats. We will use PNG.
3676 ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream(1024);
3677 try {
3678 if (!ImageIO.write(image.getSubimage(0, 0, image.getWidth(),
3679 Math.min(image.getHeight(), fullHeight)),
3680 "PNG", pngOutputStream)
3681 ) {
3682 // We failed to render image, bail out.
3683 return "";
3684 }
3685 } catch (IOException e) {
3686 // We failed to render image, bail out.
3687 return "";
3688 }
3689
3690 sb.append("\033]1337;File=");
3691 /*
3692 sb.append(String.format("width=$d;height=1;preserveAspectRatio=1;",
3693 cells.size()));
3694 */
3695 /*
3696 sb.append(String.format("width=$dpx;height=%dpx;preserveAspectRatio=1;",
3697 image.getWidth(), Math.min(image.getHeight(),
3698 getTextHeight())));
3699 */
3700 sb.append("inline=1:");
3701 sb.append(StringUtils.toBase64(pngOutputStream.toByteArray()));
3702 sb.append("\007");
3703
3704 if (saveInCache) {
3705 // This row is OK to save into the cache.
3706 iterm2Cache.put(cells, sb.toString());
3707 }
3708
3709 return (gotoXY(x, y) + sb.toString());
3710 }
3711
3712 /**
3713 * Get the iTerm2 images support flag.
3714 *
3715 * @return true if this terminal is emitting iTerm2 images
3716 */
3717 public boolean hasIterm2Images() {
3718 return iterm2Images;
3719 }
3720
3721 // ------------------------------------------------------------------------
3722 // End iTerm2 image output support ----------------------------------------
3723 // ------------------------------------------------------------------------
3724
3725 // ------------------------------------------------------------------------
3726 // Jexer image output support ---------------------------------------------
3727 // ------------------------------------------------------------------------
3728
3729 /**
3730 * Create a Jexer images string representing a row of several cells
3731 * containing bitmap data.
3732 *
3733 * @param x column coordinate. 0 is the left-most column.
3734 * @param y row coordinate. 0 is the top-most row.
3735 * @param cells the cells containing the bitmap data
3736 * @return the string to emit to an ANSI / ECMA-style terminal
3737 */
3738 private String toJexerImage(final int x, final int y,
3739 final ArrayList<Cell> cells) {
3740
3741 StringBuilder sb = new StringBuilder();
3742
3743 assert (cells != null);
3744 assert (cells.size() > 0);
3745 assert (cells.get(0).getImage() != null);
3746
3747 if (jexerImageOption == JexerImageOption.DISABLED) {
3748 sb.append(normal());
3749 sb.append(gotoXY(x, y));
3750 for (int i = 0; i < cells.size(); i++) {
3751 sb.append(' ');
3752 }
3753 return sb.toString();
3754 }
3755
3756 if (jexerCache == null) {
3757 jexerCache = new ImageCache(height * 10);
3758 }
3759
3760 // Save and get rows to/from the cache that do NOT have inverted
3761 // cells.
3762 boolean saveInCache = true;
3763 for (Cell cell: cells) {
3764 if (cell.isInvertedImage()) {
3765 saveInCache = false;
3766 }
3767 }
3768 if (saveInCache) {
3769 String cachedResult = jexerCache.get(cells);
3770 if (cachedResult != null) {
3771 // System.err.println("CACHE HIT");
3772 sb.append(gotoXY(x, y));
3773 sb.append(cachedResult);
3774 return sb.toString();
3775 }
3776 // System.err.println("CACHE MISS");
3777 }
3778
3779 int imageWidth = cells.get(0).getImage().getWidth();
3780 int imageHeight = cells.get(0).getImage().getHeight();
3781
3782 // Piece cells.get(x).getImage() pieces together into one larger
3783 // image for final rendering.
3784 int totalWidth = 0;
3785 int fullWidth = cells.size() * imageWidth;
3786 int fullHeight = imageHeight;
3787 for (int i = 0; i < cells.size(); i++) {
3788 totalWidth += cells.get(i).getImage().getWidth();
3789 }
3790
3791 BufferedImage image = new BufferedImage(fullWidth,
3792 fullHeight, BufferedImage.TYPE_INT_ARGB);
3793
3794 int [] rgbArray;
3795 for (int i = 0; i < cells.size() - 1; i++) {
3796 int tileWidth = imageWidth;
3797 int tileHeight = imageHeight;
3798 if (false && cells.get(i).isInvertedImage()) {
3799 // I used to put an all-white cell over the cursor, don't do
3800 // that anymore.
3801 rgbArray = new int[imageWidth * imageHeight];
3802 for (int j = 0; j < rgbArray.length; j++) {
3803 rgbArray[j] = 0xFFFFFF;
3804 }
3805 } else {
3806 try {
3807 rgbArray = cells.get(i).getImage().getRGB(0, 0,
3808 tileWidth, tileHeight, null, 0, tileWidth);
3809 } catch (Exception e) {
3810 throw new RuntimeException("image " + imageWidth + "x" +
3811 imageHeight +
3812 "tile " + tileWidth + "x" +
3813 tileHeight +
3814 " cells.get(i).getImage() " +
3815 cells.get(i).getImage() +
3816 " i " + i +
3817 " fullWidth " + fullWidth +
3818 " fullHeight " + fullHeight, e);
3819 }
3820 }
3821
3822 /*
3823 System.err.printf("calling image.setRGB(): %d %d %d %d %d\n",
3824 i * imageWidth, 0, imageWidth, imageHeight,
3825 0, imageWidth);
3826 System.err.printf(" fullWidth %d fullHeight %d cells.size() %d textWidth %d\n",
3827 fullWidth, fullHeight, cells.size(), getTextWidth());
3828 */
3829
3830 image.setRGB(i * imageWidth, 0, tileWidth, tileHeight,
3831 rgbArray, 0, tileWidth);
3832 if (tileHeight < fullHeight) {
3833 int backgroundColor = cells.get(i).getBackground().getRGB();
3834 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
3835 for (int imageY = imageHeight; imageY < fullHeight;
3836 imageY++) {
3837
3838 image.setRGB(imageX, imageY, backgroundColor);
3839 }
3840 }
3841 }
3842 }
3843 totalWidth -= ((cells.size() - 1) * imageWidth);
3844 if (false && cells.get(cells.size() - 1).isInvertedImage()) {
3845 // I used to put an all-white cell over the cursor, don't do that
3846 // anymore.
3847 rgbArray = new int[totalWidth * imageHeight];
3848 for (int j = 0; j < rgbArray.length; j++) {
3849 rgbArray[j] = 0xFFFFFF;
3850 }
3851 } else {
3852 try {
3853 rgbArray = cells.get(cells.size() - 1).getImage().getRGB(0, 0,
3854 totalWidth, imageHeight, null, 0, totalWidth);
3855 } catch (Exception e) {
3856 throw new RuntimeException("image " + imageWidth + "x" +
3857 imageHeight + " cells.get(cells.size() - 1).getImage() " +
3858 cells.get(cells.size() - 1).getImage(), e);
3859 }
3860 }
3861 image.setRGB((cells.size() - 1) * imageWidth, 0, totalWidth,
3862 imageHeight, rgbArray, 0, totalWidth);
3863
3864 if (totalWidth < imageWidth) {
3865 int backgroundColor = cells.get(cells.size() - 1).getBackground().getRGB();
3866
3867 for (int imageX = image.getWidth() - totalWidth;
3868 imageX < image.getWidth(); imageX++) {
3869
3870 for (int imageY = 0; imageY < fullHeight; imageY++) {
3871 image.setRGB(imageX, imageY, backgroundColor);
3872 }
3873 }
3874 }
3875
3876 if ((image.getWidth() != cells.size() * getTextWidth())
3877 || (image.getHeight() != getTextHeight())
3878 ) {
3879 // Rescale the image to fit the text cells it is going into.
3880 BufferedImage newImage;
3881 newImage = new BufferedImage(cells.size() * getTextWidth(),
3882 getTextHeight(), BufferedImage.TYPE_INT_ARGB);
3883
3884 java.awt.Graphics gr = newImage.getGraphics();
3885 gr.drawImage(image, 0, 0, newImage.getWidth(),
3886 newImage.getHeight(), null, null);
3887 gr.dispose();
3888 image = newImage;
3889 fullHeight = image.getHeight();
3890 }
3891
3892 if (jexerImageOption == JexerImageOption.PNG) {
3893 // Encode as PNG
3894 ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream(1024);
3895 try {
3896 if (!ImageIO.write(image.getSubimage(0, 0, image.getWidth(),
3897 Math.min(image.getHeight(), fullHeight)),
3898 "PNG", pngOutputStream)
3899 ) {
3900 // We failed to render image, bail out.
3901 return "";
3902 }
3903 } catch (IOException e) {
3904 // We failed to render image, bail out.
3905 return "";
3906 }
3907
3908 sb.append("\033]444;1;0;");
3909 sb.append(StringUtils.toBase64(pngOutputStream.toByteArray()));
3910 sb.append("\007");
3911
3912 } else if (jexerImageOption == JexerImageOption.JPG) {
3913
3914 // Encode as JPG
3915 ByteArrayOutputStream jpgOutputStream = new ByteArrayOutputStream(1024);
3916
3917 // Convert from ARGB to RGB, otherwise the JPG encode will fail.
3918 BufferedImage jpgImage = new BufferedImage(image.getWidth(),
3919 image.getHeight(), BufferedImage.TYPE_INT_RGB);
3920 int [] pixels = new int[image.getWidth() * image.getHeight()];
3921 image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels,
3922 0, image.getWidth());
3923 jpgImage.setRGB(0, 0, image.getWidth(), image.getHeight(), pixels,
3924 0, image.getWidth());
3925
3926 try {
3927 if (!ImageIO.write(jpgImage.getSubimage(0, 0,
3928 jpgImage.getWidth(),
3929 Math.min(jpgImage.getHeight(), fullHeight)),
3930 "JPG", jpgOutputStream)
3931 ) {
3932 // We failed to render image, bail out.
3933 return "";
3934 }
3935 } catch (IOException e) {
3936 // We failed to render image, bail out.
3937 return "";
3938 }
3939
3940 sb.append("\033]444;2;0;");
3941 sb.append(StringUtils.toBase64(jpgOutputStream.toByteArray()));
3942 sb.append("\007");
3943
3944 } else if (jexerImageOption == JexerImageOption.RGB) {
3945
3946 // RGB
3947 sb.append(String.format("\033]444;0;%d;%d;0;", image.getWidth(),
3948 Math.min(image.getHeight(), fullHeight)));
3949
3950 byte [] bytes = new byte[image.getWidth() * image.getHeight() * 3];
3951 int stride = image.getWidth();
3952 for (int px = 0; px < stride; px++) {
3953 for (int py = 0; py < image.getHeight(); py++) {
3954 int rgb = image.getRGB(px, py);
3955 bytes[(py * stride * 3) + (px * 3)] = (byte) ((rgb >>> 16) & 0xFF);
3956 bytes[(py * stride * 3) + (px * 3) + 1] = (byte) ((rgb >>> 8) & 0xFF);
3957 bytes[(py * stride * 3) + (px * 3) + 2] = (byte) ( rgb & 0xFF);
3958 }
3959 }
3960 sb.append(StringUtils.toBase64(bytes));
3961 sb.append("\007");
3962 }
3963
3964 if (saveInCache) {
3965 // This row is OK to save into the cache.
3966 jexerCache.put(cells, sb.toString());
3967 }
3968
3969 return (gotoXY(x, y) + sb.toString());
3970 }
3971
3972 /**
3973 * Get the Jexer images support flag.
3974 *
3975 * @return true if this terminal is emitting Jexer images
3976 */
3977 public boolean hasJexerImages() {
3978 return (jexerImageOption != JexerImageOption.DISABLED);
3979 }
3980
3981 // ------------------------------------------------------------------------
3982 // End Jexer image output support -----------------------------------------
3983 // ------------------------------------------------------------------------
3984
3985 /**
3986 * Setup system colors to match DOS color palette.
3987 */
3988 private void setDOSColors() {
3989 MYBLACK = new java.awt.Color(0x00, 0x00, 0x00);
3990 MYRED = new java.awt.Color(0xa8, 0x00, 0x00);
3991 MYGREEN = new java.awt.Color(0x00, 0xa8, 0x00);
3992 MYYELLOW = new java.awt.Color(0xa8, 0x54, 0x00);
3993 MYBLUE = new java.awt.Color(0x00, 0x00, 0xa8);
3994 MYMAGENTA = new java.awt.Color(0xa8, 0x00, 0xa8);
3995 MYCYAN = new java.awt.Color(0x00, 0xa8, 0xa8);
3996 MYWHITE = new java.awt.Color(0xa8, 0xa8, 0xa8);
3997 MYBOLD_BLACK = new java.awt.Color(0x54, 0x54, 0x54);
3998 MYBOLD_RED = new java.awt.Color(0xfc, 0x54, 0x54);
3999 MYBOLD_GREEN = new java.awt.Color(0x54, 0xfc, 0x54);
4000 MYBOLD_YELLOW = new java.awt.Color(0xfc, 0xfc, 0x54);
4001 MYBOLD_BLUE = new java.awt.Color(0x54, 0x54, 0xfc);
4002 MYBOLD_MAGENTA = new java.awt.Color(0xfc, 0x54, 0xfc);
4003 MYBOLD_CYAN = new java.awt.Color(0x54, 0xfc, 0xfc);
4004 MYBOLD_WHITE = new java.awt.Color(0xfc, 0xfc, 0xfc);
4005 }
4006
4007 /**
4008 * Setup ECMA48 colors to match those provided in system properties.
4009 */
4010 private void setCustomSystemColors() {
4011 setDOSColors();
4012
4013 MYBLACK = getCustomColor("jexer.ECMA48.color0", MYBLACK);
4014 MYRED = getCustomColor("jexer.ECMA48.color1", MYRED);
4015 MYGREEN = getCustomColor("jexer.ECMA48.color2", MYGREEN);
4016 MYYELLOW = getCustomColor("jexer.ECMA48.color3", MYYELLOW);
4017 MYBLUE = getCustomColor("jexer.ECMA48.color4", MYBLUE);
4018 MYMAGENTA = getCustomColor("jexer.ECMA48.color5", MYMAGENTA);
4019 MYCYAN = getCustomColor("jexer.ECMA48.color6", MYCYAN);
4020 MYWHITE = getCustomColor("jexer.ECMA48.color7", MYWHITE);
4021 MYBOLD_BLACK = getCustomColor("jexer.ECMA48.color8", MYBOLD_BLACK);
4022 MYBOLD_RED = getCustomColor("jexer.ECMA48.color9", MYBOLD_RED);
4023 MYBOLD_GREEN = getCustomColor("jexer.ECMA48.color10", MYBOLD_GREEN);
4024 MYBOLD_YELLOW = getCustomColor("jexer.ECMA48.color11", MYBOLD_YELLOW);
4025 MYBOLD_BLUE = getCustomColor("jexer.ECMA48.color12", MYBOLD_BLUE);
4026 MYBOLD_MAGENTA = getCustomColor("jexer.ECMA48.color13", MYBOLD_MAGENTA);
4027 MYBOLD_CYAN = getCustomColor("jexer.ECMA48.color14", MYBOLD_CYAN);
4028 MYBOLD_WHITE = getCustomColor("jexer.ECMA48.color15", MYBOLD_WHITE);
4029 }
4030
4031 /**
4032 * Setup one system color to match the RGB value provided in system
4033 * properties.
4034 *
4035 * @param key the system property key
4036 * @param defaultColor the default color to return if key is not set, or
4037 * incorrect
4038 * @return a color from the RGB string, or defaultColor
4039 */
4040 private java.awt.Color getCustomColor(final String key,
4041 final java.awt.Color defaultColor) {
4042
4043 String rgb = System.getProperty(key);
4044 if (rgb == null) {
4045 return defaultColor;
4046 }
4047 if (rgb.startsWith("#")) {
4048 rgb = rgb.substring(1);
4049 }
4050 int rgbInt = 0;
4051 try {
4052 rgbInt = Integer.parseInt(rgb, 16);
4053 } catch (NumberFormatException e) {
4054 return defaultColor;
4055 }
4056 java.awt.Color color = new java.awt.Color((rgbInt & 0xFF0000) >>> 16,
4057 (rgbInt & 0x00FF00) >>> 8,
4058 (rgbInt & 0x0000FF));
4059
4060 return color;
4061 }
4062
4063 /**
4064 * Create a T.416 RGB parameter sequence for a custom system color.
4065 *
4066 * @param color one of the MYBLACK, MYBOLD_BLUE, etc. colors
4067 * @return the color portion of the string to emit to an ANSI /
4068 * ECMA-style terminal
4069 */
4070 private String systemColorRGB(final java.awt.Color color) {
4071 return String.format("%d;%d;%d", color.getRed(), color.getGreen(),
4072 color.getBlue());
4073 }
4074
4075 /**
4076 * Create a SGR parameter sequence for a single color change.
4077 *
4078 * @param bold if true, set bold
4079 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
4080 * @param foreground if true, this is a foreground color
4081 * @return the string to emit to an ANSI / ECMA-style terminal,
4082 * e.g. "\033[42m"
4083 */
4084 private String color(final boolean bold, final Color color,
4085 final boolean foreground) {
4086 return color(color, foreground, true) +
4087 rgbColor(bold, color, foreground);
4088 }
4089
4090 /**
4091 * Create a T.416 RGB parameter sequence for a single color change.
4092 *
4093 * @param colorRGB a 24-bit RGB value for foreground color
4094 * @param foreground if true, this is a foreground color
4095 * @return the string to emit to an ANSI / ECMA-style terminal,
4096 * e.g. "\033[42m"
4097 */
4098 private String colorRGB(final int colorRGB, final boolean foreground) {
4099
4100 int colorRed = (colorRGB >>> 16) & 0xFF;
4101 int colorGreen = (colorRGB >>> 8) & 0xFF;
4102 int colorBlue = colorRGB & 0xFF;
4103
4104 StringBuilder sb = new StringBuilder();
4105 if (foreground) {
4106 sb.append("\033[38;2;");
4107 } else {
4108 sb.append("\033[48;2;");
4109 }
4110 sb.append(String.format("%d;%d;%dm", colorRed, colorGreen, colorBlue));
4111 return sb.toString();
4112 }
4113
4114 /**
4115 * Create a T.416 RGB parameter sequence for both foreground and
4116 * background color change.
4117 *
4118 * @param foreColorRGB a 24-bit RGB value for foreground color
4119 * @param backColorRGB a 24-bit RGB value for foreground color
4120 * @return the string to emit to an ANSI / ECMA-style terminal,
4121 * e.g. "\033[42m"
4122 */
4123 private String colorRGB(final int foreColorRGB, final int backColorRGB) {
4124 int foreColorRed = (foreColorRGB >>> 16) & 0xFF;
4125 int foreColorGreen = (foreColorRGB >>> 8) & 0xFF;
4126 int foreColorBlue = foreColorRGB & 0xFF;
4127 int backColorRed = (backColorRGB >>> 16) & 0xFF;
4128 int backColorGreen = (backColorRGB >>> 8) & 0xFF;
4129 int backColorBlue = backColorRGB & 0xFF;
4130
4131 StringBuilder sb = new StringBuilder();
4132 sb.append(String.format("\033[38;2;%d;%d;%dm",
4133 foreColorRed, foreColorGreen, foreColorBlue));
4134 sb.append(String.format("\033[48;2;%d;%d;%dm",
4135 backColorRed, backColorGreen, backColorBlue));
4136 return sb.toString();
4137 }
4138
4139 /**
4140 * Create a T.416 RGB parameter sequence for a single color change.
4141 *
4142 * @param bold if true, set bold
4143 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
4144 * @param foreground if true, this is a foreground color
4145 * @return the string to emit to an xterm terminal with RGB support,
4146 * e.g. "\033[38;2;RR;GG;BBm"
4147 */
4148 private String rgbColor(final boolean bold, final Color color,
4149 final boolean foreground) {
4150 if (doRgbColor == false) {
4151 return "";
4152 }
4153 StringBuilder sb = new StringBuilder("\033[");
4154 if (bold) {
4155 // Bold implies foreground only
4156 sb.append("38;2;");
4157 if (color.equals(Color.BLACK)) {
4158 sb.append(systemColorRGB(MYBOLD_BLACK));
4159 } else if (color.equals(Color.RED)) {
4160 sb.append(systemColorRGB(MYBOLD_RED));
4161 } else if (color.equals(Color.GREEN)) {
4162 sb.append(systemColorRGB(MYBOLD_GREEN));
4163 } else if (color.equals(Color.YELLOW)) {
4164 sb.append(systemColorRGB(MYBOLD_YELLOW));
4165 } else if (color.equals(Color.BLUE)) {
4166 sb.append(systemColorRGB(MYBOLD_BLUE));
4167 } else if (color.equals(Color.MAGENTA)) {
4168 sb.append(systemColorRGB(MYBOLD_MAGENTA));
4169 } else if (color.equals(Color.CYAN)) {
4170 sb.append(systemColorRGB(MYBOLD_CYAN));
4171 } else if (color.equals(Color.WHITE)) {
4172 sb.append(systemColorRGB(MYBOLD_WHITE));
4173 }
4174 } else {
4175 if (foreground) {
4176 sb.append("38;2;");
4177 } else {
4178 sb.append("48;2;");
4179 }
4180 if (color.equals(Color.BLACK)) {
4181 sb.append(systemColorRGB(MYBLACK));
4182 } else if (color.equals(Color.RED)) {
4183 sb.append(systemColorRGB(MYRED));
4184 } else if (color.equals(Color.GREEN)) {
4185 sb.append(systemColorRGB(MYGREEN));
4186 } else if (color.equals(Color.YELLOW)) {
4187 sb.append(systemColorRGB(MYYELLOW));
4188 } else if (color.equals(Color.BLUE)) {
4189 sb.append(systemColorRGB(MYBLUE));
4190 } else if (color.equals(Color.MAGENTA)) {
4191 sb.append(systemColorRGB(MYMAGENTA));
4192 } else if (color.equals(Color.CYAN)) {
4193 sb.append(systemColorRGB(MYCYAN));
4194 } else if (color.equals(Color.WHITE)) {
4195 sb.append(systemColorRGB(MYWHITE));
4196 }
4197 }
4198 sb.append("m");
4199 return sb.toString();
4200 }
4201
4202 /**
4203 * Create a T.416 RGB parameter sequence for both foreground and
4204 * background color change.
4205 *
4206 * @param bold if true, set bold
4207 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4208 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4209 * @return the string to emit to an xterm terminal with RGB support,
4210 * e.g. "\033[38;2;RR;GG;BB;48;2;RR;GG;BBm"
4211 */
4212 private String rgbColor(final boolean bold, final Color foreColor,
4213 final Color backColor) {
4214 if (doRgbColor == false) {
4215 return "";
4216 }
4217
4218 return rgbColor(bold, foreColor, true) +
4219 rgbColor(false, backColor, false);
4220 }
4221
4222 /**
4223 * Create a SGR parameter sequence for a single color change.
4224 *
4225 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
4226 * @param foreground if true, this is a foreground color
4227 * @param header if true, make the full header, otherwise just emit the
4228 * color parameter e.g. "42;"
4229 * @return the string to emit to an ANSI / ECMA-style terminal,
4230 * e.g. "\033[42m"
4231 */
4232 private String color(final Color color, final boolean foreground,
4233 final boolean header) {
4234
4235 int ecmaColor = color.getValue();
4236
4237 // Convert Color.* values to SGR numerics
4238 if (foreground) {
4239 ecmaColor += 30;
4240 } else {
4241 ecmaColor += 40;
4242 }
4243
4244 if (header) {
4245 return String.format("\033[%dm", ecmaColor);
4246 } else {
4247 return String.format("%d;", ecmaColor);
4248 }
4249 }
4250
4251 /**
4252 * Create a SGR parameter sequence for both foreground and background
4253 * color change.
4254 *
4255 * @param bold if true, set bold
4256 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4257 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4258 * @return the string to emit to an ANSI / ECMA-style terminal,
4259 * e.g. "\033[31;42m"
4260 */
4261 private String color(final boolean bold, final Color foreColor,
4262 final Color backColor) {
4263 return color(foreColor, backColor, true) +
4264 rgbColor(bold, foreColor, backColor);
4265 }
4266
4267 /**
4268 * Create a SGR parameter sequence for both foreground and
4269 * background color change.
4270 *
4271 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4272 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4273 * @param header if true, make the full header, otherwise just emit the
4274 * color parameter e.g. "31;42;"
4275 * @return the string to emit to an ANSI / ECMA-style terminal,
4276 * e.g. "\033[31;42m"
4277 */
4278 private String color(final Color foreColor, final Color backColor,
4279 final boolean header) {
4280
4281 int ecmaForeColor = foreColor.getValue();
4282 int ecmaBackColor = backColor.getValue();
4283
4284 // Convert Color.* values to SGR numerics
4285 ecmaBackColor += 40;
4286 ecmaForeColor += 30;
4287
4288 if (header) {
4289 return String.format("\033[%d;%dm", ecmaForeColor, ecmaBackColor);
4290 } else {
4291 return String.format("%d;%d;", ecmaForeColor, ecmaBackColor);
4292 }
4293 }
4294
4295 /**
4296 * Create a SGR parameter sequence for foreground, background, and
4297 * several attributes. This sequence first resets all attributes to
4298 * default, then sets attributes as per the parameters.
4299 *
4300 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
4301 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
4302 * @param bold if true, set bold
4303 * @param reverse if true, set reverse
4304 * @param blink if true, set blink
4305 * @param underline if true, set underline
4306 * @return the string to emit to an ANSI / ECMA-style terminal,
4307 * e.g. "\033[0;1;31;42m"
4308 */
4309 private String color(final Color foreColor, final Color backColor,
4310 final boolean bold, final boolean reverse, final boolean blink,
4311 final boolean underline) {
4312
4313 int ecmaForeColor = foreColor.getValue();
4314 int ecmaBackColor = backColor.getValue();
4315
4316 // Convert Color.* values to SGR numerics
4317 ecmaBackColor += 40;
4318 ecmaForeColor += 30;
4319
4320 StringBuilder sb = new StringBuilder();
4321 if ( bold && reverse && blink && !underline ) {
4322 sb.append("\033[0;1;7;5;");
4323 } else if ( bold && reverse && !blink && !underline ) {
4324 sb.append("\033[0;1;7;");
4325 } else if ( !bold && reverse && blink && !underline ) {
4326 sb.append("\033[0;7;5;");
4327 } else if ( bold && !reverse && blink && !underline ) {
4328 sb.append("\033[0;1;5;");
4329 } else if ( bold && !reverse && !blink && !underline ) {
4330 sb.append("\033[0;1;");
4331 } else if ( !bold && reverse && !blink && !underline ) {
4332 sb.append("\033[0;7;");
4333 } else if ( !bold && !reverse && blink && !underline) {
4334 sb.append("\033[0;5;");
4335 } else if ( bold && reverse && blink && underline ) {
4336 sb.append("\033[0;1;7;5;4;");
4337 } else if ( bold && reverse && !blink && underline ) {
4338 sb.append("\033[0;1;7;4;");
4339 } else if ( !bold && reverse && blink && underline ) {
4340 sb.append("\033[0;7;5;4;");
4341 } else if ( bold && !reverse && blink && underline ) {
4342 sb.append("\033[0;1;5;4;");
4343 } else if ( bold && !reverse && !blink && underline ) {
4344 sb.append("\033[0;1;4;");
4345 } else if ( !bold && reverse && !blink && underline ) {
4346 sb.append("\033[0;7;4;");
4347 } else if ( !bold && !reverse && blink && underline) {
4348 sb.append("\033[0;5;4;");
4349 } else if ( !bold && !reverse && !blink && underline) {
4350 sb.append("\033[0;4;");
4351 } else {
4352 assert (!bold && !reverse && !blink && !underline);
4353 sb.append("\033[0;");
4354 }
4355 sb.append(String.format("%d;%dm", ecmaForeColor, ecmaBackColor));
4356 sb.append(rgbColor(bold, foreColor, backColor));
4357 return sb.toString();
4358 }
4359
4360 /**
4361 * Create a SGR parameter sequence for foreground, background, and
4362 * several attributes. This sequence first resets all attributes to
4363 * default, then sets attributes as per the parameters.
4364 *
4365 * @param foreColorRGB a 24-bit RGB value for foreground color
4366 * @param backColorRGB a 24-bit RGB value for foreground color
4367 * @param bold if true, set bold
4368 * @param reverse if true, set reverse
4369 * @param blink if true, set blink
4370 * @param underline if true, set underline
4371 * @return the string to emit to an ANSI / ECMA-style terminal,
4372 * e.g. "\033[0;1;31;42m"
4373 */
4374 private String colorRGB(final int foreColorRGB, final int backColorRGB,
4375 final boolean bold, final boolean reverse, final boolean blink,
4376 final boolean underline) {
4377
4378 int foreColorRed = (foreColorRGB >>> 16) & 0xFF;
4379 int foreColorGreen = (foreColorRGB >>> 8) & 0xFF;
4380 int foreColorBlue = foreColorRGB & 0xFF;
4381 int backColorRed = (backColorRGB >>> 16) & 0xFF;
4382 int backColorGreen = (backColorRGB >>> 8) & 0xFF;
4383 int backColorBlue = backColorRGB & 0xFF;
4384
4385 StringBuilder sb = new StringBuilder();
4386 if ( bold && reverse && blink && !underline ) {
4387 sb.append("\033[0;1;7;5;");
4388 } else if ( bold && reverse && !blink && !underline ) {
4389 sb.append("\033[0;1;7;");
4390 } else if ( !bold && reverse && blink && !underline ) {
4391 sb.append("\033[0;7;5;");
4392 } else if ( bold && !reverse && blink && !underline ) {
4393 sb.append("\033[0;1;5;");
4394 } else if ( bold && !reverse && !blink && !underline ) {
4395 sb.append("\033[0;1;");
4396 } else if ( !bold && reverse && !blink && !underline ) {
4397 sb.append("\033[0;7;");
4398 } else if ( !bold && !reverse && blink && !underline) {
4399 sb.append("\033[0;5;");
4400 } else if ( bold && reverse && blink && underline ) {
4401 sb.append("\033[0;1;7;5;4;");
4402 } else if ( bold && reverse && !blink && underline ) {
4403 sb.append("\033[0;1;7;4;");
4404 } else if ( !bold && reverse && blink && underline ) {
4405 sb.append("\033[0;7;5;4;");
4406 } else if ( bold && !reverse && blink && underline ) {
4407 sb.append("\033[0;1;5;4;");
4408 } else if ( bold && !reverse && !blink && underline ) {
4409 sb.append("\033[0;1;4;");
4410 } else if ( !bold && reverse && !blink && underline ) {
4411 sb.append("\033[0;7;4;");
4412 } else if ( !bold && !reverse && blink && underline) {
4413 sb.append("\033[0;5;4;");
4414 } else if ( !bold && !reverse && !blink && underline) {
4415 sb.append("\033[0;4;");
4416 } else {
4417 assert (!bold && !reverse && !blink && !underline);
4418 sb.append("\033[0;");
4419 }
4420
4421 sb.append("m\033[38;2;");
4422 sb.append(String.format("%d;%d;%d", foreColorRed, foreColorGreen,
4423 foreColorBlue));
4424 sb.append("m\033[48;2;");
4425 sb.append(String.format("%d;%d;%d", backColorRed, backColorGreen,
4426 backColorBlue));
4427 sb.append("m");
4428 return sb.toString();
4429 }
4430
4431 /**
4432 * Create a SGR parameter sequence to reset to VT100 defaults.
4433 *
4434 * @return the string to emit to an ANSI / ECMA-style terminal,
4435 * e.g. "\033[0m"
4436 */
4437 private String normal() {
4438 return normal(true) + rgbColor(false, Color.WHITE, Color.BLACK);
4439 }
4440
4441 /**
4442 * Create a SGR parameter sequence to reset to ECMA-48 default
4443 * foreground/background.
4444 *
4445 * @return the string to emit to an ANSI / ECMA-style terminal,
4446 * e.g. "\033[0m"
4447 */
4448 private String defaultColor() {
4449 /*
4450 * VT100 normal.
4451 * Normal (neither bold nor faint).
4452 * Not italicized.
4453 * Not underlined.
4454 * Steady (not blinking).
4455 * Positive (not inverse).
4456 * Visible (not hidden).
4457 * Not crossed-out.
4458 * Default foreground color.
4459 * Default background color.
4460 */
4461 return "\033[0;22;23;24;25;27;28;29;39;49m";
4462 }
4463
4464 /**
4465 * Create a SGR parameter sequence to reset to defaults.
4466 *
4467 * @param header if true, make the full header, otherwise just emit the
4468 * bare parameter e.g. "0;"
4469 * @return the string to emit to an ANSI / ECMA-style terminal,
4470 * e.g. "\033[0m"
4471 */
4472 private String normal(final boolean header) {
4473 if (header) {
4474 return "\033[0;37;40m";
4475 }
4476 return "0;37;40";
4477 }
4478
4479 /**
4480 * Create a SGR parameter sequence for enabling the visible cursor.
4481 *
4482 * @param on if true, turn on cursor
4483 * @return the string to emit to an ANSI / ECMA-style terminal
4484 */
4485 private String cursor(final boolean on) {
4486 if (on && !cursorOn) {
4487 cursorOn = true;
4488 return "\033[?25h";
4489 }
4490 if (!on && cursorOn) {
4491 cursorOn = false;
4492 return "\033[?25l";
4493 }
4494 return "";
4495 }
4496
4497 /**
4498 * Clear the entire screen. Because some terminals use back-color-erase,
4499 * set the color to white-on-black beforehand.
4500 *
4501 * @return the string to emit to an ANSI / ECMA-style terminal
4502 */
4503 private String clearAll() {
4504 return "\033[0;37;40m\033[2J";
4505 }
4506
4507 /**
4508 * Clear the line from the cursor (inclusive) to the end of the screen.
4509 * Because some terminals use back-color-erase, set the color to
4510 * white-on-black beforehand.
4511 *
4512 * @return the string to emit to an ANSI / ECMA-style terminal
4513 */
4514 private String clearRemainingLine() {
4515 return "\033[0;37;40m\033[K";
4516 }
4517
4518 /**
4519 * Move the cursor to (x, y).
4520 *
4521 * @param x column coordinate. 0 is the left-most column.
4522 * @param y row coordinate. 0 is the top-most row.
4523 * @return the string to emit to an ANSI / ECMA-style terminal
4524 */
4525 private String gotoXY(final int x, final int y) {
4526 return String.format("\033[%d;%dH", y + 1, x + 1);
4527 }
4528
4529 /**
4530 * Tell (u)xterm that we want to receive mouse events based on "Any event
4531 * tracking", UTF-8 coordinates, and then SGR coordinates. Ideally we
4532 * will end up with SGR coordinates with UTF-8 coordinates as a fallback.
4533 * See
4534 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
4535 *
4536 * Note that this also sets the alternate/primary screen buffer.
4537 *
4538 * Finally, also emit a Privacy Message sequence that Jexer recognizes to
4539 * mean "hide the mouse pointer." We have to use our own sequence to do
4540 * this because there is no standard in xterm for unilaterally hiding the
4541 * pointer all the time (regardless of typing).
4542 *
4543 * @param on If true, enable mouse report and use the alternate screen
4544 * buffer. If false disable mouse reporting and use the primary screen
4545 * buffer.
4546 * @return the string to emit to xterm
4547 */
4548 private String mouse(final boolean on) {
4549 if (on) {
4550 return "\033[?1002;1003;1005;1006h\033[?1049h\033^hideMousePointer\033\\";
4551 }
4552 return "\033[?1002;1003;1006;1005l\033[?1049l\033^showMousePointer\033\\";
4553 }
4554
4555 }