JAL-1645 Version-Rel Version 2.9 Year-Rel 2015 Licensing glob
[jalview.git] / src / jalview / io / JalviewFileChooser.java
index c8248ef..951b998 100755 (executable)
-\r
-/*///////////////////////////////////////////////////////////////////\r
-// This file was taken from java forum\r
-// Re: JFileChooser functioning like normal Windows Apps FileChooser\r
-// Author: ddanimal\r
-// http://forum.java.sun.com/thread.jspa?forumID=57&threadID=327712\r
-*///////////////////////////////////////////////////////////////////\r
-\r
-package jalview.io;\r
-\r
-import java.awt.*;\r
-import java.awt.event.*;\r
-import java.io.*;\r
-import java.util.*;\r
-\r
-import javax.swing.*;\r
-import javax.swing.plaf.*;\r
-import javax.swing.plaf.basic.*;\r
-import javax.swing.plaf.metal.*;\r
-import javax.swing.table.*;\r
-\r
-public class JalviewFileChooser extends JFileChooser\r
-{\r
-\r
-  private static final int COLUMN_FILENAME = 0;\r
-  private static final int COLUMN_FILESIZE = 1;\r
-  private static final int COLUMN_FILETYPE = 2;\r
-  private static final int COLUMN_FILEDATE = 3;\r
-  private static final int COLUMN_FILEATTR = 4;\r
-  private static final int COLUMN_COLCOUNT = 5;\r
-  private static String[] COLUMNS = null;\r
-\r
-\r
-  public JalviewFileChooser(String dir, String [] suffix, String [] desc, String selected)\r
-  {\r
-    super(dir);\r
-\r
-    JalviewFileFilter chosen = null;\r
-    for(int i=0; i<suffix.length; i++)\r
-    {\r
-      JalviewFileFilter jvf = new JalviewFileFilter(suffix[i], desc[i]);\r
-      addChoosableFileFilter(jvf);\r
-      if(selected!=null && selected.equals(desc[i]))\r
-        chosen = jvf;\r
-    }\r
-    if(chosen!=null)\r
-      setFileFilter(chosen);\r
-    initColumns();\r
-  }\r
-\r
-  public String getSelectedFormat()\r
-  {\r
-\r
-    String format = getFileFilter().getDescription();\r
-    if (format.startsWith("Jalview"))\r
-      format = "Jalview";\r
-    else if (format.startsWith("Fasta"))\r
-      format = "FASTA";\r
-    else if (format.startsWith("MSF"))\r
-      format = "MSF";\r
-    else if (format.startsWith("Clustal"))\r
-      format = "CLUSTAL";\r
-    else if (format.startsWith("BLC"))\r
-      format = "BLC";\r
-    else if (format.startsWith("PIR"))\r
-      format = "PIR";\r
-    else if (format.startsWith("PFAM"))\r
-      format = "PFAM";\r
-\r
-    return format;\r
-  }\r
-  public JalviewFileChooser(String dir)\r
-  {\r
-    super(dir);\r
-    initColumns();\r
-  }\r
-\r
-  public int showSaveDialog(Component parent) throws HeadlessException {\r
-      setDialogType(SAVE_DIALOG);\r
-      int ret = showDialog(parent, null);\r
-\r
-      JalviewFileFilter jvf = (JalviewFileFilter)getFileFilter();\r
-      if( !jvf.accept( getSelectedFile() ) )\r
-      {\r
-        String withExtension = getSelectedFile()+"."+jvf.getAcceptableExtension();\r
-        setSelectedFile(new File(withExtension));\r
-      }\r
-\r
-      if(ret == JalviewFileChooser.APPROVE_OPTION  &&  getSelectedFile().exists() )\r
-      {\r
-       int confirm =  JOptionPane.showConfirmDialog(parent,\r
-                                      "Overwrite existing file?",\r
-                                      "File exists",\r
-                                      JOptionPane.YES_NO_OPTION);\r
-       if(confirm!=JOptionPane.YES_OPTION)\r
-         ret = this.CANCEL_OPTION;\r
-      }\r
-      return ret;\r
-  }\r
-\r
-\r
-  void initColumns()\r
-  {\r
-    if (COLUMNS == null)\r
-    {\r
-        Locale l = getLocale();\r
-        COLUMNS = new String[]{\r
-        UIManager.getString("FileChooser.fileNameHeaderText",l),\r
-        UIManager.getString("FileChooser.fileSizeHeaderText",l),\r
-        UIManager.getString("FileChooser.fileTypeHeaderText",l),\r
-        UIManager.getString("FileChooser.fileDateHeaderText",l),\r
-        UIManager.getString("FileChooser.fileAttrHeaderText",l)\r
-      };\r
-    }\r
-  }\r
-\r
-  /**************************************************************************\r
-   * Always create the local UI\r
-   * @param comp\r
-   *************************************************************************/\r
-  public final void setUI(ComponentUI comp)\r
-  {\r
-    super.setUI(new UI(this));\r
-  }\r
-\r
-   /**************************************************************************\r
-    * Internal implementation of Metal LookAndFeel to create the table sorting\r
-    * ability.\r
-    *************************************************************************/\r
-   private final static class UI extends MetalFileChooserUI\r
-   {\r
-     private DirectoryModel model;\r
-\r
-     /**************************************************************************\r
-      * Must be overridden to extend\r
-      * @param e\r
-      *************************************************************************/\r
-     public UI(JFileChooser e)\r
-     {\r
-       super(e);\r
-     }\r
-\r
-     /**************************************************************************\r
-      * Overridden to create our own model\r
-      *************************************************************************/\r
-     protected final void createModel()\r
-     {\r
-       model = new DirectoryModel(getFileChooser());\r
-     }\r
-\r
-     /**************************************************************************\r
-      * Overridden to get our own model\r
-      * @return\r
-      *************************************************************************/\r
-     public final BasicDirectoryModel getModel() {       return model;     }\r
-\r
-     /**************************************************************************\r
-      * Calls the default method then adds a MouseListener to the JTable\r
-      * @param chooser\r
-      * @return\r
-      *************************************************************************/\r
-     protected final JPanel createDetailsView(JFileChooser chooser)\r
-     {\r
-       final JPanel panel = super.createDetailsView(chooser);\r
-\r
-       //Since we can't access MetalFileChooserUI's private member detailsTable\r
-       //directly, we have to find it in the JPanel\r
-       final JTable tbl = findJTable(panel.getComponents());\r
-       if (tbl != null)\r
-       {\r
-         //Fix the columns so they can't be rearranged, if we don't do this\r
-         //we would need to keep track when each column is moved\r
-         tbl.getTableHeader().setReorderingAllowed(false);\r
-\r
-         //Add a mouselistener to listen for clicks on column headers\r
-         tbl.getTableHeader().addMouseListener(new MouseAdapter(){\r
-           public void mouseClicked(MouseEvent e)\r
-           {\r
-             //Only process single clicks\r
-             if (e.getClickCount() > 1) return;\r
-             e.consume();\r
-             final int col = tbl.getTableHeader().columnAtPoint(e.getPoint());\r
-             if (col == COLUMN_FILENAME || col == COLUMN_FILESIZE ||\r
-                 col == COLUMN_FILEDATE)\r
-               model.sort(col,tbl);\r
-           }\r
-         });\r
-       }\r
-       return panel;\r
-     }\r
-\r
-     /**************************************************************************\r
-      * Finds the JTable in the panel so we can add MouseListener\r
-      * @param comp\r
-      * @return\r
-      *************************************************************************/\r
-     private final static JTable findJTable(Component[] comp)\r
-     {\r
-       for (int i=0;i<comp.length;i++)\r
-       {\r
-         if (comp[i] instanceof JTable)\r
-         {\r
-           return (JTable)comp[i];\r
-         }\r
-         if (comp[i] instanceof Container)\r
-         {\r
-           JTable tbl = findJTable(((Container)comp[i]).getComponents());\r
-           if (tbl != null) return tbl;\r
-         }\r
-       }\r
-       return null;\r
-     }\r
-   }\r
-\r
-  /***************************************************************************\r
-   * Implementation of BasicDirectoryModel that sorts the Files by column\r
-   **************************************************************************/\r
-  private final static class DirectoryModel extends BasicDirectoryModel\r
-   {\r
-     int col = 0;\r
-     boolean ascending;\r
-\r
-     /**************************************************************************\r
-      * Must be overridden to extend BasicDirectoryModel\r
-      * @param chooser\r
-      *************************************************************************/\r
-     DirectoryModel(JFileChooser chooser)\r
-     {\r
-       super(chooser);\r
-     }\r
-\r
-\r
-     /**************************************************************************\r
-      * Supposedly this is not used anymore, hopefully not.  We implemented\r
-      * some basic attempt at sorting just in case\r
-      * @param a\r
-      * @param b\r
-      * @return\r
-      *************************************************************************/\r
-     protected final boolean lt(File a, File b)\r
-     {\r
-       System.out.println("LT called?");\r
-       boolean less = false;\r
-       switch (col)\r
-       {\r
-         case COLUMN_FILEDATE:\r
-           less = a.lastModified() > b.lastModified();\r
-           break;\r
-         case COLUMN_FILESIZE:\r
-           less = a.length() > b.length();\r
-           break;\r
-         default:\r
-           less = a.getName().compareToIgnoreCase(b.getName()) > 0;\r
-         break;\r
-       }\r
-       if (ascending) return less = !less;\r
-       return less;\r
-     }\r
-\r
-     /**************************************************************************\r
-      * Resorts the JFileChooser table based on new column\r
-      * @param c\r
-      *************************************************************************/\r
-     protected final void sort(int c, JTable tbl)\r
-     {\r
-       //Set column and order\r
-       col = c;\r
-       ascending = !ascending;\r
-       String indicator = " (^)";\r
-       if (ascending)\r
-         indicator = " (v)";\r
-\r
-       final JTableHeader th = tbl.getTableHeader();\r
-       final TableColumnModel tcm = th.getColumnModel();\r
-\r
-       for (int i=0;i<JalviewFileChooser.COLUMN_COLCOUNT;i++)\r
-       {\r
-         final TableColumn tc = tcm.getColumn( i ); // the column to change\r
-         tc.setHeaderValue( COLUMNS[i] );\r
-       }\r
-\r
-       final TableColumn tc = tcm.getColumn( col ); // the column to change\r
-       tc.setHeaderValue( COLUMNS[col] + indicator );\r
-\r
-       th.repaint();\r
-\r
-       //Requery the file listing\r
-       validateFileCache();\r
-     }\r
-\r
-     /**************************************************************************\r
-      * Sorts the data based on current column setting\r
-      * @param data\r
-      *************************************************************************/\r
-     protected final void sort(Vector data)\r
-     {\r
-       switch (col)\r
-       {\r
-         case COLUMN_FILEDATE:\r
-           Collections.sort(data,new Comparator(){\r
-             public int compare(Object o1,Object o2)\r
-             {\r
-               int ret = 1;\r
-               final File a = (File)o1;\r
-               final File b = (File)o2;\r
-               if (a.lastModified() > b.lastModified())\r
-                 ret = -1;\r
-               else if (a.lastModified() == b.lastModified())\r
-                 ret = 0;\r
-\r
-               if (ascending)\r
-                 ret *= -1;\r
-               return ret;\r
-             }\r
-\r
-           });\r
-           break;\r
-         case COLUMN_FILESIZE:\r
-           Collections.sort(data,new Comparator(){\r
-             public int compare(Object o1,Object o2)\r
-             {\r
-               int ret = 1;\r
-               final File a = (File)o1;\r
-               final File b = (File)o2;\r
-               if (a.length() > b.length())\r
-                 ret = -1;\r
-               else if (a.length() == b.length())\r
-                 ret = 0;\r
-\r
-               if (ascending)\r
-                 ret *= -1;\r
-               return ret;\r
-             }\r
-\r
-           });\r
-           break;\r
-         case COLUMN_FILENAME:\r
-           Collections.sort(data,new Comparator(){\r
-             public int compare(Object o1,Object o2)\r
-             {\r
-               final File a = (File)o1;\r
-               final File b = (File)o2;\r
-               if (ascending)\r
-                 return a.getName().compareToIgnoreCase(b.getName());\r
-               else\r
-                 return -1 * a.getName().compareToIgnoreCase(b.getName());\r
-             }\r
-\r
-           });\r
-           break;\r
-       }\r
-     }\r
-  }\r
-}\r
-\r
+/*
+ * Jalview - A Sequence Alignment Editor and Viewer (Version 2.9)
+ * Copyright (C) 2015 The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
+//////////////////////////////////////////////////////////////////
+package jalview.io;
+
+import jalview.util.MessageManager;
+import jalview.util.Platform;
+
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.EventQueue;
+import java.awt.HeadlessException;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.io.File;
+import java.util.StringTokenizer;
+import java.util.Vector;
+
+import javax.swing.DefaultListCellRenderer;
+import javax.swing.JFileChooser;
+import javax.swing.JList;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.SpringLayout;
+
+/**
+ * Enhanced file chooser dialog box.
+ *
+ * NOTE: bug on Windows systems when filechooser opened on directory to view
+ * files with colons in title.
+ *
+ * @author AMW
+ *
+ */
+public class JalviewFileChooser extends JFileChooser
+{
+  public JalviewFileChooser(String dir)
+  {
+    super(safePath(dir));
+    setAccessory(new RecentlyOpened());
+  }
+
+  private static File safePath(String dir)
+  {
+    if (dir == null)
+    {
+      return null;
+    }
+
+    File f = new File(dir);
+    if (f.getName().indexOf(':') > -1)
+    {
+      return null;
+    }
+    return f;
+  }
+
+  public JalviewFileChooser(String dir, String[] suffix, String[] desc,
+          String selected, boolean selectAll)
+  {
+    super(safePath(dir));
+    init(suffix, desc, selected, selectAll);
+  }
+
+  public JalviewFileChooser(String dir, String[] suffix, String[] desc,
+          String selected)
+  {
+    super(safePath(dir));
+    init(suffix, desc, selected, true);
+  }
+
+  void init(String[] suffix, String[] desc, String selected,
+          boolean selectAll)
+  {
+
+    JalviewFileFilter chosen = null;
+
+    // SelectAllFilter needs to be set first before adding further
+    // file filters to fix bug on Mac OSX
+    setAcceptAllFileFilterUsed(selectAll);
+
+    for (int i = 0; i < suffix.length; i++)
+    {
+      JalviewFileFilter jvf = new JalviewFileFilter(suffix[i], desc[i]);
+      addChoosableFileFilter(jvf);
+      if ((selected != null) && selected.equalsIgnoreCase(desc[i]))
+      {
+        chosen = jvf;
+      }
+    }
+
+    if (chosen != null)
+    {
+      setFileFilter(chosen);
+    }
+
+    setAccessory(new RecentlyOpened());
+  }
+
+  @Override
+  public void setFileFilter(javax.swing.filechooser.FileFilter filter)
+  {
+    super.setFileFilter(filter);
+
+    try
+    {
+      if (getUI() instanceof javax.swing.plaf.basic.BasicFileChooserUI)
+      {
+        final javax.swing.plaf.basic.BasicFileChooserUI ui = (javax.swing.plaf.basic.BasicFileChooserUI) getUI();
+        final String name = ui.getFileName().trim();
+
+        if ((name == null) || (name.length() == 0))
+        {
+          return;
+        }
+
+        EventQueue.invokeLater(new Thread()
+        {
+          @Override
+          public void run()
+          {
+            String currentName = ui.getFileName();
+            if ((currentName == null) || (currentName.length() == 0))
+            {
+              ui.setFileName(name);
+            }
+          }
+        });
+      }
+    } catch (Exception ex)
+    {
+      ex.printStackTrace();
+      // Some platforms do not have BasicFileChooserUI
+    }
+  }
+
+  public String getSelectedFormat()
+  {
+    if (getFileFilter() == null)
+    {
+      return null;
+    }
+
+    String format = getFileFilter().getDescription();
+
+    if (format.toUpperCase().startsWith("JALVIEW"))
+    {
+      format = "Jalview";
+    }
+    else if (format.toUpperCase().startsWith("FASTA"))
+    {
+      format = "FASTA";
+    }
+    else if (format.toUpperCase().startsWith("MSF"))
+    {
+      format = "MSF";
+    }
+    else if (format.toUpperCase().startsWith("CLUSTAL"))
+    {
+      format = "CLUSTAL";
+    }
+    else if (format.toUpperCase().startsWith("BLC"))
+    {
+      format = "BLC";
+    }
+    else if (format.toUpperCase().startsWith("PIR"))
+    {
+      format = "PIR";
+    }
+    else if (format.toUpperCase().startsWith("PFAM"))
+    {
+      format = "PFAM";
+    }
+    else if (format.toUpperCase().startsWith(PhylipFile.FILE_DESC))
+    {
+      format = PhylipFile.FILE_DESC;
+    }
+
+    return format;
+  }
+
+  @Override
+  public int showSaveDialog(Component parent) throws HeadlessException
+  {
+    this.setAccessory(null);
+
+    setDialogType(SAVE_DIALOG);
+
+    int ret = showDialog(parent, MessageManager.getString("action.save"));
+
+    if (getFileFilter() instanceof JalviewFileFilter)
+    {
+      JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
+
+      if (!jvf.accept(getSelectedFile()))
+      {
+        String withExtension = getSelectedFile() + "."
+                + jvf.getAcceptableExtension();
+        setSelectedFile(new File(withExtension));
+      }
+    }
+    // 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)
+            && getSelectedFile().exists())
+    {
+      int confirm = JOptionPane.showConfirmDialog(parent,
+              MessageManager.getString("label.overwrite_existing_file"),
+              MessageManager.getString("label.file_already_exists"),
+              JOptionPane.YES_NO_OPTION);
+
+      if (confirm != JOptionPane.YES_OPTION)
+      {
+        ret = JalviewFileChooser.CANCEL_OPTION;
+      }
+    }
+
+    return ret;
+  }
+
+  void recentListSelectionChanged(Object selection)
+  {
+    setSelectedFile(null);
+    if (selection != null)
+    {
+      File file = new File((String) selection);
+      if (getFileFilter() instanceof JalviewFileFilter)
+      {
+        JalviewFileFilter jvf = (JalviewFileFilter) this.getFileFilter();
+
+        if (!jvf.accept(file))
+        {
+          setFileFilter(getChoosableFileFilters()[0]);
+        }
+      }
+
+      setSelectedFile(file);
+    }
+  }
+
+  class RecentlyOpened extends JPanel
+  {
+    JList list;
+
+    public RecentlyOpened()
+    {
+
+      String historyItems = jalview.bin.Cache.getProperty("RECENT_FILE");
+      StringTokenizer st;
+      Vector recent = new Vector();
+
+      if (historyItems != null)
+      {
+        st = new StringTokenizer(historyItems, "\t");
+
+        while (st.hasMoreTokens())
+        {
+          recent.addElement(st.nextElement());
+        }
+      }
+
+      list = new JList(recent);
+
+      DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
+      dlcr.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
+      list.setCellRenderer(dlcr);
+
+      list.addMouseListener(new MouseAdapter()
+      {
+        @Override
+        public void mousePressed(MouseEvent evt)
+        {
+          recentListSelectionChanged(list.getSelectedValue());
+        }
+      });
+
+      this.setBorder(new javax.swing.border.TitledBorder(MessageManager
+              .getString("label.recently_opened")));
+
+      final JScrollPane scroller = new JScrollPane(list);
+
+      SpringLayout layout = new SpringLayout();
+      layout.putConstraint(SpringLayout.WEST, scroller, 5,
+              SpringLayout.WEST, this);
+      layout.putConstraint(SpringLayout.NORTH, scroller, 5,
+              SpringLayout.NORTH, this);
+
+      if (new Platform().isAMac())
+      {
+        scroller.setPreferredSize(new Dimension(500, 100));
+      }
+      else
+      {
+        scroller.setPreferredSize(new Dimension(130, 200));
+      }
+
+      this.add(scroller);
+
+      javax.swing.SwingUtilities.invokeLater(new Runnable()
+      {
+        @Override
+        public void run()
+        {
+          scroller.getHorizontalScrollBar().setValue(
+                  scroller.getHorizontalScrollBar().getMaximum());
+        }
+      });
+
+    }
+
+  }
+}