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