JAL-3141. This adds quite a lot of code to allow an 'Include backup files' checkbox...
[jalview.git] / src / jalview / io / JalviewFileChooser.java
index 052cf68..7c3cf92 100755 (executable)
@@ -30,16 +30,19 @@ 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;
@@ -59,6 +62,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
    * 
@@ -140,6 +151,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 +165,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 +199,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 +215,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 +231,57 @@ 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));
+            jfc.rescanCurrentDirectory();
+            jfc.revalidate();
+            jfc.repaint();
+            // This is a kludge. Cannot find out how to get the file list to
+            // refresh!
+            /*
+            Object o = jfc.getClientProperty(
+                    CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY);
+            jfc.firePropertyChange(CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY,
+                    o, o);
+            */
+          }
+        });
+      }
+      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
@@ -337,10 +414,13 @@ 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
+    // USER PROMPTED FOR A NEW FILENAME.
+    // DO NOT need to confirm file overwrite if using backup files (the files
+    // aren't being overwritten!)
     if ((ret == JalviewFileChooser.APPROVE_OPTION)
-            && ourselectedFile.exists())
+            && ourselectedFile.exists() && (!BackupFiles.getEnabled()))
     {
       int confirm = JvOptionPane.showConfirmDialog(parent,
               MessageManager.getString("label.overwrite_existing_file"),
@@ -352,114 +432,6 @@ public class JalviewFileChooser extends JFileChooser
         ret = JalviewFileChooser.CANCEL_OPTION;
       }
 
-      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;