Merge branch 'feature/JAL-3169cancelOverwrite' into develop
[jalview.git] / src / jalview / io / JalviewFileChooser.java
index 052cf68..7fbe801 100755 (executable)
@@ -30,21 +30,27 @@ import java.awt.Component;
 import java.awt.Dimension;
 import java.awt.EventQueue;
 import java.awt.HeadlessException;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
 import java.io.File;
-import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.StringTokenizer;
 import java.util.Vector;
 
+import javax.swing.BoxLayout;
 import javax.swing.DefaultListCellRenderer;
+import javax.swing.JCheckBox;
 import javax.swing.JFileChooser;
 import javax.swing.JList;
 import javax.swing.JPanel;
 import javax.swing.JScrollPane;
 import javax.swing.SpringLayout;
+import javax.swing.SwingUtilities;
+import javax.swing.border.TitledBorder;
+import javax.swing.filechooser.FileFilter;
 import javax.swing.plaf.basic.BasicFileChooserUI;
 
 /**
@@ -59,6 +65,14 @@ import javax.swing.plaf.basic.BasicFileChooserUI;
 public class JalviewFileChooser extends JFileChooser
 {
   /**
+   * backupfilesCheckBox = "Include backup files" checkbox includeBackupfiles =
+   * flag set by checkbox
+   */
+  private JCheckBox backupfilesCheckBox = null;
+
+  protected boolean includeBackupFiles = false;
+
+  /**
    * Factory method to return a file chooser that offers readable alignment file
    * formats
    * 
@@ -69,6 +83,12 @@ public class JalviewFileChooser extends JFileChooser
   public static JalviewFileChooser forRead(String directory,
           String selected)
   {
+    return JalviewFileChooser.forRead(directory, selected, false);
+  }
+
+  public static JalviewFileChooser forRead(String directory,
+          String selected, boolean allowBackupFiles)
+  {
     List<String> extensions = new ArrayList<>();
     List<String> descs = new ArrayList<>();
     for (FileFormatI format : FileFormats.getInstance().getFormats())
@@ -79,9 +99,11 @@ public class JalviewFileChooser extends JFileChooser
         descs.add(format.getName());
       }
     }
+
     return new JalviewFileChooser(directory,
             extensions.toArray(new String[extensions.size()]),
-            descs.toArray(new String[descs.size()]), selected, true);
+            descs.toArray(new String[descs.size()]), selected, true,
+            allowBackupFiles);
   }
 
   /**
@@ -140,6 +162,12 @@ public class JalviewFileChooser extends JFileChooser
   JalviewFileChooser(String dir, String[] extensions, String[] descs,
           String selected, boolean allFiles)
   {
+    this(dir, extensions, descs, selected, allFiles, false);
+  }
+
+  public JalviewFileChooser(String dir, String[] extensions, String[] descs,
+          String selected, boolean allFiles, boolean allowBackupFiles)
+  {
     super(safePath(dir));
     if (extensions.length == descs.length)
     {
@@ -148,7 +176,7 @@ public class JalviewFileChooser extends JFileChooser
       {
         formats.add(new String[] { extensions[i], descs[i] });
       }
-      init(formats, selected, allFiles);
+      init(formats, selected, allFiles, allowBackupFiles);
     }
     else
     {
@@ -182,6 +210,12 @@ public class JalviewFileChooser extends JFileChooser
    */
   void init(List<String[]> formats, String selected, boolean allFiles)
   {
+    init(formats, selected, allFiles, false);
+  }
+
+  void init(List<String[]> formats, String selected, boolean allFiles,
+          boolean allowBackupFiles)
+  {
 
     JalviewFileFilter chosen = null;
 
@@ -192,6 +226,10 @@ public class JalviewFileChooser extends JFileChooser
     for (String[] format : formats)
     {
       JalviewFileFilter jvf = new JalviewFileFilter(format[0], format[1]);
+      if (allowBackupFiles)
+      {
+        jvf.setParentJFC(this);
+      }
       addChoosableFileFilter(jvf);
       if ((selected != null) && selected.equalsIgnoreCase(format[1]))
       {
@@ -204,7 +242,64 @@ public class JalviewFileChooser extends JFileChooser
       setFileFilter(chosen);
     }
 
-    setAccessory(new RecentlyOpened());
+    if (allowBackupFiles)
+    {
+      JPanel multi = new JPanel();
+      multi.setLayout(new BoxLayout(multi, BoxLayout.PAGE_AXIS));
+      if (backupfilesCheckBox == null)
+      {
+        try {
+          includeBackupFiles = Boolean.parseBoolean(
+                  Cache.getProperty(BackupFiles.NS + "_FC_INCLUDE"));
+        } catch (Exception e)
+        {
+          includeBackupFiles = false;
+        }
+        backupfilesCheckBox = new JCheckBox(
+                MessageManager.getString("label.include_backup_files"),
+                includeBackupFiles);
+        backupfilesCheckBox.setAlignmentX(Component.CENTER_ALIGNMENT);
+        JalviewFileChooser jfc = this;
+        backupfilesCheckBox.addActionListener(new ActionListener()
+        {
+          @Override
+          public void actionPerformed(ActionEvent e)
+          {
+            includeBackupFiles = backupfilesCheckBox.isSelected();
+            Cache.setProperty(BackupFiles.NS + "_FC_INCLUDE",
+                    String.valueOf(includeBackupFiles));
+
+            FileFilter f = jfc.getFileFilter();
+            // deselect the selected file if it's no longer choosable
+            File selectedFile = jfc.getSelectedFile();
+            if (selectedFile != null && !f.accept(selectedFile))
+            {
+              jfc.setSelectedFile(null);
+            }
+            // fake the OK button changing (to force it to upate)
+            String s = jfc.getApproveButtonText();
+            jfc.firePropertyChange(
+                    APPROVE_BUTTON_TEXT_CHANGED_PROPERTY, null, s);
+            // fake the file filter changing (its behaviour actually has)
+            jfc.firePropertyChange(FILE_FILTER_CHANGED_PROPERTY, null, f);
+
+            jfc.rescanCurrentDirectory();
+            jfc.revalidate();
+            jfc.repaint();
+          }
+        });
+      }
+      multi.add(new RecentlyOpened());
+      multi.add(backupfilesCheckBox);
+      setAccessory(multi);
+    }
+    else
+    {
+      // set includeBackupFiles=false to avoid other file choosers from picking
+      // up backup files (Just In Case)
+      includeBackupFiles = false;
+      setAccessory(new RecentlyOpened());
+    }
   }
 
   @Override
@@ -296,14 +391,29 @@ public class JalviewFileChooser extends JFileChooser
   public int showSaveDialog(Component parent) throws HeadlessException
   {
     this.setAccessory(null);
+    this.setSelectedFile(null);
+    return super.showSaveDialog(parent);
+  }
 
-    setDialogType(SAVE_DIALOG);
+  /**
+   * If doing a Save, and an existing file is chosen or entered, prompt for
+   * confirmation of overwrite. Proceed if Yes, else leave the file chooser
+   * open.
+   * 
+   * @see https://stackoverflow.com/questions/8581215/jfilechooser-and-checking-for-overwrite
+   */
+  @Override
+  public void approveSelection()
+  {
+    if (getDialogType() != SAVE_DIALOG)
+    {
+      super.approveSelection();
+      return;
+    }
 
-    this.setSelectedFile(null);
-    int ret = showDialog(parent, MessageManager.getString("action.save"));
     ourselectedFile = getSelectedFile();
 
-    if (getSelectedFile() == null)
+    if (ourselectedFile == null)
     {
       // Workaround for Java 9,10 on OSX - no selected file, but there is a
       // filename typed in
@@ -320,11 +430,15 @@ public class JalviewFileChooser extends JFileChooser
                 "Unexpected exception when trying to get filename.");
         x.printStackTrace();
       }
+      // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND
+      // THE
+      // USER PROMPTED FOR A NEW FILENAME
     }
     if (ourselectedFile == null)
     {
-      return JalviewFileChooser.CANCEL_OPTION;
+      return;
     }
