LICENSE CHANGED TO MIT
[nikiroo-utils.git] / src / jexer / io / SwingScreen.java
index bdd74a7ca7e47728905f88f9b7bb58947fe83639..1519079d50b68e6578a0d7cf060763ba1bbaa5b9 100644 (file)
@@ -1,39 +1,33 @@
-/**
+/*
  * Jexer - Java Text User Interface
  *
- * License: LGPLv3 or later
- *
- * This module is licensed under the GNU Lesser General Public License
- * Version 3.  Please see the file "COPYING" in this directory for more
- * information about the GNU Lesser General Public License Version 3.
+ * The MIT License (MIT)
  *
- *     Copyright (C) 2015  Kevin Lamonte
+ * Copyright (C) 2016 Kevin Lamonte
  *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public License
- * as published by the Free Software Foundation; either version 3 of
- * the License, or (at your option) any later version.
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
  *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
  *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this program; if not, see
- * http://www.gnu.org/licenses/, or write to the Free Software
- * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
  *
  * @author Kevin Lamonte [kevin.lamonte@gmail.com]
  * @version 1
  */
 package jexer.io;
 
-import jexer.bits.Cell;
-import jexer.bits.CellAttributes;
-import jexer.session.SwingSessionInfo;
-
 import java.awt.Color;
 import java.awt.Cursor;
 import java.awt.Font;
@@ -45,15 +39,46 @@ import java.awt.Rectangle;
 import java.awt.Toolkit;
 import java.awt.geom.Rectangle2D;
 import java.awt.image.BufferedImage;
+import java.awt.image.BufferStrategy;
 import java.io.InputStream;
+import java.util.Date;
 import javax.swing.JFrame;
 import javax.swing.SwingUtilities;
 
