Prep for 2019 release
[nikiroo-utils.git] / src / jexer / backend / ECMA48Terminal.java
1 /*
2 * Jexer - Java Text User Interface
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (C) 2019 Kevin Lamonte
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
25 *
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
27 * @version 1
28 */
29 package jexer.backend;
30
31 import java.awt.image.BufferedImage;
32 import java.io.BufferedReader;
33 import java.io.FileDescriptor;
34 import java.io.FileInputStream;
35 import java.io.InputStream;
36 import java.io.InputStreamReader;
37 import java.io.IOException;
38 import java.io.OutputStream;
39 import java.io.OutputStreamWriter;
40 import java.io.PrintWriter;
41 import java.io.Reader;
42 import java.io.UnsupportedEncodingException;
43 import java.util.ArrayList;
44 import java.util.Collections;
45 import java.util.HashMap;
46 import java.util.List;
47 import java.util.LinkedList;
48 import java.util.Map;
49
50 import jexer.TImage;
51 import jexer.bits.Cell;
52 import jexer.bits.CellAttributes;
53 import jexer.bits.Color;
54 import jexer.event.TInputEvent;
55 import jexer.event.TKeypressEvent;
56 import jexer.event.TMouseEvent;
57 import jexer.event.TResizeEvent;
58 import static jexer.TKeypress.*;
59
60 /**
61 * This class reads keystrokes and mouse events and emits output to ANSI
62 * X3.64 / ECMA-48 type terminals e.g. xterm, linux, vt100, ansi.sys, etc.
63 */
64 public class ECMA48Terminal extends LogicalScreen
65 implements TerminalReader, Runnable {
66
67 // ------------------------------------------------------------------------
68 // Constants --------------------------------------------------------------
69 // ------------------------------------------------------------------------
70
71 /**
72 * States in the input parser.
73 */
74 private enum ParseState {
75 GROUND,
76 ESCAPE,
77 ESCAPE_INTERMEDIATE,
78 CSI_ENTRY,
79 CSI_PARAM,
80 MOUSE,
81 MOUSE_SGR,
82 }
83
84 /**
85 * Number of colors in the sixel palette. Xterm 335 defines the max as
86 * 1024.
87 */
88 private static final int MAX_COLOR_REGISTERS = 1024;
89
90 // ------------------------------------------------------------------------
91 // Variables --------------------------------------------------------------
92 // ------------------------------------------------------------------------
93
94 /**
95 * Emit debugging to stderr.
96 */
97 private boolean debugToStderr = false;
98
99 /**
100 * If true, emit T.416-style RGB colors for normal system colors. This
101 * is a) expensive in bandwidth, and b) potentially terrible looking for
102 * non-xterms.
103 */
104 private static boolean doRgbColor = false;
105
106 /**
107 * The session information.
108 */
109 private SessionInfo sessionInfo;
110
111 /**
112 * The event queue, filled up by a thread reading on input.
113 */
114 private List<TInputEvent> eventQueue;
115
116 /**
117 * If true, we want the reader thread to exit gracefully.
118 */
119 private boolean stopReaderThread;
120
121 /**
122 * The reader thread.
123 */
124 private Thread readerThread;
125
126 /**
127 * Parameters being collected. E.g. if the string is \033[1;3m, then
128 * params[0] will be 1 and params[1] will be 3.
129 */
130 private List<String> params;
131
132 /**
133 * Current parsing state.
134 */
135 private ParseState state;
136
137 /**
138 * The time we entered ESCAPE. If we get a bare escape without a code
139 * following it, this is used to return that bare escape.
140 */
141 private long escapeTime;
142
143 /**
144 * The time we last checked the window size. We try not to spawn stty
145 * more than once per second.
146 */
147 private long windowSizeTime;
148
149 /**
150 * true if mouse1 was down. Used to report mouse1 on the release event.
151 */
152 private boolean mouse1;
153
154 /**
155 * true if mouse2 was down. Used to report mouse2 on the release event.
156 */
157 private boolean mouse2;
158
159 /**
160 * true if mouse3 was down. Used to report mouse3 on the release event.
161 */
162 private boolean mouse3;
163
164 /**
165 * Cache the cursor visibility value so we only emit the sequence when we
166 * need to.
167 */
168 private boolean cursorOn = true;
169
170 /**
171 * Cache the last window size to figure out if a TResizeEvent needs to be
172 * generated.
173 */
174 private TResizeEvent windowResize = null;
175
176 /**
177 * Window width in pixels. Used for sixel support.
178 */
179 private int widthPixels = 640;
180
181 /**
182 * Window height in pixels. Used for sixel support.
183 */
184 private int heightPixels = 400;
185
186 /**
187 * If true, emit image data via sixel.
188 */
189 private boolean sixel = true;
190
191 /**
192 * The sixel palette handler.
193 */
194 private SixelPalette palette = null;
195
196 /**
197 * The sixel post-rendered string cache.
198 */
199 private SixelCache sixelCache = null;
200
201 /**
202 * If true, then we changed System.in and need to change it back.
203 */
204 private boolean setRawMode;
205
206 /**
207 * The terminal's input. If an InputStream is not specified in the
208 * constructor, then this InputStreamReader will be bound to System.in
209 * with UTF-8 encoding.
210 */
211 private Reader input;
212
213 /**
214 * The terminal's raw InputStream. If an InputStream is not specified in
215 * the constructor, then this InputReader will be bound to System.in.
216 * This is used by run() to see if bytes are available() before calling
217 * (Reader)input.read().
218 */
219 private InputStream inputStream;
220
221 /**
222 * The terminal's output. If an OutputStream is not specified in the
223 * constructor, then this PrintWriter will be bound to System.out with
224 * UTF-8 encoding.
225 */
226 private PrintWriter output;
227
228 /**
229 * The listening object that run() wakes up on new input.
230 */
231 private Object listener;
232
233 /**
234 * SixelPalette is used to manage the conversion of images between 24-bit
235 * RGB color and a palette of MAX_COLOR_REGISTERS colors.
236 */
237 private class SixelPalette {
238
239 /**
240 * Color palette for sixel output, sorted low to high.
241 */
242 private List<Integer> rgbColors = new ArrayList<Integer>();
243
244 /**
245 * Map of color palette index for sixel output, from the order it was
246 * generated by makePalette() to rgbColors.
247 */
248 private int [] rgbSortedIndex = new int[MAX_COLOR_REGISTERS];
249
250 /**
251 * The color palette, organized by hue, saturation, and luminance.
252 * This is used for a fast color match.
253 */
254 private ArrayList<ArrayList<ArrayList<ColorIdx>>> hslColors;
255
256 /**
257 * Number of bits for hue.
258 */
259 private int hueBits = -1;
260
261 /**
262 * Number of bits for saturation.
263 */
264 private int satBits = -1;
265
266 /**
267 * Number of bits for luminance.
268 */
269 private int lumBits = -1;
270
271 /**
272 * Step size for hue bins.
273 */
274 private int hueStep = -1;
275
276 /**
277 * Step size for saturation bins.
278 */
279 private int satStep = -1;
280
281 /**
282 * Cached RGB to HSL result.
283 */
284 private int hsl[] = new int[3];
285
286 /**
287 * ColorIdx records a RGB color and its palette index.
288 */
289 private class ColorIdx {
290 /**
291 * The 24-bit RGB color.
292 */
293 public int color;
294
295 /**
296 * The palette index for this color.
297 */
298 public int index;
299
300 /**
301 * Public constructor.
302 *
303 * @param color the 24-bit RGB color
304 * @param index the palette index for this color
305 */
306 public ColorIdx(final int color, final int index) {
307 this.color = color;
308 this.index = index;
309 }
310 }
311
312 /**
313 * Public constructor.
314 */
315 public SixelPalette() {
316 makePalette();
317 }
318
319 /**
320 * Find the nearest match for a color in the palette.
321 *
322 * @param color the RGB color
323 * @return the index in rgbColors that is closest to color
324 */
325 public int matchColor(final int color) {
326
327 assert (color >= 0);
328
329 /*
330 * matchColor() is a critical performance bottleneck. To make it
331 * decent, we do the following:
332 *
333 * 1. Find the nearest two hues that bracket this color.
334 *
335 * 2. Find the nearest two saturations that bracket this color.
336 *
337 * 3. Iterate within these four bands of luminance values,
338 * returning the closest color by Euclidean distance.
339 *
340 * This strategy reduces the search space by about 97%.
341 */
342 int red = (color >>> 16) & 0xFF;
343 int green = (color >>> 8) & 0xFF;
344 int blue = color & 0xFF;
345
346 rgbToHsl(red, green, blue, hsl);
347 int hue = hsl[0];
348 int sat = hsl[1];
349 int lum = hsl[2];
350 // System.err.printf("%d %d %d\n", hue, sat, lum);
351
352 double diff = Double.MAX_VALUE;
353 int idx = -1;
354
355 int hue1 = hue / (360/hueStep);
356 int hue2 = hue1 + 1;
357 if (hue1 >= hslColors.size() - 1) {
358 // Bracket pure red from above.
359 hue1 = hslColors.size() - 1;
360 hue2 = 0;
361 } else if (hue1 == 0) {
362 // Bracket pure red from below.
363 hue2 = hslColors.size() - 1;
364 }
365
366 for (int hI = hue1; hI != -1;) {
367 ArrayList<ArrayList<ColorIdx>> sats = hslColors.get(hI);
368 if (hI == hue1) {
369 hI = hue2;
370 } else if (hI == hue2) {
371 hI = -1;
372 }
373
374 int sMin = (sat / satStep) - 1;
375 int sMax = sMin + 1;
376 if (sMin < 0) {
377 sMin = 0;
378 sMax = 1;
379 } else if (sMin == sats.size() - 1) {
380 sMax = sMin;
381 sMin--;
382 }
383 assert (sMin >= 0);
384 assert (sMax - sMin == 1);
385
386 // int sMin = 0;
387 // int sMax = sats.size() - 1;
388
389 for (int sI = sMin; sI <= sMax; sI++) {
390 ArrayList<ColorIdx> lums = sats.get(sI);
391
392 // True 3D colorspace match for the remaining values
393 for (ColorIdx c: lums) {
394 int rgbColor = c.color;
395 double newDiff = 0;
396 int red2 = (rgbColor >>> 16) & 0xFF;
397 int green2 = (rgbColor >>> 8) & 0xFF;
398 int blue2 = rgbColor & 0xFF;
399 newDiff += Math.pow(red2 - red, 2);
400 newDiff += Math.pow(green2 - green, 2);
401 newDiff += Math.pow(blue2 - blue, 2);
402 if (newDiff < diff) {
403 idx = rgbSortedIndex[c.index];
404 diff = newDiff;
405 }
406 }
407 }
408 }
409
410 if (((red * red) + (green * green) + (blue * blue)) < diff) {
411 // Black is a closer match.
412 idx = 0;
413 } else if ((((255 - red) * (255 - red)) +
414 ((255 - green) * (255 - green)) +
415 ((255 - blue) * (255 - blue))) < diff) {
416
417 // White is a closer match.
418 idx = MAX_COLOR_REGISTERS - 1;
419 }
420 assert (idx != -1);
421 return idx;
422 }
423
424 /**
425 * Clamp an int value to [0, 255].
426 *
427 * @param x the int value
428 * @return an int between 0 and 255.
429 */
430 private int clamp(final int x) {
431 if (x < 0) {
432 return 0;
433 }
434 if (x > 255) {
435 return 255;
436 }
437 return x;
438 }
439
440 /**
441 * Dither an image to a MAX_COLOR_REGISTERS palette. The dithered
442 * image cells will contain indexes into the palette.
443 *
444 * @param image the image to dither
445 * @return the dithered image. Every pixel is an index into the
446 * palette.
447 */
448 public BufferedImage ditherImage(final BufferedImage image) {
449
450 BufferedImage ditheredImage = new BufferedImage(image.getWidth(),
451 image.getHeight(), BufferedImage.TYPE_INT_ARGB);
452
453 int [] rgbArray = image.getRGB(0, 0, image.getWidth(),
454 image.getHeight(), null, 0, image.getWidth());
455 ditheredImage.setRGB(0, 0, image.getWidth(), image.getHeight(),
456 rgbArray, 0, image.getWidth());
457
458 for (int imageY = 0; imageY < image.getHeight(); imageY++) {
459 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
460 int oldPixel = ditheredImage.getRGB(imageX,
461 imageY) & 0xFFFFFF;
462 int colorIdx = matchColor(oldPixel);
463 assert (colorIdx >= 0);
464 assert (colorIdx < MAX_COLOR_REGISTERS);
465 int newPixel = rgbColors.get(colorIdx);
466 ditheredImage.setRGB(imageX, imageY, colorIdx);
467
468 int oldRed = (oldPixel >>> 16) & 0xFF;
469 int oldGreen = (oldPixel >>> 8) & 0xFF;
470 int oldBlue = oldPixel & 0xFF;
471
472 int newRed = (newPixel >>> 16) & 0xFF;
473 int newGreen = (newPixel >>> 8) & 0xFF;
474 int newBlue = newPixel & 0xFF;
475
476 int redError = (oldRed - newRed) / 16;
477 int greenError = (oldGreen - newGreen) / 16;
478 int blueError = (oldBlue - newBlue) / 16;
479
480 int red, green, blue;
481 if (imageX < image.getWidth() - 1) {
482 int pXpY = ditheredImage.getRGB(imageX + 1, imageY);
483 red = (int) ((pXpY >>> 16) & 0xFF) + (7 * redError);
484 green = (int) ((pXpY >>> 8) & 0xFF) + (7 * greenError);
485 blue = (int) ( pXpY & 0xFF) + (7 * blueError);
486 red = clamp(red);
487 green = clamp(green);
488 blue = clamp(blue);
489 pXpY = ((red & 0xFF) << 16);
490 pXpY |= ((green & 0xFF) << 8) | (blue & 0xFF);
491 ditheredImage.setRGB(imageX + 1, imageY, pXpY);
492
493 if (imageY < image.getHeight() - 1) {
494 int pXpYp = ditheredImage.getRGB(imageX + 1,
495 imageY + 1);
496 red = (int) ((pXpYp >>> 16) & 0xFF) + redError;
497 green = (int) ((pXpYp >>> 8) & 0xFF) + greenError;
498 blue = (int) ( pXpYp & 0xFF) + blueError;
499 red = clamp(red);
500 green = clamp(green);
501 blue = clamp(blue);
502 pXpYp = ((red & 0xFF) << 16);
503 pXpYp |= ((green & 0xFF) << 8) | (blue & 0xFF);
504 ditheredImage.setRGB(imageX + 1, imageY + 1, pXpYp);
505 }
506 } else if (imageY < image.getHeight() - 1) {
507 int pXmYp = ditheredImage.getRGB(imageX - 1,
508 imageY + 1);
509 int pXYp = ditheredImage.getRGB(imageX,
510 imageY + 1);
511
512 red = (int) ((pXmYp >>> 16) & 0xFF) + (3 * redError);
513 green = (int) ((pXmYp >>> 8) & 0xFF) + (3 * greenError);
514 blue = (int) ( pXmYp & 0xFF) + (3 * blueError);
515 red = clamp(red);
516 green = clamp(green);
517 blue = clamp(blue);
518 pXmYp = ((red & 0xFF) << 16);
519 pXmYp |= ((green & 0xFF) << 8) | (blue & 0xFF);
520 ditheredImage.setRGB(imageX - 1, imageY + 1, pXmYp);
521
522 red = (int) ((pXYp >>> 16) & 0xFF) + (5 * redError);
523 green = (int) ((pXYp >>> 8) & 0xFF) + (5 * greenError);
524 blue = (int) ( pXYp & 0xFF) + (5 * blueError);
525 red = clamp(red);
526 green = clamp(green);
527 blue = clamp(blue);
528 pXYp = ((red & 0xFF) << 16);
529 pXYp |= ((green & 0xFF) << 8) | (blue & 0xFF);
530 ditheredImage.setRGB(imageX, imageY + 1, pXYp);
531 }
532 } // for (int imageY = 0; imageY < image.getHeight(); imageY++)
533 } // for (int imageX = 0; imageX < image.getWidth(); imageX++)
534
535 return ditheredImage;
536 }
537
538 /**
539 * Convert an RGB color to HSL.
540 *
541 * @param red red color, between 0 and 255
542 * @param green green color, between 0 and 255
543 * @param blue blue color, between 0 and 255
544 * @param hsl the hsl color as [hue, saturation, luminance]
545 */
546 private void rgbToHsl(final int red, final int green,
547 final int blue, final int [] hsl) {
548
549 assert ((red >= 0) && (red <= 255));
550 assert ((green >= 0) && (green <= 255));
551 assert ((blue >= 0) && (blue <= 255));
552
553 double R = red / 255.0;
554 double G = green / 255.0;
555 double B = blue / 255.0;
556 boolean Rmax = false;
557 boolean Gmax = false;
558 boolean Bmax = false;
559 double min = (R < G ? R : G);
560 min = (min < B ? min : B);
561 double max = 0;
562 if ((R >= G) && (R >= B)) {
563 max = R;
564 Rmax = true;
565 } else if ((G >= R) && (G >= B)) {
566 max = G;
567 Gmax = true;
568 } else if ((B >= G) && (B >= R)) {
569 max = B;
570 Bmax = true;
571 }
572
573 double L = (min + max) / 2.0;
574 double H = 0.0;
575 double S = 0.0;
576 if (min != max) {
577 if (L < 0.5) {
578 S = (max - min) / (max + min);
579 } else {
580 S = (max - min) / (2.0 - max - min);
581 }
582 }
583 if (Rmax) {
584 assert (Gmax == false);
585 assert (Bmax == false);
586 H = (G - B) / (max - min);
587 } else if (Gmax) {
588 assert (Rmax == false);
589 assert (Bmax == false);
590 H = 2.0 + (B - R) / (max - min);
591 } else if (Bmax) {
592 assert (Rmax == false);
593 assert (Gmax == false);
594 H = 4.0 + (R - G) / (max - min);
595 }
596 if (H < 0.0) {
597 H += 6.0;
598 }
599 hsl[0] = (int) (H * 60.0);
600 hsl[1] = (int) (S * 100.0);
601 hsl[2] = (int) (L * 100.0);
602
603 assert ((hsl[0] >= 0) && (hsl[0] <= 360));
604 assert ((hsl[1] >= 0) && (hsl[1] <= 100));
605 assert ((hsl[2] >= 0) && (hsl[2] <= 100));
606 }
607
608 /**
609 * Convert a HSL color to RGB.
610 *
611 * @param hue hue, between 0 and 359
612 * @param sat saturation, between 0 and 100
613 * @param lum luminance, between 0 and 100
614 * @return the rgb color as 0x00RRGGBB
615 */
616 private int hslToRgb(final int hue, final int sat, final int lum) {
617 assert ((hue >= 0) && (hue <= 360));
618 assert ((sat >= 0) && (sat <= 100));
619 assert ((lum >= 0) && (lum <= 100));
620
621 double S = sat / 100.0;
622 double L = lum / 100.0;
623 double C = (1.0 - Math.abs((2.0 * L) - 1.0)) * S;
624 double Hp = hue / 60.0;
625 double X = C * (1.0 - Math.abs((Hp % 2) - 1.0));
626 double Rp = 0.0;
627 double Gp = 0.0;
628 double Bp = 0.0;
629 if (Hp <= 1.0) {
630 Rp = C;
631 Gp = X;
632 } else if (Hp <= 2.0) {
633 Rp = X;
634 Gp = C;
635 } else if (Hp <= 3.0) {
636 Gp = C;
637 Bp = X;
638 } else if (Hp <= 4.0) {
639 Gp = X;
640 Bp = C;
641 } else if (Hp <= 5.0) {
642 Rp = X;
643 Bp = C;
644 } else if (Hp <= 6.0) {
645 Rp = C;
646 Bp = X;
647 }
648 double m = L - (C / 2.0);
649 int red = ((int) ((Rp + m) * 255.0)) << 16;
650 int green = ((int) ((Gp + m) * 255.0)) << 8;
651 int blue = (int) ((Bp + m) * 255.0);
652
653 return (red | green | blue);
654 }
655
656 /**
657 * Create the sixel palette.
658 */
659 private void makePalette() {
660 // Generate the sixel palette. Because we have no idea at this
661 // layer which image(s) will be shown, we have to use a common
662 // palette with MAX_COLOR_REGISTERS colors for everything, and
663 // map the BufferedImage colors to their nearest neighbor in RGB
664 // space.
665
666 // We build a palette using the Hue-Saturation-Luminence model,
667 // with 5+ bits for Hue, 2+ bits for Saturation, and 1+ bit for
668 // Luminance. We convert these colors to 24-bit RGB, sort them
669 // ascending, and steal the first index for pure black and the
670 // last for pure white. The 8-bit final palette favors bright
671 // colors, somewhere between pastel and classic television
672 // technicolor. 9- and 10-bit palettes are more uniform.
673
674 // Default at 256 colors.
675 hueBits = 5;
676 satBits = 2;
677 lumBits = 1;
678
679 assert (MAX_COLOR_REGISTERS >= 256);
680 assert ((MAX_COLOR_REGISTERS == 256)
681 || (MAX_COLOR_REGISTERS == 512)
682 || (MAX_COLOR_REGISTERS == 1024)
683 || (MAX_COLOR_REGISTERS == 2048));
684
685 switch (MAX_COLOR_REGISTERS) {
686 case 512:
687 hueBits = 5;
688 satBits = 2;
689 lumBits = 2;
690 break;
691 case 1024:
692 hueBits = 5;
693 satBits = 2;
694 lumBits = 3;
695 break;
696 case 2048:
697 hueBits = 5;
698 satBits = 3;
699 lumBits = 3;
700 break;
701 }
702 hueStep = (int) (Math.pow(2, hueBits));
703 satStep = (int) (100 / Math.pow(2, satBits));
704 // 1 bit for luminance: 40 and 70.
705 int lumBegin = 40;
706 int lumStep = 30;
707 switch (lumBits) {
708 case 2:
709 // 2 bits: 20, 40, 60, 80
710 lumBegin = 20;
711 lumStep = 20;
712 break;
713 case 3:
714 // 3 bits: 8, 20, 32, 44, 56, 68, 80, 92
715 lumBegin = 8;
716 lumStep = 12;
717 break;
718 }
719
720 // System.err.printf("<html><body>\n");
721 // Hue is evenly spaced around the wheel.
722 hslColors = new ArrayList<ArrayList<ArrayList<ColorIdx>>>();
723
724 final boolean DEBUG = false;
725 ArrayList<Integer> rawRgbList = new ArrayList<Integer>();
726
727 for (int hue = 0; hue < (360 - (360 % hueStep));
728 hue += (360/hueStep)) {
729
730 ArrayList<ArrayList<ColorIdx>> satList = null;
731 satList = new ArrayList<ArrayList<ColorIdx>>();
732 hslColors.add(satList);
733
734 // Saturation is linearly spaced between pastel and pure.
735 for (int sat = satStep; sat <= 100; sat += satStep) {
736
737 ArrayList<ColorIdx> lumList = new ArrayList<ColorIdx>();
738 satList.add(lumList);
739
740 // Luminance brackets the pure color, but leaning toward
741 // lighter.
742 for (int lum = lumBegin; lum < 100; lum += lumStep) {
743 /*
744 System.err.printf("<font style = \"color:");
745 System.err.printf("hsl(%d, %d%%, %d%%)",
746 hue, sat, lum);
747 System.err.printf(";\">=</font>\n");
748 */
749 int rgbColor = hslToRgb(hue, sat, lum);
750 rgbColors.add(rgbColor);
751 ColorIdx colorIdx = new ColorIdx(rgbColor,
752 rgbColors.size() - 1);
753 lumList.add(colorIdx);
754
755 rawRgbList.add(rgbColor);
756 if (DEBUG) {
757 int red = (rgbColor >>> 16) & 0xFF;
758 int green = (rgbColor >>> 8) & 0xFF;
759 int blue = rgbColor & 0xFF;
760 int [] backToHsl = new int[3];
761 rgbToHsl(red, green, blue, backToHsl);
762 System.err.printf("%d [%d] %d [%d] %d [%d]\n",
763 hue, backToHsl[0], sat, backToHsl[1],
764 lum, backToHsl[2]);
765 }
766 }
767 }
768 }
769 // System.err.printf("\n</body></html>\n");
770
771 assert (rgbColors.size() == MAX_COLOR_REGISTERS);
772
773 /*
774 * We need to sort rgbColors, so that toSixel() can know where
775 * BLACK and WHITE are in it. But we also need to be able to
776 * find the sorted values using the old unsorted indexes. So we
777 * will sort it, put all the indexes into a HashMap, and then
778 * build rgbSortedIndex[].
779 */
780 Collections.sort(rgbColors);
781 HashMap<Integer, Integer> rgbColorIndices = null;
782 rgbColorIndices = new HashMap<Integer, Integer>();
783 for (int i = 0; i < MAX_COLOR_REGISTERS; i++) {
784 rgbColorIndices.put(rgbColors.get(i), i);
785 }
786 for (int i = 0; i < MAX_COLOR_REGISTERS; i++) {
787 int rawColor = rawRgbList.get(i);
788 rgbSortedIndex[i] = rgbColorIndices.get(rawColor);
789 }
790 if (DEBUG) {
791 for (int i = 0; i < MAX_COLOR_REGISTERS; i++) {
792 assert (rawRgbList != null);
793 int idx = rgbSortedIndex[i];
794 int rgbColor = rgbColors.get(idx);
795 if ((idx != 0) && (idx != MAX_COLOR_REGISTERS - 1)) {
796 /*
797 System.err.printf("%d %06x --> %d %06x\n",
798 i, rawRgbList.get(i), idx, rgbColors.get(idx));
799 */
800 assert (rgbColor == rawRgbList.get(i));
801 }
802 }
803 }
804
805 // Set the dimmest color as true black, and the brightest as true
806 // white.
807 rgbColors.set(0, 0);
808 rgbColors.set(MAX_COLOR_REGISTERS - 1, 0xFFFFFF);
809
810 /*
811 System.err.printf("<html><body>\n");
812 for (Integer rgb: rgbColors) {
813 System.err.printf("<font style = \"color:");
814 System.err.printf("#%06x", rgb);
815 System.err.printf(";\">=</font>\n");
816 }
817 System.err.printf("\n</body></html>\n");
818 */
819
820 }
821
822 /**
823 * Emit the sixel palette.
824 *
825 * @param sb the StringBuilder to append to
826 * @param used array of booleans set to true for each color actually
827 * used in this cell, or null to emit the entire palette
828 * @return the string to emit to an ANSI / ECMA-style terminal
829 */
830 public String emitPalette(final StringBuilder sb,
831 final boolean [] used) {
832
833 for (int i = 0; i < MAX_COLOR_REGISTERS; i++) {
834 if (((used != null) && (used[i] == true)) || (used == null)) {
835 int rgbColor = rgbColors.get(i);
836 sb.append(String.format("#%d;2;%d;%d;%d", i,
837 ((rgbColor >>> 16) & 0xFF) * 100 / 255,
838 ((rgbColor >>> 8) & 0xFF) * 100 / 255,
839 ( rgbColor & 0xFF) * 100 / 255));
840 }
841 }
842 return sb.toString();
843 }
844 }
845
846 /**
847 * SixelCache is a least-recently-used cache that hangs on to the
848 * post-rendered sixel string for a particular set of cells.
849 */
850 private class SixelCache {
851
852 /**
853 * Maximum size of the cache.
854 */
855 private int maxSize = 100;
856
857 /**
858 * The entries stored in the cache.
859 */
860 private HashMap<String, CacheEntry> cache = null;
861
862 /**
863 * CacheEntry is one entry in the cache.
864 */
865 private class CacheEntry {
866 /**
867 * The cache key.
868 */
869 public String key;
870
871 /**
872 * The cache data.
873 */
874 public String data;
875
876 /**
877 * The last time this entry was used.
878 */
879 public long millis = 0;
880
881 /**
882 * Public constructor.
883 *
884 * @param key the cache entry key
885 * @param data the cache entry data
886 */
887 public CacheEntry(final String key, final String data) {
888 this.key = key;
889 this.data = data;
890 this.millis = System.currentTimeMillis();
891 }
892 }
893
894 /**
895 * Public constructor.
896 *
897 * @param maxSize the maximum size of the cache
898 */
899 public SixelCache(final int maxSize) {
900 this.maxSize = maxSize;
901 cache = new HashMap<String, CacheEntry>();
902 }
903
904 /**
905 * Make a unique key for a list of cells.
906 *
907 * @param cells the cells
908 * @return the key
909 */
910 private String makeKey(final ArrayList<Cell> cells) {
911 StringBuilder sb = new StringBuilder();
912 for (Cell cell: cells) {
913 sb.append(cell.hashCode());
914 }
915 return sb.toString();
916 }
917
918 /**
919 * Get an entry from the cache.
920 *
921 * @param cells the list of cells that are the cache key
922 * @return the sixel string representing these cells, or null if this
923 * list of cells is not in the cache
924 */
925 public String get(final ArrayList<Cell> cells) {
926 CacheEntry entry = cache.get(makeKey(cells));
927 if (entry == null) {
928 return null;
929 }
930 entry.millis = System.currentTimeMillis();
931 return entry.data;
932 }
933
934 /**
935 * Put an entry into the cache.
936 *
937 * @param cells the list of cells that are the cache key
938 * @param data the sixel string representing these cells
939 */
940 public void put(final ArrayList<Cell> cells, final String data) {
941 String key = makeKey(cells);
942
943 // System.err.println("put() " + key + " size " + cache.size());
944
945 assert (!cache.containsKey(key));
946
947 assert (cache.size() <= maxSize);
948 if (cache.size() == maxSize) {
949 // Cache is at limit, evict oldest entry.
950 long oldestTime = Long.MAX_VALUE;
951 String keyToRemove = null;
952 for (CacheEntry entry: cache.values()) {
953 if ((entry.millis < oldestTime) || (keyToRemove == null)) {
954 keyToRemove = entry.key;
955 oldestTime = entry.millis;
956 }
957 }
958 /*
959 System.err.println("put() remove key = " + keyToRemove +
960 " size " + cache.size());
961 */
962 assert (keyToRemove != null);
963 cache.remove(keyToRemove);
964 /*
965 System.err.println("put() removed, size " + cache.size());
966 */
967 }
968 assert (cache.size() <= maxSize);
969 CacheEntry entry = new CacheEntry(key, data);
970 assert (key.equals(entry.key));
971 cache.put(key, entry);
972 /*
973 System.err.println("put() added key " + key + " " +
974 " size " + cache.size());
975 */
976 }
977
978 }
979
980 // ------------------------------------------------------------------------
981 // Constructors -----------------------------------------------------------
982 // ------------------------------------------------------------------------
983
984 /**
985 * Constructor sets up state for getEvent().
986 *
987 * @param listener the object this backend needs to wake up when new
988 * input comes in
989 * @param input an InputStream connected to the remote user, or null for
990 * System.in. If System.in is used, then on non-Windows systems it will
991 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
992 * mode. input is always converted to a Reader with UTF-8 encoding.
993 * @param output an OutputStream connected to the remote user, or null
994 * for System.out. output is always converted to a Writer with UTF-8
995 * encoding.
996 * @param windowWidth the number of text columns to start with
997 * @param windowHeight the number of text rows to start with
998 * @throws UnsupportedEncodingException if an exception is thrown when
999 * creating the InputStreamReader
1000 */
1001 public ECMA48Terminal(final Object listener, final InputStream input,
1002 final OutputStream output, final int windowWidth,
1003 final int windowHeight) throws UnsupportedEncodingException {
1004
1005 this(listener, input, output);
1006
1007 // Send dtterm/xterm sequences, which will probably not work because
1008 // allowWindowOps is defaulted to false.
1009 String resizeString = String.format("\033[8;%d;%dt", windowHeight,
1010 windowWidth);
1011 this.output.write(resizeString);
1012 this.output.flush();
1013 }
1014
1015 /**
1016 * Constructor sets up state for getEvent().
1017 *
1018 * @param listener the object this backend needs to wake up when new
1019 * input comes in
1020 * @param input an InputStream connected to the remote user, or null for
1021 * System.in. If System.in is used, then on non-Windows systems it will
1022 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
1023 * mode. input is always converted to a Reader with UTF-8 encoding.
1024 * @param output an OutputStream connected to the remote user, or null
1025 * for System.out. output is always converted to a Writer with UTF-8
1026 * encoding.
1027 * @throws UnsupportedEncodingException if an exception is thrown when
1028 * creating the InputStreamReader
1029 */
1030 public ECMA48Terminal(final Object listener, final InputStream input,
1031 final OutputStream output) throws UnsupportedEncodingException {
1032
1033 resetParser();
1034 mouse1 = false;
1035 mouse2 = false;
1036 mouse3 = false;
1037 stopReaderThread = false;
1038 this.listener = listener;
1039
1040 if (input == null) {
1041 // inputStream = System.in;
1042 inputStream = new FileInputStream(FileDescriptor.in);
1043 sttyRaw();
1044 setRawMode = true;
1045 } else {
1046 inputStream = input;
1047 }
1048 this.input = new InputStreamReader(inputStream, "UTF-8");
1049
1050 if (input instanceof SessionInfo) {
1051 // This is a TelnetInputStream that exposes window size and
1052 // environment variables from the telnet layer.
1053 sessionInfo = (SessionInfo) input;
1054 }
1055 if (sessionInfo == null) {
1056 if (input == null) {
1057 // Reading right off the tty
1058 sessionInfo = new TTYSessionInfo();
1059 } else {
1060 sessionInfo = new TSessionInfo();
1061 }
1062 }
1063
1064 if (output == null) {
1065 this.output = new PrintWriter(new OutputStreamWriter(System.out,
1066 "UTF-8"));
1067 } else {
1068 this.output = new PrintWriter(new OutputStreamWriter(output,
1069 "UTF-8"));
1070 }
1071
1072 // Request xterm report window dimensions in pixels
1073 this.output.printf("%s", xtermReportWindowPixelDimensions());
1074
1075 // Enable mouse reporting and metaSendsEscape
1076 this.output.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
1077 this.output.flush();
1078
1079 // Query the screen size
1080 sessionInfo.queryWindowSize();
1081 setDimensions(sessionInfo.getWindowWidth(),
1082 sessionInfo.getWindowHeight());
1083
1084 // Hang onto the window size
1085 windowResize = new TResizeEvent(TResizeEvent.Type.SCREEN,
1086 sessionInfo.getWindowWidth(), sessionInfo.getWindowHeight());
1087
1088 // Permit RGB colors only if externally requested.
1089 if (System.getProperty("jexer.ECMA48.rgbColor") != null) {
1090 if (System.getProperty("jexer.ECMA48.rgbColor").equals("true")) {
1091 doRgbColor = true;
1092 } else {
1093 doRgbColor = false;
1094 }
1095 }
1096
1097 // Pull the system properties for sixel output.
1098 if (System.getProperty("jexer.ECMA48.sixel") != null) {
1099 if (System.getProperty("jexer.ECMA48.sixel").equals("true")) {
1100 sixel = true;
1101 } else {
1102 sixel = false;
1103 }
1104 }
1105
1106 // Spin up the input reader
1107 eventQueue = new LinkedList<TInputEvent>();
1108 readerThread = new Thread(this);
1109 readerThread.start();
1110
1111 // Clear the screen
1112 this.output.write(clearAll());
1113 this.output.flush();
1114 }
1115
1116 /**
1117 * Constructor sets up state for getEvent().
1118 *
1119 * @param listener the object this backend needs to wake up when new
1120 * input comes in
1121 * @param input the InputStream underlying 'reader'. Its available()
1122 * method is used to determine if reader.read() will block or not.
1123 * @param reader a Reader connected to the remote user.
1124 * @param writer a PrintWriter connected to the remote user.
1125 * @param setRawMode if true, set System.in into raw mode with stty.
1126 * This should in general not be used. It is here solely for Demo3,
1127 * which uses System.in.
1128 * @throws IllegalArgumentException if input, reader, or writer are null.
1129 */
1130 public ECMA48Terminal(final Object listener, final InputStream input,
1131 final Reader reader, final PrintWriter writer,
1132 final boolean setRawMode) {
1133
1134 if (input == null) {
1135 throw new IllegalArgumentException("InputStream must be specified");
1136 }
1137 if (reader == null) {
1138 throw new IllegalArgumentException("Reader must be specified");
1139 }
1140 if (writer == null) {
1141 throw new IllegalArgumentException("Writer must be specified");
1142 }
1143 resetParser();
1144 mouse1 = false;
1145 mouse2 = false;
1146 mouse3 = false;
1147 stopReaderThread = false;
1148 this.listener = listener;
1149
1150 inputStream = input;
1151 this.input = reader;
1152
1153 if (setRawMode == true) {
1154 sttyRaw();
1155 }
1156 this.setRawMode = setRawMode;
1157
1158 if (input instanceof SessionInfo) {
1159 // This is a TelnetInputStream that exposes window size and
1160 // environment variables from the telnet layer.
1161 sessionInfo = (SessionInfo) input;
1162 }
1163 if (sessionInfo == null) {
1164 if (setRawMode == true) {
1165 // Reading right off the tty
1166 sessionInfo = new TTYSessionInfo();
1167 } else {
1168 sessionInfo = new TSessionInfo();
1169 }
1170 }
1171
1172 this.output = writer;
1173
1174 // Request xterm report window dimensions in pixels
1175 this.output.printf("%s", xtermReportWindowPixelDimensions());
1176
1177 // Enable mouse reporting and metaSendsEscape
1178 this.output.printf("%s%s", mouse(true), xtermMetaSendsEscape(true));
1179 this.output.flush();
1180
1181 // Query the screen size
1182 sessionInfo.queryWindowSize();
1183 setDimensions(sessionInfo.getWindowWidth(),
1184 sessionInfo.getWindowHeight());
1185
1186 // Hang onto the window size
1187 windowResize = new TResizeEvent(TResizeEvent.Type.SCREEN,
1188 sessionInfo.getWindowWidth(), sessionInfo.getWindowHeight());
1189
1190 // Permit RGB colors only if externally requested
1191 if (System.getProperty("jexer.ECMA48.rgbColor") != null) {
1192 if (System.getProperty("jexer.ECMA48.rgbColor").equals("true")) {
1193 doRgbColor = true;
1194 } else {
1195 doRgbColor = false;
1196 }
1197 }
1198
1199 // Pull the system properties for sixel output.
1200 if (System.getProperty("jexer.ECMA48.sixel") != null) {
1201 if (System.getProperty("jexer.ECMA48.sixel").equals("true")) {
1202 sixel = true;
1203 } else {
1204 sixel = false;
1205 }
1206 }
1207
1208 // Spin up the input reader
1209 eventQueue = new LinkedList<TInputEvent>();
1210 readerThread = new Thread(this);
1211 readerThread.start();
1212
1213 // Clear the screen
1214 this.output.write(clearAll());
1215 this.output.flush();
1216 }
1217
1218 /**
1219 * Constructor sets up state for getEvent().
1220 *
1221 * @param listener the object this backend needs to wake up when new
1222 * input comes in
1223 * @param input the InputStream underlying 'reader'. Its available()
1224 * method is used to determine if reader.read() will block or not.
1225 * @param reader a Reader connected to the remote user.
1226 * @param writer a PrintWriter connected to the remote user.
1227 * @throws IllegalArgumentException if input, reader, or writer are null.
1228 */
1229 public ECMA48Terminal(final Object listener, final InputStream input,
1230 final Reader reader, final PrintWriter writer) {
1231
1232 this(listener, input, reader, writer, false);
1233 }
1234
1235 // ------------------------------------------------------------------------
1236 // LogicalScreen ----------------------------------------------------------
1237 // ------------------------------------------------------------------------
1238
1239 /**
1240 * Set the window title.
1241 *
1242 * @param title the new title
1243 */
1244 @Override
1245 public void setTitle(final String title) {
1246 output.write(getSetTitleString(title));
1247 flush();
1248 }
1249
1250 /**
1251 * Push the logical screen to the physical device.
1252 */
1253 @Override
1254 public void flushPhysical() {
1255 StringBuilder sb = new StringBuilder();
1256 if ((cursorVisible)
1257 && (cursorY >= 0)
1258 && (cursorX >= 0)
1259 && (cursorY <= height - 1)
1260 && (cursorX <= width - 1)
1261 ) {
1262 flushString(sb);
1263 sb.append(cursor(true));
1264 sb.append(gotoXY(cursorX, cursorY));
1265 } else {
1266 sb.append(cursor(false));
1267 flushString(sb);
1268 }
1269 output.write(sb.toString());
1270 flush();
1271 }
1272
1273 // ------------------------------------------------------------------------
1274 // TerminalReader ---------------------------------------------------------
1275 // ------------------------------------------------------------------------
1276
1277 /**
1278 * Check if there are events in the queue.
1279 *
1280 * @return if true, getEvents() has something to return to the backend
1281 */
1282 public boolean hasEvents() {
1283 synchronized (eventQueue) {
1284 return (eventQueue.size() > 0);
1285 }
1286 }
1287
1288 /**
1289 * Return any events in the IO queue.
1290 *
1291 * @param queue list to append new events to
1292 */
1293 public void getEvents(final List<TInputEvent> queue) {
1294 synchronized (eventQueue) {
1295 if (eventQueue.size() > 0) {
1296 synchronized (queue) {
1297 queue.addAll(eventQueue);
1298 }
1299 eventQueue.clear();
1300 }
1301 }
1302 }
1303
1304 /**
1305 * Restore terminal to normal state.
1306 */
1307 public void closeTerminal() {
1308
1309 // System.err.println("=== shutdown() ==="); System.err.flush();
1310
1311 // Tell the reader thread to stop looking at input
1312 stopReaderThread = true;
1313 try {
1314 readerThread.join();
1315 } catch (InterruptedException e) {
1316 if (debugToStderr) {
1317 e.printStackTrace();
1318 }
1319 }
1320
1321 // Disable mouse reporting and show cursor. Defensive null check
1322 // here in case closeTerminal() is called twice.
1323 if (output != null) {
1324 output.printf("%s%s%s", mouse(false), cursor(true), normal());
1325 output.flush();
1326 }
1327
1328 if (setRawMode) {
1329 sttyCooked();
1330 setRawMode = false;
1331 // We don't close System.in/out
1332 } else {
1333 // Shut down the streams, this should wake up the reader thread
1334 // and make it exit.
1335 if (input != null) {
1336 try {
1337 input.close();
1338 } catch (IOException e) {
1339 // SQUASH
1340 }
1341 input = null;
1342 }
1343 if (output != null) {
1344 output.close();
1345 output = null;
1346 }
1347 }
1348 }
1349
1350 /**
1351 * Set listener to a different Object.
1352 *
1353 * @param listener the new listening object that run() wakes up on new
1354 * input
1355 */
1356 public void setListener(final Object listener) {
1357 this.listener = listener;
1358 }
1359
1360 // ------------------------------------------------------------------------
1361 // Runnable ---------------------------------------------------------------
1362 // ------------------------------------------------------------------------
1363
1364 /**
1365 * Read function runs on a separate thread.
1366 */
1367 public void run() {
1368 boolean done = false;
1369 // available() will often return > 1, so we need to read in chunks to
1370 // stay caught up.
1371 char [] readBuffer = new char[128];
1372 List<TInputEvent> events = new LinkedList<TInputEvent>();
1373
1374 while (!done && !stopReaderThread) {
1375 try {
1376 // We assume that if inputStream has bytes available, then
1377 // input won't block on read().
1378 int n = inputStream.available();
1379
1380 /*
1381 System.err.printf("inputStream.available(): %d\n", n);
1382 System.err.flush();
1383 */
1384
1385 if (n > 0) {
1386 if (readBuffer.length < n) {
1387 // The buffer wasn't big enough, make it huger
1388 readBuffer = new char[readBuffer.length * 2];
1389 }
1390
1391 // System.err.printf("BEFORE read()\n"); System.err.flush();
1392
1393 int rc = input.read(readBuffer, 0, readBuffer.length);
1394
1395 /*
1396 System.err.printf("AFTER read() %d\n", rc);
1397 System.err.flush();
1398 */
1399
1400 if (rc == -1) {
1401 // This is EOF
1402 done = true;
1403 } else {
1404 for (int i = 0; i < rc; i++) {
1405 int ch = readBuffer[i];
1406 processChar(events, (char)ch);
1407 }
1408 getIdleEvents(events);
1409 if (events.size() > 0) {
1410 // Add to the queue for the backend thread to
1411 // be able to obtain.
1412 synchronized (eventQueue) {
1413 eventQueue.addAll(events);
1414 }
1415 if (listener != null) {
1416 synchronized (listener) {
1417 listener.notifyAll();
1418 }
1419 }
1420 events.clear();
1421 }
1422 }
1423 } else {
1424 getIdleEvents(events);
1425 if (events.size() > 0) {
1426 synchronized (eventQueue) {
1427 eventQueue.addAll(events);
1428 }
1429 if (listener != null) {
1430 synchronized (listener) {
1431 listener.notifyAll();
1432 }
1433 }
1434 events.clear();
1435 }
1436
1437 // Wait 20 millis for more data
1438 Thread.sleep(20);
1439 }
1440 // System.err.println("end while loop"); System.err.flush();
1441 } catch (InterruptedException e) {
1442 // SQUASH
1443 } catch (IOException e) {
1444 e.printStackTrace();
1445 done = true;
1446 }
1447 } // while ((done == false) && (stopReaderThread == false))
1448 // System.err.println("*** run() exiting..."); System.err.flush();
1449 }
1450
1451 // ------------------------------------------------------------------------
1452 // ECMA48Terminal ---------------------------------------------------------
1453 // ------------------------------------------------------------------------
1454
1455 /**
1456 * Get the width of a character cell in pixels.
1457 *
1458 * @return the width in pixels of a character cell
1459 */
1460 public int getTextWidth() {
1461 return (widthPixels / sessionInfo.getWindowWidth());
1462 }
1463
1464 /**
1465 * Get the height of a character cell in pixels.
1466 *
1467 * @return the height in pixels of a character cell
1468 */
1469 public int getTextHeight() {
1470 return (heightPixels / sessionInfo.getWindowHeight());
1471 }
1472
1473 /**
1474 * Getter for sessionInfo.
1475 *
1476 * @return the SessionInfo
1477 */
1478 public SessionInfo getSessionInfo() {
1479 return sessionInfo;
1480 }
1481
1482 /**
1483 * Get the output writer.
1484 *
1485 * @return the Writer
1486 */
1487 public PrintWriter getOutput() {
1488 return output;
1489 }
1490
1491 /**
1492 * Call 'stty' to set cooked mode.
1493 *
1494 * <p>Actually executes '/bin/sh -c stty sane cooked &lt; /dev/tty'
1495 */
1496 private void sttyCooked() {
1497 doStty(false);
1498 }
1499
1500 /**
1501 * Call 'stty' to set raw mode.
1502 *
1503 * <p>Actually executes '/bin/sh -c stty -ignbrk -brkint -parmrk -istrip
1504 * -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten
1505 * -parenb cs8 min 1 &lt; /dev/tty'
1506 */
1507 private void sttyRaw() {
1508 doStty(true);
1509 }
1510
1511 /**
1512 * Call 'stty' to set raw or cooked mode.
1513 *
1514 * @param mode if true, set raw mode, otherwise set cooked mode
1515 */
1516 private void doStty(final boolean mode) {
1517 String [] cmdRaw = {
1518 "/bin/sh", "-c", "stty -ignbrk -brkint -parmrk -istrip -inlcr -igncr -icrnl -ixon -opost -echo -echonl -icanon -isig -iexten -parenb cs8 min 1 < /dev/tty"
1519 };
1520 String [] cmdCooked = {
1521 "/bin/sh", "-c", "stty sane cooked < /dev/tty"
1522 };
1523 try {
1524 Process process;
1525 if (mode) {
1526 process = Runtime.getRuntime().exec(cmdRaw);
1527 } else {
1528 process = Runtime.getRuntime().exec(cmdCooked);
1529 }
1530 BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
1531 String line = in.readLine();
1532 if ((line != null) && (line.length() > 0)) {
1533 System.err.println("WEIRD?! Normal output from stty: " + line);
1534 }
1535 while (true) {
1536 BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
1537 line = err.readLine();
1538 if ((line != null) && (line.length() > 0)) {
1539 System.err.println("Error output from stty: " + line);
1540 }
1541 try {
1542 process.waitFor();
1543 break;
1544 } catch (InterruptedException e) {
1545 if (debugToStderr) {
1546 e.printStackTrace();
1547 }
1548 }
1549 }
1550 int rc = process.exitValue();
1551 if (rc != 0) {
1552 System.err.println("stty returned error code: " + rc);
1553 }
1554 } catch (IOException e) {
1555 e.printStackTrace();
1556 }
1557 }
1558
1559 /**
1560 * Flush output.
1561 */
1562 public void flush() {
1563 output.flush();
1564 }
1565
1566 /**
1567 * Perform a somewhat-optimal rendering of a line.
1568 *
1569 * @param y row coordinate. 0 is the top-most row.
1570 * @param sb StringBuilder to write escape sequences to
1571 * @param lastAttr cell attributes from the last call to flushLine
1572 */
1573 private void flushLine(final int y, final StringBuilder sb,
1574 CellAttributes lastAttr) {
1575
1576 int lastX = -1;
1577 int textEnd = 0;
1578 for (int x = 0; x < width; x++) {
1579 Cell lCell = logical[x][y];
1580 if (!lCell.isBlank()) {
1581 textEnd = x;
1582 }
1583 }
1584 // Push textEnd to first column beyond the text area
1585 textEnd++;
1586
1587 // DEBUG
1588 // reallyCleared = true;
1589
1590 boolean hasImage = false;
1591
1592 for (int x = 0; x < width; x++) {
1593 Cell lCell = logical[x][y];
1594 Cell pCell = physical[x][y];
1595
1596 if (!lCell.equals(pCell) || reallyCleared) {
1597
1598 if (debugToStderr) {
1599 System.err.printf("\n--\n");
1600 System.err.printf(" Y: %d X: %d\n", y, x);
1601 System.err.printf(" lCell: %s\n", lCell);
1602 System.err.printf(" pCell: %s\n", pCell);
1603 System.err.printf(" ==== \n");
1604 }
1605
1606 if (lastAttr == null) {
1607 lastAttr = new CellAttributes();
1608 sb.append(normal());
1609 }
1610
1611 // Place the cell
1612 if ((lastX != (x - 1)) || (lastX == -1)) {
1613 // Advancing at least one cell, or the first gotoXY
1614 sb.append(gotoXY(x, y));
1615 }
1616
1617 assert (lastAttr != null);
1618
1619 if ((x == textEnd) && (textEnd < width - 1)) {
1620 assert (lCell.isBlank());
1621
1622 for (int i = x; i < width; i++) {
1623 assert (logical[i][y].isBlank());
1624 // Physical is always updated
1625 physical[i][y].reset();
1626 }
1627
1628 // Clear remaining line
1629 sb.append(clearRemainingLine());
1630 lastAttr.reset();
1631 return;
1632 }
1633
1634 // Image cell: bypass the rest of the loop, it is not
1635 // rendered here.
1636 if (lCell.isImage()) {
1637 hasImage = true;
1638
1639 // Save the last rendered cell
1640 lastX = x;
1641
1642 // Physical is always updated
1643 physical[x][y].setTo(lCell);
1644 continue;
1645 }
1646
1647 assert (!lCell.isImage());
1648 if (hasImage) {
1649 hasImage = false;
1650 sb.append(gotoXY(x, y));
1651 }
1652
1653 // Now emit only the modified attributes
1654 if ((lCell.getForeColor() != lastAttr.getForeColor())
1655 && (lCell.getBackColor() != lastAttr.getBackColor())
1656 && (!lCell.isRGB())
1657 && (lCell.isBold() == lastAttr.isBold())
1658 && (lCell.isReverse() == lastAttr.isReverse())
1659 && (lCell.isUnderline() == lastAttr.isUnderline())
1660 && (lCell.isBlink() == lastAttr.isBlink())
1661 ) {
1662 // Both colors changed, attributes the same
1663 sb.append(color(lCell.isBold(),
1664 lCell.getForeColor(), lCell.getBackColor()));
1665
1666 if (debugToStderr) {
1667 System.err.printf("1 Change only fore/back colors\n");
1668 }
1669
1670 } else if (lCell.isRGB()
1671 && (lCell.getForeColorRGB() != lastAttr.getForeColorRGB())
1672 && (lCell.getBackColorRGB() != lastAttr.getBackColorRGB())
1673 && (lCell.isBold() == lastAttr.isBold())
1674 && (lCell.isReverse() == lastAttr.isReverse())
1675 && (lCell.isUnderline() == lastAttr.isUnderline())
1676 && (lCell.isBlink() == lastAttr.isBlink())
1677 ) {
1678 // Both colors changed, attributes the same
1679 sb.append(colorRGB(lCell.getForeColorRGB(),
1680 lCell.getBackColorRGB()));
1681
1682 if (debugToStderr) {
1683 System.err.printf("1 Change only fore/back colors (RGB)\n");
1684 }
1685 } else if ((lCell.getForeColor() != lastAttr.getForeColor())
1686 && (lCell.getBackColor() != lastAttr.getBackColor())
1687 && (!lCell.isRGB())
1688 && (lCell.isBold() != lastAttr.isBold())
1689 && (lCell.isReverse() != lastAttr.isReverse())
1690 && (lCell.isUnderline() != lastAttr.isUnderline())
1691 && (lCell.isBlink() != lastAttr.isBlink())
1692 ) {
1693 // Everything is different
1694 sb.append(color(lCell.getForeColor(),
1695 lCell.getBackColor(),
1696 lCell.isBold(), lCell.isReverse(),
1697 lCell.isBlink(),
1698 lCell.isUnderline()));
1699
1700 if (debugToStderr) {
1701 System.err.printf("2 Set all attributes\n");
1702 }
1703 } else if ((lCell.getForeColor() != lastAttr.getForeColor())
1704 && (lCell.getBackColor() == lastAttr.getBackColor())
1705 && (!lCell.isRGB())
1706 && (lCell.isBold() == lastAttr.isBold())
1707 && (lCell.isReverse() == lastAttr.isReverse())
1708 && (lCell.isUnderline() == lastAttr.isUnderline())
1709 && (lCell.isBlink() == lastAttr.isBlink())
1710 ) {
1711
1712 // Attributes same, foreColor different
1713 sb.append(color(lCell.isBold(),
1714 lCell.getForeColor(), true));
1715
1716 if (debugToStderr) {
1717 System.err.printf("3 Change foreColor\n");
1718 }
1719 } else if (lCell.isRGB()
1720 && (lCell.getForeColorRGB() != lastAttr.getForeColorRGB())
1721 && (lCell.getBackColorRGB() == lastAttr.getBackColorRGB())
1722 && (lCell.getForeColorRGB() >= 0)
1723 && (lCell.getBackColorRGB() >= 0)
1724 && (lCell.isBold() == lastAttr.isBold())
1725 && (lCell.isReverse() == lastAttr.isReverse())
1726 && (lCell.isUnderline() == lastAttr.isUnderline())
1727 && (lCell.isBlink() == lastAttr.isBlink())
1728 ) {
1729 // Attributes same, foreColor different
1730 sb.append(colorRGB(lCell.getForeColorRGB(), true));
1731
1732 if (debugToStderr) {
1733 System.err.printf("3 Change foreColor (RGB)\n");
1734 }
1735 } else if ((lCell.getForeColor() == lastAttr.getForeColor())
1736 && (lCell.getBackColor() != lastAttr.getBackColor())
1737 && (!lCell.isRGB())
1738 && (lCell.isBold() == lastAttr.isBold())
1739 && (lCell.isReverse() == lastAttr.isReverse())
1740 && (lCell.isUnderline() == lastAttr.isUnderline())
1741 && (lCell.isBlink() == lastAttr.isBlink())
1742 ) {
1743 // Attributes same, backColor different
1744 sb.append(color(lCell.isBold(),
1745 lCell.getBackColor(), false));
1746
1747 if (debugToStderr) {
1748 System.err.printf("4 Change backColor\n");
1749 }
1750 } else if (lCell.isRGB()
1751 && (lCell.getForeColorRGB() == lastAttr.getForeColorRGB())
1752 && (lCell.getBackColorRGB() != lastAttr.getBackColorRGB())
1753 && (lCell.isBold() == lastAttr.isBold())
1754 && (lCell.isReverse() == lastAttr.isReverse())
1755 && (lCell.isUnderline() == lastAttr.isUnderline())
1756 && (lCell.isBlink() == lastAttr.isBlink())
1757 ) {
1758 // Attributes same, foreColor different
1759 sb.append(colorRGB(lCell.getBackColorRGB(), false));
1760
1761 if (debugToStderr) {
1762 System.err.printf("4 Change backColor (RGB)\n");
1763 }
1764 } else if ((lCell.getForeColor() == lastAttr.getForeColor())
1765 && (lCell.getBackColor() == lastAttr.getBackColor())
1766 && (lCell.getForeColorRGB() == lastAttr.getForeColorRGB())
1767 && (lCell.getBackColorRGB() == lastAttr.getBackColorRGB())
1768 && (lCell.isBold() == lastAttr.isBold())
1769 && (lCell.isReverse() == lastAttr.isReverse())
1770 && (lCell.isUnderline() == lastAttr.isUnderline())
1771 && (lCell.isBlink() == lastAttr.isBlink())
1772 ) {
1773
1774 // All attributes the same, just print the char
1775 // NOP
1776
1777 if (debugToStderr) {
1778 System.err.printf("5 Only emit character\n");
1779 }
1780 } else {
1781 // Just reset everything again
1782 if (!lCell.isRGB()) {
1783 sb.append(color(lCell.getForeColor(),
1784 lCell.getBackColor(),
1785 lCell.isBold(),
1786 lCell.isReverse(),
1787 lCell.isBlink(),
1788 lCell.isUnderline()));
1789
1790 if (debugToStderr) {
1791 System.err.printf("6 Change all attributes\n");
1792 }
1793 } else {
1794 sb.append(colorRGB(lCell.getForeColorRGB(),
1795 lCell.getBackColorRGB(),
1796 lCell.isBold(),
1797 lCell.isReverse(),
1798 lCell.isBlink(),
1799 lCell.isUnderline()));
1800 if (debugToStderr) {
1801 System.err.printf("6 Change all attributes (RGB)\n");
1802 }
1803 }
1804
1805 }
1806 // Emit the character
1807 sb.append(lCell.getChar());
1808
1809 // Save the last rendered cell
1810 lastX = x;
1811 lastAttr.setTo(lCell);
1812
1813 // Physical is always updated
1814 physical[x][y].setTo(lCell);
1815
1816 } // if (!lCell.equals(pCell) || (reallyCleared == true))
1817
1818 } // for (int x = 0; x < width; x++)
1819 }
1820
1821 /**
1822 * Render the screen to a string that can be emitted to something that
1823 * knows how to process ECMA-48/ANSI X3.64 escape sequences.
1824 *
1825 * @param sb StringBuilder to write escape sequences to
1826 * @return escape sequences string that provides the updates to the
1827 * physical screen
1828 */
1829 private String flushString(final StringBuilder sb) {
1830 CellAttributes attr = null;
1831
1832 if (reallyCleared) {
1833 attr = new CellAttributes();
1834 sb.append(clearAll());
1835 }
1836
1837 /*
1838 * For sixel support, draw all of the sixel output first, and then
1839 * draw everything else afterwards. This works OK, but performance
1840 * is still a drag on larger pictures.
1841 */
1842 for (int y = 0; y < height; y++) {
1843 for (int x = 0; x < width; x++) {
1844 // If physical had non-image data that is now image data, the
1845 // entire row must be redrawn.
1846 Cell lCell = logical[x][y];
1847 Cell pCell = physical[x][y];
1848 if (lCell.isImage() && !pCell.isImage()) {
1849 unsetImageRow(y);
1850 break;
1851 }
1852 }
1853 }
1854 for (int y = 0; y < height; y++) {
1855 for (int x = 0; x < width; x++) {
1856 Cell lCell = logical[x][y];
1857 Cell pCell = physical[x][y];
1858
1859 if (!lCell.isImage()) {
1860 continue;
1861 }
1862
1863 int left = x;
1864 int right = x;
1865 while ((right < width)
1866 && (logical[right][y].isImage())
1867 && (!logical[right][y].equals(physical[right][y])
1868 || reallyCleared)
1869 ) {
1870 right++;
1871 }
1872 ArrayList<Cell> cellsToDraw = new ArrayList<Cell>();
1873 for (int i = 0; i < (right - x); i++) {
1874 assert (logical[x + i][y].isImage());
1875 cellsToDraw.add(logical[x + i][y]);
1876
1877 // Physical is always updated.
1878 physical[x + i][y].setTo(lCell);
1879 }
1880 if (cellsToDraw.size() > 0) {
1881 sb.append(toSixel(x, y, cellsToDraw));
1882 }
1883
1884 x = right;
1885 }
1886 }
1887
1888 // Draw the text part now.
1889 for (int y = 0; y < height; y++) {
1890 flushLine(y, sb, attr);
1891 }
1892
1893 reallyCleared = false;
1894
1895 String result = sb.toString();
1896 if (debugToStderr) {
1897 System.err.printf("flushString(): %s\n", result);
1898 }
1899 return result;
1900 }
1901
1902 /**
1903 * Reset keyboard/mouse input parser.
1904 */
1905 private void resetParser() {
1906 state = ParseState.GROUND;
1907 params = new ArrayList<String>();
1908 params.clear();
1909 params.add("");
1910 }
1911
1912 /**
1913 * Produce a control character or one of the special ones (ENTER, TAB,
1914 * etc.).
1915 *
1916 * @param ch Unicode code point
1917 * @param alt if true, set alt on the TKeypress
1918 * @return one TKeypress event, either a control character (e.g. isKey ==
1919 * false, ch == 'A', ctrl == true), or a special key (e.g. isKey == true,
1920 * fnKey == ESC)
1921 */
1922 private TKeypressEvent controlChar(final char ch, final boolean alt) {
1923 // System.err.printf("controlChar: %02x\n", ch);
1924
1925 switch (ch) {
1926 case 0x0D:
1927 // Carriage return --> ENTER
1928 return new TKeypressEvent(kbEnter, alt, false, false);
1929 case 0x0A:
1930 // Linefeed --> ENTER
1931 return new TKeypressEvent(kbEnter, alt, false, false);
1932 case 0x1B:
1933 // ESC
1934 return new TKeypressEvent(kbEsc, alt, false, false);
1935 case '\t':
1936 // TAB
1937 return new TKeypressEvent(kbTab, alt, false, false);
1938 default:
1939 // Make all other control characters come back as the alphabetic
1940 // character with the ctrl field set. So SOH would be 'A' +
1941 // ctrl.
1942 return new TKeypressEvent(false, 0, (char)(ch + 0x40),
1943 alt, true, false);
1944 }
1945 }
1946
1947 /**
1948 * Produce special key from CSI Pn ; Pm ; ... ~
1949 *
1950 * @return one KEYPRESS event representing a special key
1951 */
1952 private TInputEvent csiFnKey() {
1953 int key = 0;
1954 if (params.size() > 0) {
1955 key = Integer.parseInt(params.get(0));
1956 }
1957 boolean alt = false;
1958 boolean ctrl = false;
1959 boolean shift = false;
1960 if (params.size() > 1) {
1961 shift = csiIsShift(params.get(1));
1962 alt = csiIsAlt(params.get(1));
1963 ctrl = csiIsCtrl(params.get(1));
1964 }
1965
1966 switch (key) {
1967 case 1:
1968 return new TKeypressEvent(kbHome, alt, ctrl, shift);
1969 case 2:
1970 return new TKeypressEvent(kbIns, alt, ctrl, shift);
1971 case 3:
1972 return new TKeypressEvent(kbDel, alt, ctrl, shift);
1973 case 4:
1974 return new TKeypressEvent(kbEnd, alt, ctrl, shift);
1975 case 5:
1976 return new TKeypressEvent(kbPgUp, alt, ctrl, shift);
1977 case 6:
1978 return new TKeypressEvent(kbPgDn, alt, ctrl, shift);
1979 case 15:
1980 return new TKeypressEvent(kbF5, alt, ctrl, shift);
1981 case 17:
1982 return new TKeypressEvent(kbF6, alt, ctrl, shift);
1983 case 18:
1984 return new TKeypressEvent(kbF7, alt, ctrl, shift);
1985 case 19:
1986 return new TKeypressEvent(kbF8, alt, ctrl, shift);
1987 case 20:
1988 return new TKeypressEvent(kbF9, alt, ctrl, shift);
1989 case 21:
1990 return new TKeypressEvent(kbF10, alt, ctrl, shift);
1991 case 23:
1992 return new TKeypressEvent(kbF11, alt, ctrl, shift);
1993 case 24:
1994 return new TKeypressEvent(kbF12, alt, ctrl, shift);
1995 default:
1996 // Unknown
1997 return null;
1998 }
1999 }
2000
2001 /**
2002 * Produce mouse events based on "Any event tracking" and UTF-8
2003 * coordinates. See
2004 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
2005 *
2006 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
2007 */
2008 private TInputEvent parseMouse() {
2009 int buttons = params.get(0).charAt(0) - 32;
2010 int x = params.get(0).charAt(1) - 32 - 1;
2011 int y = params.get(0).charAt(2) - 32 - 1;
2012
2013 // Clamp X and Y to the physical screen coordinates.
2014 if (x >= windowResize.getWidth()) {
2015 x = windowResize.getWidth() - 1;
2016 }
2017 if (y >= windowResize.getHeight()) {
2018 y = windowResize.getHeight() - 1;
2019 }
2020
2021 TMouseEvent.Type eventType = TMouseEvent.Type.MOUSE_DOWN;
2022 boolean eventMouse1 = false;
2023 boolean eventMouse2 = false;
2024 boolean eventMouse3 = false;
2025 boolean eventMouseWheelUp = false;
2026 boolean eventMouseWheelDown = false;
2027
2028 // System.err.printf("buttons: %04x\r\n", buttons);
2029
2030 switch (buttons) {
2031 case 0:
2032 eventMouse1 = true;
2033 mouse1 = true;
2034 break;
2035 case 1:
2036 eventMouse2 = true;
2037 mouse2 = true;
2038 break;
2039 case 2:
2040 eventMouse3 = true;
2041 mouse3 = true;
2042 break;
2043 case 3:
2044 // Release or Move
2045 if (!mouse1 && !mouse2 && !mouse3) {
2046 eventType = TMouseEvent.Type.MOUSE_MOTION;
2047 } else {
2048 eventType = TMouseEvent.Type.MOUSE_UP;
2049 }
2050 if (mouse1) {
2051 mouse1 = false;
2052 eventMouse1 = true;
2053 }
2054 if (mouse2) {
2055 mouse2 = false;
2056 eventMouse2 = true;
2057 }
2058 if (mouse3) {
2059 mouse3 = false;
2060 eventMouse3 = true;
2061 }
2062 break;
2063
2064 case 32:
2065 // Dragging with mouse1 down
2066 eventMouse1 = true;
2067 mouse1 = true;
2068 eventType = TMouseEvent.Type.MOUSE_MOTION;
2069 break;
2070
2071 case 33:
2072 // Dragging with mouse2 down
2073 eventMouse2 = true;
2074 mouse2 = true;
2075 eventType = TMouseEvent.Type.MOUSE_MOTION;
2076 break;
2077
2078 case 34:
2079 // Dragging with mouse3 down
2080 eventMouse3 = true;
2081 mouse3 = true;
2082 eventType = TMouseEvent.Type.MOUSE_MOTION;
2083 break;
2084
2085 case 96:
2086 // Dragging with mouse2 down after wheelUp
2087 eventMouse2 = true;
2088 mouse2 = true;
2089 eventType = TMouseEvent.Type.MOUSE_MOTION;
2090 break;
2091
2092 case 97:
2093 // Dragging with mouse2 down after wheelDown
2094 eventMouse2 = true;
2095 mouse2 = true;
2096 eventType = TMouseEvent.Type.MOUSE_MOTION;
2097 break;
2098
2099 case 64:
2100 eventMouseWheelUp = true;
2101 break;
2102
2103 case 65:
2104 eventMouseWheelDown = true;
2105 break;
2106
2107 default:
2108 // Unknown, just make it motion
2109 eventType = TMouseEvent.Type.MOUSE_MOTION;
2110 break;
2111 }
2112 return new TMouseEvent(eventType, x, y, x, y,
2113 eventMouse1, eventMouse2, eventMouse3,
2114 eventMouseWheelUp, eventMouseWheelDown);
2115 }
2116
2117 /**
2118 * Produce mouse events based on "Any event tracking" and SGR
2119 * coordinates. See
2120 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
2121 *
2122 * @param release if true, this was a release ('m')
2123 * @return a MOUSE_MOTION, MOUSE_UP, or MOUSE_DOWN event
2124 */
2125 private TInputEvent parseMouseSGR(final boolean release) {
2126 // SGR extended coordinates - mode 1006
2127 if (params.size() < 3) {
2128 // Invalid position, bail out.
2129 return null;
2130 }
2131 int buttons = Integer.parseInt(params.get(0));
2132 int x = Integer.parseInt(params.get(1)) - 1;
2133 int y = Integer.parseInt(params.get(2)) - 1;
2134
2135 // Clamp X and Y to the physical screen coordinates.
2136 if (x >= windowResize.getWidth()) {
2137 x = windowResize.getWidth() - 1;
2138 }
2139 if (y >= windowResize.getHeight()) {
2140 y = windowResize.getHeight() - 1;
2141 }
2142
2143 TMouseEvent.Type eventType = TMouseEvent.Type.MOUSE_DOWN;
2144 boolean eventMouse1 = false;
2145 boolean eventMouse2 = false;
2146 boolean eventMouse3 = false;
2147 boolean eventMouseWheelUp = false;
2148 boolean eventMouseWheelDown = false;
2149
2150 if (release) {
2151 eventType = TMouseEvent.Type.MOUSE_UP;
2152 }
2153
2154 switch (buttons) {
2155 case 0:
2156 eventMouse1 = true;
2157 break;
2158 case 1:
2159 eventMouse2 = true;
2160 break;
2161 case 2:
2162 eventMouse3 = true;
2163 break;
2164 case 35:
2165 // Motion only, no buttons down
2166 eventType = TMouseEvent.Type.MOUSE_MOTION;
2167 break;
2168
2169 case 32:
2170 // Dragging with mouse1 down
2171 eventMouse1 = true;
2172 eventType = TMouseEvent.Type.MOUSE_MOTION;
2173 break;
2174
2175 case 33:
2176 // Dragging with mouse2 down
2177 eventMouse2 = true;
2178 eventType = TMouseEvent.Type.MOUSE_MOTION;
2179 break;
2180
2181 case 34:
2182 // Dragging with mouse3 down
2183 eventMouse3 = true;
2184 eventType = TMouseEvent.Type.MOUSE_MOTION;
2185 break;
2186
2187 case 96:
2188 // Dragging with mouse2 down after wheelUp
2189 eventMouse2 = true;
2190 eventType = TMouseEvent.Type.MOUSE_MOTION;
2191 break;
2192
2193 case 97:
2194 // Dragging with mouse2 down after wheelDown
2195 eventMouse2 = true;
2196 eventType = TMouseEvent.Type.MOUSE_MOTION;
2197 break;
2198
2199 case 64:
2200 eventMouseWheelUp = true;
2201 break;
2202
2203 case 65:
2204 eventMouseWheelDown = true;
2205 break;
2206
2207 default:
2208 // Unknown, bail out
2209 return null;
2210 }
2211 return new TMouseEvent(eventType, x, y, x, y,
2212 eventMouse1, eventMouse2, eventMouse3,
2213 eventMouseWheelUp, eventMouseWheelDown);
2214 }
2215
2216 /**
2217 * Return any events in the IO queue due to timeout.
2218 *
2219 * @param queue list to append new events to
2220 */
2221 private void getIdleEvents(final List<TInputEvent> queue) {
2222 long nowTime = System.currentTimeMillis();
2223
2224 // Check for new window size
2225 long windowSizeDelay = nowTime - windowSizeTime;
2226 if (windowSizeDelay > 1000) {
2227 sessionInfo.queryWindowSize();
2228 int newWidth = sessionInfo.getWindowWidth();
2229 int newHeight = sessionInfo.getWindowHeight();
2230
2231 if ((newWidth != windowResize.getWidth())
2232 || (newHeight != windowResize.getHeight())
2233 ) {
2234
2235 if (debugToStderr) {
2236 System.err.println("Screen size changed, old size " +
2237 windowResize);
2238 System.err.println(" new size " +
2239 newWidth + " x " + newHeight);
2240 }
2241
2242 // Request xterm report window dimensions in pixels again.
2243 this.output.printf("%s", xtermReportWindowPixelDimensions());
2244 this.output.flush();
2245
2246 TResizeEvent event = new TResizeEvent(TResizeEvent.Type.SCREEN,
2247 newWidth, newHeight);
2248 windowResize = new TResizeEvent(TResizeEvent.Type.SCREEN,
2249 newWidth, newHeight);
2250 queue.add(event);
2251 }
2252 windowSizeTime = nowTime;
2253 }
2254
2255 // ESCDELAY type timeout
2256 if (state == ParseState.ESCAPE) {
2257 long escDelay = nowTime - escapeTime;
2258 if (escDelay > 100) {
2259 // After 0.1 seconds, assume a true escape character
2260 queue.add(controlChar((char)0x1B, false));
2261 resetParser();
2262 }
2263 }
2264 }
2265
2266 /**
2267 * Returns true if the CSI parameter for a keyboard command means that
2268 * shift was down.
2269 */
2270 private boolean csiIsShift(final String x) {
2271 if ((x.equals("2"))
2272 || (x.equals("4"))
2273 || (x.equals("6"))
2274 || (x.equals("8"))
2275 ) {
2276 return true;
2277 }
2278 return false;
2279 }
2280
2281 /**
2282 * Returns true if the CSI parameter for a keyboard command means that
2283 * alt was down.
2284 */
2285 private boolean csiIsAlt(final String x) {
2286 if ((x.equals("3"))
2287 || (x.equals("4"))
2288 || (x.equals("7"))
2289 || (x.equals("8"))
2290 ) {
2291 return true;
2292 }
2293 return false;
2294 }
2295
2296 /**
2297 * Returns true if the CSI parameter for a keyboard command means that
2298 * ctrl was down.
2299 */
2300 private boolean csiIsCtrl(final String x) {
2301 if ((x.equals("5"))
2302 || (x.equals("6"))
2303 || (x.equals("7"))
2304 || (x.equals("8"))
2305 ) {
2306 return true;
2307 }
2308 return false;
2309 }
2310
2311 /**
2312 * Parses the next character of input to see if an InputEvent is
2313 * fully here.
2314 *
2315 * @param events list to append new events to
2316 * @param ch Unicode code point
2317 */
2318 private void processChar(final List<TInputEvent> events, final char ch) {
2319
2320 // ESCDELAY type timeout
2321 long nowTime = System.currentTimeMillis();
2322 if (state == ParseState.ESCAPE) {
2323 long escDelay = nowTime - escapeTime;
2324 if (escDelay > 250) {
2325 // After 0.25 seconds, assume a true escape character
2326 events.add(controlChar((char)0x1B, false));
2327 resetParser();
2328 }
2329 }
2330
2331 // TKeypress fields
2332 boolean ctrl = false;
2333 boolean alt = false;
2334 boolean shift = false;
2335
2336 // System.err.printf("state: %s ch %c\r\n", state, ch);
2337
2338 switch (state) {
2339 case GROUND:
2340
2341 if (ch == 0x1B) {
2342 state = ParseState.ESCAPE;
2343 escapeTime = nowTime;
2344 return;
2345 }
2346
2347 if (ch <= 0x1F) {
2348 // Control character
2349 events.add(controlChar(ch, false));
2350 resetParser();
2351 return;
2352 }
2353
2354 if (ch >= 0x20) {
2355 // Normal character
2356 events.add(new TKeypressEvent(false, 0, ch,
2357 false, false, false));
2358 resetParser();
2359 return;
2360 }
2361
2362 break;
2363
2364 case ESCAPE:
2365 if (ch <= 0x1F) {
2366 // ALT-Control character
2367 events.add(controlChar(ch, true));
2368 resetParser();
2369 return;
2370 }
2371
2372 if (ch == 'O') {
2373 // This will be one of the function keys
2374 state = ParseState.ESCAPE_INTERMEDIATE;
2375 return;
2376 }
2377
2378 // '[' goes to CSI_ENTRY
2379 if (ch == '[') {
2380 state = ParseState.CSI_ENTRY;
2381 return;
2382 }
2383
2384 // Everything else is assumed to be Alt-keystroke
2385 if ((ch >= 'A') && (ch <= 'Z')) {
2386 shift = true;
2387 }
2388 alt = true;
2389 events.add(new TKeypressEvent(false, 0, ch, alt, ctrl, shift));
2390 resetParser();
2391 return;
2392
2393 case ESCAPE_INTERMEDIATE:
2394 if ((ch >= 'P') && (ch <= 'S')) {
2395 // Function key
2396 switch (ch) {
2397 case 'P':
2398 events.add(new TKeypressEvent(kbF1));
2399 break;
2400 case 'Q':
2401 events.add(new TKeypressEvent(kbF2));
2402 break;
2403 case 'R':
2404 events.add(new TKeypressEvent(kbF3));
2405 break;
2406 case 'S':
2407 events.add(new TKeypressEvent(kbF4));
2408 break;
2409 default:
2410 break;
2411 }
2412 resetParser();
2413 return;
2414 }
2415
2416 // Unknown keystroke, ignore
2417 resetParser();
2418 return;
2419
2420 case CSI_ENTRY:
2421 // Numbers - parameter values
2422 if ((ch >= '0') && (ch <= '9')) {
2423 params.set(params.size() - 1,
2424 params.get(params.size() - 1) + ch);
2425 state = ParseState.CSI_PARAM;
2426 return;
2427 }
2428 // Parameter separator
2429 if (ch == ';') {
2430 params.add("");
2431 return;
2432 }
2433
2434 if ((ch >= 0x30) && (ch <= 0x7E)) {
2435 switch (ch) {
2436 case 'A':
2437 // Up
2438 events.add(new TKeypressEvent(kbUp, alt, ctrl, shift));
2439 resetParser();
2440 return;
2441 case 'B':
2442 // Down
2443 events.add(new TKeypressEvent(kbDown, alt, ctrl, shift));
2444 resetParser();
2445 return;
2446 case 'C':
2447 // Right
2448 events.add(new TKeypressEvent(kbRight, alt, ctrl, shift));
2449 resetParser();
2450 return;
2451 case 'D':
2452 // Left
2453 events.add(new TKeypressEvent(kbLeft, alt, ctrl, shift));
2454 resetParser();
2455 return;
2456 case 'H':
2457 // Home
2458 events.add(new TKeypressEvent(kbHome));
2459 resetParser();
2460 return;
2461 case 'F':
2462 // End
2463 events.add(new TKeypressEvent(kbEnd));
2464 resetParser();
2465 return;
2466 case 'Z':
2467 // CBT - Cursor backward X tab stops (default 1)
2468 events.add(new TKeypressEvent(kbBackTab));
2469 resetParser();
2470 return;
2471 case 'M':
2472 // Mouse position
2473 state = ParseState.MOUSE;
2474 return;
2475 case '<':
2476 // Mouse position, SGR (1006) coordinates
2477 state = ParseState.MOUSE_SGR;
2478 return;
2479 default:
2480 break;
2481 }
2482 }
2483
2484 // Unknown keystroke, ignore
2485 resetParser();
2486 return;
2487
2488 case MOUSE_SGR:
2489 // Numbers - parameter values
2490 if ((ch >= '0') && (ch <= '9')) {
2491 params.set(params.size() - 1,
2492 params.get(params.size() - 1) + ch);
2493 return;
2494 }
2495 // Parameter separator
2496 if (ch == ';') {
2497 params.add("");
2498 return;
2499 }
2500
2501 switch (ch) {
2502 case 'M':
2503 // Generate a mouse press event
2504 TInputEvent event = parseMouseSGR(false);
2505 if (event != null) {
2506 events.add(event);
2507 }
2508 resetParser();
2509 return;
2510 case 'm':
2511 // Generate a mouse release event
2512 event = parseMouseSGR(true);
2513 if (event != null) {
2514 events.add(event);
2515 }
2516 resetParser();
2517 return;
2518 default:
2519 break;
2520 }
2521
2522 // Unknown keystroke, ignore
2523 resetParser();
2524 return;
2525
2526 case CSI_PARAM:
2527 // Numbers - parameter values
2528 if ((ch >= '0') && (ch <= '9')) {
2529 params.set(params.size() - 1,
2530 params.get(params.size() - 1) + ch);
2531 state = ParseState.CSI_PARAM;
2532 return;
2533 }
2534 // Parameter separator
2535 if (ch == ';') {
2536 params.add("");
2537 return;
2538 }
2539
2540 if (ch == '~') {
2541 events.add(csiFnKey());
2542 resetParser();
2543 return;
2544 }
2545
2546 if ((ch >= 0x30) && (ch <= 0x7E)) {
2547 switch (ch) {
2548 case 'A':
2549 // Up
2550 if (params.size() > 1) {
2551 shift = csiIsShift(params.get(1));
2552 alt = csiIsAlt(params.get(1));
2553 ctrl = csiIsCtrl(params.get(1));
2554 }
2555 events.add(new TKeypressEvent(kbUp, alt, ctrl, shift));
2556 resetParser();
2557 return;
2558 case 'B':
2559 // Down
2560 if (params.size() > 1) {
2561 shift = csiIsShift(params.get(1));
2562 alt = csiIsAlt(params.get(1));
2563 ctrl = csiIsCtrl(params.get(1));
2564 }
2565 events.add(new TKeypressEvent(kbDown, alt, ctrl, shift));
2566 resetParser();
2567 return;
2568 case 'C':
2569 // Right
2570 if (params.size() > 1) {
2571 shift = csiIsShift(params.get(1));
2572 alt = csiIsAlt(params.get(1));
2573 ctrl = csiIsCtrl(params.get(1));
2574 }
2575 events.add(new TKeypressEvent(kbRight, alt, ctrl, shift));
2576 resetParser();
2577 return;
2578 case 'D':
2579 // Left
2580 if (params.size() > 1) {
2581 shift = csiIsShift(params.get(1));
2582 alt = csiIsAlt(params.get(1));
2583 ctrl = csiIsCtrl(params.get(1));
2584 }
2585 events.add(new TKeypressEvent(kbLeft, alt, ctrl, shift));
2586 resetParser();
2587 return;
2588 case 'H':
2589 // Home
2590 if (params.size() > 1) {
2591 shift = csiIsShift(params.get(1));
2592 alt = csiIsAlt(params.get(1));
2593 ctrl = csiIsCtrl(params.get(1));
2594 }
2595 events.add(new TKeypressEvent(kbHome, alt, ctrl, shift));
2596 resetParser();
2597 return;
2598 case 'F':
2599 // End
2600 if (params.size() > 1) {
2601 shift = csiIsShift(params.get(1));
2602 alt = csiIsAlt(params.get(1));
2603 ctrl = csiIsCtrl(params.get(1));
2604 }
2605 events.add(new TKeypressEvent(kbEnd, alt, ctrl, shift));
2606 resetParser();
2607 return;
2608 case 't':
2609 // windowOps
2610 if ((params.size() > 2) && (params.get(0).equals("4"))) {
2611 if (debugToStderr) {
2612 System.err.printf("windowOp pixels: " +
2613 "height %s width %s\n",
2614 params.get(1), params.get(2));
2615 }
2616 try {
2617 widthPixels = Integer.parseInt(params.get(2));
2618 heightPixels = Integer.parseInt(params.get(1));
2619 } catch (NumberFormatException e) {
2620 if (debugToStderr) {
2621 e.printStackTrace();
2622 }
2623 }
2624 if (widthPixels <= 0) {
2625 widthPixels = 640;
2626 }
2627 if (heightPixels <= 0) {
2628 heightPixels = 400;
2629 }
2630 }
2631 resetParser();
2632 return;
2633 default:
2634 break;
2635 }
2636 }
2637
2638 // Unknown keystroke, ignore
2639 resetParser();
2640 return;
2641
2642 case MOUSE:
2643 params.set(0, params.get(params.size() - 1) + ch);
2644 if (params.get(0).length() == 3) {
2645 // We have enough to generate a mouse event
2646 events.add(parseMouse());
2647 resetParser();
2648 }
2649 return;
2650
2651 default:
2652 break;
2653 }
2654
2655 // This "should" be impossible to reach
2656 return;
2657 }
2658
2659 /**
2660 * Request (u)xterm to report the current window size dimensions.
2661 *
2662 * @return the string to emit to xterm
2663 */
2664 private String xtermReportWindowPixelDimensions() {
2665 return "\033[14t";
2666 }
2667
2668 /**
2669 * Tell (u)xterm that we want alt- keystrokes to send escape + character
2670 * rather than set the 8th bit. Anyone who wants UTF8 should want this
2671 * enabled.
2672 *
2673 * @param on if true, enable metaSendsEscape
2674 * @return the string to emit to xterm
2675 */
2676 private String xtermMetaSendsEscape(final boolean on) {
2677 if (on) {
2678 return "\033[?1036h\033[?1034l";
2679 }
2680 return "\033[?1036l";
2681 }
2682
2683 /**
2684 * Create an xterm OSC sequence to change the window title.
2685 *
2686 * @param title the new title
2687 * @return the string to emit to xterm
2688 */
2689 private String getSetTitleString(final String title) {
2690 return "\033]2;" + title + "\007";
2691 }
2692
2693 // ------------------------------------------------------------------------
2694 // Sixel output support ---------------------------------------------------
2695 // ------------------------------------------------------------------------
2696
2697 /**
2698 * Start a sixel string for display one row's worth of bitmap data.
2699 *
2700 * @param x column coordinate. 0 is the left-most column.
2701 * @param y row coordinate. 0 is the top-most row.
2702 * @return the string to emit to an ANSI / ECMA-style terminal
2703 */
2704 private String startSixel(final int x, final int y) {
2705 StringBuilder sb = new StringBuilder();
2706
2707 assert (sixel == true);
2708
2709 // Place the cursor
2710 sb.append(gotoXY(x, y));
2711
2712 // DCS
2713 sb.append("\033Pq");
2714
2715 if (palette == null) {
2716 palette = new SixelPalette();
2717 }
2718
2719 return sb.toString();
2720 }
2721
2722 /**
2723 * End a sixel string for display one row's worth of bitmap data.
2724 *
2725 * @return the string to emit to an ANSI / ECMA-style terminal
2726 */
2727 private String endSixel() {
2728 assert (sixel == true);
2729
2730 // ST
2731 return ("\033\\");
2732 }
2733
2734 /**
2735 * Create a sixel string representing a row of several cells containing
2736 * bitmap data.
2737 *
2738 * @param x column coordinate. 0 is the left-most column.
2739 * @param y row coordinate. 0 is the top-most row.
2740 * @param cells the cells containing the bitmap data
2741 * @return the string to emit to an ANSI / ECMA-style terminal
2742 */
2743 private String toSixel(final int x, final int y,
2744 final ArrayList<Cell> cells) {
2745
2746 StringBuilder sb = new StringBuilder();
2747
2748 assert (sixel == true);
2749 assert (cells != null);
2750 assert (cells.size() > 0);
2751 assert (cells.get(0).getImage() != null);
2752
2753 if (sixelCache == null) {
2754 sixelCache = new SixelCache(height * 10);
2755 }
2756
2757 // Save and get rows to/from the cache that do NOT have inverted
2758 // cells.
2759 boolean saveInCache = true;
2760 for (Cell cell: cells) {
2761 if (cell.isInvertedImage()) {
2762 saveInCache = false;
2763 }
2764 }
2765 if (saveInCache) {
2766 String cachedResult = sixelCache.get(cells);
2767 if (cachedResult != null) {
2768 // System.err.println("CACHE HIT");
2769 sb.append(startSixel(x, y));
2770 sb.append(cachedResult);
2771 sb.append(endSixel());
2772 return sb.toString();
2773 }
2774 // System.err.println("CACHE MISS");
2775 }
2776
2777 int imageWidth = cells.get(0).getImage().getWidth();
2778 int imageHeight = cells.get(0).getImage().getHeight();
2779
2780 // cells.get(x).getImage() has a dithered bitmap containing indexes
2781 // into the color palette. Piece these together into one larger
2782 // image for final rendering.
2783 int totalWidth = 0;
2784 int fullWidth = cells.size() * getTextWidth();
2785 int fullHeight = getTextHeight();
2786 for (int i = 0; i < cells.size(); i++) {
2787 totalWidth += cells.get(i).getImage().getWidth();
2788 }
2789
2790 BufferedImage image = new BufferedImage(fullWidth,
2791 fullHeight, BufferedImage.TYPE_INT_ARGB);
2792
2793 int [] rgbArray;
2794 for (int i = 0; i < cells.size() - 1; i++) {
2795 if (cells.get(i).isInvertedImage()) {
2796 rgbArray = new int[imageWidth * imageHeight];
2797 for (int j = 0; j < rgbArray.length; j++) {
2798 rgbArray[j] = 0xFFFFFF;
2799 }
2800 } else {
2801 rgbArray = cells.get(i).getImage().getRGB(0, 0,
2802 imageWidth, imageHeight, null, 0, imageWidth);
2803 }
2804 image.setRGB(i * imageWidth, 0, imageWidth, imageHeight,
2805 rgbArray, 0, imageWidth);
2806 if (imageHeight < fullHeight) {
2807 int backgroundColor = cells.get(i).getBackground().getRGB();
2808 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
2809 for (int imageY = imageHeight; imageY < fullHeight;
2810 imageY++) {
2811
2812 image.setRGB(imageX, imageY, backgroundColor);
2813 }
2814 }
2815 }
2816 }
2817 totalWidth -= ((cells.size() - 1) * imageWidth);
2818 if (cells.get(cells.size() - 1).isInvertedImage()) {
2819 rgbArray = new int[totalWidth * imageHeight];
2820 for (int j = 0; j < rgbArray.length; j++) {
2821 rgbArray[j] = 0xFFFFFF;
2822 }
2823 } else {
2824 rgbArray = cells.get(cells.size() - 1).getImage().getRGB(0, 0,
2825 totalWidth, imageHeight, null, 0, totalWidth);
2826 }
2827 image.setRGB((cells.size() - 1) * imageWidth, 0, totalWidth,
2828 imageHeight, rgbArray, 0, totalWidth);
2829
2830 if (totalWidth < getTextWidth()) {
2831 int backgroundColor = cells.get(cells.size() - 1).getBackground().getRGB();
2832
2833 for (int imageX = image.getWidth() - totalWidth;
2834 imageX < image.getWidth(); imageX++) {
2835
2836 for (int imageY = 0; imageY < fullHeight; imageY++) {
2837 image.setRGB(imageX, imageY, backgroundColor);
2838 }
2839 }
2840 }
2841
2842 // Dither the image. It is ok to lose the original here.
2843 if (palette == null) {
2844 palette = new SixelPalette();
2845 }
2846 image = palette.ditherImage(image);
2847
2848 // Emit the palette, but only for the colors actually used by these
2849 // cells.
2850 boolean [] usedColors = new boolean[MAX_COLOR_REGISTERS];
2851 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
2852 for (int imageY = 0; imageY < image.getHeight(); imageY++) {
2853 usedColors[image.getRGB(imageX, imageY)] = true;
2854 }
2855 }
2856 palette.emitPalette(sb, usedColors);
2857
2858 // Render the entire row of cells.
2859 for (int currentRow = 0; currentRow < fullHeight; currentRow += 6) {
2860 int [][] sixels = new int[image.getWidth()][6];
2861
2862 // See which colors are actually used in this band of sixels.
2863 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
2864 for (int imageY = 0;
2865 (imageY < 6) && (imageY + currentRow < fullHeight);
2866 imageY++) {
2867
2868 int colorIdx = image.getRGB(imageX, imageY + currentRow);
2869 assert (colorIdx >= 0);
2870 assert (colorIdx < MAX_COLOR_REGISTERS);
2871
2872 sixels[imageX][imageY] = colorIdx;
2873 }
2874 }
2875
2876 for (int i = 0; i < MAX_COLOR_REGISTERS; i++) {
2877 boolean isUsed = false;
2878 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
2879 for (int j = 0; j < 6; j++) {
2880 if (sixels[imageX][j] == i) {
2881 isUsed = true;
2882 }
2883 }
2884 }
2885 if (isUsed == false) {
2886 continue;
2887 }
2888
2889 // Set to the beginning of scan line for the next set of
2890 // colored pixels, and select the color.
2891 sb.append(String.format("$#%d", i));
2892
2893 for (int imageX = 0; imageX < image.getWidth(); imageX++) {
2894
2895 // Add up all the pixels that match this color.
2896 int data = 0;
2897 for (int j = 0;
2898 (j < 6) && (currentRow + j < fullHeight);
2899 j++) {
2900
2901 if (sixels[imageX][j] == i) {
2902 switch (j) {
2903 case 0:
2904 data += 1;
2905 break;
2906 case 1:
2907 data += 2;
2908 break;
2909 case 2:
2910 data += 4;
2911 break;
2912 case 3:
2913 data += 8;
2914 break;
2915 case 4:
2916 data += 16;
2917 break;
2918 case 5:
2919 data += 32;
2920 break;
2921 }
2922 }
2923 }
2924 assert (data >= 0);
2925 assert (data < 127);
2926 data += 63;
2927 sb.append((char) data);
2928 } // for (int imageX = 0; imageX < image.getWidth(); imageX++)
2929 } // for (int i = 0; i < MAX_COLOR_REGISTERS; i++)
2930
2931 // Advance to the next scan line.
2932 sb.append("-");
2933
2934 } // for (int currentRow = 0; currentRow < imageHeight; currentRow += 6)
2935
2936 // Kill the very last "-", because it is unnecessary.
2937 sb.deleteCharAt(sb.length() - 1);
2938
2939 if (saveInCache) {
2940 // This row is OK to save into the cache.
2941 sixelCache.put(cells, sb.toString());
2942 }
2943
2944 return (startSixel(x, y) + sb.toString() + endSixel());
2945 }
2946
2947 // ------------------------------------------------------------------------
2948 // End sixel output support -----------------------------------------------
2949 // ------------------------------------------------------------------------
2950
2951 /**
2952 * Create a SGR parameter sequence for a single color change.
2953 *
2954 * @param bold if true, set bold
2955 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
2956 * @param foreground if true, this is a foreground color
2957 * @return the string to emit to an ANSI / ECMA-style terminal,
2958 * e.g. "\033[42m"
2959 */
2960 private String color(final boolean bold, final Color color,
2961 final boolean foreground) {
2962 return color(color, foreground, true) +
2963 rgbColor(bold, color, foreground);
2964 }
2965
2966 /**
2967 * Create a T.416 RGB parameter sequence for a single color change.
2968 *
2969 * @param colorRGB a 24-bit RGB value for foreground color
2970 * @param foreground if true, this is a foreground color
2971 * @return the string to emit to an ANSI / ECMA-style terminal,
2972 * e.g. "\033[42m"
2973 */
2974 private String colorRGB(final int colorRGB, final boolean foreground) {
2975
2976 int colorRed = (colorRGB >>> 16) & 0xFF;
2977 int colorGreen = (colorRGB >>> 8) & 0xFF;
2978 int colorBlue = colorRGB & 0xFF;
2979
2980 StringBuilder sb = new StringBuilder();
2981 if (foreground) {
2982 sb.append("\033[38;2;");
2983 } else {
2984 sb.append("\033[48;2;");
2985 }
2986 sb.append(String.format("%d;%d;%dm", colorRed, colorGreen, colorBlue));
2987 return sb.toString();
2988 }
2989
2990 /**
2991 * Create a T.416 RGB parameter sequence for both foreground and
2992 * background color change.
2993 *
2994 * @param foreColorRGB a 24-bit RGB value for foreground color
2995 * @param backColorRGB a 24-bit RGB value for foreground color
2996 * @return the string to emit to an ANSI / ECMA-style terminal,
2997 * e.g. "\033[42m"
2998 */
2999 private String colorRGB(final int foreColorRGB, final int backColorRGB) {
3000 int foreColorRed = (foreColorRGB >>> 16) & 0xFF;
3001 int foreColorGreen = (foreColorRGB >>> 8) & 0xFF;
3002 int foreColorBlue = foreColorRGB & 0xFF;
3003 int backColorRed = (backColorRGB >>> 16) & 0xFF;
3004 int backColorGreen = (backColorRGB >>> 8) & 0xFF;
3005 int backColorBlue = backColorRGB & 0xFF;
3006
3007 StringBuilder sb = new StringBuilder();
3008 sb.append(String.format("\033[38;2;%d;%d;%dm",
3009 foreColorRed, foreColorGreen, foreColorBlue));
3010 sb.append(String.format("\033[48;2;%d;%d;%dm",
3011 backColorRed, backColorGreen, backColorBlue));
3012 return sb.toString();
3013 }
3014
3015 /**
3016 * Create a T.416 RGB parameter sequence for a single color change.
3017 *
3018 * @param bold if true, set bold
3019 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
3020 * @param foreground if true, this is a foreground color
3021 * @return the string to emit to an xterm terminal with RGB support,
3022 * e.g. "\033[38;2;RR;GG;BBm"
3023 */
3024 private String rgbColor(final boolean bold, final Color color,
3025 final boolean foreground) {
3026 if (doRgbColor == false) {
3027 return "";
3028 }
3029 StringBuilder sb = new StringBuilder("\033[");
3030 if (bold) {
3031 // Bold implies foreground only
3032 sb.append("38;2;");
3033 if (color.equals(Color.BLACK)) {
3034 sb.append("84;84;84");
3035 } else if (color.equals(Color.RED)) {
3036 sb.append("252;84;84");
3037 } else if (color.equals(Color.GREEN)) {
3038 sb.append("84;252;84");
3039 } else if (color.equals(Color.YELLOW)) {
3040 sb.append("252;252;84");
3041 } else if (color.equals(Color.BLUE)) {
3042 sb.append("84;84;252");
3043 } else if (color.equals(Color.MAGENTA)) {
3044 sb.append("252;84;252");
3045 } else if (color.equals(Color.CYAN)) {
3046 sb.append("84;252;252");
3047 } else if (color.equals(Color.WHITE)) {
3048 sb.append("252;252;252");
3049 }
3050 } else {
3051 if (foreground) {
3052 sb.append("38;2;");
3053 } else {
3054 sb.append("48;2;");
3055 }
3056 if (color.equals(Color.BLACK)) {
3057 sb.append("0;0;0");
3058 } else if (color.equals(Color.RED)) {
3059 sb.append("168;0;0");
3060 } else if (color.equals(Color.GREEN)) {
3061 sb.append("0;168;0");
3062 } else if (color.equals(Color.YELLOW)) {
3063 sb.append("168;84;0");
3064 } else if (color.equals(Color.BLUE)) {
3065 sb.append("0;0;168");
3066 } else if (color.equals(Color.MAGENTA)) {
3067 sb.append("168;0;168");
3068 } else if (color.equals(Color.CYAN)) {
3069 sb.append("0;168;168");
3070 } else if (color.equals(Color.WHITE)) {
3071 sb.append("168;168;168");
3072 }
3073 }
3074 sb.append("m");
3075 return sb.toString();
3076 }
3077
3078 /**
3079 * Create a T.416 RGB parameter sequence for both foreground and
3080 * background color change.
3081 *
3082 * @param bold if true, set bold
3083 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3084 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3085 * @return the string to emit to an xterm terminal with RGB support,
3086 * e.g. "\033[38;2;RR;GG;BB;48;2;RR;GG;BBm"
3087 */
3088 private String rgbColor(final boolean bold, final Color foreColor,
3089 final Color backColor) {
3090 if (doRgbColor == false) {
3091 return "";
3092 }
3093
3094 return rgbColor(bold, foreColor, true) +
3095 rgbColor(false, backColor, false);
3096 }
3097
3098 /**
3099 * Create a SGR parameter sequence for a single color change.
3100 *
3101 * @param color one of the Color.WHITE, Color.BLUE, etc. constants
3102 * @param foreground if true, this is a foreground color
3103 * @param header if true, make the full header, otherwise just emit the
3104 * color parameter e.g. "42;"
3105 * @return the string to emit to an ANSI / ECMA-style terminal,
3106 * e.g. "\033[42m"
3107 */
3108 private String color(final Color color, final boolean foreground,
3109 final boolean header) {
3110
3111 int ecmaColor = color.getValue();
3112
3113 // Convert Color.* values to SGR numerics
3114 if (foreground) {
3115 ecmaColor += 30;
3116 } else {
3117 ecmaColor += 40;
3118 }
3119
3120 if (header) {
3121 return String.format("\033[%dm", ecmaColor);
3122 } else {
3123 return String.format("%d;", ecmaColor);
3124 }
3125 }
3126
3127 /**
3128 * Create a SGR parameter sequence for both foreground and background
3129 * color change.
3130 *
3131 * @param bold if true, set bold
3132 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3133 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3134 * @return the string to emit to an ANSI / ECMA-style terminal,
3135 * e.g. "\033[31;42m"
3136 */
3137 private String color(final boolean bold, final Color foreColor,
3138 final Color backColor) {
3139 return color(foreColor, backColor, true) +
3140 rgbColor(bold, foreColor, backColor);
3141 }
3142
3143 /**
3144 * Create a SGR parameter sequence for both foreground and
3145 * background color change.
3146 *
3147 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3148 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3149 * @param header if true, make the full header, otherwise just emit the
3150 * color parameter e.g. "31;42;"
3151 * @return the string to emit to an ANSI / ECMA-style terminal,
3152 * e.g. "\033[31;42m"
3153 */
3154 private String color(final Color foreColor, final Color backColor,
3155 final boolean header) {
3156
3157 int ecmaForeColor = foreColor.getValue();
3158 int ecmaBackColor = backColor.getValue();
3159
3160 // Convert Color.* values to SGR numerics
3161 ecmaBackColor += 40;
3162 ecmaForeColor += 30;
3163
3164 if (header) {
3165 return String.format("\033[%d;%dm", ecmaForeColor, ecmaBackColor);
3166 } else {
3167 return String.format("%d;%d;", ecmaForeColor, ecmaBackColor);
3168 }
3169 }
3170
3171 /**
3172 * Create a SGR parameter sequence for foreground, background, and
3173 * several attributes. This sequence first resets all attributes to
3174 * default, then sets attributes as per the parameters.
3175 *
3176 * @param foreColor one of the Color.WHITE, Color.BLUE, etc. constants
3177 * @param backColor one of the Color.WHITE, Color.BLUE, etc. constants
3178 * @param bold if true, set bold
3179 * @param reverse if true, set reverse
3180 * @param blink if true, set blink
3181 * @param underline if true, set underline
3182 * @return the string to emit to an ANSI / ECMA-style terminal,
3183 * e.g. "\033[0;1;31;42m"
3184 */
3185 private String color(final Color foreColor, final Color backColor,
3186 final boolean bold, final boolean reverse, final boolean blink,
3187 final boolean underline) {
3188
3189 int ecmaForeColor = foreColor.getValue();
3190 int ecmaBackColor = backColor.getValue();
3191
3192 // Convert Color.* values to SGR numerics
3193 ecmaBackColor += 40;
3194 ecmaForeColor += 30;
3195
3196 StringBuilder sb = new StringBuilder();
3197 if ( bold && reverse && blink && !underline ) {
3198 sb.append("\033[0;1;7;5;");
3199 } else if ( bold && reverse && !blink && !underline ) {
3200 sb.append("\033[0;1;7;");
3201 } else if ( !bold && reverse && blink && !underline ) {
3202 sb.append("\033[0;7;5;");
3203 } else if ( bold && !reverse && blink && !underline ) {
3204 sb.append("\033[0;1;5;");
3205 } else if ( bold && !reverse && !blink && !underline ) {
3206 sb.append("\033[0;1;");
3207 } else if ( !bold && reverse && !blink && !underline ) {
3208 sb.append("\033[0;7;");
3209 } else if ( !bold && !reverse && blink && !underline) {
3210 sb.append("\033[0;5;");
3211 } else if ( bold && reverse && blink && underline ) {
3212 sb.append("\033[0;1;7;5;4;");
3213 } else if ( bold && reverse && !blink && underline ) {
3214 sb.append("\033[0;1;7;4;");
3215 } else if ( !bold && reverse && blink && underline ) {
3216 sb.append("\033[0;7;5;4;");
3217 } else if ( bold && !reverse && blink && underline ) {
3218 sb.append("\033[0;1;5;4;");
3219 } else if ( bold && !reverse && !blink && underline ) {
3220 sb.append("\033[0;1;4;");
3221 } else if ( !bold && reverse && !blink && underline ) {
3222 sb.append("\033[0;7;4;");
3223 } else if ( !bold && !reverse && blink && underline) {
3224 sb.append("\033[0;5;4;");
3225 } else if ( !bold && !reverse && !blink && underline) {
3226 sb.append("\033[0;4;");
3227 } else {
3228 assert (!bold && !reverse && !blink && !underline);
3229 sb.append("\033[0;");
3230 }
3231 sb.append(String.format("%d;%dm", ecmaForeColor, ecmaBackColor));
3232 sb.append(rgbColor(bold, foreColor, backColor));
3233 return sb.toString();
3234 }
3235
3236 /**
3237 * Create a SGR parameter sequence for foreground, background, and
3238 * several attributes. This sequence first resets all attributes to
3239 * default, then sets attributes as per the parameters.
3240 *
3241 * @param foreColorRGB a 24-bit RGB value for foreground color
3242 * @param backColorRGB a 24-bit RGB value for foreground color
3243 * @param bold if true, set bold
3244 * @param reverse if true, set reverse
3245 * @param blink if true, set blink
3246 * @param underline if true, set underline
3247 * @return the string to emit to an ANSI / ECMA-style terminal,
3248 * e.g. "\033[0;1;31;42m"
3249 */
3250 private String colorRGB(final int foreColorRGB, final int backColorRGB,
3251 final boolean bold, final boolean reverse, final boolean blink,
3252 final boolean underline) {
3253
3254 int foreColorRed = (foreColorRGB >>> 16) & 0xFF;
3255 int foreColorGreen = (foreColorRGB >>> 8) & 0xFF;
3256 int foreColorBlue = foreColorRGB & 0xFF;
3257 int backColorRed = (backColorRGB >>> 16) & 0xFF;
3258 int backColorGreen = (backColorRGB >>> 8) & 0xFF;
3259 int backColorBlue = backColorRGB & 0xFF;
3260
3261 StringBuilder sb = new StringBuilder();
3262 if ( bold && reverse && blink && !underline ) {
3263 sb.append("\033[0;1;7;5;");
3264 } else if ( bold && reverse && !blink && !underline ) {
3265 sb.append("\033[0;1;7;");
3266 } else if ( !bold && reverse && blink && !underline ) {
3267 sb.append("\033[0;7;5;");
3268 } else if ( bold && !reverse && blink && !underline ) {
3269 sb.append("\033[0;1;5;");
3270 } else if ( bold && !reverse && !blink && !underline ) {
3271 sb.append("\033[0;1;");
3272 } else if ( !bold && reverse && !blink && !underline ) {
3273 sb.append("\033[0;7;");
3274 } else if ( !bold && !reverse && blink && !underline) {
3275 sb.append("\033[0;5;");
3276 } else if ( bold && reverse && blink && underline ) {
3277 sb.append("\033[0;1;7;5;4;");
3278 } else if ( bold && reverse && !blink && underline ) {
3279 sb.append("\033[0;1;7;4;");
3280 } else if ( !bold && reverse && blink && underline ) {
3281 sb.append("\033[0;7;5;4;");
3282 } else if ( bold && !reverse && blink && underline ) {
3283 sb.append("\033[0;1;5;4;");
3284 } else if ( bold && !reverse && !blink && underline ) {
3285 sb.append("\033[0;1;4;");
3286 } else if ( !bold && reverse && !blink && underline ) {
3287 sb.append("\033[0;7;4;");
3288 } else if ( !bold && !reverse && blink && underline) {
3289 sb.append("\033[0;5;4;");
3290 } else if ( !bold && !reverse && !blink && underline) {
3291 sb.append("\033[0;4;");
3292 } else {
3293 assert (!bold && !reverse && !blink && !underline);
3294 sb.append("\033[0;");
3295 }
3296
3297 sb.append("m\033[38;2;");
3298 sb.append(String.format("%d;%d;%d", foreColorRed, foreColorGreen,
3299 foreColorBlue));
3300 sb.append("m\033[48;2;");
3301 sb.append(String.format("%d;%d;%d", backColorRed, backColorGreen,
3302 backColorBlue));
3303 sb.append("m");
3304 return sb.toString();
3305 }
3306
3307 /**
3308 * Create a SGR parameter sequence to reset to defaults.
3309 *
3310 * @return the string to emit to an ANSI / ECMA-style terminal,
3311 * e.g. "\033[0m"
3312 */
3313 private String normal() {
3314 return normal(true) + rgbColor(false, Color.WHITE, Color.BLACK);
3315 }
3316
3317 /**
3318 * Create a SGR parameter sequence to reset to defaults.
3319 *
3320 * @param header if true, make the full header, otherwise just emit the
3321 * bare parameter e.g. "0;"
3322 * @return the string to emit to an ANSI / ECMA-style terminal,
3323 * e.g. "\033[0m"
3324 */
3325 private String normal(final boolean header) {
3326 if (header) {
3327 return "\033[0;37;40m";
3328 }
3329 return "0;37;40";
3330 }
3331
3332 /**
3333 * Create a SGR parameter sequence for enabling the visible cursor.
3334 *
3335 * @param on if true, turn on cursor
3336 * @return the string to emit to an ANSI / ECMA-style terminal
3337 */
3338 private String cursor(final boolean on) {
3339 if (on && !cursorOn) {
3340 cursorOn = true;
3341 return "\033[?25h";
3342 }
3343 if (!on && cursorOn) {
3344 cursorOn = false;
3345 return "\033[?25l";
3346 }
3347 return "";
3348 }
3349
3350 /**
3351 * Clear the entire screen. Because some terminals use back-color-erase,
3352 * set the color to white-on-black beforehand.
3353 *
3354 * @return the string to emit to an ANSI / ECMA-style terminal
3355 */
3356 private String clearAll() {
3357 return "\033[0;37;40m\033[2J";
3358 }
3359
3360 /**
3361 * Clear the line from the cursor (inclusive) to the end of the screen.
3362 * Because some terminals use back-color-erase, set the color to
3363 * white-on-black beforehand.
3364 *
3365 * @return the string to emit to an ANSI / ECMA-style terminal
3366 */
3367 private String clearRemainingLine() {
3368 return "\033[0;37;40m\033[K";
3369 }
3370
3371 /**
3372 * Move the cursor to (x, y).
3373 *
3374 * @param x column coordinate. 0 is the left-most column.
3375 * @param y row coordinate. 0 is the top-most row.
3376 * @return the string to emit to an ANSI / ECMA-style terminal
3377 */
3378 private String gotoXY(final int x, final int y) {
3379 return String.format("\033[%d;%dH", y + 1, x + 1);
3380 }
3381
3382 /**
3383 * Tell (u)xterm that we want to receive mouse events based on "Any event
3384 * tracking", UTF-8 coordinates, and then SGR coordinates. Ideally we
3385 * will end up with SGR coordinates with UTF-8 coordinates as a fallback.
3386 * See
3387 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
3388 *
3389 * Note that this also sets the alternate/primary screen buffer.
3390 *
3391 * @param on If true, enable mouse report and use the alternate screen
3392 * buffer. If false disable mouse reporting and use the primary screen
3393 * buffer.
3394 * @return the string to emit to xterm
3395 */
3396 private String mouse(final boolean on) {
3397 if (on) {
3398 return "\033[?1002;1003;1005;1006h\033[?1049h";
3399 }
3400 return "\033[?1002;1003;1006;1005l\033[?1049l";
3401 }
3402
3403 }