+
     if (getFileFilter() instanceof JalviewFileFilter)
     {
       JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
@@ -337,132 +451,21 @@ public class JalviewFileChooser extends JFileChooser
         setSelectedFile(ourselectedFile);
       }
     }
-    // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND THE
-    // USER PROMPTED FOR A NEW FILENAME
-    if ((ret == JalviewFileChooser.APPROVE_OPTION)
-            && ourselectedFile.exists())
+
+    if (ourselectedFile.exists())
     {
-      int confirm = JvOptionPane.showConfirmDialog(parent,
+      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)
       {
-        ret = JalviewFileChooser.CANCEL_OPTION;
+        return;
       }
-
-      rollBackupFiles(ourselectedFile);
     }
 
-    return ret;
-  }
-
-  // attempts to roll backup files for this file (before overwriting). Returns
-  // true if it rolled all the files it was supposed to, false otherwise.
-  public static boolean rollBackupFiles(String filename)
-  {
-    File file = new File(filename);
-    return rollBackupFiles(file);
-  }
-
-  public static boolean rollBackupFiles(File file)
-  {
-    return rollBackupFiles(file, true, "-bak-%n", 4);
-  }
-
-  public static boolean rollBackupFiles(File file, boolean defaultDo,
-          String defaultSuffix, int defaultMax)
-  {
-
-    if (!(file.exists()
-            && jalview.bin.Cache.getDefault("BACKUP_FILES",
-                    defaultDo)))
-    {
-      // nothing to do
-      return true;
-    }
-
-    // split filename up to insert suffix template in the right place. template
-    // and backupMax can be set in .jalview_properties
-    String backupSuffixTemplate = jalview.bin.Cache
-            .getDefault("BACKUP_SUFFIX", defaultSuffix);
-    int backupMax = jalview.bin.Cache.getDefault("BACKUP_ROLL_MAX",
-            defaultMax);
-    String dir = "";
-    try
-    {
-      File dirFile = file.getParentFile();
-      dir = dirFile.getCanonicalPath();
-    } catch (Exception e)
-    {
-      System.out.println(
-              "Could not get canonical path for file '" + file + "'");
-      return false;
-    }
-    String filename = file.getName();
-    String basename = filename;
-    String extension = "";
-    int dotchar = filename.lastIndexOf('.');
-    // don't split of filenames with the last '.' at the very beginning or
-    // very end of the filename
-    if ((dotchar > 0) && (dotchar < filename.length() - 1))
-    {
-      basename = filename.substring(0, dotchar);
-      extension = filename.substring(dotchar); // NOTE this includes the '.'
-    }
-
-    boolean ret = true;
-    if (backupMax >= 1)
-    {
-      // Create/move backups up one
-      String numString = null;
-      File lastfile = null;
-      for (int n = backupMax; n > 0; n--)
-      {
-        numString = String.format("%02d", n);
-        String backupSuffix = backupSuffixTemplate.replaceAll("%n",
-                numString);
-        String backupfilename = dir + File.separatorChar + basename
-                + backupSuffix + extension;
-        File backupfile_n = new File(backupfilename);
-
-        if (! backupfile_n.exists()) {
-          lastfile = backupfile_n;
-          continue;
-        }
-        
-        if (n == backupMax)
-        { // Move the max backup to /tmp instead of deleting (Just In
-          // Case)
-          String tmpfile = "tmp-" + backupfile_n.getName();
-          try
-          {
-            File tmpFile = File.createTempFile(tmpfile, ".tmp");
-            ret = ret && backupfile_n.renameTo(tmpFile);
-          } catch (IOException e)
-          {
-            System.out.println(
-                    "Could not create temp file '" + tmpfile + ".tmp'");
-          }
-        }
-        else
-        {
-          // Just In Case
-          if (lastfile != null)
-          {
-            ret = ret && backupfile_n.renameTo(lastfile);
-          }
-        }
-
-        lastfile = backupfile_n;
-      }
-      
-      // now actually backup the important file!
-      ret = ret && file.renameTo(lastfile);
-    }
-
-    return ret;
+    super.approveSelection();
   }
 
   void recentListSelectionChanged(Object selection)
