JAL-629 Add a timeout to modal dialogs for command line warning
[jalview.git] / src / jalview / gui / JvOptionPane.java
index 3f5de0a..0a7c49e 100644 (file)
@@ -88,6 +88,13 @@ public class JvOptionPane extends JOptionPane
 
   private Map<Object, Runnable> callbacks = new HashMap<>();
 
+  private int timeout = -1;
+
+  public void setTimeout(int i)
+  {
+    timeout = i;
+  }
+
   /*
    * JalviewJS reports user choice in the dialog as the selected option (text);
    * this list allows conversion to index (int)
@@ -851,6 +858,38 @@ public class JvOptionPane extends JOptionPane
                   "Supplied buttons array not the same length as supplied options array.");
           break NOTNULL;
         }
+
+        // run through buttons for initialValue first so can set a final
+        // timeoutThreadF
+        Thread timeoutThread = null;
+        for (int i = 0; i < options.length; i++)
+        {
+          Object o = options[i];
+          JButton jb = buttons[i];
+          if (o.equals(initialValue))
+          {
+            initialValueButton = jb;
+            if (timeout > 0 && initialValueButton != null
+                    && initialValueButton instanceof JButton)
+            {
+              Runnable timeoutClose = () -> {
+                try
+                {
+                  Thread.sleep(timeout);
+                } catch (InterruptedException e)
+                {
+                  Console.debug(
+                          "Dialog timeout interrupted.  Probably a button pressed.");
+                }
+                jb.doClick();
+              };
+              timeoutThread = new Thread(timeoutClose);
+            }
+          }
+        }
+        final Thread timeoutThreadF = timeoutThread;
+        timeoutThreadF.start();
+
         int[] buttonActions = { JOptionPane.YES_OPTION,
             JOptionPane.NO_OPTION, JOptionPane.CANCEL_OPTION };
         for (int i = 0; i < options.length; i++)
@@ -860,9 +899,6 @@ public class JvOptionPane extends JOptionPane
                   "Setting button " + i + " to '" + o.toString() + "'");
           JButton jb = buttons[i];
 
-          if (o.equals(initialValue))
-            initialValueButton = jb;
-
           int buttonAction = buttonActions[i];
           Runnable action = callbacks.get(buttonAction);
           jb.setText((String) o);
@@ -871,6 +907,10 @@ public class JvOptionPane extends JOptionPane
             @Override
             public void actionPerformed(ActionEvent e)
             {
+              if (timeoutThreadF != null)
+              {
+                timeoutThreadF.interrupt();
+              }
 
               Object obj = e.getSource();
               if (obj == null || !(obj instanceof Component))