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.JCheckBox;
44 import javax.swing.JDialog;
45 import javax.swing.JFileChooser;
46 import javax.swing.JLabel;
47 import javax.swing.JList;
48 import javax.swing.JOptionPane;
49 import javax.swing.JPanel;
50 import javax.swing.JScrollPane;
51 import javax.swing.ListCellRenderer;
52 import javax.swing.SpringLayout;
53 import javax.swing.SwingConstants;
54 import javax.swing.filechooser.FileFilter;
55 import javax.swing.plaf.basic.BasicFileChooserUI;
57 import jalview.bin.Cache;
58 import jalview.gui.JvOptionPane;
59 import jalview.util.ChannelProperties;
60 import jalview.util.MessageManager;
61 import jalview.util.Platform;
62 import jalview.util.dialogrunner.DialogRunnerI;
65 * Enhanced file chooser dialog box.
67 * NOTE: bug on Windows systems when filechooser opened on directory to view
68 * files with colons in title.
73 public class JalviewFileChooser extends JFileChooser
74 implements DialogRunnerI, PropertyChangeListener
76 private static final long serialVersionUID = 1L;
78 private Map<Object, Runnable> callbacks = new HashMap<>();
80 File selectedFile = null;
83 * backupfilesCheckBox = "Include backup files" checkbox includeBackupfiles =
84 * flag set by checkbox
86 private JCheckBox backupfilesCheckBox = null;
88 protected boolean includeBackupFiles = false;
91 * Factory method to return a file chooser that offers readable alignment file
98 public static JalviewFileChooser forRead(String directory,
101 return JalviewFileChooser.forRead(directory, selected, false);
104 public static JalviewFileChooser forRead(String directory,
105 String selected, boolean allowBackupFiles)
107 List<String> extensions = new ArrayList<>();
108 List<String> descs = new ArrayList<>();
109 for (FileFormatI format : FileFormats.getInstance().getFormats())
111 if (format.isReadable())
113 extensions.add(format.getExtensions());
114 descs.add(format.getName());
118 return new JalviewFileChooser(directory,
119 extensions.toArray(new String[extensions.size()]),
120 descs.toArray(new String[descs.size()]), selected, true,
125 * Factory method to return a file chooser that offers writable alignment file
132 public static JalviewFileChooser forWrite(String directory,
135 // TODO in Java 8, forRead and forWrite can be a single method
136 // with a lambda expression parameter for isReadable/isWritable
137 List<String> extensions = new ArrayList<>();
138 List<String> descs = new ArrayList<>();
139 for (FileFormatI format : FileFormats.getInstance().getFormats())
141 if (format.isWritable())
143 extensions.add(format.getExtensions());
144 descs.add(format.getName());
147 return new JalviewFileChooser(directory,
148 extensions.toArray(new String[extensions.size()]),
149 descs.toArray(new String[descs.size()]), selected, false);
152 public JalviewFileChooser(String dir)
154 super(safePath(dir));
155 setAccessory(new RecentlyOpened());
158 public JalviewFileChooser(String dir, String[] suffix, String[] desc,
161 this(dir, suffix, desc, selected, true);
165 * Constructor for a single choice of file extension and description
170 public JalviewFileChooser(String extension, String desc)
172 this(Cache.getProperty("LAST_DIRECTORY"), new String[] { extension },
174 { desc }, desc, true);
177 JalviewFileChooser(String dir, String[] extensions, String[] descs,
178 String selected, boolean acceptAny)
180 this(dir, extensions, descs, selected, acceptAny, false);
183 public JalviewFileChooser(String dir, String[] extensions, String[] descs,
184 String selected, boolean acceptAny, boolean allowBackupFiles)
186 super(safePath(dir));
187 if (extensions.length == descs.length)
189 List<String[]> formats = new ArrayList<>();
190 for (int i = 0; i < extensions.length; i++)
192 formats.add(new String[] { extensions[i], descs[i] });
194 init(formats, selected, acceptAny, allowBackupFiles);
198 System.err.println("JalviewFileChooser arguments mismatch: "
199 + extensions + ", " + descs);
203 private static File safePath(String dir)
210 File f = new File(dir);
211 if (f.getName().indexOf(':') > -1)
219 * Overridden for JalviewJS compatibility: only one thread in Javascript, so
220 * we can't wait for user choice in another thread and then perform the
224 public int showOpenDialog(Component parent)
226 int value = super.showOpenDialog(this);
228 if (!Platform.isJS())
236 * code here is not run in JalviewJS, instead
237 * propertyChange() is called for dialog action
239 handleResponse(value);
247 * a list of {extensions, description} for each file format
250 * if true, 'any format' option is included
252 void init(List<String[]> formats, String selected, boolean acceptAny)
254 init(formats, selected, acceptAny, false);
257 void init(List<String[]> formats, String selected, boolean acceptAny,
258 boolean allowBackupFiles)
261 JalviewFileFilter chosen = null;
263 // SelectAllFilter needs to be set first before adding further
264 // file filters to fix bug on Mac OSX
265 setAcceptAllFileFilterUsed(acceptAny);
267 // add a "All known alignment files" option
268 List<String> allExtensions = new ArrayList<>();
269 for (String[] format : formats)
271 String[] extensions = format[0].split(",");
272 for (String ext : extensions)
274 if (!allExtensions.contains(ext))
276 allExtensions.add(ext);
280 allExtensions.sort(null);
281 JalviewFileFilter alljvf = new JalviewFileFilter(
282 allExtensions.toArray(new String[] {}),
283 MessageManager.getString("label.all_known_alignment_files"));
284 alljvf.setExtensionListInDescription(false);
285 addChoosableFileFilter(alljvf);
287 for (String[] format : formats)
289 JalviewFileFilter jvf = new JalviewFileFilter(format[0], format[1]);
290 if (allowBackupFiles)
292 jvf.setParentJFC(this);
294 addChoosableFileFilter(jvf);
295 if ((selected != null) && selected.equalsIgnoreCase(format[1]))
303 setFileFilter(chosen);
306 if (allowBackupFiles)
308 JPanel multi = new JPanel();
309 multi.setLayout(new BoxLayout(multi, BoxLayout.PAGE_AXIS));
310 if (backupfilesCheckBox == null)
314 includeBackupFiles = Boolean.parseBoolean(
315 Cache.getProperty(BackupFiles.NS + "_FC_INCLUDE"));
316 } catch (Exception e)
318 includeBackupFiles = false;
320 backupfilesCheckBox = new JCheckBox(
321 MessageManager.getString("label.include_backup_files"),
323 backupfilesCheckBox.setAlignmentX(Component.CENTER_ALIGNMENT);
324 JalviewFileChooser jfc = this;
325 backupfilesCheckBox.addActionListener(new ActionListener()
328 public void actionPerformed(ActionEvent e)
330 includeBackupFiles = backupfilesCheckBox.isSelected();
331 Cache.setProperty(BackupFiles.NS + "_FC_INCLUDE",
332 String.valueOf(includeBackupFiles));
334 FileFilter f = jfc.getFileFilter();
335 // deselect the selected file if it's no longer choosable
336 File selectedFile = jfc.getSelectedFile();
337 if (selectedFile != null && !f.accept(selectedFile))
339 jfc.setSelectedFile(null);
341 // fake the OK button changing (to force it to upate)
342 String s = jfc.getApproveButtonText();
343 jfc.firePropertyChange(APPROVE_BUTTON_TEXT_CHANGED_PROPERTY,
345 // fake the file filter changing (its behaviour actually has)
346 jfc.firePropertyChange(FILE_FILTER_CHANGED_PROPERTY, null, f);
348 jfc.rescanCurrentDirectory();
354 multi.add(new RecentlyOpened());
355 multi.add(backupfilesCheckBox);
360 // set includeBackupFiles=false to avoid other file choosers from picking
361 // up backup files (Just In Case)
362 includeBackupFiles = false;
363 setAccessory(new RecentlyOpened());
368 public void setFileFilter(javax.swing.filechooser.FileFilter filter)
370 super.setFileFilter(filter);
374 if (getUI() instanceof BasicFileChooserUI)
376 final BasicFileChooserUI fcui = (BasicFileChooserUI) getUI();
377 final String name = fcui.getFileName().trim();
379 if ((name == null) || (name.length() == 0))
384 EventQueue.invokeLater(new Thread()
389 String currentName = fcui.getFileName();
390 if ((currentName == null) || (currentName.length() == 0))
392 fcui.setFileName(name);
397 } catch (Exception ex)
399 ex.printStackTrace();
400 // Some platforms do not have BasicFileChooserUI
405 * Returns the selected file format, or null if none selected
409 public FileFormatI getSelectedFormat()
411 if (getFileFilter() == null)
417 * logic here depends on option description being formatted as
418 * formatName (extension, extension...)
419 * or the 'no option selected' value
421 * @see JalviewFileFilter.getDescription
423 String format = getFileFilter().getDescription();
424 int parenPos = format.indexOf("(");
427 format = format.substring(0, parenPos).trim();
430 return FileFormats.getInstance().forName(format);
431 } catch (IllegalArgumentException e)
433 System.err.println("Unexpected format: " + format);
440 public File getSelectedFile()
442 File f = super.getSelectedFile();
443 return f == null ? selectedFile : f;
447 public int showSaveDialog(Component parent) throws HeadlessException
449 this.setAccessory(null);
450 // Java 9,10,11 on OSX - clear selected file so name isn't auto populated
451 this.setSelectedFile(null);
453 return super.showSaveDialog(parent);
457 * If doing a Save, and an existing file is chosen or entered, prompt for
458 * confirmation of overwrite. Proceed if Yes, else leave the file chooser
461 * @see https://stackoverflow.com/questions/8581215/jfilechooser-and-checking-for-overwrite
464 public void approveSelection()
466 if (getDialogType() != SAVE_DIALOG)
468 super.approveSelection();
472 selectedFile = getSelectedFile();
474 if (selectedFile == null)
476 // Workaround for Java 9,10 on OSX - no selected file, but there is a
480 String filename = ((BasicFileChooserUI) getUI()).getFileName();
481 if (filename != null && filename.length() > 0)
483 selectedFile = new File(getCurrentDirectory(), filename);
485 } catch (Throwable x)
488 "Unexpected exception when trying to get filename.");
491 // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND
493 // USER PROMPTED FOR A NEW FILENAME
496 if (selectedFile == null)
501 if (getFileFilter() instanceof JalviewFileFilter)
503 JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
505 if (!jvf.accept(selectedFile))
507 String withExtension = getSelectedFile().getName() + "."
508 + jvf.getAcceptableExtension();
509 selectedFile = (new File(getCurrentDirectory(), withExtension));
510 setSelectedFile(selectedFile);
514 if (selectedFile.exists())
516 int confirm = Cache.getDefault("CONFIRM_OVERWRITE_FILE", true)
517 ? JvOptionPane.showConfirmDialog(this,
519 .getString("label.overwrite_existing_file"),
520 MessageManager.getString("label.file_already_exists"),
521 JvOptionPane.YES_NO_OPTION)
522 : JOptionPane.YES_OPTION;
524 if (confirm != JvOptionPane.YES_OPTION)
530 super.approveSelection();
533 void recentListSelectionChanged(Object selection)
535 setSelectedFile(null);
536 if (selection != null)
538 File file = new File((String) selection);
539 if (getFileFilter() instanceof JalviewFileFilter)
541 JalviewFileFilter jvf = (JalviewFileFilter) this.getFileFilter();
543 if (!jvf.accept(file))
545 setFileFilter(getChoosableFileFilters()[0]);
549 setSelectedFile(file);
553 class RecentlyOpened extends JPanel
555 private static final long serialVersionUID = 1L;
561 setPreferredSize(new Dimension(300, 100));
562 String historyItems = Cache.getProperty("RECENT_FILE");
564 Vector<String> recent = new Vector<>();
566 if (historyItems != null)
568 st = new StringTokenizer(historyItems, "\t");
570 while (st.hasMoreTokens())
572 recent.addElement(st.nextToken());
576 list = new JList<>(recent);
577 list.setCellRenderer(new recentlyOpenedCellRenderer());
580 DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
581 dlcr.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
582 list.setCellRenderer(dlcr);
585 list.addMouseListener(new MouseAdapter()
588 public void mousePressed(MouseEvent evt)
590 recentListSelectionChanged(list.getSelectedValue());
594 this.setBorder(new javax.swing.border.TitledBorder(
595 MessageManager.getString("label.recently_opened")));
597 final JScrollPane scroller = new JScrollPane(list);
599 SpringLayout layout = new SpringLayout();
600 layout.putConstraint(SpringLayout.WEST, scroller, 5,
601 SpringLayout.WEST, this);
602 layout.putConstraint(SpringLayout.NORTH, scroller, 5,
603 SpringLayout.NORTH, this);
605 // TODO are we now all using FlatLaf -- check same dimensions for
607 if (Platform.isAMacAndNotJS())
609 scroller.setPreferredSize(new Dimension(280, 100));
613 scroller.setPreferredSize(new Dimension(500, 200));
618 javax.swing.SwingUtilities.invokeLater(new Runnable()
623 scroller.getHorizontalScrollBar()
624 .setValue(scroller.getHorizontalScrollBar().getMaximum());
632 class recentlyOpenedCellRenderer extends JLabel
633 implements ListCellRenderer<String>
635 private final static int maxChars = 46;
637 private final static String ellipsis = "...";
640 public Component getListCellRendererComponent(
641 JList<? extends String> list, String value, int index,
642 boolean isSelected, boolean cellHasFocus)
644 String filename = value.toString();
645 String displayFilename;
646 if (filename.length() > maxChars)
648 StringBuilder displayFileSB = new StringBuilder();
649 File file = new File(filename);
650 displayFileSB.append(file.getName());
651 if (file.getParent() != null)
654 boolean spaceleft = true;
655 while (spaceleft && parent.getParent() != null)
657 parent = parent.getParentFile();
658 String name = parent.getName();
659 displayFileSB.insert(0, File.separator);
660 if (displayFileSB.length() + name.length() < maxChars - 1)
662 displayFileSB.insert(0, name);
666 displayFileSB.insert(0, ellipsis);
670 if (spaceleft && filename.startsWith(File.separator)
671 && !(displayFileSB.charAt(0) == File.separatorChar))
673 displayFileSB.insert(0, File.separator);
676 displayFilename = displayFileSB.toString();
680 displayFilename = filename;
682 this.setText(displayFilename.toString());
683 this.setToolTipText(filename);
686 setBackground(list.getSelectionBackground());
687 setForeground(list.getSelectionForeground());
691 setBackground(list.getBackground());
692 setForeground(list.getForeground());
694 this.setHorizontalAlignment(SwingConstants.TRAILING);
695 this.setEnabled(list.isEnabled());
696 this.setFont(list.getFont().deriveFont(12f));
697 this.setOpaque(true);
705 public JalviewFileChooser setResponseHandler(Object response,
708 callbacks.put(response, new Callable<Void>()
722 public DialogRunnerI setResponseHandler(Object response, Runnable action)
724 callbacks.put(response, action);
729 public void handleResponse(Object response)
732 * this test is for NaN in Chrome
734 if (response != null && !response.equals(response))
738 Runnable action = callbacks.get(response);
744 } catch (Exception e)
752 * JalviewJS signals file selection by a property change event for property
753 * "SelectedFile". This methods responds to that by running the response
754 * action for 'OK' in the dialog.
759 public void propertyChange(PropertyChangeEvent evt)
761 // TODO other properties need runners...
762 switch (evt.getPropertyName())
765 * property name here matches that used in JFileChooser.js
768 handleResponse(APPROVE_OPTION);
774 protected JDialog createDialog(Component parent) throws HeadlessException
776 JDialog dialog = super.createDialog(parent);
777 dialog.setIconImages(ChannelProperties.getIconList());