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