JAL-3048 DialogRunner changes (wip)
[jalview.git] / src / jalview / io / JalviewFileChooser.java
index 6838824..73a99e3 100755 (executable)
 package jalview.io;
 
 import jalview.bin.Cache;
+import jalview.bin.Jalview;
 import jalview.gui.JvOptionPane;
 import jalview.util.MessageManager;
 import jalview.util.Platform;
 import jalview.util.dialogrunner.DialogRunner;
 import jalview.util.dialogrunner.DialogRunnerI;
-import jalview.util.dialogrunner.Response;
 import jalview.util.dialogrunner.RunResponse;
 
 import java.awt.Component;
@@ -61,11 +61,87 @@ import javax.swing.plaf.basic.BasicFileChooserUI;
  * @author AMW
  *
  */
-public class JalviewFileChooser extends JFileChooser
-        implements PropertyChangeListener, DialogRunnerI
+public class JalviewFileChooser extends JFileChooser implements DialogRunnerI,
+    PropertyChangeListener
 {
-  DialogRunner<JalviewFileChooser> runner = new DialogRunner<>(this);
+  private DialogRunnerI runner = new DialogRunner();
   
+  File selectedFile = null;
+
+  /**
+   * On user selecting a file to save to, this response is run to check if the
+   * file already exists, and if so show a dialog to prompt for confirmation of
+   * overwrite.
+   */
+  RunResponse overwriteCheck = new RunResponse(JalviewFileChooser.APPROVE_OPTION)
+  {
+    @Override
+    public void run()
+       {
+           selectedFile = getSelectedFile();
+       
+           if (selectedFile == null)
+           {
+             // Workaround for Java 9,10 on OSX - no selected file, but there is a
+             // filename typed in
+             // TODO is this needed in Java 8 or 11?
+             try
+             {
+               String filename = ((BasicFileChooserUI) getUI()).getFileName();
+               if (filename != null && filename.length() > 0)
+               {
+                 selectedFile = new File(getCurrentDirectory(), filename);
+               }
+             } catch (Throwable x)
+             {
+               System.err.println(
+                       "Unexpected exception when trying to get filename.");
+               x.printStackTrace();
+             }
+           }
+           if (selectedFile == null)
+           {
+             setReturnValue(JalviewFileChooser.CANCEL_OPTION);
+             return;
+           }
+           // JBP Note - this code was executed regardless of 'SAVE' being pressed
+           // need to see if there were side effects
+           if (getFileFilter() instanceof JalviewFileFilter)
+           {
+             JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
+       
+             if (!jvf.accept(getSelectedFile()))
+             {
+               String withExtension = getSelectedFile() + "."
+                       + jvf.getAcceptableExtension();
+               setSelectedFile(new File(withExtension));
+             }
+           }
+           // All good, so we continue to save
+           setReturnValue(JalviewFileChooser.APPROVE_OPTION);
+       
+           // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND THE
+           // USER PROMPTED FOR A NEW FILENAME
+           if (!Jalview.isJS())
+           {
+             if (getSelectedFile().exists())
+             {
+               // JAL-3048 - may not need to raise this for browser saves
+               // yes/no cancel
+               int confirm = JvOptionPane.showConfirmDialog(JalviewFileChooser.this,
+                       MessageManager.getString("label.overwrite_existing_file"),
+                       MessageManager.getString("label.file_already_exists"),
+                 JvOptionPane.YES_NO_OPTION);
+       
+             if (confirm != JvOptionPane.YES_OPTION)
+             {
+                  setReturnValue(JalviewFileChooser.CANCEL_OPTION);
+                }
+              }
+            }
+       };
+  };
+
   /**
    * Factory method to return a file chooser that offers readable alignment file
    * formats
@@ -146,7 +222,7 @@ public class JalviewFileChooser extends JFileChooser
   }
 
   JalviewFileChooser(String dir, String[] extensions, String[] descs,
-          String selected, boolean allFiles)
+          String selected, boolean acceptAny)
   {
     super(safePath(dir));
     if (extensions.length == descs.length)
@@ -156,7 +232,7 @@ public class JalviewFileChooser extends JFileChooser
       {
         formats.add(new String[] { extensions[i], descs[i] });
       }
-      init(formats, selected, allFiles);
+      init(formats, selected, acceptAny);
     }
     else
     {
@@ -165,18 +241,6 @@ public class JalviewFileChooser extends JFileChooser
     }
   }
 
-  @Override
-  public void propertyChange(PropertyChangeEvent evt)
-  {
-    // TODO other properties need runners...
-    switch (evt.getPropertyName())
-    {
-    case "SelectedFile": 
-      runner.run(APPROVE_OPTION);
-      break;
-    }
-  }
-
   private static File safePath(String dir)
   {
     if (dir == null)
@@ -200,13 +264,11 @@ public class JalviewFileChooser extends JFileChooser
   @Override
   public int showOpenDialog(Component parent)
   {
-    runner.resetResponses();
+   // runner.resetResponses();
     int value = super.showOpenDialog(this);
-    /**
-     * @j2sNative
-     */
+    if (!Jalview.isJS())
     {
-      runner.firstRun(value);
+      runner.handleResponse(value);
     }
     return value;
   }
@@ -216,17 +278,17 @@ public class JalviewFileChooser extends JFileChooser
    * @param formats
    *          a list of {extensions, description} for each file format
    * @param selected
-   * @param allFiles
+   * @param acceptAny
    *          if true, 'any format' option is included
    */
