Fix Swing triple-buffering
[nikiroo-utils.git] / src / jexer / TApplication.java
index a37cf03d7382fe564562a2faa06059c5be900c2c..e9a7a44c62ddb4c9cd53b17a3ca7eee35e8985b8 100644 (file)
@@ -1,29 +1,27 @@
-/**
+/*
  * 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;
 
 import java.io.InputStream;
+import java.io.IOException;
 import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.io.Reader;
 import java.io.UnsupportedEncodingException;
 import java.util.Collections;
 import java.util.Date;
@@ -88,7 +89,7 @@ public class TApplication implements Runnable {
         ECMA48,
 
         /**
-         * Synonym for ECMA48
+         * Synonym for ECMA48.
          */
         XTERM
     }
@@ -429,6 +430,11 @@ public class TApplication implements Runnable {
      */
     private Map<TKeypress, TMenuItem> accelerators;
 
+    /**
+     * All menu items.
+     */
+    private List<TMenuItem> menuItems;
+
     /**
      * Windows and widgets pull colors from this ColorTheme.
      */
@@ -512,6 +518,10 @@ public class TApplication implements Runnable {
             // Fall through...
         case ECMA48:
             backend = new ECMA48Backend(this, null, null);
+            break;
+        default:
+            throw new IllegalArgumentException("Invalid backend type: "
+                + backendType);
         }
         TApplicationImpl();
     }
@@ -536,6 +546,40 @@ public class TApplication implements Runnable {
         TApplicationImpl();
     }
 
