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 List<String> extensions = new ArrayList<>();
85 List<String> descs = new ArrayList<>();
86 for (FileFormatI format : FileFormats.getInstance().getFormats())
88 if (format.isReadable())
90 extensions.add(format.getExtensions());
91 descs.add(format.getName());
94 return new JalviewFileChooser(directory,
95 extensions.toArray(new String[extensions.size()]),
96 descs.toArray(new String[descs.size()]), selected, true);
100 * Factory method to return a file chooser that offers writable alignment file
107 public static JalviewFileChooser forWrite(String directory,
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())
116 if (format.isWritable())
118 extensions.add(format.getExtensions());
119 descs.add(format.getName());
122 return new JalviewFileChooser(directory,
123 extensions.toArray(new String[extensions.size()]),
124 descs.toArray(new String[descs.size()]), selected, false);
127 public JalviewFileChooser(String dir)
129 super(safePath(dir));
130 setAccessory(new RecentlyOpened());
133 public JalviewFileChooser(String dir, String[] suffix, String[] desc,
136 this(dir, suffix, desc, selected, true);
140 * Constructor for a single choice of file extension and description
145 public JalviewFileChooser(String extension, String desc)
147 this(Cache.getProperty("LAST_DIRECTORY"), new String[] { extension },
149 { desc }, desc, true);
152 JalviewFileChooser(String dir, String[] extensions, String[] descs,
153 String selected, boolean allFiles)
155 this(dir, extensions, descs, selected, allFiles, false);
158 public JalviewFileChooser(String dir, String[] extensions, String[] descs,
159 String selected, boolean allFiles, boolean allowBackupFiles)
161 super(safePath(dir));
162 if (extensions.length == descs.length)
164 List<String[]> formats = new ArrayList<>();
165 for (int i = 0; i < extensions.length; i++)
167 formats.add(new String[] { extensions[i], descs[i] });
169 init(formats, selected, allFiles, allowBackupFiles);
173 System.err.println("JalviewFileChooser arguments mismatch: "
174 + extensions + ", " + descs);
178 private static File safePath(String dir)
185 File f = new File(dir);
186 if (f.getName().indexOf(':') > -1)
196 * a list of {extensions, description} for each file format
199 * if true, 'any format' option is included
201 void init(List<String[]> formats, String selected, boolean allFiles)
203 init(formats, selected, allFiles, false);
206 void init(List<String[]> formats, String selected, boolean allFiles,
207 boolean allowBackupFiles)
210 JalviewFileFilter chosen = null;
212 // SelectAllFilter needs to be set first before adding further
213 // file filters to fix bug on Mac OSX
214 setAcceptAllFileFilterUsed(allFiles);
216 for (String[] format : formats)
218 JalviewFileFilter jvf = new JalviewFileFilter(format[0], format[1]);
219 if (allowBackupFiles)
221 jvf.setParentJFC(this);
223 addChoosableFileFilter(jvf);
224 if ((selected != null) && selected.equalsIgnoreCase(format[1]))
232 setFileFilter(chosen);
235 if (allowBackupFiles)
237 JPanel multi = new JPanel();
238 multi.setLayout(new BoxLayout(multi, BoxLayout.PAGE_AXIS));
239 if (backupfilesCheckBox == null)
242 includeBackupFiles = Boolean.parseBoolean(
243 Cache.getProperty(BackupFiles.NS + "_FC_INCLUDE"));
244 } catch (Exception e)
246 includeBackupFiles = false;
248 backupfilesCheckBox = new JCheckBox(
249 MessageManager.getString("label.include_backup_files"),
251 backupfilesCheckBox.setAlignmentX(Component.CENTER_ALIGNMENT);
252 JalviewFileChooser jfc = this;
253 backupfilesCheckBox.addActionListener(new ActionListener()
256 public void actionPerformed(ActionEvent e)
258 includeBackupFiles = backupfilesCheckBox.isSelected();
259 Cache.setProperty(BackupFiles.NS + "_FC_INCLUDE",
260 String.valueOf(includeBackupFiles));
262 FileFilter f = jfc.getFileFilter();
263 // deselect the selected file if it's no longer choosable
264 File selectedFile = jfc.getSelectedFile();
265 if (selectedFile != null && !f.accept(selectedFile))
267 jfc.setSelectedFile(null);
269 // fake the OK button changing (to force it to upate)
270 String s = jfc.getApproveButtonText();
271 jfc.firePropertyChange(
272 APPROVE_BUTTON_TEXT_CHANGED_PROPERTY, null, s);
273 // fake the file filter changing (its behaviour actually has)
274 jfc.firePropertyChange(FILE_FILTER_CHANGED_PROPERTY, null, f);
276 jfc.rescanCurrentDirectory();
282 multi.add(new RecentlyOpened());
283 multi.add(backupfilesCheckBox);
288 // set includeBackupFiles=false to avoid other file choosers from picking
289 // up backup files (Just In Case)
290 includeBackupFiles = false;
291 setAccessory(new RecentlyOpened());
296 public void setFileFilter(javax.swing.filechooser.FileFilter filter)
298 super.setFileFilter(filter);
302 if (getUI() instanceof BasicFileChooserUI)
304 final BasicFileChooserUI fcui = (BasicFileChooserUI) getUI();
305 final String name = fcui.getFileName().trim();
307 if ((name == null) || (name.length() == 0))
312 EventQueue.invokeLater(new Thread()
317 String currentName = fcui.getFileName();
318 if ((currentName == null) || (currentName.length() == 0))
320 fcui.setFileName(name);
325 } catch (Exception ex)
327 ex.printStackTrace();
328 // Some platforms do not have BasicFileChooserUI
333 * Returns the selected file format, or null if none selected
337 public FileFormatI getSelectedFormat()
339 if (getFileFilter() == null)
345 * logic here depends on option description being formatted as
346 * formatName (extension, extension...)
347 * or the 'no option selected' value
349 * @see JalviewFileFilter.getDescription
351 String format = getFileFilter().getDescription();
352 int parenPos = format.indexOf("(");
355 format = format.substring(0, parenPos).trim();
358 return FileFormats.getInstance().forName(format);
359 } catch (IllegalArgumentException e)
361 System.err.println("Unexpected format: " + format);
367 File ourselectedFile = null;
370 public File getSelectedFile()
372 File selfile = super.getSelectedFile();
373 if (selfile == null && ourselectedFile != null)
375 return ourselectedFile;
381 public int showSaveDialog(Component parent) throws HeadlessException
383 this.setAccessory(null);
385 setDialogType(SAVE_DIALOG);
387 this.setSelectedFile(null);
388 int ret = showDialog(parent, MessageManager.getString("action.save"));
389 ourselectedFile = getSelectedFile();
391 if (getSelectedFile() == null)
393 // Workaround for Java 9,10 on OSX - no selected file, but there is a
397 String filename = ((BasicFileChooserUI) getUI()).getFileName();
398 if (filename != null && filename.length() > 0)
400 ourselectedFile = new File(getCurrentDirectory(), filename);
402 } catch (Throwable x)
405 "Unexpected exception when trying to get filename.");
409 if (ourselectedFile == null)
411 return JalviewFileChooser.CANCEL_OPTION;
413 if (getFileFilter() instanceof JalviewFileFilter)
415 JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
417 if (!jvf.accept(ourselectedFile))
419 String withExtension = getSelectedFile().getName() + "."
420 + jvf.getAcceptableExtension();
421 ourselectedFile = (new File(getCurrentDirectory(), withExtension));
422 setSelectedFile(ourselectedFile);
426 // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND THE
427 // USER PROMPTED FOR A NEW FILENAME.
428 // DO NOT need to confirm file overwrite if using backup files (the files
429 // aren't being overwritten!)
430 if ((ret == JalviewFileChooser.APPROVE_OPTION)
431 && ourselectedFile.exists() && (!BackupFiles.getEnabled()))
433 int confirm = JvOptionPane.showConfirmDialog(parent,
434 MessageManager.getString("label.overwrite_existing_file"),
435 MessageManager.getString("label.file_already_exists"),
436 JvOptionPane.YES_NO_OPTION);
438 if (confirm != JvOptionPane.YES_OPTION)
440 ret = JalviewFileChooser.CANCEL_OPTION;
448 void recentListSelectionChanged(Object selection)
450 setSelectedFile(null);
451 if (selection != null)
453 File file = new File((String) selection);
454 if (getFileFilter() instanceof JalviewFileFilter)
456 JalviewFileFilter jvf = (JalviewFileFilter) this.getFileFilter();
458 if (!jvf.accept(file))
460 setFileFilter(getChoosableFileFilters()[0]);
464 setSelectedFile(file);
468 class RecentlyOpened extends JPanel
472 public RecentlyOpened()
475 String historyItems = jalview.bin.Cache.getProperty("RECENT_FILE");
477 Vector recent = new Vector();
479 if (historyItems != null)
481 st = new StringTokenizer(historyItems, "\t");
483 while (st.hasMoreTokens())
485 recent.addElement(st.nextElement());
489 list = new JList(recent);
491 DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
492 dlcr.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
493 list.setCellRenderer(dlcr);
495 list.addMouseListener(new MouseAdapter()
498 public void mousePressed(MouseEvent evt)
500 recentListSelectionChanged(list.getSelectedValue());
504 this.setBorder(new javax.swing.border.TitledBorder(
505 MessageManager.getString("label.recently_opened")));
507 final JScrollPane scroller = new JScrollPane(list);
509 SpringLayout layout = new SpringLayout();
510 layout.putConstraint(SpringLayout.WEST, scroller, 5,
511 SpringLayout.WEST, this);
512 layout.putConstraint(SpringLayout.NORTH, scroller, 5,
513 SpringLayout.NORTH, this);
515 if (new Platform().isAMac())
517 scroller.setPreferredSize(new Dimension(500, 100));
521 scroller.setPreferredSize(new Dimension(130, 200));
526 javax.swing.SwingUtilities.invokeLater(new Runnable()
531 scroller.getHorizontalScrollBar()
532 .setValue(scroller.getHorizontalScrollBar().getMaximum());