@@ -485,28 +488,35 @@ public class JalviewFileChooser extends JFileChooser
     }
   }
 
+  /**
+   * A panel to set as the 'accessory' component to the file chooser dialog,
+   * holding a list of recently opened files (if any). These are held as a
+   * tab-separated list of file paths under key <code>RECENT_FILE</code> in
+   * <code>.jalview_properties</code>. A click in the list calls a method in
+   * JalviewFileChooser to set the chosen file as the selection.
+   */
   class RecentlyOpened extends JPanel
   {
-    JList list;
+    private static final long serialVersionUID = 1L;
 
-    public RecentlyOpened()
-    {
+    private JList<String> list;
 
-      String historyItems = jalview.bin.Cache.getProperty("RECENT_FILE");
+    RecentlyOpened()
+    {
+      String historyItems = Cache.getProperty("RECENT_FILE");
       StringTokenizer st;
-      Vector recent = new Vector();
+      Vector<String> recent = new Vector<>();
 
       if (historyItems != null)
       {
         st = new StringTokenizer(historyItems, "\t");
-
         while (st.hasMoreTokens())
         {
-          recent.addElement(st.nextElement());
+          recent.addElement(st.nextToken());
         }
       }
 
-      list = new JList(recent);
+      list = new JList<>(recent);
 
       DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
       dlcr.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
@@ -521,7 +531,7 @@ public class JalviewFileChooser extends JFileChooser
         }
       });
 
-      this.setBorder(new javax.swing.border.TitledBorder(
+      this.setBorder(new TitledBorder(
               MessageManager.getString("label.recently_opened")));
 
       final JScrollPane scroller = new JScrollPane(list);
@@ -532,7 +542,7 @@ public class JalviewFileChooser extends JFileChooser
       layout.putConstraint(SpringLayout.NORTH, scroller, 5,
               SpringLayout.NORTH, this);
 
-      if (new Platform().isAMac())
+      if (Platform.isAMac())
       {
         scroller.setPreferredSize(new Dimension(500, 100));
       }
@@ -543,7 +553,7 @@ public class JalviewFileChooser extends JFileChooser
 
       this.add(scroller);
 
-      javax.swing.SwingUtilities.invokeLater(new Runnable()
+      SwingUtilities.invokeLater(new Runnable()
       {
         @Override
         public void run()
@@ -552,8 +562,6 @@ public class JalviewFileChooser extends JFileChooser
                   .setValue(scroller.getHorizontalScrollBar().getMaximum());
         }
       });
-
     }
-
   }
 }