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;
28 import jalview.util.dialogrunner.DialogRunnerI;
30 import java.awt.Component;
31 import java.awt.Dimension;
32 import java.awt.EventQueue;
33 import java.awt.HeadlessException;
34 import java.awt.event.ActionEvent;
35 import java.awt.event.ActionListener;
36 import java.awt.event.MouseAdapter;
37 import java.awt.event.MouseEvent;
38 import java.beans.PropertyChangeEvent;
39 import java.beans.PropertyChangeListener;
41 import java.util.ArrayList;
42 import java.util.HashMap;
43 import java.util.List;
45 import java.util.StringTokenizer;
46 import java.util.Vector;
48 import javax.swing.BoxLayout;
49 import javax.swing.DefaultListCellRenderer;
50 import javax.swing.JCheckBox;
51 import javax.swing.JFileChooser;
52 import javax.swing.JList;
53 import javax.swing.JPanel;
54 import javax.swing.JScrollPane;
55 import javax.swing.SpringLayout;
56 import javax.swing.filechooser.FileFilter;
57 import javax.swing.plaf.basic.BasicFileChooserUI;
60 * Enhanced file chooser dialog box.
62 * NOTE: bug on Windows systems when filechooser opened on directory to view
63 * files with colons in title.
68 public class JalviewFileChooser extends JFileChooser implements DialogRunnerI,
69 PropertyChangeListener
71 private static final long serialVersionUID = 1L;
73 private Map<Object, Runnable> callbacks = new HashMap<>();
75 File selectedFile = null;
78 * backupfilesCheckBox = "Include backup files" checkbox includeBackupfiles =
79 * flag set by checkbox
81 private JCheckBox backupfilesCheckBox = null;
83 protected boolean includeBackupFiles = false;
86 * Factory method to return a file chooser that offers readable alignment file
93 public static JalviewFileChooser forRead(String directory,
96 return JalviewFileChooser.forRead(directory, selected, false);
99 public static JalviewFileChooser forRead(String directory,
100 String selected, boolean allowBackupFiles)
102 List<String> extensions = new ArrayList<>();
103 List<String> descs = new ArrayList<>();
104 for (FileFormatI format : FileFormats.getInstance().getFormats())
106 if (format.isReadable())
108 extensions.add(format.getExtensions());
109 descs.add(format.getName());
113 return new JalviewFileChooser(directory,
114 extensions.toArray(new String[extensions.size()]),
115 descs.toArray(new String[descs.size()]), selected, true,
120 * Factory method to return a file chooser that offers writable alignment file
127 public static JalviewFileChooser forWrite(String directory,
130 // TODO in Java 8, forRead and forWrite can be a single method
131 // with a lambda expression parameter for isReadable/isWritable
132 List<String> extensions = new ArrayList<>();
133 List<String> descs = new ArrayList<>();
134 for (FileFormatI format : FileFormats.getInstance().getFormats())
136 if (format.isWritable())
138 extensions.add(format.getExtensions());
139 descs.add(format.getName());
142 return new JalviewFileChooser(directory,
143 extensions.toArray(new String[extensions.size()]),
144 descs.toArray(new String[descs.size()]), selected, false);
147 public JalviewFileChooser(String dir)
149 super(safePath(dir));
150 setAccessory(new RecentlyOpened());
153 public JalviewFileChooser(String dir, String[] suffix, String[] desc,
156 this(dir, suffix, desc, selected, true);
160 * Constructor for a single choice of file extension and description
165 public JalviewFileChooser(String extension, String desc)
167 this(Cache.getProperty("LAST_DIRECTORY"), new String[] { extension },
169 { desc }, desc, true);
172 JalviewFileChooser(String dir, String[] extensions, String[] descs,
173 String selected, boolean acceptAny)
175 this(dir, extensions, descs, selected, acceptAny, false);
178 public JalviewFileChooser(String dir, String[] extensions, String[] descs,
179 String selected, boolean acceptAny, boolean allowBackupFiles)
181 super(safePath(dir));
182 if (extensions.length == descs.length)
184 List<String[]> formats = new ArrayList<>();
185 for (int i = 0; i < extensions.length; i++)
187 formats.add(new String[] { extensions[i], descs[i] });
189 init(formats, selected, acceptAny, allowBackupFiles);
193 System.err.println("JalviewFileChooser arguments mismatch: "
194 + extensions + ", " + descs);
198 private static File safePath(String dir)
205 File f = new File(dir);
206 if (f.getName().indexOf(':') > -1)
214 * Overridden for JalviewJS compatibility: only one thread in Javascript,
215 * so we can't wait for user choice in another thread and then perform the
219 public int showOpenDialog(Component parent)
221 int value = super.showOpenDialog(this);
223 if (!Platform.isJS())
231 * code here is not run in JalviewJS, instead
232 * propertyChange() is called for dialog action
234 handleResponse(value);
242 * a list of {extensions, description} for each file format
245 * if true, 'any format' option is included
247 void init(List<String[]> formats, String selected, boolean acceptAny)
249 init(formats, selected, acceptAny, false);
252 void init(List<String[]> formats, String selected, boolean acceptAny,
253 boolean allowBackupFiles)
256 JalviewFileFilter chosen = null;
258 // SelectAllFilter needs to be set first before adding further
259 // file filters to fix bug on Mac OSX
260 setAcceptAllFileFilterUsed(acceptAny);
262 for (String[] format : formats)
264 JalviewFileFilter jvf = new JalviewFileFilter(format[0], format[1]);
265 if (allowBackupFiles)
267 jvf.setParentJFC(this);
269 addChoosableFileFilter(jvf);
270 if ((selected != null) && selected.equalsIgnoreCase(format[1]))
278 setFileFilter(chosen);
281 if (allowBackupFiles)
283 JPanel multi = new JPanel();
284 multi.setLayout(new BoxLayout(multi, BoxLayout.PAGE_AXIS));
285 if (backupfilesCheckBox == null)
288 includeBackupFiles = Boolean.parseBoolean(
289 Cache.getProperty(BackupFiles.NS + "_FC_INCLUDE"));
290 } catch (Exception e)
292 includeBackupFiles = false;
294 backupfilesCheckBox = new JCheckBox(
295 MessageManager.getString("label.include_backup_files"),
297 backupfilesCheckBox.setAlignmentX(Component.CENTER_ALIGNMENT);
298 JalviewFileChooser jfc = this;
299 backupfilesCheckBox.addActionListener(new ActionListener()
302 public void actionPerformed(ActionEvent e)
304 includeBackupFiles = backupfilesCheckBox.isSelected();
305 Cache.setProperty(BackupFiles.NS + "_FC_INCLUDE",
306 String.valueOf(includeBackupFiles));
308 FileFilter f = jfc.getFileFilter();
309 // deselect the selected file if it's no longer choosable
310 File selectedFile = jfc.getSelectedFile();
311 if (selectedFile != null && !f.accept(selectedFile))
313 jfc.setSelectedFile(null);
315 // fake the OK button changing (to force it to upate)
316 String s = jfc.getApproveButtonText();
317 jfc.firePropertyChange(
318 APPROVE_BUTTON_TEXT_CHANGED_PROPERTY, null, s);
319 // fake the file filter changing (its behaviour actually has)
320 jfc.firePropertyChange(FILE_FILTER_CHANGED_PROPERTY, null, f);
322 jfc.rescanCurrentDirectory();
328 multi.add(new RecentlyOpened());
329 multi.add(backupfilesCheckBox);
334 // set includeBackupFiles=false to avoid other file choosers from picking
335 // up backup files (Just In Case)
336 includeBackupFiles = false;
337 setAccessory(new RecentlyOpened());
342 public void setFileFilter(javax.swing.filechooser.FileFilter filter)
344 super.setFileFilter(filter);
348 if (getUI() instanceof BasicFileChooserUI)
350 final BasicFileChooserUI fcui = (BasicFileChooserUI) getUI();
351 final String name = fcui.getFileName().trim();
353 if ((name == null) || (name.length() == 0))
358 EventQueue.invokeLater(new Thread()
363 String currentName = fcui.getFileName();
364 if ((currentName == null) || (currentName.length() == 0))
366 fcui.setFileName(name);
371 } catch (Exception ex)
373 ex.printStackTrace();
374 // Some platforms do not have BasicFileChooserUI
379 * Returns the selected file format, or null if none selected
383 public FileFormatI getSelectedFormat()
385 if (getFileFilter() == null)
391 * logic here depends on option description being formatted as
392 * formatName (extension, extension...)
393 * or the 'no option selected' value
395 * @see JalviewFileFilter.getDescription
397 String format = getFileFilter().getDescription();
398 int parenPos = format.indexOf("(");
401 format = format.substring(0, parenPos).trim();
404 return FileFormats.getInstance().forName(format);
405 } catch (IllegalArgumentException e)
407 System.err.println("Unexpected format: " + format);
414 public File getSelectedFile()
416 File f = super.getSelectedFile();
417 return f == null ? selectedFile : f;
421 public int showSaveDialog(Component parent) throws HeadlessException
423 this.setAccessory(null);
424 // Java 9,10,11 on OSX - clear selected file so name isn't auto populated
425 this.setSelectedFile(null);
427 return super.showSaveDialog(parent);
431 * If doing a Save, and an existing file is chosen or entered, prompt for
432 * confirmation of overwrite. Proceed if Yes, else leave the file chooser
435 * @see https://stackoverflow.com/questions/8581215/jfilechooser-and-checking-for-overwrite
438 public void approveSelection()
440 if (getDialogType() != SAVE_DIALOG)
442 super.approveSelection();
446 selectedFile = getSelectedFile();
448 if (selectedFile == null)
450 // Workaround for Java 9,10 on OSX - no selected file, but there is a
454 String filename = ((BasicFileChooserUI) getUI()).getFileName();
455 if (filename != null && filename.length() > 0)
457 selectedFile = new File(getCurrentDirectory(), filename);
459 } catch (Throwable x)
462 "Unexpected exception when trying to get filename.");
465 // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND
467 // USER PROMPTED FOR A NEW FILENAME
470 if (selectedFile == null)
475 if (getFileFilter() instanceof JalviewFileFilter)
477 JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
479 if (!jvf.accept(selectedFile))
481 String withExtension = getSelectedFile().getName() + "."
482 + jvf.getAcceptableExtension();
483 selectedFile = (new File(getCurrentDirectory(), withExtension));
484 setSelectedFile(selectedFile);
488 if (selectedFile.exists())
490 int confirm = JvOptionPane.showConfirmDialog(this,
491 MessageManager.getString("label.overwrite_existing_file"),
492 MessageManager.getString("label.file_already_exists"),
493 JvOptionPane.YES_NO_OPTION);
495 if (confirm != JvOptionPane.YES_OPTION)
501 super.approveSelection();
504 void recentListSelectionChanged(Object selection)
506 setSelectedFile(null);
507 if (selection != null)
509 File file = new File((String) selection);
510 if (getFileFilter() instanceof JalviewFileFilter)
512 JalviewFileFilter jvf = (JalviewFileFilter) this.getFileFilter();
514 if (!jvf.accept(file))
516 setFileFilter(getChoosableFileFilters()[0]);
520 setSelectedFile(file);
524 class RecentlyOpened extends JPanel
526 private static final long serialVersionUID = 1L;
531 setPreferredSize(new Dimension(300,100));
532 String historyItems = Cache.getProperty("RECENT_FILE");
534 Vector<String> recent = new Vector<>();
536 if (historyItems != null)
538 st = new StringTokenizer(historyItems, "\t");
540 while (st.hasMoreTokens())
542 recent.addElement(st.nextToken());
546 list = new JList<>(recent);
548 DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
549 dlcr.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
550 list.setCellRenderer(dlcr);
552 list.addMouseListener(new MouseAdapter()
555 public void mousePressed(MouseEvent evt)
557 recentListSelectionChanged(list.getSelectedValue());
561 this.setBorder(new javax.swing.border.TitledBorder(
562 MessageManager.getString("label.recently_opened")));
564 final JScrollPane scroller = new JScrollPane(list);
566 SpringLayout layout = new SpringLayout();
567 layout.putConstraint(SpringLayout.WEST, scroller, 5,
568 SpringLayout.WEST, this);
569 layout.putConstraint(SpringLayout.NORTH, scroller, 5,
570 SpringLayout.NORTH, this);
572 if (Platform.isAMacAndNotJS())
574 scroller.setPreferredSize(new Dimension(500, 100));
578 scroller.setPreferredSize(new Dimension(530, 200));
583 javax.swing.SwingUtilities.invokeLater(new Runnable()
588 scroller.getHorizontalScrollBar()
589 .setValue(scroller.getHorizontalScrollBar().getMaximum());
598 public DialogRunnerI setResponseHandler(Object response, Runnable action)
600 callbacks.put(response, action);
605 public void handleResponse(Object response)
608 * this test is for NaN in Chrome
610 if (response != null && !response.equals(response))
614 Runnable action = callbacks.get(response);
622 * JalviewJS signals file selection by a property change event
623 * for property "SelectedFile". This methods responds to that by
624 * running the response action for 'OK' in the dialog.
629 public void propertyChange(PropertyChangeEvent evt)
631 // TODO other properties need runners...
632 switch (evt.getPropertyName())
635 * property name here matches that used in JFileChooser.js
638 handleResponse(APPROVE_OPTION);