2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 //////////////////////////////////////////////////////////////////
24 import jalview.bin.Cache;
25 import jalview.gui.JvOptionPane;
26 import jalview.util.MessageManager;
27 import jalview.util.Platform;
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;
36 import java.util.ArrayList;
37 import java.util.List;
38 import java.util.StringTokenizer;
39 import java.util.Vector;
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;
50 * Enhanced file chooser dialog box.
52 * NOTE: bug on Windows systems when filechooser opened on directory to view
53 * files with colons in title.
58 public class JalviewFileChooser extends JFileChooser
61 * Factory method to return a file chooser that offers readable alignment file
68 public static JalviewFileChooser forRead(String directory,
71 List<String> extensions = new ArrayList<>();
72 List<String> descs = new ArrayList<>();
73 for (FileFormatI format : FileFormats.getInstance().getFormats())
75 if (format.isReadable())
77 extensions.add(format.getExtensions());
78 descs.add(format.getName());
81 return new JalviewFileChooser(directory,
82 extensions.toArray(new String[extensions.size()]),
83 descs.toArray(new String[descs.size()]), selected, true);
87 * Factory method to return a file chooser that offers writable alignment file
94 public static JalviewFileChooser forWrite(String directory,
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())
103 if (format.isWritable())
105 extensions.add(format.getExtensions());
106 descs.add(format.getName());
109 return new JalviewFileChooser(directory,
110 extensions.toArray(new String[extensions.size()]),
111 descs.toArray(new String[descs.size()]), selected, false);
114 public JalviewFileChooser(String dir)
116 super(safePath(dir));
117 setAccessory(new RecentlyOpened());
120 public JalviewFileChooser(String dir, String[] suffix, String[] desc,
123 this(dir, suffix, desc, selected, true);
127 * Constructor for a single choice of file extension and description
132 public JalviewFileChooser(String extension, String desc)
134 this(Cache.getProperty("LAST_DIRECTORY"), new String[] { extension },
136 { desc }, desc, true);
139 JalviewFileChooser(String dir, String[] extensions, String[] descs,
140 String selected, boolean allFiles)
142 super(safePath(dir));
143 if (extensions.length == descs.length)
145 List<String[]> formats = new ArrayList<>();
146 for (int i = 0; i < extensions.length; i++)
148 formats.add(new String[] { extensions[i], descs[i] });
150 init(formats, selected, allFiles);
154 System.err.println("JalviewFileChooser arguments mismatch: "
155 + extensions + ", " + descs);
159 private static File safePath(String dir)
166 File f = new File(dir);
167 if (f.getName().indexOf(':') > -1)
177 * a list of {extensions, description} for each file format
180 * if true, 'any format' option is included
182 void init(List<String[]> formats, String selected, boolean allFiles)
185 JalviewFileFilter chosen = null;
187 // SelectAllFilter needs to be set first before adding further
188 // file filters to fix bug on Mac OSX
189 setAcceptAllFileFilterUsed(allFiles);
191 for (String[] format : formats)
193 JalviewFileFilter jvf = new JalviewFileFilter(format[0], format[1]);
194 addChoosableFileFilter(jvf);
195 if ((selected != null) && selected.equalsIgnoreCase(format[1]))
203 setFileFilter(chosen);
206 setAccessory(new RecentlyOpened());
210 public void setFileFilter(javax.swing.filechooser.FileFilter filter)
212 super.setFileFilter(filter);
216 if (getUI() instanceof BasicFileChooserUI)
218 final BasicFileChooserUI fcui = (BasicFileChooserUI) getUI();
219 final String name = fcui.getFileName().trim();
221 if ((name == null) || (name.length() == 0))
226 EventQueue.invokeLater(new Thread()
231 String currentName = fcui.getFileName();
232 if ((currentName == null) || (currentName.length() == 0))
234 fcui.setFileName(name);
239 } catch (Exception ex)
241 ex.printStackTrace();
242 // Some platforms do not have BasicFileChooserUI
247 * Returns the selected file format, or null if none selected
251 public FileFormatI getSelectedFormat()
253 if (getFileFilter() == null)
259 * logic here depends on option description being formatted as
260 * formatName (extension, extension...)
261 * or the 'no option selected' value
263 * @see JalviewFileFilter.getDescription
265 String format = getFileFilter().getDescription();
266 int parenPos = format.indexOf("(");
269 format = format.substring(0, parenPos).trim();
272 return FileFormats.getInstance().forName(format);
273 } catch (IllegalArgumentException e)
275 System.err.println("Unexpected format: " + format);
281 File ourselectedFile = null;
284 public File getSelectedFile()
286 File selfile = super.getSelectedFile();
287 if (selfile == null && ourselectedFile != null)
289 return ourselectedFile;
295 public int showSaveDialog(Component parent) throws HeadlessException
297 this.setAccessory(null);
299 setDialogType(SAVE_DIALOG);
301 this.setSelectedFile(null);
302 int ret = showDialog(parent, MessageManager.getString("action.save"));
303 ourselectedFile = getSelectedFile();
305 if (getSelectedFile() == null)
307 // Workaround for Java 9,10 on OSX - no selected file, but there is a
311 String filename = ((BasicFileChooserUI) getUI()).getFileName();
312 if (filename != null && filename.length() > 0)
314 ourselectedFile = new File(getCurrentDirectory(), filename);
316 } catch (Throwable x)
319 "Unexpected exception when trying to get filename.");
323 if (ourselectedFile == null)
325 return JalviewFileChooser.CANCEL_OPTION;
327 if (getFileFilter() instanceof JalviewFileFilter)
329 JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
331 if (!jvf.accept(ourselectedFile))
333 String withExtension = getSelectedFile().getName() + "."
334 + jvf.getAcceptableExtension();
335 ourselectedFile = (new File(getCurrentDirectory(), withExtension));
336 setSelectedFile(ourselectedFile);
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())
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);
349 if (confirm != JvOptionPane.YES_OPTION)
351 ret = JalviewFileChooser.CANCEL_OPTION;
358 void recentListSelectionChanged(Object selection)
360 setSelectedFile(null);
361 if (selection != null)
363 File file = new File((String) selection);
364 if (getFileFilter() instanceof JalviewFileFilter)
366 JalviewFileFilter jvf = (JalviewFileFilter) this.getFileFilter();
368 if (!jvf.accept(file))
370 setFileFilter(getChoosableFileFilters()[0]);
374 setSelectedFile(file);
378 class RecentlyOpened extends JPanel
382 public RecentlyOpened()
385 String historyItems = jalview.bin.Cache.getProperty("RECENT_FILE");
387 Vector recent = new Vector();
389 if (historyItems != null)
391 st = new StringTokenizer(historyItems, "\t");
393 while (st.hasMoreTokens())
395 recent.addElement(st.nextElement());
399 list = new JList(recent);
401 DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
402 dlcr.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
403 list.setCellRenderer(dlcr);
405 list.addMouseListener(new MouseAdapter()
408 public void mousePressed(MouseEvent evt)
410 recentListSelectionChanged(list.getSelectedValue());
414 this.setBorder(new javax.swing.border.TitledBorder(
415 MessageManager.getString("label.recently_opened")));
417 final JScrollPane scroller = new JScrollPane(list);
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);
425 if (new Platform().isAMac())
427 scroller.setPreferredSize(new Dimension(500, 100));
431 scroller.setPreferredSize(new Dimension(130, 200));
436 javax.swing.SwingUtilities.invokeLater(new Runnable()
441 scroller.getHorizontalScrollBar()
442 .setValue(scroller.getHorizontalScrollBar().getMaximum());