Merge branch 'Jalview-BH/JAL-3026-JAL-3063-JAXB' into
[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.bin.Jalview;
26 import jalview.gui.JvOptionPane;
27 import jalview.util.MessageManager;
28 import jalview.util.Platform;
29 import jalview.util.dialogrunner.DialogRunner;
30 import jalview.util.dialogrunner.DialogRunnerI;
31 import jalview.util.dialogrunner.RunResponse;
32
33 import java.awt.Component;
34 import java.awt.Dimension;
35 import java.awt.EventQueue;
36 import java.awt.HeadlessException;
37 import java.awt.event.MouseAdapter;
38 import java.awt.event.MouseEvent;
39 import java.beans.PropertyChangeEvent;
40 import java.beans.PropertyChangeListener;
41 import java.io.File;
42 import java.util.ArrayList;
43 import java.util.List;
44 import java.util.StringTokenizer;
45 import java.util.Vector;
46
47 import javax.swing.DefaultListCellRenderer;
48 import javax.swing.JFileChooser;
49 import javax.swing.JList;
50 import javax.swing.JPanel;
51 import javax.swing.JScrollPane;
52 import javax.swing.SpringLayout;
53 import javax.swing.plaf.basic.BasicFileChooserUI;
54
55 /**
56  * Enhanced file chooser dialog box.
57  *
58  * NOTE: bug on Windows systems when filechooser opened on directory to view
59  * files with colons in title.
60  *
61  * @author AMW
62  *
63  */
64 public class JalviewFileChooser extends JFileChooser implements DialogRunnerI,
65     PropertyChangeListener
66 {
67   private static final long serialVersionUID = 1L;
68
69   private DialogRunnerI runner = new DialogRunner();
70   
71   File selectedFile = null;
72
73   /**
74    * Factory method to return a file chooser that offers readable alignment file
75    * formats
76    * 
77    * @param directory
78    * @param selected
79    * @return
80    */
81   public static JalviewFileChooser forRead(String directory,
82           String selected)
83   {
84     List<String> extensions = new ArrayList<>();
85     List<String> descs = new ArrayList<>();
86     for (FileFormatI format : FileFormats.getInstance().getFormats())
87     {
88       if (format.isReadable())
89       {
90         extensions.add(format.getExtensions());
91         descs.add(format.getName());
92       }
93     }
94     return new JalviewFileChooser(directory,
95             extensions.toArray(new String[extensions.size()]),
96             descs.toArray(new String[descs.size()]), selected, true);
97   }
98
99   /**
100    * Factory method to return a file chooser that offers writable alignment file
101    * formats
102    * 
103    * @param directory
104    * @param selected
105    * @return
106    */
107   public static JalviewFileChooser forWrite(String directory,
108           String selected)
109   {
110     // TODO in Java 8, forRead and forWrite can be a single method
111     // with a lambda expression parameter for isReadable/isWritable
112     List<String> extensions = new ArrayList<>();
113     List<String> descs = new ArrayList<>();
114     for (FileFormatI format : FileFormats.getInstance().getFormats())
115     {
116       if (format.isWritable())
117       {
118         extensions.add(format.getExtensions());
119         descs.add(format.getName());
120       }
121     }
122     return new JalviewFileChooser(directory,
123             extensions.toArray(new String[extensions.size()]),
124             descs.toArray(new String[descs.size()]), selected, false);
125   }
126
127   public JalviewFileChooser(String dir)
128   {
129     super(safePath(dir));
130     setAccessory(new RecentlyOpened());
131   }
132
133   public JalviewFileChooser(String dir, String[] suffix, String[] desc,
134           String selected)
135   {
136     this(dir, suffix, desc, selected, true);
137   }
138
139   /**
140    * Constructor for a single choice of file extension and description
141    * 
142    * @param extension
143    * @param desc
144    */
145   public JalviewFileChooser(String extension, String desc)
146   {
147     this(Cache.getProperty("LAST_DIRECTORY"), new String[] { extension },
148             new String[]
149             { desc }, desc, true);
150   }
151
152   JalviewFileChooser(String dir, String[] extensions, String[] descs,
153           String selected, boolean acceptAny)
154   {
155     super(safePath(dir));
156     if (extensions.length == descs.length)
157     {
158       List<String[]> formats = new ArrayList<>();
159       for (int i = 0; i < extensions.length; i++)
160       {
161         formats.add(new String[] { extensions[i], descs[i] });
162       }
163       init(formats, selected, acceptAny);
164     }
165     else
166     {
167       System.err.println("JalviewFileChooser arguments mismatch: "
168               + extensions + ", " + descs);
169     }
170   }
171
172   private static File safePath(String dir)
173   {
174     if (dir == null)
175     {
176       return null;
177     }
178
179     File f = new File(dir);
180     if (f.getName().indexOf(':') > -1)
181     {
182       return null;
183     }
184     return f;
185   }
186
187   /**
188    * Overridden for JalviewJS compatibility: only one thread in Javascript, 
189    * so we can't wait for user choice in another thread and then perform the 
190    * desired action
191    */
192   @Override
193   public int showOpenDialog(Component parent)
194   {
195    // runner.resetResponses();
196     int value = super.showOpenDialog(this);
197     if (!Jalview.isJS())
198     {
199       runner.handleResponse(value);
200     }
201     return value;
202   }
203
204   /**
205    * 
206    * @param formats
207    *          a list of {extensions, description} for each file format
208    * @param selected
209    * @param acceptAny
210    *          if true, 'any format' option is included
211    */
212   void init(List<String[]> formats, String selected, boolean acceptAny)
213   {
214
215     JalviewFileFilter chosen = null;
216
217     // SelectAllFilter needs to be set first before adding further
218     // file filters to fix bug on Mac OSX
219     setAcceptAllFileFilterUsed(acceptAny);
220
221     for (String[] format : formats)
222     {
223       JalviewFileFilter jvf = new JalviewFileFilter(format[0], format[1]);
224       addChoosableFileFilter(jvf);
225       if ((selected != null) && selected.equalsIgnoreCase(format[1]))
226       {
227         chosen = jvf;
228       }
229     }
230
231     if (chosen != null)
232     {
233       setFileFilter(chosen);
234     }
235
236     setAccessory(new RecentlyOpened());
237   }
238
239   @Override
240   public void setFileFilter(javax.swing.filechooser.FileFilter filter)
241   {
242     super.setFileFilter(filter);
243
244     try
245     {
246       if (getUI() instanceof BasicFileChooserUI)
247       {
248         final BasicFileChooserUI fcui = (BasicFileChooserUI) getUI();
249         final String name = fcui.getFileName().trim();
250
251         if ((name == null) || (name.length() == 0))
252         {
253           return;
254         }
255
256         EventQueue.invokeLater(new Thread()
257         {
258           @Override
259           public void run()
260           {
261             String currentName = fcui.getFileName();
262             if ((currentName == null) || (currentName.length() == 0))
263             {
264               fcui.setFileName(name);
265             }
266           }
267         });
268       }
269     } catch (Exception ex)
270     {
271       ex.printStackTrace();
272       // Some platforms do not have BasicFileChooserUI
273     }
274   }
275
276   /**
277    * Returns the selected file format, or null if none selected
278    * 
279    * @return
280    */
281   public FileFormatI getSelectedFormat()
282   {
283     if (getFileFilter() == null)
284     {
285       return null;
286     }
287
288     /*
289      * logic here depends on option description being formatted as 
290      * formatName (extension, extension...)
291      * or the 'no option selected' value
292      * All Files
293      * @see JalviewFileFilter.getDescription
294      */
295     String format = getFileFilter().getDescription();
296     int parenPos = format.indexOf("(");
297     if (parenPos > 0)
298     {
299       format = format.substring(0, parenPos).trim();
300       try
301       {
302         return FileFormats.getInstance().forName(format);
303       } catch (IllegalArgumentException e)
304       {
305         System.err.println("Unexpected format: " + format);
306       }
307     }
308     return null;
309   }
310
311   @Override
312   public File getSelectedFile()
313   {
314     File f = super.getSelectedFile();
315     return f == null ? selectedFile : f;
316   }
317
318   @Override
319   public int showSaveDialog(Component parent) throws HeadlessException
320   {
321     this.setAccessory(null);
322     // Java 9,10,11 on OSX - clear selected file so name isn't auto populated
323     this.setSelectedFile(null);
324
325     return super.showSaveDialog(parent);
326   }
327
328   /**
329    * If doing a Save, and an existing file is chosen or entered, prompt for
330    * confirmation of overwrite. Proceed if Yes, else leave the file chooser
331    * open.
332    * 
333    * @see https://stackoverflow.com/questions/8581215/jfilechooser-and-checking-for-overwrite
334    */
335   @Override
336   public void approveSelection()
337   {
338     if (getDialogType() != SAVE_DIALOG)
339     {
340       super.approveSelection();
341       return;
342     }
343
344     selectedFile = getSelectedFile();
345
346     if (selectedFile == null)
347     {
348       // Workaround for Java 9,10 on OSX - no selected file, but there is a
349       // filename typed in
350       try
351       {
352         String filename = ((BasicFileChooserUI) getUI()).getFileName();
353         if (filename != null && filename.length() > 0)
354         {
355           selectedFile = new File(getCurrentDirectory(), filename);
356         }
357       } catch (Throwable x)
358       {
359         System.err.println(
360                 "Unexpected exception when trying to get filename.");
361         x.printStackTrace();
362       }
363       // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND
364       // THE
365       // USER PROMPTED FOR A NEW FILENAME
366     }
367
368     if (selectedFile == null)
369     {
370       return;
371     }
372
373     if (getFileFilter() instanceof JalviewFileFilter)
374     {
375       JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
376
377       if (!jvf.accept(selectedFile))
378       {
379         String withExtension = getSelectedFile().getName() + "."
380                 + jvf.getAcceptableExtension();
381         selectedFile = (new File(getCurrentDirectory(), withExtension));
382         setSelectedFile(selectedFile);
383       }
384     }
385
386     if (selectedFile.exists())
387     {
388       int confirm = JvOptionPane.showConfirmDialog(this,
389               MessageManager.getString("label.overwrite_existing_file"),
390               MessageManager.getString("label.file_already_exists"),
391               JvOptionPane.YES_NO_OPTION);
392       if (confirm != JvOptionPane.YES_OPTION)
393       {
394         return;
395       }
396     }
397
398     super.approveSelection();
399   }
400
401   void recentListSelectionChanged(Object selection)
402   {
403     setSelectedFile(null);
404     if (selection != null)
405     {
406       File file = new File((String) selection);
407       if (getFileFilter() instanceof JalviewFileFilter)
408       {
409         JalviewFileFilter jvf = (JalviewFileFilter) this.getFileFilter();
410
411         if (!jvf.accept(file))
412         {
413           setFileFilter(getChoosableFileFilters()[0]);
414         }
415       }
416
417       setSelectedFile(file);
418     }
419   }
420
421   class RecentlyOpened extends JPanel
422   {
423     private static final long serialVersionUID = 1L;
424     JList<String> list;
425
426     RecentlyOpened()
427     {
428       setPreferredSize(new Dimension(300,100));
429       String historyItems = Cache.getProperty("RECENT_FILE");
430       StringTokenizer st;
431       Vector<String> recent = new Vector<>();
432
433       if (historyItems != null)
434       {
435         st = new StringTokenizer(historyItems, "\t");
436
437         while (st.hasMoreTokens())
438         {
439           recent.addElement(st.nextToken());
440         }
441       }
442
443       list = new JList<>(recent);
444   
445       DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
446 //      dlcr.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
447       list.setCellRenderer(dlcr);
448
449       list.addMouseListener(new MouseAdapter()
450       {
451         @Override
452         public void mousePressed(MouseEvent evt)
453         {
454           recentListSelectionChanged(list.getSelectedValue());
455         }
456       });
457
458       this.setBorder(new javax.swing.border.TitledBorder(
459               MessageManager.getString("label.recently_opened")));
460
461       final JScrollPane scroller = new JScrollPane(list);
462
463       SpringLayout layout = new SpringLayout();
464       layout.putConstraint(SpringLayout.WEST, scroller, 5,
465               SpringLayout.WEST, this);
466       layout.putConstraint(SpringLayout.NORTH, scroller, 5,
467               SpringLayout.NORTH, this);
468
469       if (Platform.isAMac())
470       {
471         scroller.setPreferredSize(new Dimension(500, 100));
472       }
473       else
474       {
475         scroller.setPreferredSize(new Dimension(530, 200));
476       }
477
478       this.add(scroller);
479
480       javax.swing.SwingUtilities.invokeLater(new Runnable()
481       {
482         @Override
483         public void run()
484         {
485           scroller.getHorizontalScrollBar()
486                   .setValue(scroller.getHorizontalScrollBar().getMaximum());
487         }
488       });
489
490     }
491
492   }
493
494   @Override
495   public DialogRunnerI addResponse(Object response, RunResponse action)
496   {
497     return runner.addResponse(response, action);
498   }
499
500   /**
501    * JalviewJS signals file selection by a property change event
502    * for property "SelectedFile".  This methods responds to that by
503    * running the response action for 'OK' in the dialog.
504    * 
505    * @param evt
506    */
507   @Override
508   public void propertyChange(PropertyChangeEvent evt)
509   {
510     // TODO other properties need runners...
511     switch (evt.getPropertyName())
512     {
513     case "SelectedFile": 
514       runner.handleResponse(APPROVE_OPTION);
515       break;
516     }
517   }
518 }