LICENSE CHANGED TO MIT
[nikiroo-utils.git] / src / jexer / io / SwingScreen.java
1 /*
2 * Jexer - Java Text User Interface
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (C) 2016 Kevin Lamonte
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
25 *
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
27 * @version 1
28 */
29 package jexer.io;
30
31 import java.awt.Color;
32 import java.awt.Cursor;
33 import java.awt.Font;
34 import java.awt.FontMetrics;
35 import java.awt.Graphics;
36 import java.awt.Insets;
37 import java.awt.Point;
38 import java.awt.Rectangle;
39 import java.awt.Toolkit;
40 import java.awt.geom.Rectangle2D;
41 import java.awt.image.BufferedImage;
42 import java.awt.image.BufferStrategy;
43 import java.io.InputStream;
44 import java.util.Date;
45 import javax.swing.JFrame;
46 import javax.swing.SwingUtilities;
47
48 import jexer.bits.Cell;
49 import jexer.bits.CellAttributes;
50 import jexer.session.SwingSessionInfo;
51
52 /**
53 * This Screen implementation draws to a Java Swing JFrame.
54 */
55 public final class SwingScreen extends Screen {
56
57 /**
58 * If true, use double buffering thread.
59 */
60 private static final boolean doubleBuffer = true;
61
62 /**
63 * Cursor style to draw.
64 */
65 public enum CursorStyle {
66 /**
67 * Use an underscore for the cursor.
68 */
69 UNDERLINE,
70
71 /**
72 * Use a solid block for the cursor.
73 */
74 BLOCK,
75
76 /**
77 * Use an outlined block for the cursor.
78 */
79 OUTLINE
80 }
81
82 private static Color MYBLACK;
83 private static Color MYRED;
84 private static Color MYGREEN;
85 private static Color MYYELLOW;
86 private static Color MYBLUE;
87 private static Color MYMAGENTA;
88 private static Color MYCYAN;
89 private static Color MYWHITE;
90
91 private static Color MYBOLD_BLACK;
92 private static Color MYBOLD_RED;
93 private static Color MYBOLD_GREEN;
94 private static Color MYBOLD_YELLOW;
95 private static Color MYBOLD_BLUE;
96 private static Color MYBOLD_MAGENTA;
97 private static Color MYBOLD_CYAN;
98 private static Color MYBOLD_WHITE;
99
100 private static boolean dosColors = false;
101
102 /**
103 * Setup Swing colors to match DOS color palette.
104 */
105 private static void setDOSColors() {
106 if (dosColors) {
107 return;
108 }
109 MYBLACK = new Color(0x00, 0x00, 0x00);
110 MYRED = new Color(0xa8, 0x00, 0x00);
111 MYGREEN = new Color(0x00, 0xa8, 0x00);
112 MYYELLOW = new Color(0xa8, 0x54, 0x00);
113 MYBLUE = new Color(0x00, 0x00, 0xa8);
114 MYMAGENTA = new Color(0xa8, 0x00, 0xa8);
115 MYCYAN = new Color(0x00, 0xa8, 0xa8);
116 MYWHITE = new Color(0xa8, 0xa8, 0xa8);
117 MYBOLD_BLACK = new Color(0x54, 0x54, 0x54);
118 MYBOLD_RED = new Color(0xfc, 0x54, 0x54);
119 MYBOLD_GREEN = new Color(0x54, 0xfc, 0x54);
120 MYBOLD_YELLOW = new Color(0xfc, 0xfc, 0x54);
121 MYBOLD_BLUE = new Color(0x54, 0x54, 0xfc);
122 MYBOLD_MAGENTA = new Color(0xfc, 0x54, 0xfc);
123 MYBOLD_CYAN = new Color(0x54, 0xfc, 0xfc);
124 MYBOLD_WHITE = new Color(0xfc, 0xfc, 0xfc);
125
126 dosColors = true;
127 }
128
129 /**
130 * SwingFrame is our top-level hook into the Swing system.
131 */
132 class SwingFrame extends JFrame {
133
134 /**
135 * Serializable version.
136 */
137 private static final long serialVersionUID = 1;
138
139 /**
140 * The terminus font resource filename.
141 */
142 private static final String FONTFILE = "terminus-ttf-4.39/TerminusTTF-Bold-4.39.ttf";
143
144 /**
145 * The BufferStrategy object needed for double-buffering.
146 */
147 private BufferStrategy bufferStrategy;
148
149 /**
150 * The TUI Screen data.
151 */
152 SwingScreen screen;
153
154 /**
155 * Width of a character cell.
156 */
157 private int textWidth = 1;
158
159 /**
160 * Height of a character cell.
161 */
162 private int textHeight = 1;
163
164 /**
165 * Descent of a character cell.
166 */
167 private int maxDescent = 0;
168
169 /**
170 * System-dependent Y adjustment for text in the character cell.
171 */
172 private int textAdjustY = 0;
173
174 /**
175 * System-dependent X adjustment for text in the character cell.
176 */
177 private int textAdjustX = 0;
178
179 /**
180 * Top pixel absolute location.
181 */
182 private int top = 30;
183
184 /**
185 * Left pixel absolute location.
186 */
187 private int left = 30;
188
189 /**
190 * The cursor style to draw.
191 */
192 private CursorStyle cursorStyle = CursorStyle.UNDERLINE;
193
194 /**
195 * The number of millis to wait before switching the blink from
196 * visible to invisible.
197 */
198 private long blinkMillis = 500;
199
200 /**
201 * If true, the cursor should be visible right now based on the blink
202 * time.
203 */
204 private boolean cursorBlinkVisible = true;
205
206 /**
207 * The time that the blink last flipped from visible to invisible or
208 * from invisible to visible.
209 */
210 private long lastBlinkTime = 0;
211
212 /**
213 * Convert a CellAttributes foreground color to an Swing Color.
214 *
215 * @param attr the text attributes
216 * @return the Swing Color
217 */
218 private Color attrToForegroundColor(final CellAttributes attr) {
219 if (attr.isBold()) {
220 if (attr.getForeColor().equals(jexer.bits.Color.BLACK)) {
221 return MYBOLD_BLACK;
222 } else if (attr.getForeColor().equals(jexer.bits.Color.RED)) {
223 return MYBOLD_RED;
224 } else if (attr.getForeColor().equals(jexer.bits.Color.BLUE)) {
225 return MYBOLD_BLUE;
226 } else if (attr.getForeColor().equals(jexer.bits.Color.GREEN)) {
227 return MYBOLD_GREEN;
228 } else if (attr.getForeColor().equals(jexer.bits.Color.YELLOW)) {
229 return MYBOLD_YELLOW;
230 } else if (attr.getForeColor().equals(jexer.bits.Color.CYAN)) {
231 return MYBOLD_CYAN;
232 } else if (attr.getForeColor().equals(jexer.bits.Color.MAGENTA)) {
233 return MYBOLD_MAGENTA;
234 } else if (attr.getForeColor().equals(jexer.bits.Color.WHITE)) {
235 return MYBOLD_WHITE;
236 }
237 } else {
238 if (attr.getForeColor().equals(jexer.bits.Color.BLACK)) {
239 return MYBLACK;
240 } else if (attr.getForeColor().equals(jexer.bits.Color.RED)) {
241 return MYRED;
242 } else if (attr.getForeColor().equals(jexer.bits.Color.BLUE)) {
243 return MYBLUE;
244 } else if (attr.getForeColor().equals(jexer.bits.Color.GREEN)) {
245 return MYGREEN;
246 } else if (attr.getForeColor().equals(jexer.bits.Color.YELLOW)) {
247 return MYYELLOW;
248 } else if (attr.getForeColor().equals(jexer.bits.Color.CYAN)) {
249 return MYCYAN;
250 } else if (attr.getForeColor().equals(jexer.bits.Color.MAGENTA)) {
251 return MYMAGENTA;
252 } else if (attr.getForeColor().equals(jexer.bits.Color.WHITE)) {
253 return MYWHITE;
254 }
255 }
256 throw new IllegalArgumentException("Invalid color: " + attr.getForeColor().getValue());
257 }
258
259 /**
260 * Convert a CellAttributes background color to an Swing Color.
261 *
262 * @param attr the text attributes
263 * @return the Swing Color
264 */
265 private Color attrToBackgroundColor(final CellAttributes attr) {
266 if (attr.getBackColor().equals(jexer.bits.Color.BLACK)) {
267 return MYBLACK;
268 } else if (attr.getBackColor().equals(jexer.bits.Color.RED)) {
269 return MYRED;
270 } else if (attr.getBackColor().equals(jexer.bits.Color.BLUE)) {
271 return MYBLUE;
272 } else if (attr.getBackColor().equals(jexer.bits.Color.GREEN)) {
273 return MYGREEN;
274 } else if (attr.getBackColor().equals(jexer.bits.Color.YELLOW)) {
275 return MYYELLOW;
276 } else if (attr.getBackColor().equals(jexer.bits.Color.CYAN)) {
277 return MYCYAN;
278 } else if (attr.getBackColor().equals(jexer.bits.Color.MAGENTA)) {
279 return MYMAGENTA;
280 } else if (attr.getBackColor().equals(jexer.bits.Color.WHITE)) {
281 return MYWHITE;
282 }
283 throw new IllegalArgumentException("Invalid color: " + attr.getBackColor().getValue());
284 }
285
286 /**
287 * Public constructor.
288 *
289 * @param screen the Screen that Backend talks to
290 */
291 public SwingFrame(final SwingScreen screen) {
292 this.screen = screen;
293 setDOSColors();
294
295 // Figure out my cursor style
296 String cursorStyleString = System.getProperty("jexer.Swing.cursorStyle",
297 "underline").toLowerCase();
298
299 if (cursorStyleString.equals("underline")) {
300 cursorStyle = CursorStyle.UNDERLINE;
301 } else if (cursorStyleString.equals("outline")) {
302 cursorStyle = CursorStyle.OUTLINE;
303 } else if (cursorStyleString.equals("block")) {
304 cursorStyle = CursorStyle.BLOCK;
305 }
306
307 setTitle("Jexer Application");
308 setBackground(Color.black);
309
310 try {
311 // Always try to use Terminus, the one decent font.
312 ClassLoader loader = Thread.currentThread().getContextClassLoader();
313 InputStream in = loader.getResourceAsStream(FONTFILE);
314 Font terminusRoot = Font.createFont(Font.TRUETYPE_FONT, in);
315 Font terminus = terminusRoot.deriveFont(Font.PLAIN, 22);
316 setFont(terminus);
317 } catch (Exception e) {
318 e.printStackTrace();
319 // setFont(new Font("Liberation Mono", Font.PLAIN, 24));
320 setFont(new Font(Font.MONOSPACED, Font.PLAIN, 24));
321 }
322 pack();
323
324 // Kill the X11 cursor
325 // Transparent 16 x 16 pixel cursor image.
326 BufferedImage cursorImg = new BufferedImage(16, 16,
327 BufferedImage.TYPE_INT_ARGB);
328 // Create a new blank cursor.
329 Cursor blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(
330 cursorImg, new Point(0, 0), "blank cursor");
331 setCursor(blankCursor);
332
333 // Be capable of seeing Tab / Shift-Tab
334 setFocusTraversalKeysEnabled(false);
335
336 // Save the text cell width/height
337 getFontDimensions();
338
339 // Setup double-buffering
340 if (SwingScreen.doubleBuffer) {
341 setIgnoreRepaint(true);
342 createBufferStrategy(2);
343 bufferStrategy = getBufferStrategy();
344 }
345 }
346
347 /**
348 * Figure out my font dimensions.
349 */
350 private void getFontDimensions() {
351 Graphics gr = getGraphics();
352 FontMetrics fm = gr.getFontMetrics();
353 maxDescent = fm.getMaxDescent();
354 Rectangle2D bounds = fm.getMaxCharBounds(gr);
355 int leading = fm.getLeading();
356 textWidth = (int)Math.round(bounds.getWidth());
357 textHeight = (int)Math.round(bounds.getHeight()) - maxDescent;
358 // This also produces the same number, but works better for ugly
359 // monospace.
360 textHeight = fm.getMaxAscent() + maxDescent - leading;
361
362 if (System.getProperty("os.name").startsWith("Windows")) {
363 textAdjustY = -1;
364 textAdjustX = 0;
365 }
366 }
367
368 /**
369 * Resize to font dimensions.
370 */
371 public void resizeToScreen() {
372 // Figure out the thickness of borders and use that to set the
373 // final size.
374 Insets insets = getInsets();
375 left = insets.left;
376 top = insets.top;
377
378 setSize(textWidth * screen.width + insets.left + insets.right,
379 textHeight * screen.height + insets.top + insets.bottom);
380 }
381
382 /**
383 * Update redraws the whole screen.
384 *
385 * @param gr the Swing Graphics context
386 */
387 @Override
388 public void update(final Graphics gr) {
389 // The default update clears the area. Don't do that, instead
390 // just paint it directly.
391 paint(gr);
392 }
393
394 /**
395 * Paint redraws the whole screen.
396 *
397 * @param gr the Swing Graphics context
398 */
399 @Override
400 public void paint(final Graphics gr) {
401 // Do nothing until the screen reference has been set.
402 if (screen == null) {
403 return;
404 }
405 if (screen.frame == null) {
406 return;
407 }
408
409 // See if it is time to flip the blink time.
410 long nowTime = (new Date()).getTime();
411 if (nowTime > blinkMillis + lastBlinkTime) {
412 lastBlinkTime = nowTime;
413 cursorBlinkVisible = !cursorBlinkVisible;
414 }
415
416 int xCellMin = 0;
417 int xCellMax = screen.width;
418 int yCellMin = 0;
419 int yCellMax = screen.height;
420
421 Rectangle bounds = gr.getClipBounds();
422 if (bounds != null) {
423 // Only update what is in the bounds
424 xCellMin = screen.textColumn(bounds.x);
425 xCellMax = screen.textColumn(bounds.x + bounds.width);
426 if (xCellMax > screen.width) {
427 xCellMax = screen.width;
428 }
429 if (xCellMin >= xCellMax) {
430 xCellMin = xCellMax - 2;
431 }
432 if (xCellMin < 0) {
433 xCellMin = 0;
434 }
435 yCellMin = screen.textRow(bounds.y);
436 yCellMax = screen.textRow(bounds.y + bounds.height);
437 if (yCellMax > screen.height) {
438 yCellMax = screen.height;
439 }
440 if (yCellMin >= yCellMax) {
441 yCellMin = yCellMax - 2;
442 }
443 if (yCellMin < 0) {
444 yCellMin = 0;
445 }
446 } else {
447 // We need a total repaint
448 reallyCleared = true;
449 }
450
451 // Prevent updates to the screen's data from the TApplication
452 // threads.
453 synchronized (screen) {
454 /*
455 System.err.printf("bounds %s X %d %d Y %d %d\n",
456 bounds, xCellMin, xCellMax, yCellMin, yCellMax);
457 */
458
459 for (int y = yCellMin; y < yCellMax; y++) {
460 for (int x = xCellMin; x < xCellMax; x++) {
461
462 int xPixel = x * textWidth + left;
463 int yPixel = y * textHeight + top;
464
465 Cell lCell = screen.logical[x][y];
466 Cell pCell = screen.physical[x][y];
467
468 if (!lCell.equals(pCell)
469 || lCell.isBlink()
470 || reallyCleared) {
471
472 Cell lCellColor = new Cell();
473 lCellColor.setTo(lCell);
474
475 // Check for reverse
476 if (lCell.isReverse()) {
477 lCellColor.setForeColor(lCell.getBackColor());
478 lCellColor.setBackColor(lCell.getForeColor());
479 }
480
481 // Draw the background rectangle, then the
482 // foreground character.
483 gr.setColor(attrToBackgroundColor(lCellColor));
484 gr.fillRect(xPixel, yPixel, textWidth, textHeight);
485
486 // Handle blink and underline
487 if (!lCell.isBlink()
488 || (lCell.isBlink() && cursorBlinkVisible)
489 ) {
490 gr.setColor(attrToForegroundColor(lCellColor));
491 char [] chars = new char[1];
492 chars[0] = lCell.getChar();
493 gr.drawChars(chars, 0, 1, xPixel + textAdjustX,
494 yPixel + textHeight - maxDescent
495 + textAdjustY);
496
497 if (lCell.isUnderline()) {
498 gr.fillRect(xPixel, yPixel + textHeight - 2,
499 textWidth, 2);
500 }
501 }
502
503 // Physical is always updated
504 physical[x][y].setTo(lCell);
505 }
506 }
507 }
508
509 // Draw the cursor if it is visible
510 if (cursorVisible
511 && (cursorY <= screen.height - 1)
512 && (cursorX <= screen.width - 1)
513 && cursorBlinkVisible
514 ) {
515 int xPixel = cursorX * textWidth + left;
516 int yPixel = cursorY * textHeight + top;
517 Cell lCell = screen.logical[cursorX][cursorY];
518 gr.setColor(attrToForegroundColor(lCell));
519 switch (cursorStyle) {
520 default:
521 // Fall through...
522 case UNDERLINE:
523 gr.fillRect(xPixel, yPixel + textHeight - 2,
524 textWidth, 2);
525 break;
526 case BLOCK:
527 gr.fillRect(xPixel, yPixel, textWidth, textHeight);
528 break;
529 case OUTLINE:
530 gr.drawRect(xPixel, yPixel, textWidth - 1,
531 textHeight - 1);
532 break;
533 }
534 }
535
536 dirty = false;
537 reallyCleared = false;
538 } // synchronized (screen)
539 }
540
541 } // class SwingFrame
542
543 /**
544 * The raw Swing JFrame. Note package private access.
545 */
546 SwingFrame frame;
547
548 /**
549 * Restore terminal to normal state.
550 */
551 public void shutdown() {
552 frame.dispose();
553 }
554
555 /**
556 * Public constructor.
557 */
558 public SwingScreen() {
559 try {
560 SwingUtilities.invokeAndWait(new Runnable() {
561 public void run() {
562 SwingScreen.this.frame = new SwingFrame(SwingScreen.this);
563 SwingScreen.this.sessionInfo =
564 new SwingSessionInfo(SwingScreen.this.frame,
565 frame.textWidth,
566 frame.textHeight);
567
568 SwingScreen.this.setDimensions(sessionInfo.getWindowWidth(),
569 sessionInfo.getWindowHeight());
570
571 SwingScreen.this.frame.resizeToScreen();
572 SwingScreen.this.frame.setVisible(true);
573 }
574 });
575 } catch (Exception e) {
576 e.printStackTrace();
577 }
578 }
579
580 /**
581 * The sessionInfo.
582 */
583 private SwingSessionInfo sessionInfo;
584
585 /**
586 * Create the SwingSessionInfo. Note package private access.
587 *
588 * @return the sessionInfo
589 */
590 SwingSessionInfo getSessionInfo() {
591 return sessionInfo;
592 }
593
594 /**
595 * Push the logical screen to the physical device.
596 */
597 @Override
598 public void flushPhysical() {
599
600 if (reallyCleared) {
601 // Really refreshed, do it all
602 if (SwingScreen.doubleBuffer) {
603 Graphics gr = frame.bufferStrategy.getDrawGraphics();
604 frame.paint(gr);
605 gr.dispose();
606 frame.bufferStrategy.show();
607 Toolkit.getDefaultToolkit().sync();
608 } else {
609 frame.repaint();
610 }
611 return;
612 }
613
614 // Do nothing if nothing happened.
615 if (!dirty) {
616 return;
617 }
618
619 // Request a repaint, let the frame's repaint/update methods do the
620 // right thing.
621
622 // Find the minimum-size damaged region.
623 int xMin = frame.getWidth();
624 int xMax = 0;
625 int yMin = frame.getHeight();
626 int yMax = 0;
627
628 synchronized (this) {
629 for (int y = 0; y < height; y++) {
630 for (int x = 0; x < width; x++) {
631 Cell lCell = logical[x][y];
632 Cell pCell = physical[x][y];
633
634 int xPixel = x * frame.textWidth + frame.left;
635 int yPixel = y * frame.textHeight + frame.top;
636
637 if (!lCell.equals(pCell)
638 || ((x == cursorX)
639 && (y == cursorY)
640 && cursorVisible)
641 || lCell.isBlink()
642 ) {
643 if (xPixel < xMin) {
644 xMin = xPixel;
645 }
646 if (xPixel + frame.textWidth > xMax) {
647 xMax = xPixel + frame.textWidth;
648 }
649 if (yPixel < yMin) {
650 yMin = yPixel;
651 }
652 if (yPixel + frame.textHeight > yMax) {
653 yMax = yPixel + frame.textHeight;
654 }
655 }
656 }
657 }
658 }
659 if (xMin + frame.textWidth >= xMax) {
660 xMax += frame.textWidth;
661 }
662 if (yMin + frame.textHeight >= yMax) {
663 yMax += frame.textHeight;
664 }
665
666 // Repaint the desired area
667 // System.err.printf("REPAINT X %d %d Y %d %d\n", xMin, xMax,
668 // yMin, yMax);
669 if (SwingScreen.doubleBuffer) {
670 Graphics gr = frame.bufferStrategy.getDrawGraphics();
671 Rectangle bounds = new Rectangle(xMin, yMin, xMax - xMin,
672 yMax - yMin);
673 gr.setClip(bounds);
674 frame.paint(gr);
675 gr.dispose();
676 frame.bufferStrategy.show();
677 Toolkit.getDefaultToolkit().sync();
678 } else {
679 frame.repaint(xMin, yMin, xMax - xMin, yMax - yMin);
680 }
681 }
682
683 /**
684 * Put the cursor at (x,y).
685 *
686 * @param visible if true, the cursor should be visible
687 * @param x column coordinate to put the cursor on
688 * @param y row coordinate to put the cursor on
689 */
690 @Override
691 public void putCursor(final boolean visible, final int x, final int y) {
692
693 if ((visible == cursorVisible) && ((x == cursorX) && (y == cursorY))) {
694 // See if it is time to flip the blink time.
695 long nowTime = (new Date()).getTime();
696 if (nowTime < frame.blinkMillis + frame.lastBlinkTime) {
697 // Nothing has changed, so don't do anything.
698 return;
699 }
700 }
701
702 if (cursorVisible
703 && (cursorY <= height - 1)
704 && (cursorX <= width - 1)
705 ) {
706 // Make the current cursor position dirty
707 if (physical[cursorX][cursorY].getChar() == 'Q') {
708 physical[cursorX][cursorY].setChar('X');
709 } else {
710 physical[cursorX][cursorY].setChar('Q');
711 }
712 }
713
714 super.putCursor(visible, x, y);
715 }
716
717 /**
718 * Convert pixel column position to text cell column position.
719 *
720 * @param x pixel column position
721 * @return text cell column position
722 */
723 public int textColumn(final int x) {
724 return ((x - frame.left) / frame.textWidth);
725 }
726
727 /**
728 * Convert pixel row position to text cell row position.
729 *
730 * @param y pixel row position
731 * @return text cell row position
732 */
733 public int textRow(final int y) {
734 return ((y - frame.top) / frame.textHeight);
735 }
736
737 }