+import jexer.bits.Cell;
+import jexer.bits.CellAttributes;
+import jexer.session.SwingSessionInfo;
+
 /**
  * This Screen implementation draws to a Java Swing JFrame.
  */
 public final class SwingScreen extends Screen {
 
+    /**
+     * If true, use double buffering thread.
+     */
+    private static final boolean doubleBuffer = true;
+
+    /**
+     * Cursor style to draw.
+     */
+    public enum CursorStyle {
+        /**
+         * Use an underscore for the cursor.
+         */
+        UNDERLINE,
+
+        /**
+         * Use a solid block for the cursor.
+         */
+        BLOCK,
+
+        /**
+         * Use an outlined block for the cursor.
+         */
+        OUTLINE
+    }
+
     private static Color MYBLACK;
     private static Color MYRED;
     private static Color MYGREEN;
@@ -116,6 +141,11 @@ public final class SwingScreen extends Screen {
          */
         private static final String FONTFILE = "terminus-ttf-4.39/TerminusTTF-Bold-4.39.ttf";
 
+        /**
+         * The BufferStrategy object needed for double-buffering.
+         */
+        private BufferStrategy bufferStrategy;
+
         /**
          * The TUI Screen data.
          */
@@ -137,15 +167,48 @@ public final class SwingScreen extends Screen {
         private int maxDescent = 0;
 
         /**
-         * Top pixel value.
+         * System-dependent Y adjustment for text in the  character cell.
+         */
+        private int textAdjustY = 0;
+
+        /**
+         * System-dependent X adjustment for text in the  character cell.
+         */
+        private int textAdjustX = 0;
+
+        /**
+         * Top pixel absolute location.
          */
         private int top = 30;
 
         /**
-         * Left pixel value.
+         * Left pixel absolute location.
          */
         private int left = 30;
 
+        /**
+         * The cursor style to draw.
+         */
+        private CursorStyle cursorStyle = CursorStyle.UNDERLINE;
+
+        /**
+         * The number of millis to wait before switching the blink from
+         * visible to invisible.
+         */
+        private long blinkMillis = 500;
+
+        /**
+         * If true, the cursor should be visible right now based on the blink
+         * time.
+         */
+        private boolean cursorBlinkVisible = true;
+
+        /**
+         * The time that the blink last flipped from visible to invisible or
+         * from invisible to visible.
+         */
+        private long lastBlinkTime = 0;
+
         /**
          * Convert a CellAttributes foreground color to an Swing Color.
          *
@@ -153,12 +216,6 @@ public final class SwingScreen extends Screen {
          * @return the Swing Color
          */
         private Color attrToForegroundColor(final CellAttributes attr) {
-            /*
-             * TODO:
-             *   reverse
-             *   blink
-             *   underline
-             */
             if (attr.isBold()) {
                 if (attr.getForeColor().equals(jexer.bits.Color.BLACK)) {
                     return MYBOLD_BLACK;
@@ -206,12 +263,6 @@ public final class SwingScreen extends Screen {
          * @return the Swing Color
          */
         private Color attrToBackgroundColor(final CellAttributes attr) {
-            /*
-             * TODO:
-             *   reverse
-             *   blink
-             *   underline
-             */
             if (attr.getBackColor().equals(jexer.bits.Color.BLACK)) {
                 return MYBLACK;
             } else if (attr.getBackColor().equals(jexer.bits.Color.RED)) {
@@ -241,11 +292,20 @@ public final class SwingScreen extends Screen {
             this.screen = screen;
             setDOSColors();
 
+            // Figure out my cursor style
+            String cursorStyleString = System.getProperty("jexer.Swing.cursorStyle",
+                "underline").toLowerCase();
+
+            if (cursorStyleString.equals("underline")) {
+                cursorStyle = CursorStyle.UNDERLINE;
+            } else if (cursorStyleString.equals("outline")) {
+                cursorStyle = CursorStyle.OUTLINE;
+            } else if (cursorStyleString.equals("block")) {
+                cursorStyle = CursorStyle.BLOCK;
+            }
+
             setTitle("Jexer Application");
             setBackground(Color.black);
-            // setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
-            // setFont(new Font("Liberation Mono", Font.BOLD, 16));
-            // setFont(new Font(Font.MONOSPACED, Font.PLAIN, 16));
 
             try {
                 // Always try to use Terminus, the one decent font.
@@ -275,6 +335,13 @@ public final class SwingScreen extends Screen {
 
             // Save the text cell width/height
             getFontDimensions();
+
+            // Setup double-buffering
+            if (SwingScreen.doubleBuffer) {
+                setIgnoreRepaint(true);
+                createBufferStrategy(2);
+                bufferStrategy = getBufferStrategy();
+            }
         }
 
         /**
@@ -291,6 +358,11 @@ public final class SwingScreen extends Screen {
             // This also produces the same number, but works better for ugly
             // monospace.
             textHeight = fm.getMaxAscent() + maxDescent - leading;
+
+            if (System.getProperty("os.name").startsWith("Windows")) {
+                textAdjustY = -1;
+                textAdjustX = 0;
+            }
         }
 
         /**
@@ -334,6 +406,13 @@ public final class SwingScreen extends Screen {
                 return;
             }
 
+            // See if it is time to flip the blink time.
+            long nowTime = (new Date()).getTime();
+            if (nowTime > blinkMillis + lastBlinkTime) {
+                lastBlinkTime = nowTime;
+                cursorBlinkVisible = !cursorBlinkVisible;
+            }
+
             int xCellMin = 0;
             int xCellMax = screen.width;
             int yCellMin = 0;
@@ -386,16 +465,40 @@ public final class SwingScreen extends Screen {
                         Cell lCell = screen.logical[x][y];
                         Cell pCell = screen.physical[x][y];
 
-                        if (!lCell.equals(pCell) || reallyCleared) {
+                        if (!lCell.equals(pCell)
+                            || lCell.isBlink()
+                            || reallyCleared) {
+
+                            Cell lCellColor = new Cell();
+                            lCellColor.setTo(lCell);
+
+                            // Check for reverse
+                            if (lCell.isReverse()) {
+                                lCellColor.setForeColor(lCell.getBackColor());
+                                lCellColor.setBackColor(lCell.getForeColor());
+                            }
+
                             // Draw the background rectangle, then the
                             // foreground character.
-                            gr.setColor(attrToBackgroundColor(lCell));
+                            gr.setColor(attrToBackgroundColor(lCellColor));
                             gr.fillRect(xPixel, yPixel, textWidth, textHeight);
-                            gr.setColor(attrToForegroundColor(lCell));
-                            char [] chars = new char[1];
-                            chars[0] = lCell.getChar();
-                            gr.drawChars(chars, 0, 1, xPixel,
-                                yPixel + textHeight - maxDescent);
+
+                            // Handle blink and underline
+                            if (!lCell.isBlink()
+                                || (lCell.isBlink() && cursorBlinkVisible)
+                            ) {
+                                gr.setColor(attrToForegroundColor(lCellColor));
+                                char [] chars = new char[1];
+                                chars[0] = lCell.getChar();
+                                gr.drawChars(chars, 0, 1, xPixel + textAdjustX,
+                                    yPixel + textHeight - maxDescent
+                                    + textAdjustY);
+
+                                if (lCell.isUnderline()) {
+                                    gr.fillRect(xPixel, yPixel + textHeight - 2,
+                                        textWidth, 2);
+                                }
+                            }
 
                             // Physical is always updated
                             physical[x][y].setTo(lCell);
@@ -404,15 +507,30 @@ public final class SwingScreen extends Screen {
                 }
 
                 // Draw the cursor if it is visible
-                if ((cursorVisible)
+                if (cursorVisible
                     && (cursorY <= screen.height - 1)
                     && (cursorX <= screen.width - 1)
+                    && cursorBlinkVisible
                 ) {
                     int xPixel = cursorX * textWidth + left;
                     int yPixel = cursorY * textHeight + top;
                     Cell lCell = screen.logical[cursorX][cursorY];
                     gr.setColor(attrToForegroundColor(lCell));
-                    gr.fillRect(xPixel, yPixel + textHeight - 2, textWidth, 2);
+                    switch (cursorStyle) {
+                    default:
+                        // Fall through...
+                    case UNDERLINE:
+                        gr.fillRect(xPixel, yPixel + textHeight - 2,
+                            textWidth, 2);
+                        break;
+                    case BLOCK:
+                        gr.fillRect(xPixel, yPixel, textWidth, textHeight);
+                        break;
+                    case OUTLINE:
+                        gr.drawRect(xPixel, yPixel, textWidth - 1,
+                            textHeight - 1);
+                        break;
+                    }
                 }
 
                 dirty = false;
@@ -427,6 +545,13 @@ public final class SwingScreen extends Screen {
      */
     SwingFrame frame;
 
+    /**
+     * Restore terminal to normal state.
+     */
+    public void shutdown() {
+        frame.dispose();
+    }
+
     /**
      * Public constructor.
      */
@@ -446,7 +571,7 @@ public final class SwingScreen extends Screen {
                     SwingScreen.this.frame.resizeToScreen();
                     SwingScreen.this.frame.setVisible(true);
                 }
-            } );
+            });
         } catch (Exception e) {
             e.printStackTrace();
         }
@@ -474,7 +599,15 @@ public final class SwingScreen extends Screen {
 
         if (reallyCleared) {
             // Really refreshed, do it all
-            frame.repaint();
+            if (SwingScreen.doubleBuffer) {
+                Graphics gr = frame.bufferStrategy.getDrawGraphics();
+                frame.paint(gr);
+                gr.dispose();
+                frame.bufferStrategy.show();
+                Toolkit.getDefaultToolkit().sync();
+            } else {
+                frame.repaint();
+            }
             return;
         }
 
@@ -505,6 +638,7 @@ public final class SwingScreen extends Screen {
                         || ((x == cursorX)
                             && (y == cursorY)
                             && cursorVisible)
+                        || lCell.isBlink()
                     ) {
                         if (xPixel < xMin) {
                             xMin = xPixel;
@@ -530,8 +664,20 @@ public final class SwingScreen extends Screen {
         }
 
         // Repaint the desired area
-        frame.repaint(xMin, yMin, xMax - xMin, yMax - yMin);
-        // System.err.printf("REPAINT X %d %d Y %d %d\n", xMin, xMax, yMin, yMax);
+        // System.err.printf("REPAINT X %d %d Y %d %d\n", xMin, xMax,
+        //     yMin, yMax);
+        if (SwingScreen.doubleBuffer) {
+            Graphics gr = frame.bufferStrategy.getDrawGraphics();
+            Rectangle bounds = new Rectangle(xMin, yMin, xMax - xMin,
+                yMax - yMin);
+            gr.setClip(bounds);
+            frame.paint(gr);
+            gr.dispose();
+            frame.bufferStrategy.show();
+            Toolkit.getDefaultToolkit().sync();
+        } else {
+            frame.repaint(xMin, yMin, xMax - xMin, yMax - yMin);
+        }
     }
 
     /**
@@ -543,7 +689,17 @@ public final class SwingScreen extends Screen {
      */
     @Override
     public void putCursor(final boolean visible, final int x, final int y) {
-        if ((cursorVisible)
+
+        if ((visible == cursorVisible) && ((x == cursorX) && (y == cursorY))) {
+            // See if it is time to flip the blink time.
+            long nowTime = (new Date()).getTime();
+            if (nowTime < frame.blinkMillis + frame.lastBlinkTime) {
+                // Nothing has changed, so don't do anything.
+                return;
+            }
+        }
+
+        if (cursorVisible
             && (cursorY <= height - 1)
             && (cursorX <= width - 1)
         ) {