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 java.awt.Component;
25 import java.awt.Dimension;
26 import java.awt.EventQueue;
27 import java.awt.HeadlessException;
28 import java.awt.event.ActionEvent;
29 import java.awt.event.ActionListener;
30 import java.awt.event.MouseAdapter;
31 import java.awt.event.MouseEvent;
32 import java.beans.PropertyChangeEvent;
33 import java.beans.PropertyChangeListener;
35 import java.util.ArrayList;
36 import java.util.HashMap;
37 import java.util.List;
39 import java.util.StringTokenizer;
40 import java.util.Vector;
42 import javax.swing.BoxLayout;
43 import javax.swing.DefaultListCellRenderer;
44 import javax.swing.JCheckBox;
45 import javax.swing.JDialog;
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;
54 import jalview.bin.Cache;
55 import jalview.gui.JvOptionPane;
56 import jalview.util.MessageManager;
57 import jalview.util.Platform;
58 import jalview.util.dialogrunner.DialogRunnerI;
61 * Enhanced file chooser dialog box.
63 * NOTE: bug on Windows systems when filechooser opened on directory to view
64 * files with colons in title.
69 public class JalviewFileChooser extends JFileChooser
70 implements DialogRunnerI, PropertyChangeListener
72 private static final long serialVersionUID = 1L;
74 private Map<Object, Runnable> callbacks = new HashMap<>();
76 File selectedFile = null;
79 * backupfilesCheckBox = "Include backup files" checkbox includeBackupfiles =
80 * flag set by checkbox
82 private JCheckBox backupfilesCheckBox = null;
84 protected boolean includeBackupFiles = false;
87 * Factory method to return a file chooser that offers readable alignment file
94 public static JalviewFileChooser forRead(String directory,
97 return JalviewFileChooser.forRead(directory, selected, false);
100 public static JalviewFileChooser forRead(String directory,
101 String selected, boolean allowBackupFiles)
103 List<String> extensions = new ArrayList<>();
104 List<String> descs = new ArrayList<>();
105 for (FileFormatI format : FileFormats.getInstance().getFormats())
107 if (format.isReadable())
109 extensions.add(format.getExtensions());
110 descs.add(format.getName());
114 return new JalviewFileChooser(directory,
115 extensions.toArray(new String[extensions.size()]),
116 descs.toArray(new String[descs.size()]), selected, true,
121 * Factory method to return a file chooser that offers writable alignment file
128 public static JalviewFileChooser forWrite(String directory,
131 // TODO in Java 8, forRead and forWrite can be a single method
132 // with a lambda expression parameter for isReadable/isWritable
133 List<String> extensions = new ArrayList<>();
134 List<String> descs = new ArrayList<>();
135 for (FileFormatI format : FileFormats.getInstance().getFormats())
137 if (format.isWritable())
139 extensions.add(format.getExtensions());
140 descs.add(format.getName());
143 return new JalviewFileChooser(directory,
144 extensions.toArray(new String[extensions.size()]),
145 descs.toArray(new String[descs.size()]), selected, false);
148 public JalviewFileChooser(String dir)
150 super(safePath(dir));
151 setAccessory(new RecentlyOpened());
154 public JalviewFileChooser(String dir, String[] suffix, String[] desc,
157 this(dir, suffix, desc, selected, true);
161 * Constructor for a single choice of file extension and description
166 public JalviewFileChooser(String extension, String desc)
168 this(Cache.getProperty("LAST_DIRECTORY"), new String[] { extension },
170 { desc }, desc, true);
173 JalviewFileChooser(String dir, String[] extensions, String[] descs,
174 String selected, boolean acceptAny)
176 this(dir, extensions, descs, selected, acceptAny, false);
179 public JalviewFileChooser(String dir, String[] extensions, String[] descs,
180 String selected, boolean acceptAny, boolean allowBackupFiles)
182 super(safePath(dir));
183 if (extensions.length == descs.length)
185 List<String[]> formats = new ArrayList<>();
186 for (int i = 0; i < extensions.length; i++)
188 formats.add(new String[] { extensions[i], descs[i] });
190 init(formats, selected, acceptAny, allowBackupFiles);
194 System.err.println("JalviewFileChooser arguments mismatch: "
195 + extensions + ", " + descs);
199 private static File safePath(String dir)
206 File f = new File(dir);
207 if (f.getName().indexOf(':') > -1)
215 * Overridden for JalviewJS compatibility: only one thread in Javascript, so
216 * we can't wait for user choice in another thread and then perform the
220 public int showOpenDialog(Component parent)
222 int value = super.showOpenDialog(this);
224 if (!Platform.isJS())
232 * code here is not run in JalviewJS, instead
233 * propertyChange() is called for dialog action
235 handleResponse(value);
243 * a list of {extensions, description} for each file format
246 * if true, 'any format' option is included
248 void init(List<String[]> formats, String selected, boolean acceptAny)
250 init(formats, selected, acceptAny, false);
253 void init(List<String[]> formats, String selected, boolean acceptAny,
254 boolean allowBackupFiles)
257 JalviewFileFilter chosen = null;
259 // SelectAllFilter needs to be set first before adding further
260 // file filters to fix bug on Mac OSX
261 setAcceptAllFileFilterUsed(acceptAny);
263 for (String[] format : formats)
265 JalviewFileFilter jvf = new JalviewFileFilter(format[0], format[1]);
266 if (allowBackupFiles)
268 jvf.setParentJFC(this);
270 addChoosableFileFilter(jvf);
271 if ((selected != null) && selected.equalsIgnoreCase(format[1]))
279 setFileFilter(chosen);
282 if (allowBackupFiles)
284 JPanel multi = new JPanel();
285 multi.setLayout(new BoxLayout(multi, BoxLayout.PAGE_AXIS));
286 if (backupfilesCheckBox == null)
290 includeBackupFiles = Boolean.parseBoolean(
291 Cache.getProperty(BackupFiles.NS + "_FC_INCLUDE"));
292 } catch (Exception e)
294 includeBackupFiles = false;
296 backupfilesCheckBox = new JCheckBox(
297 MessageManager.getString("label.include_backup_files"),
299 backupfilesCheckBox.setAlignmentX(Component.CENTER_ALIGNMENT);
300 JalviewFileChooser jfc = this;
301 backupfilesCheckBox.addActionListener(new ActionListener()
304 public void actionPerformed(ActionEvent e)
306 includeBackupFiles = backupfilesCheckBox.isSelected();
307 Cache.setProperty(BackupFiles.NS + "_FC_INCLUDE",
308 String.valueOf(includeBackupFiles));
310 FileFilter f = jfc.getFileFilter();
311 // deselect the selected file if it's no longer choosable
312 File selectedFile = jfc.getSelectedFile();
313 if (selectedFile != null && !f.accept(selectedFile))
315 jfc.setSelectedFile(null);
317 // fake the OK button changing (to force it to upate)
318 String s = jfc.getApproveButtonText();
319 jfc.firePropertyChange(APPROVE_BUTTON_TEXT_CHANGED_PROPERTY,
321 // fake the file filter changing (its behaviour actually has)
322 jfc.firePropertyChange(FILE_FILTER_CHANGED_PROPERTY, null, f);
324 jfc.rescanCurrentDirectory();
330 multi.add(new RecentlyOpened());
331 multi.add(backupfilesCheckBox);
336 // set includeBackupFiles=false to avoid other file choosers from picking
337 // up backup files (Just In Case)
338 includeBackupFiles = false;
339 setAccessory(new RecentlyOpened());
344 public void setFileFilter(javax.swing.filechooser.FileFilter filter)
346 super.setFileFilter(filter);
350 if (getUI() instanceof BasicFileChooserUI)
352 final BasicFileChooserUI fcui = (BasicFileChooserUI) getUI();
353 final String name = fcui.getFileName().trim();
355 if ((name == null) || (name.length() == 0))
360 EventQueue.invokeLater(new Thread()
365 String currentName = fcui.getFileName();
366 if ((currentName == null) || (currentName.length() == 0))
368 fcui.setFileName(name);
373 } catch (Exception ex)
375 ex.printStackTrace();
376 // Some platforms do not have BasicFileChooserUI
381 * Returns the selected file format, or null if none selected
385 public FileFormatI getSelectedFormat()
387 if (getFileFilter() == null)
393 * logic here depends on option description being formatted as
394 * formatName (extension, extension...)
395 * or the 'no option selected' value
397 * @see JalviewFileFilter.getDescription
399 String format = getFileFilter().getDescription();
400 int parenPos = format.indexOf("(");
403 format = format.substring(0, parenPos).trim();
406 return FileFormats.getInstance().forName(format);
407 } catch (IllegalArgumentException e)
409 System.err.println("Unexpected format: " + format);
416 public File getSelectedFile()
418 File f = super.getSelectedFile();
419 return f == null ? selectedFile : f;
423 public int showSaveDialog(Component parent) throws HeadlessException
425 this.setAccessory(null);
426 // Java 9,10,11 on OSX - clear selected file so name isn't auto populated
427 this.setSelectedFile(null);
429 return super.showSaveDialog(parent);
433 * If doing a Save, and an existing file is chosen or entered, prompt for
434 * confirmation of overwrite. Proceed if Yes, else leave the file chooser
437 * @see https://stackoverflow.com/questions/8581215/jfilechooser-and-checking-for-overwrite
440 public void approveSelection()
442 if (getDialogType() != SAVE_DIALOG)
444 super.approveSelection();
448 selectedFile = getSelectedFile();
450 if (selectedFile == null)
452 // Workaround for Java 9,10 on OSX - no selected file, but there is a
456 String filename = ((BasicFileChooserUI) getUI()).getFileName();
457 if (filename != null && filename.length() > 0)
459 selectedFile = new File(getCurrentDirectory(), filename);
461 } catch (Throwable x)
464 "Unexpected exception when trying to get filename.");
467 // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND
469 // USER PROMPTED FOR A NEW FILENAME
472 if (selectedFile == null)
477 if (getFileFilter() instanceof JalviewFileFilter)
479 JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
481 if (!jvf.accept(selectedFile))
483 String withExtension = getSelectedFile().getName() + "."
484 + jvf.getAcceptableExtension();
485 selectedFile = (new File(getCurrentDirectory(), withExtension));
486 setSelectedFile(selectedFile);
490 if (selectedFile.exists())
492 int confirm = JvOptionPane.showConfirmDialog(this,
493 MessageManager.getString("label.overwrite_existing_file"),
494 MessageManager.getString("label.file_already_exists"),
495 JvOptionPane.YES_NO_OPTION);
497 if (confirm != JvOptionPane.YES_OPTION)
503 super.approveSelection();
506 void recentListSelectionChanged(Object selection)
508 setSelectedFile(null);
509 if (selection != null)
511 File file = new File((String) selection);
512 if (getFileFilter() instanceof JalviewFileFilter)
514 JalviewFileFilter jvf = (JalviewFileFilter) this.getFileFilter();
516 if (!jvf.accept(file))
518 setFileFilter(getChoosableFileFilters()[0]);
522 setSelectedFile(file);
526 class RecentlyOpened extends JPanel
528 private static final long serialVersionUID = 1L;
534 setPreferredSize(new Dimension(300, 100));
535 String historyItems = Cache.getProperty("RECENT_FILE");
537 Vector<String> recent = new Vector<>();
539 if (historyItems != null)
541 st = new StringTokenizer(historyItems, "\t");
543 while (st.hasMoreTokens())
545 recent.addElement(st.nextToken());
549 list = new JList<>(recent);
551 DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
552 dlcr.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
553 list.setCellRenderer(dlcr);
555 list.addMouseListener(new MouseAdapter()
558 public void mousePressed(MouseEvent evt)
560 recentListSelectionChanged(list.getSelectedValue());
564 this.setBorder(new javax.swing.border.TitledBorder(
565 MessageManager.getString("label.recently_opened")));
567 final JScrollPane scroller = new JScrollPane(list);
569 SpringLayout layout = new SpringLayout();
570 layout.putConstraint(SpringLayout.WEST, scroller, 5,
571 SpringLayout.WEST, this);
572 layout.putConstraint(SpringLayout.NORTH, scroller, 5,
573 SpringLayout.NORTH, this);
575 if (Platform.isAMacAndNotJS())
577 scroller.setPreferredSize(new Dimension(500, 100));
581 scroller.setPreferredSize(new Dimension(530, 200));
586 javax.swing.SwingUtilities.invokeLater(new Runnable()
591 scroller.getHorizontalScrollBar()
592 .setValue(scroller.getHorizontalScrollBar().getMaximum());
601 public DialogRunnerI setResponseHandler(Object response, Runnable action)
603 callbacks.put(response, action);
608 public void handleResponse(Object response)
611 * this test is for NaN in Chrome
613 if (response != null && !response.equals(response))
617 Runnable action = callbacks.get(response);
625 * JalviewJS signals file selection by a property change event for property
626 * "SelectedFile". This methods responds to that by running the response
627 * action for 'OK' in the dialog.
632 public void propertyChange(PropertyChangeEvent evt)
634 // TODO other properties need runners...
635 switch (evt.getPropertyName())
638 * property name here matches that used in JFileChooser.js
641 handleResponse(APPROVE_OPTION);
647 protected JDialog createDialog(Component parent) throws HeadlessException
649 JDialog dialog = super.createDialog(parent);
650 dialog.setIconImage(null);