JAL-3106 normalise extension before checking if it is '.jar' when constructing filefo...
[jalview.git] / src / jalview / io / JalviewFileChooser.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  *
5  * This file is part of Jalview.
6  *
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *
12  * Jalview is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15  * PURPOSE.  See the GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 //////////////////////////////////////////////////////////////////
22 package jalview.io;
23
24 import jalview.bin.Cache;
25 import jalview.gui.JvOptionPane;
26 import jalview.util.MessageManager;
27 import jalview.util.Platform;
28
29 import java.awt.Component;
30 import java.awt.Dimension;
31 import java.awt.EventQueue;
32 import java.awt.HeadlessException;
33 import java.awt.event.MouseAdapter;
34 import java.awt.event.MouseEvent;
35 import java.io.File;
36 import java.util.ArrayList;
37 import java.util.List;
38 import java.util.StringTokenizer;
39 import java.util.Vector;
40
41 import javax.swing.DefaultListCellRenderer;
42 import javax.swing.JFileChooser;
43 import javax.swing.JList;
44 import javax.swing.JPanel;
45 import javax.swing.JScrollPane;
46 import javax.swing.SpringLayout;
47 import javax.swing.plaf.basic.BasicFileChooserUI;
48
49 /**
50  * Enhanced file chooser dialog box.
51  *
52  * NOTE: bug on Windows systems when filechooser opened on directory to view
53  * files with colons in title.
54  *
55  * @author AMW
56  *
57  */
58 public class JalviewFileChooser extends JFileChooser
59 {
60   /**
61    * Factory method to return a file chooser that offers readable alignment file
62    * formats
63    * 
64    * @param directory
65    * @param selected
66    * @return
67    */
68   public static JalviewFileChooser forRead(String directory,
69           String selected)
70   {
71     List<String> extensions = new ArrayList<>();
72     List<String> descs = new ArrayList<>();
73     for (FileFormatI format : FileFormats.getInstance().getFormats())
74     {
75       if (format.isReadable())
76       {
77         extensions.add(format.getExtensions());
78         descs.add(format.getName());
79       }
80     }
81     return new JalviewFileChooser(directory,
82             extensions.toArray(new String[extensions.size()]),
83             descs.toArray(new String[descs.size()]), selected, true);
84   }
85
86   /**
87    * Factory method to return a file chooser that offers writable alignment file
88    * formats
89    * 
90    * @param directory
91    * @param selected
92    * @return
93    */
94   public static JalviewFileChooser forWrite(String directory,
95           String selected)
96   {
97     // TODO in Java 8, forRead and forWrite can be a single method
98     // with a lambda expression parameter for isReadable/isWritable
99     List<String> extensions = new ArrayList<>();
100     List<String> descs = new ArrayList<>();
101     for (FileFormatI format : FileFormats.getInstance().getFormats())
102     {
103       if (format.isWritable())
104       {
105         extensions.add(format.getExtensions());
106         descs.add(format.getName());
107       }
108     }
109     return new JalviewFileChooser(directory,
110             extensions.toArray(new String[extensions.size()]),
111             descs.toArray(new String[descs.size()]), selected, false);
112   }
113
114   public JalviewFileChooser(String dir)
115   {
116     super(safePath(dir));
117     setAccessory(new RecentlyOpened());
118   }
119
120   public JalviewFileChooser(String dir, String[] suffix, String[] desc,
121           String selected)
122   {
123     this(dir, suffix, desc, selected, true);
124   }
125
126   /**
127    * Constructor for a single choice of file extension and description
128    * 
129    * @param extension
130    * @param desc
131    */
132   public JalviewFileChooser(String extension, String desc)
133   {
134     this(Cache.getProperty("LAST_DIRECTORY"), new String[] { extension },
135             new String[]
136             { desc }, desc, true);
137   }
138
139   JalviewFileChooser(String dir, String[] extensions, String[] descs,
140           String selected, boolean allFiles)
141   {
142     super(safePath(dir));
143     if (extensions.length == descs.length)
144     {
145       List<String[]> formats = new ArrayList<>();
146       for (int i = 0; i < extensions.length; i++)
147       {
148         formats.add(new String[] { extensions[i], descs[i] });
149       }
150       init(formats, selected, allFiles);
151     }
152     else
153     {
154       System.err.println("JalviewFileChooser arguments mismatch: "
155               + extensions + ", " + descs);
156     }
157   }
158
159   private static File safePath(String dir)
160   {
161     if (dir == null)
162     {
163       return null;
164     }
165
166     File f = new File(dir);
167     if (f.getName().indexOf(':') > -1)
168     {
169       return null;
170     }
171     return f;
172   }
173
174   /**
175    * 
176    * @param formats
177    *          a list of {extensions, description} for each file format
178    * @param selected
179    * @param allFiles
180    *          if true, 'any format' option is included
181    */
182   void init(List<String[]> formats, String selected, boolean allFiles)
183   {
184
185     JalviewFileFilter chosen = null;
186
187     // SelectAllFilter needs to be set first before adding further
188     // file filters to fix bug on Mac OSX
189     setAcceptAllFileFilterUsed(allFiles);
190
191     for (String[] format : formats)
192     {
193       JalviewFileFilter jvf = new JalviewFileFilter(format[0], format[1]);
194       addChoosableFileFilter(jvf);
195       if ((selected != null) && selected.equalsIgnoreCase(format[1]))
196       {
197         chosen = jvf;
198       }
199     }
200
201     if (chosen != null)
202     {
203       setFileFilter(chosen);
204     }
205
206     setAccessory(new RecentlyOpened());
207   }
208
209   @Override
210   public void setFileFilter(javax.swing.filechooser.FileFilter filter)
211   {
212     super.setFileFilter(filter);
213
214     try
215     {
216       if (getUI() instanceof BasicFileChooserUI)
217       {
218         final BasicFileChooserUI fcui = (BasicFileChooserUI) getUI();
219         final String name = fcui.getFileName().trim();
220
221         if ((name == null) || (name.length() == 0))
222         {
223           return;
224         }
225
226         EventQueue.invokeLater(new Thread()
227         {
228           @Override
229           public void run()
230           {
231             String currentName = fcui.getFileName();
232             if ((currentName == null) || (currentName.length() == 0))
233             {
234               fcui.setFileName(name);
235             }
236           }
237         });
238       }
239     } catch (Exception ex)
240     {
241       ex.printStackTrace();
242       // Some platforms do not have BasicFileChooserUI
243     }
244   }
245
246   /**
247    * Returns the selected file format, or null if none selected
248    * 
249    * @return
250    */
251   public FileFormatI getSelectedFormat()
252   {
253     if (getFileFilter() == null)
254     {
255       return null;
256     }
257
258     /*
259      * logic here depends on option description being formatted as 
260      * formatName (extension, extension...)
261      * or the 'no option selected' value
262      * All Files
263      * @see JalviewFileFilter.getDescription
264      */
265     String format = getFileFilter().getDescription();
266     int parenPos = format.indexOf("(");
267     if (parenPos > 0)
268     {
269       format = format.substring(0, parenPos).trim();
270       try
271       {
272         return FileFormats.getInstance().forName(format);
273       } catch (IllegalArgumentException e)
274       {
275         System.err.println("Unexpected format: " + format);
276       }
277     }
278     return null;
279   }
280
281   File ourselectedFile = null;
282
283   @Override
284   public File getSelectedFile()
285   {
286     File selfile = super.getSelectedFile();
287     if (selfile == null && ourselectedFile != null)
288     {
289       return ourselectedFile;
290     }
291     return selfile;
292   }
293
294   @Override
295   public int showSaveDialog(Component parent) throws HeadlessException
296   {
297     this.setAccessory(null);
298
299     setDialogType(SAVE_DIALOG);
300
301     this.setSelectedFile(null);
302     int ret = showDialog(parent, MessageManager.getString("action.save"));
303     ourselectedFile = getSelectedFile();
304
305     if (getSelectedFile() == null)
306     {
307       // Workaround for Java 9,10 on OSX - no selected file, but there is a
308       // filename typed in
309       try
310       {
311         String filename = ((BasicFileChooserUI) getUI()).getFileName();
312         if (filename != null && filename.length() > 0)
313         {
314           ourselectedFile = new File(getCurrentDirectory(), filename);
315         }
316       } catch (Throwable x)
317       {
318         System.err.println(
319                 "Unexpected exception when trying to get filename.");
320         x.printStackTrace();
321       }
322     }
323     if (ourselectedFile == null)
324     {
325       return JalviewFileChooser.CANCEL_OPTION;
326     }
327     if (getFileFilter() instanceof JalviewFileFilter)
328     {
329       JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
330
331       if (!jvf.accept(ourselectedFile))
332       {
333         String withExtension = getSelectedFile().getName() + "."
334                 + jvf.getAcceptableExtension();
335         ourselectedFile = (new File(getCurrentDirectory(), withExtension));
336         setSelectedFile(ourselectedFile);
337       }
338     }
339     // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND THE
340     // USER PROMPTED FOR A NEW FILENAME
341     if ((ret == JalviewFileChooser.APPROVE_OPTION)
342             && ourselectedFile.exists())
343     {
344       int confirm = JvOptionPane.showConfirmDialog(parent,
345               MessageManager.getString("label.overwrite_existing_file"),
346               MessageManager.getString("label.file_already_exists"),
347               JvOptionPane.YES_NO_OPTION);
348
349       if (confirm != JvOptionPane.YES_OPTION)
350       {
351         ret = JalviewFileChooser.CANCEL_OPTION;
352       }
353     }
354
355     return ret;
356   }
357
358   void recentListSelectionChanged(Object selection)
359   {
360     setSelectedFile(null);
361     if (selection != null)
362     {
363       File file = new File((String) selection);
364       if (getFileFilter() instanceof JalviewFileFilter)
365       {
366         JalviewFileFilter jvf = (JalviewFileFilter) this.getFileFilter();
367
368         if (!jvf.accept(file))
369         {
370           setFileFilter(getChoosableFileFilters()[0]);
371         }
372       }
373
374       setSelectedFile(file);
375     }
376   }
377
378   class RecentlyOpened extends JPanel
379   {
380     JList list;
381
382     public RecentlyOpened()
383     {
384
385       String historyItems = jalview.bin.Cache.getProperty("RECENT_FILE");
386       StringTokenizer st;
387       Vector recent = new Vector();
388
389       if (historyItems != null)
390       {
391         st = new StringTokenizer(historyItems, "\t");
392
393         while (st.hasMoreTokens())
394         {
395           recent.addElement(st.nextElement());
396         }
397       }
398
399       list = new JList(recent);
400
401       DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
402       dlcr.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
403       list.setCellRenderer(dlcr);
404
405       list.addMouseListener(new MouseAdapter()
406       {
407         @Override
408         public void mousePressed(MouseEvent evt)
409         {
410           recentListSelectionChanged(list.getSelectedValue());
411         }
412       });
413
414       this.setBorder(new javax.swing.border.TitledBorder(
415               MessageManager.getString("label.recently_opened")));
416
417       final JScrollPane scroller = new JScrollPane(list);
418
419       SpringLayout layout = new SpringLayout();
420       layout.putConstraint(SpringLayout.WEST, scroller, 5,
421               SpringLayout.WEST, this);
422       layout.putConstraint(SpringLayout.NORTH, scroller, 5,
423               SpringLayout.NORTH, this);
424
425       if (new Platform().isAMac())
426       {
427         scroller.setPreferredSize(new Dimension(500, 100));
428       }
429       else
430       {
431         scroller.setPreferredSize(new Dimension(130, 200));
432       }
433
434       this.add(scroller);
435
436       javax.swing.SwingUtilities.invokeLater(new Runnable()
437       {
438         @Override
439         public void run()
440         {
441           scroller.getHorizontalScrollBar()
442                   .setValue(scroller.getHorizontalScrollBar().getMaximum());
443         }
444       });
445
446     }
447
448   }
449 }