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