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.ActionEvent;
34 import java.awt.event.ActionListener;
35 import java.awt.event.MouseAdapter;
36 import java.awt.event.MouseEvent;
38 import java.util.ArrayList;
39 import java.util.List;
40 import java.util.StringTokenizer;
41 import java.util.Vector;
43 import javax.swing.BoxLayout;
44 import javax.swing.DefaultListCellRenderer;
45 import javax.swing.JCheckBox;
46 import javax.swing.JFileChooser;
47 import javax.swing.JList;
48 import javax.swing.JPanel;
49 import javax.swing.JScrollPane;
50 import javax.swing.SpringLayout;
51 import javax.swing.filechooser.FileFilter;
52 import javax.swing.plaf.basic.BasicFileChooserUI;
55 * Enhanced file chooser dialog box.
57 * NOTE: bug on Windows systems when filechooser opened on directory to view
58 * files with colons in title.
63 public class JalviewFileChooser extends JFileChooser
66 * backupfilesCheckBox = "Include backup files" checkbox includeBackupfiles =
67 * flag set by checkbox
69 private JCheckBox backupfilesCheckBox = null;
71 protected boolean includeBackupFiles = false;
74 * Factory method to return a file chooser that offers readable alignment file
81 public static JalviewFileChooser forRead(String directory,
84 return JalviewFileChooser.forRead(directory, selected, false);
87 public static JalviewFileChooser forRead(String directory,
88 String selected, boolean allowBackupFiles)
90 List<String> extensions = new ArrayList<>();
91 List<String> descs = new ArrayList<>();
92 for (FileFormatI format : FileFormats.getInstance().getFormats())
94 if (format.isReadable())
96 extensions.add(format.getExtensions());
97 descs.add(format.getName());
101 return new JalviewFileChooser(directory,
102 extensions.toArray(new String[extensions.size()]),
103 descs.toArray(new String[descs.size()]), selected, true,
108 * Factory method to return a file chooser that offers writable alignment file
115 public static JalviewFileChooser forWrite(String directory,
118 // TODO in Java 8, forRead and forWrite can be a single method
119 // with a lambda expression parameter for isReadable/isWritable
120 List<String> extensions = new ArrayList<>();
121 List<String> descs = new ArrayList<>();
122 for (FileFormatI format : FileFormats.getInstance().getFormats())
124 if (format.isWritable())
126 extensions.add(format.getExtensions());
127 descs.add(format.getName());
130 return new JalviewFileChooser(directory,
131 extensions.toArray(new String[extensions.size()]),
132 descs.toArray(new String[descs.size()]), selected, false);
135 public JalviewFileChooser(String dir)
137 super(safePath(dir));
138 setAccessory(new RecentlyOpened());
141 public JalviewFileChooser(String dir, String[] suffix, String[] desc,
144 this(dir, suffix, desc, selected, true);
148 * Constructor for a single choice of file extension and description
153 public JalviewFileChooser(String extension, String desc)
155 this(Cache.getProperty("LAST_DIRECTORY"), new String[] { extension },
157 { desc }, desc, true);
160 JalviewFileChooser(String dir, String[] extensions, String[] descs,
161 String selected, boolean allFiles)
163 this(dir, extensions, descs, selected, allFiles, false);
166 public JalviewFileChooser(String dir, String[] extensions, String[] descs,
167 String selected, boolean allFiles, boolean allowBackupFiles)
169 super(safePath(dir));
170 if (extensions.length == descs.length)
172 List<String[]> formats = new ArrayList<>();
173 for (int i = 0; i < extensions.length; i++)
175 formats.add(new String[] { extensions[i], descs[i] });
177 init(formats, selected, allFiles, allowBackupFiles);
181 System.err.println("JalviewFileChooser arguments mismatch: "
182 + extensions + ", " + descs);
186 private static File safePath(String dir)
193 File f = new File(dir);
194 if (f.getName().indexOf(':') > -1)
204 * a list of {extensions, description} for each file format
207 * if true, 'any format' option is included
209 void init(List<String[]> formats, String selected, boolean allFiles)
211 init(formats, selected, allFiles, false);
214 void init(List<String[]> formats, String selected, boolean allFiles,
215 boolean allowBackupFiles)
218 JalviewFileFilter chosen = null;
220 // SelectAllFilter needs to be set first before adding further
221 // file filters to fix bug on Mac OSX
222 setAcceptAllFileFilterUsed(allFiles);
224 for (String[] format : formats)
226 JalviewFileFilter jvf = new JalviewFileFilter(format[0], format[1]);
227 if (allowBackupFiles)
229 jvf.setParentJFC(this);
231 addChoosableFileFilter(jvf);
232 if ((selected != null) && selected.equalsIgnoreCase(format[1]))
240 setFileFilter(chosen);
243 if (allowBackupFiles)
245 JPanel multi = new JPanel();
246 multi.setLayout(new BoxLayout(multi, BoxLayout.PAGE_AXIS));
247 if (backupfilesCheckBox == null)
250 includeBackupFiles = Boolean.parseBoolean(
251 Cache.getProperty(BackupFiles.NS + "_FC_INCLUDE"));
252 } catch (Exception e)
254 includeBackupFiles = false;
256 backupfilesCheckBox = new JCheckBox(
257 MessageManager.getString("label.include_backup_files"),
259 backupfilesCheckBox.setAlignmentX(Component.CENTER_ALIGNMENT);
260 JalviewFileChooser jfc = this;
261 backupfilesCheckBox.addActionListener(new ActionListener()
264 public void actionPerformed(ActionEvent e)
266 includeBackupFiles = backupfilesCheckBox.isSelected();
267 Cache.setProperty(BackupFiles.NS + "_FC_INCLUDE",
268 String.valueOf(includeBackupFiles));
270 FileFilter f = jfc.getFileFilter();
271 // deselect the selected file if it's no longer choosable
272 File selectedFile = jfc.getSelectedFile();
273 if (selectedFile != null && !f.accept(selectedFile))
275 jfc.setSelectedFile(null);
277 // fake the OK button changing (to force it to upate)
278 String s = jfc.getApproveButtonText();
279 jfc.firePropertyChange(
280 APPROVE_BUTTON_TEXT_CHANGED_PROPERTY, null, s);
281 // fake the file filter changing (its behaviour actually has)
282 jfc.firePropertyChange(FILE_FILTER_CHANGED_PROPERTY, null, f);
284 jfc.rescanCurrentDirectory();
290 multi.add(new RecentlyOpened());
291 multi.add(backupfilesCheckBox);
296 // set includeBackupFiles=false to avoid other file choosers from picking
297 // up backup files (Just In Case)
298 includeBackupFiles = false;
299 setAccessory(new RecentlyOpened());
304 public void setFileFilter(javax.swing.filechooser.FileFilter filter)
306 super.setFileFilter(filter);
310 if (getUI() instanceof BasicFileChooserUI)
312 final BasicFileChooserUI fcui = (BasicFileChooserUI) getUI();
313 final String name = fcui.getFileName().trim();
315 if ((name == null) || (name.length() == 0))
320 EventQueue.invokeLater(new Thread()
325 String currentName = fcui.getFileName();
326 if ((currentName == null) || (currentName.length() == 0))
328 fcui.setFileName(name);
333 } catch (Exception ex)
335 ex.printStackTrace();
336 // Some platforms do not have BasicFileChooserUI
341 * Returns the selected file format, or null if none selected
345 public FileFormatI getSelectedFormat()
347 if (getFileFilter() == null)
353 * logic here depends on option description being formatted as
354 * formatName (extension, extension...)
355 * or the 'no option selected' value
357 * @see JalviewFileFilter.getDescription
359 String format = getFileFilter().getDescription();
360 int parenPos = format.indexOf("(");
363 format = format.substring(0, parenPos).trim();
366 return FileFormats.getInstance().forName(format);
367 } catch (IllegalArgumentException e)
369 System.err.println("Unexpected format: " + format);
375 File ourselectedFile = null;
378 public File getSelectedFile()
380 File selfile = super.getSelectedFile();
381 if (selfile == null && ourselectedFile != null)
383 return ourselectedFile;
389 public int showSaveDialog(Component parent) throws HeadlessException
391 this.setAccessory(null);
393 setDialogType(SAVE_DIALOG);
395 this.setSelectedFile(null);
396 int ret = showDialog(parent, MessageManager.getString("action.save"));
397 ourselectedFile = getSelectedFile();
399 if (getSelectedFile() == null)
401 // Workaround for Java 9,10 on OSX - no selected file, but there is a
405 String filename = ((BasicFileChooserUI) getUI()).getFileName();
406 if (filename != null && filename.length() > 0)
408 ourselectedFile = new File(getCurrentDirectory(), filename);
410 } catch (Throwable x)
413 "Unexpected exception when trying to get filename.");
417 if (ourselectedFile == null)
419 return JalviewFileChooser.CANCEL_OPTION;
421 if (getFileFilter() instanceof JalviewFileFilter)
423 JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
425 if (!jvf.accept(ourselectedFile))
427 String withExtension = getSelectedFile().getName() + "."
428 + jvf.getAcceptableExtension();
429 ourselectedFile = (new File(getCurrentDirectory(), withExtension));
430 setSelectedFile(ourselectedFile);
434 // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND THE
435 // USER PROMPTED FOR A NEW FILENAME.
436 // DO NOT need to confirm file overwrite if using backup files (the files
437 // aren't being overwritten!)
438 if ((ret == JalviewFileChooser.APPROVE_OPTION)
439 && ourselectedFile.exists() && (!BackupFiles.getEnabled()))
441 int confirm = JvOptionPane.showConfirmDialog(parent,
442 MessageManager.getString("label.overwrite_existing_file"),
443 MessageManager.getString("label.file_already_exists"),
444 JvOptionPane.YES_NO_OPTION);
446 if (confirm != JvOptionPane.YES_OPTION)
448 ret = JalviewFileChooser.CANCEL_OPTION;
456 void recentListSelectionChanged(Object selection)
458 setSelectedFile(null);
459 if (selection != null)
461 File file = new File((String) selection);
462 if (getFileFilter() instanceof JalviewFileFilter)
464 JalviewFileFilter jvf = (JalviewFileFilter) this.getFileFilter();
466 if (!jvf.accept(file))
468 setFileFilter(getChoosableFileFilters()[0]);
472 setSelectedFile(file);
476 class RecentlyOpened extends JPanel
480 public RecentlyOpened()
483 String historyItems = jalview.bin.Cache.getProperty("RECENT_FILE");
485 Vector recent = new Vector();
487 if (historyItems != null)
489 st = new StringTokenizer(historyItems, "\t");
491 while (st.hasMoreTokens())
493 recent.addElement(st.nextElement());
497 list = new JList(recent);
499 DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
500 dlcr.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
501 list.setCellRenderer(dlcr);
503 list.addMouseListener(new MouseAdapter()
506 public void mousePressed(MouseEvent evt)
508 recentListSelectionChanged(list.getSelectedValue());
512 this.setBorder(new javax.swing.border.TitledBorder(
513 MessageManager.getString("label.recently_opened")));
515 final JScrollPane scroller = new JScrollPane(list);
517 SpringLayout layout = new SpringLayout();
518 layout.putConstraint(SpringLayout.WEST, scroller, 5,
519 SpringLayout.WEST, this);
520 layout.putConstraint(SpringLayout.NORTH, scroller, 5,
521 SpringLayout.NORTH, this);
523 if (new Platform().isAMac())
525 scroller.setPreferredSize(new Dimension(500, 100));
529 scroller.setPreferredSize(new Dimension(130, 200));
534 javax.swing.SwingUtilities.invokeLater(new Runnable()
539 scroller.getHorizontalScrollBar()
540 .setValue(scroller.getHorizontalScrollBar().getMaximum());