+    /**
+     * Public constructor.  The backend type will be BackendType.ECMA48.
+     *
+     * @param input the InputStream underlying 'reader'.  Its available()
+     * method is used to determine if reader.read() will block or not.
+     * @param reader a Reader connected to the remote user.
+     * @param writer a PrintWriter connected to the remote user.
+     * @param setRawMode if true, set System.in into raw mode with stty.
+     * This should in general not be used.  It is here solely for Demo3,
+     * which uses System.in.
+     * @throws IllegalArgumentException if input, reader, or writer are null.
+     */
+    public TApplication(final InputStream input, final Reader reader,
+        final PrintWriter writer, final boolean setRawMode) {
+
+        backend = new ECMA48Backend(this, input, reader, writer, setRawMode);
+        TApplicationImpl();
+    }
+
+    /**
+     * Public constructor.  The backend type will be BackendType.ECMA48.
+     *
+     * @param input the InputStream underlying 'reader'.  Its available()
+     * method is used to determine if reader.read() will block or not.
+     * @param reader a Reader connected to the remote user.
+     * @param writer a PrintWriter connected to the remote user.
+     * @throws IllegalArgumentException if input, reader, or writer are null.
+     */
+    public TApplication(final InputStream input, final Reader reader,
+        final PrintWriter writer) {
+
+        this(input, reader, writer, false);
+    }
+
     /**
      * Public constructor.  This hook enables use with new non-Jexer
      * backends.
@@ -560,6 +604,7 @@ public class TApplication implements Runnable {
         subMenus        = new LinkedList<TMenu>();
         timers          = new LinkedList<TTimer>();
         accelerators    = new HashMap<TKeypress, TMenuItem>();
+        menuItems       = new ArrayList<TMenuItem>();
 
         // Setup the main consumer thread
         primaryEventHandler = new WidgetEventHandler(this, true);
@@ -573,12 +618,13 @@ public class TApplication implements Runnable {
      * @param y row position
      */
     private void invertCell(final int x, final int y) {
-        synchronized (getScreen()) {
-            CellAttributes attr = getScreen().getAttrXY(x, y);
-            attr.setForeColor(attr.getForeColor().invert());
-            attr.setBackColor(attr.getBackColor().invert());
-            getScreen().putAttrXY(x, y, attr, false);
+        if (debugThreads) {
+            System.err.printf("invertCell() %d %d\n", x, y);
         }
+        CellAttributes attr = getScreen().getAttrXY(x, y);
+        attr.setForeColor(attr.getForeColor().invert());
+        attr.setBackColor(attr.getBackColor().invert());
+        getScreen().putAttrXY(x, y, attr, false);
     }
 
     /**
@@ -590,18 +636,23 @@ public class TApplication implements Runnable {
         }
 
         if (!repaint) {
-            if ((oldMouseX != mouseX) || (oldMouseY != mouseY)) {
-                // The only thing that has happened is the mouse moved.
-                // Clear the old position and draw the new position.
-                invertCell(oldMouseX, oldMouseY);
-                invertCell(mouseX, mouseY);
-                oldMouseX = mouseX;
-                oldMouseY = mouseY;
+            if (debugThreads) {
+                System.err.printf("drawAll() !repaint\n");
             }
-            if (getScreen().isDirty()) {
-                backend.flushScreen();
+            synchronized (getScreen()) {
+                if ((oldMouseX != mouseX) || (oldMouseY != mouseY)) {
+                    // The only thing that has happened is the mouse moved.
+                    // Clear the old position and draw the new position.
+                    invertCell(oldMouseX, oldMouseY);
+                    invertCell(mouseX, mouseY);
+                    oldMouseX = mouseX;
+                    oldMouseY = mouseY;
+                }
+                if (getScreen().isDirty()) {
+                    backend.flushScreen();
+                }
+                return;
             }
-            return;
         }
 
         if (debugThreads) {
@@ -646,7 +697,7 @@ public class TApplication implements Runnable {
             // Draw the menu title
             getScreen().hLineXY(x, 0, menu.getTitle().length() + 2, ' ',
                 menuColor);
-            getScreen().putStrXY(x + 1, 0, menu.getTitle(), menuColor);
+            getScreen().putStringXY(x + 1, 0, menu.getTitle(), menuColor);
             // Draw the highlight character
             getScreen().putCharXY(x + 1 + menu.getMnemonic().getShortcutIdx(),
                 0, menu.getMnemonic().getShortcut(), menuMnemonicColor);
@@ -667,6 +718,8 @@ public class TApplication implements Runnable {
 
         // Draw the mouse pointer
         invertCell(mouseX, mouseY);
+        oldMouseX = mouseX;
+        oldMouseY = mouseY;
 
         // Place the cursor if it is visible
         TWidget activeWidget = null;
@@ -685,7 +738,9 @@ public class TApplication implements Runnable {
         }
 
         // Flush the screen contents
-        backend.flushScreen();
+        if (getScreen().isDirty()) {
+            backend.flushScreen();
+        }
 
         repaint = false;
     }
@@ -979,7 +1034,8 @@ public class TApplication implements Runnable {
     public final void enableSecondaryEventReceiver(final TWidget widget) {
         assert (secondaryEventReceiver == null);
         assert (secondaryEventHandler == null);
-        assert (widget instanceof TMessageBox);
+        assert ((widget instanceof TMessageBox)
+            || (widget instanceof TFileOpenBox));
         secondaryEventReceiver = widget;
         secondaryEventHandler = new WidgetEventHandler(this, false);
         (new Thread(secondaryEventHandler)).start();
@@ -995,7 +1051,7 @@ public class TApplication implements Runnable {
         // secondary thread locks again.  When it gives up, we have the
         // single lock back.
         boolean oldLock = unlockHandleEvent();
-        assert (oldLock == true);
+        assert (oldLock);
 
         while (secondaryEventReceiver != null) {
             synchronized (primaryEventHandler) {
@@ -1073,6 +1129,7 @@ public class TApplication implements Runnable {
         synchronized (windows) {
             int z = window.getZ();
             window.setZ(-1);
+            window.onUnfocus();
             Collections.sort(windows);
             windows.remove(0);
             TWindow activeWindow = null;
@@ -1081,10 +1138,14 @@ public class TApplication implements Runnable {
                     w.setZ(w.getZ() - 1);
                     if (w.getZ() == 0) {
                         w.setActive(true);
+                        w.onFocus();
                         assert (activeWindow == null);
                         activeWindow = w;
                     } else {
-                        w.setActive(false);
+                        if (w.isActive()) {
+                            w.setActive(false);
+                            w.onUnfocus();
+                        }
                     }
                 }
             }
@@ -1150,8 +1211,10 @@ public class TApplication implements Runnable {
             }
             windows.get(activeWindowI).setActive(false);
             windows.get(activeWindowI).setZ(windows.get(nextWindowI).getZ());
+            windows.get(activeWindowI).onUnfocus();
             windows.get(nextWindowI).setZ(0);
             windows.get(nextWindowI).setActive(true);
+            windows.get(nextWindowI).onFocus();
 
         } // synchronized (windows)
 
@@ -1169,12 +1232,16 @@ public class TApplication implements Runnable {
                 assert (window.isModal());
             }
             for (TWindow w: windows) {
-                w.setActive(false);
+                if (w.isActive()) {
+                    w.setActive(false);
+                    w.onUnfocus();
+                }
                 w.setZ(w.getZ() + 1);
             }
             windows.add(window);
-            window.setActive(true);
             window.setZ(0);
+            window.setActive(true);
+            window.onFocus();
         }
     }
 
@@ -1318,10 +1385,12 @@ public class TApplication implements Runnable {
                     // We will be switching to another window
                     assert (windows.get(0).isActive());
                     assert (!window.isActive());
+                    windows.get(0).onUnfocus();
                     windows.get(0).setActive(false);
                     windows.get(0).setZ(window.getZ());
                     window.setZ(0);
                     window.setActive(true);
+                    window.onFocus();
                     return;
                 }
             }
@@ -1498,17 +1567,76 @@ public class TApplication implements Runnable {
     }
 
     /**
-     * Add a keyboard accelerator to the global hash.
+     * Add a menu item to the global list.  If it has a keyboard accelerator,
+     * that will be added the global hash.
+     *
+     * @param item the menu item
+     */
+    public final void addMenuItem(final TMenuItem item) {
+        menuItems.add(item);
+
+        TKeypress key = item.getKey();
+        if (key != null) {
+            synchronized (accelerators) {
+                assert (accelerators.get(key) == null);
+                accelerators.put(key.toLowerCase(), item);
+            }
+        }
+    }
+
+    /**
+     * Disable one menu item.
      *
-     * @param item menu item this accelerator relates to
-     * @param keypress keypress that will dispatch a TMenuEvent
+     * @param id the menu item ID
      */
-    public final void addAccelerator(final TMenuItem item,
-        final TKeypress keypress) {
+    public final void disableMenuItem(final int id) {
+        for (TMenuItem item: menuItems) {
+            if (item.getId() == id) {
+                item.setEnabled(false);
+            }
+        }
+    }
 
-        synchronized (accelerators) {
-            assert (accelerators.get(keypress) == null);
-            accelerators.put(keypress, item);
+    /**
+     * Disable the range of menu items with ID's between lower and upper,
+     * inclusive.
+     *
+     * @param lower the lowest menu item ID
+     * @param upper the highest menu item ID
+     */
+    public final void disableMenuItems(final int lower, final int upper) {
+        for (TMenuItem item: menuItems) {
+            if ((item.getId() >= lower) && (item.getId() <= upper)) {
+                item.setEnabled(false);
+            }
+        }
+    }
+
+    /**
+     * Enable one menu item.
+     *
+     * @param id the menu item ID
+     */
+    public final void enableMenuItem(final int id) {
+        for (TMenuItem item: menuItems) {
+            if (item.getId() == id) {
+                item.setEnabled(true);
+            }
+        }
+    }
+
+    /**
+     * Enable the range of menu items with ID's between lower and upper,
+     * inclusive.
+     *
+     * @param lower the lowest menu item ID
+     * @param upper the highest menu item ID
+     */
+    public final void enableMenuItems(final int lower, final int upper) {
+        for (TMenuItem item: menuItems) {
+            if ((item.getId() >= lower) && (item.getId() <= upper)) {
+                item.setEnabled(true);
+            }
         }
     }
 
@@ -1820,4 +1948,32 @@ public class TApplication implements Runnable {
         return new TTerminalWindow(this, x, y, flags);
     }
 
+    /**
+     * Convenience function to spawn an file open box.
+     *
+     * @param path path of selected file
+     * @return the result of the new file open box
+     * @throws IOException if java.io operation throws
+     */
+    public final String fileOpenBox(final String path) throws IOException {
+
+        TFileOpenBox box = new TFileOpenBox(this, path, TFileOpenBox.Type.OPEN);
+        return box.getFilename();
+    }
+
+    /**
+     * Convenience function to spawn an file open box.
+     *
+     * @param path path of selected file
+     * @param type one of the Type constants
+     * @return the result of the new file open box
+     * @throws IOException if java.io operation throws
+     */
+    public final String fileOpenBox(final String path,
+        final TFileOpenBox.Type type) throws IOException {
+
+        TFileOpenBox box = new TFileOpenBox(this, path, type);
+        return box.getFilename();
+    }
+
 }