-  void init(List<String[]> formats, String selected, boolean allFiles)
+  void init(List<String[]> formats, String selected, boolean acceptAny)
   {
 
     JalviewFileFilter chosen = null;
 
     // SelectAllFilter needs to be set first before adding further
     // file filters to fix bug on Mac OSX
-    setAcceptAllFileFilterUsed(allFiles);
+    setAcceptAllFileFilterUsed(acceptAny);
 
     for (String[] format : formats)
     {
@@ -317,93 +379,14 @@ public class JalviewFileChooser extends JFileChooser
     }
     return null;
   }
-  
-  File ourselectedFile = null;
 
   @Override
   public File getSelectedFile()
   {
-    File selfile = super.getSelectedFile();
-    if (selfile == null && ourselectedFile != null)
-    {
-      return ourselectedFile;
-    }
-    return selfile;
+    File f = super.getSelectedFile();
+    return f == null ? selectedFile : f;
   }
 
-  Component saveparent;
-  RunResponse overwriteCheck = new RunResponse(
-          JalviewFileChooser.APPROVE_OPTION)
-  {
-    @Override
-    public void run()
-    {
-    ourselectedFile = getSelectedFile();
-
-    if (getSelectedFile() == null)
-    {
-      // Workaround for Java 9,10 on OSX - no selected file, but there is a
-      // filename typed in
-      try
-      {
-        String filename = ((BasicFileChooserUI) getUI()).getFileName();
-        if (filename != null && filename.length() > 0)
-        {
-          ourselectedFile = new File(getCurrentDirectory(), filename);
-        }
-      } catch (Throwable x)
-      {
-        System.err.println(
-                "Unexpected exception when trying to get filename.");
-        x.printStackTrace();
-      }
-    }
-    if (ourselectedFile == null)
-    {
-      returned = new Response(JalviewFileChooser.CANCEL_OPTION);
-      return;
-    }
-      // JBP Note - this code was executed regardless of 'SAVE' being pressed
-      // need to see if there were side effects
-      if (getFileFilter() instanceof JalviewFileFilter)
-      {
-        JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
-
-        if (!jvf.accept(getSelectedFile()))
-        {
-          String withExtension = getSelectedFile() + "."
-                  + jvf.getAcceptableExtension();
-          setSelectedFile(new File(withExtension));
-        }
-      }
-      // All good, so we continue to save
-      returned = new Response(JalviewFileChooser.APPROVE_OPTION);
-
-      // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND THE
-      // USER PROMPTED FOR A NEW FILENAME
-      /**
-       * @j2sNative
-       */
-      {
-        if (getSelectedFile().exists())
-        {
-          // JAL-3048 - may not need to raise this for browser saves
-
-          // yes/no cancel
-          int confirm = JvOptionPane.showConfirmDialog(saveparent,
-                  MessageManager.getString("label.overwrite_existing_file"),
-                  MessageManager.getString("label.file_already_exists"),
-                  JvOptionPane.YES_NO_OPTION);
-
-          if (confirm != JvOptionPane.YES_OPTION)
-          {
-            returned = new Response(JalviewFileChooser.CANCEL_OPTION);
-          }
-        }
-      }
-    };
-  };
-
   /**
    * Overridden for JalviewJS compatibility: only one thread in Javascript, 
    * so we can't wait for user choice in another thread and then perform the 
@@ -417,30 +400,28 @@ public class JalviewFileChooser extends JFileChooser
     /*
      * Save dialog is opened until user picks a file format 
      */
+    /*
     if (!runner.isRegistered(overwriteCheck))
     {
       // first call for this instance
-      runner.firstResponse(overwriteCheck);
+      runner.setFirstResponse(overwriteCheck);
     }
     else
     {
       // reset response flags
       runner.resetResponses();
     }
-
-    setDialogType(SAVE_DIALOG);
+*/
+ //   runner.addResponse(overwriteCheck);
+//    setDialogType(SAVE_DIALOG);
     
     // Java 9,10,11 on OSX - clear selected file so name isn't auto populated
     this.setSelectedFile(null);
  
-    saveparent = parent;
-
-    int value = showDialog(parent, MessageManager.getString("action.save"));
-    /**
-     * @j2sNative
-     */
+    int value = super.showSaveDialog(parent);//, MessageManager.getString("action.save"));
+    if (!Jalview.isJS())
     {
-      runner.firstRun(value);
+      runner.handleResponse(value);
     }
     return value;
   }
@@ -538,9 +519,48 @@ public class JalviewFileChooser extends JFileChooser
   }
 
   @Override
-  public JalviewFileChooser addResponse(RunResponse action)
+  public DialogRunnerI addResponse(RunResponse action)
   {
     return runner.addResponse(action);
   }
 
+  /**
+   * JalviewJS signals file selection by a property change event
+   * for property "SelectedFile".  This methods responds to that by
+   * running the response action for 'OK' in the dialog.
+   * 
+   * @param evt
+   */
+  @Override
+  public void propertyChange(PropertyChangeEvent evt)
+  {
+    // TODO other properties need runners...
+    switch (evt.getPropertyName())
+    {
+    case "SelectedFile": 
+      runner.handleResponse(APPROVE_OPTION);
+      break;
+    }
+  }
+
+       @Override
+       public void approveSelection() 
+       {
+               if (getDialogType() == SAVE_DIALOG && !Jalview.isJS()) 
+               {
+                       File selectedFile = getSelectedFile();
+                       if ((selectedFile != null) && selectedFile.exists()) 
+                       {
+                               int confirm = JvOptionPane.showConfirmDialog(this,
+                                               MessageManager.getString("label.overwrite_existing_file"),
+                                               MessageManager.getString("label.file_already_exists"), JvOptionPane.YES_NO_OPTION);
+       
+                               if (confirm != JvOptionPane.YES_OPTION) 
+                               {
+                                       return;
+                               }
+                       }
+               }
+               super.approveSelection();
+       }
 }