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.SwingUtilities;
55 import javax.swing.border.TitledBorder;
56 import javax.swing.filechooser.FileFilter;
57 import javax.swing.plaf.basic.BasicFileChooserUI;
59 import jalview.bin.Cache;
60 import jalview.gui.JvOptionPane;
61 import jalview.util.ChannelProperties;
62 import jalview.util.MessageManager;
63 import jalview.util.Platform;
64 import jalview.util.dialogrunner.DialogRunnerI;
67 * Enhanced file chooser dialog box.
69 * NOTE: bug on Windows systems when filechooser opened on directory to view
70 * files with colons in title.
75 public class JalviewFileChooser extends JFileChooser
76 implements DialogRunnerI, PropertyChangeListener
78 private static final long serialVersionUID = 1L;
80 private Map<Object, Runnable> callbacks = new HashMap<>();
82 File selectedFile = null;
85 * backupfilesCheckBox = "Include backup files" checkbox includeBackupfiles =
86 * flag set by checkbox
88 private JCheckBox backupfilesCheckBox = null;
90 protected boolean includeBackupFiles = false;
93 * Factory method to return a file chooser that offers readable alignment file
100 public static JalviewFileChooser forRead(String directory,
103 return JalviewFileChooser.forRead(directory, selected, false);
106 public static JalviewFileChooser forRead(String directory,
107 String selected, boolean allowBackupFiles)
109 List<String> extensions = new ArrayList<>();
110 List<String> descs = new ArrayList<>();
111 for (FileFormatI format : FileFormats.getInstance().getFormats())
113 if (format.isReadable())
115 extensions.add(format.getExtensions());
116 descs.add(format.getName());
120 return new JalviewFileChooser(directory,
121 extensions.toArray(new String[extensions.size()]),
122 descs.toArray(new String[descs.size()]), selected, true,
127 * Factory method to return a file chooser that offers writable alignment file
134 public static JalviewFileChooser forWrite(String directory,
137 // TODO in Java 8, forRead and forWrite can be a single method
138 // with a lambda expression parameter for isReadable/isWritable
139 List<String> extensions = new ArrayList<>();
140 List<String> descs = new ArrayList<>();
141 for (FileFormatI format : FileFormats.getInstance().getFormats())
143 if (format.isWritable())
145 extensions.add(format.getExtensions());
146 descs.add(format.getName());
149 return new JalviewFileChooser(directory,
150 extensions.toArray(new String[extensions.size()]),
151 descs.toArray(new String[descs.size()]), selected, false);
154 public JalviewFileChooser(String dir)
156 super(safePath(dir));
157 setAccessory(new RecentlyOpened());
160 public JalviewFileChooser(String dir, String[] suffix, String[] desc,
163 this(dir, suffix, desc, selected, true);
167 * Constructor for a single choice of file extension and description
172 public JalviewFileChooser(String extension, String desc)
174 this(Cache.getProperty("LAST_DIRECTORY"), new String[] { extension },
176 { desc }, desc, true);
179 JalviewFileChooser(String dir, String[] extensions, String[] descs,
180 String selected, boolean acceptAny)
182 this(dir, extensions, descs, selected, acceptAny, false);
185 public JalviewFileChooser(String dir, String[] extensions, String[] descs,
186 String selected, boolean acceptAny, boolean allowBackupFiles)
188 super(safePath(dir));
189 if (extensions.length == descs.length)
191 List<String[]> formats = new ArrayList<>();
192 for (int i = 0; i < extensions.length; i++)
194 formats.add(new String[] { extensions[i], descs[i] });
196 init(formats, selected, acceptAny, allowBackupFiles);
200 System.err.println("JalviewFileChooser arguments mismatch: "
201 + extensions + ", " + descs);
205 private static File safePath(String dir)
212 File f = new File(dir);
213 if (f.getName().indexOf(':') > -1)
221 * Overridden for JalviewJS compatibility: only one thread in Javascript, so
222 * we can't wait for user choice in another thread and then perform the
226 public int showOpenDialog(Component parent)
228 int value = super.showOpenDialog(this);
230 if (!Platform.isJS())
238 * code here is not run in JalviewJS, instead
239 * propertyChange() is called for dialog action
241 handleResponse(value);
249 * a list of {extensions, description} for each file format
252 * if true, 'any format' option is included
254 void init(List<String[]> formats, String selected, boolean acceptAny)
256 init(formats, selected, acceptAny, false);
259 void init(List<String[]> formats, String selected, boolean acceptAny,
260 boolean allowBackupFiles)
263 JalviewFileFilter chosen = null;
265 // SelectAllFilter needs to be set first before adding further
266 // file filters to fix bug on Mac OSX
267 setAcceptAllFileFilterUsed(acceptAny);
269 // add a "All known alignment files" option
270 List<String> allExtensions = new ArrayList<>();
271 for (String[] format : formats)
273 String[] extensions = format[0].split(",");
274 for (String ext : extensions)
276 if (!allExtensions.contains(ext))
278 allExtensions.add(ext);
282 allExtensions.sort(null);
283 JalviewFileFilter alljvf = new JalviewFileFilter(
284 allExtensions.toArray(new String[] {}),
285 MessageManager.getString("label.all_known_alignment_files"));
286 alljvf.setExtensionListInDescription(false);
287 addChoosableFileFilter(alljvf);
289 for (String[] format : formats)
291 JalviewFileFilter jvf = new JalviewFileFilter(format[0], format[1]);
292 if (allowBackupFiles)
294 jvf.setParentJFC(this);
296 addChoosableFileFilter(jvf);
297 if ((selected != null) && selected.equalsIgnoreCase(format[1]))
305 setFileFilter(chosen);
308 if (allowBackupFiles)
310 JPanel multi = new JPanel();
311 multi.setLayout(new BoxLayout(multi, BoxLayout.PAGE_AXIS));
312 if (backupfilesCheckBox == null)
316 includeBackupFiles = Boolean.parseBoolean(
317 Cache.getProperty(BackupFiles.NS + "_FC_INCLUDE"));
318 } catch (Exception e)
320 includeBackupFiles = false;
322 backupfilesCheckBox = new JCheckBox(
323 MessageManager.getString("label.include_backup_files"),
325 backupfilesCheckBox.setAlignmentX(Component.CENTER_ALIGNMENT);
326 JalviewFileChooser jfc = this;
327 backupfilesCheckBox.addActionListener(new ActionListener()
330 public void actionPerformed(ActionEvent e)
332 includeBackupFiles = backupfilesCheckBox.isSelected();
333 Cache.setProperty(BackupFiles.NS + "_FC_INCLUDE",
334 String.valueOf(includeBackupFiles));
336 FileFilter f = jfc.getFileFilter();
337 // deselect the selected file if it's no longer choosable
338 File selectedFile = jfc.getSelectedFile();
339 if (selectedFile != null && !f.accept(selectedFile))
341 jfc.setSelectedFile(null);
343 // fake the OK button changing (to force it to upate)
344 String s = jfc.getApproveButtonText();
345 jfc.firePropertyChange(APPROVE_BUTTON_TEXT_CHANGED_PROPERTY,
347 // fake the file filter changing (its behaviour actually has)
348 jfc.firePropertyChange(FILE_FILTER_CHANGED_PROPERTY, null, f);
350 jfc.rescanCurrentDirectory();
356 multi.add(new RecentlyOpened());
357 multi.add(backupfilesCheckBox);
362 // set includeBackupFiles=false to avoid other file choosers from picking
363 // up backup files (Just In Case)
364 includeBackupFiles = false;
365 setAccessory(new RecentlyOpened());
370 public void setFileFilter(javax.swing.filechooser.FileFilter filter)
372 super.setFileFilter(filter);
376 if (getUI() instanceof BasicFileChooserUI)
378 final BasicFileChooserUI fcui = (BasicFileChooserUI) getUI();
379 final String name = fcui.getFileName().trim();
381 if ((name == null) || (name.length() == 0))
386 EventQueue.invokeLater(new Thread()
391 String currentName = fcui.getFileName();
392 if ((currentName == null) || (currentName.length() == 0))
394 fcui.setFileName(name);
399 } catch (Exception ex)
401 ex.printStackTrace();
402 // Some platforms do not have BasicFileChooserUI
407 * Returns the selected file format, or null if none selected
411 public FileFormatI getSelectedFormat()
413 if (getFileFilter() == null)
419 * logic here depends on option description being formatted as
420 * formatName (extension, extension...)
421 * or the 'no option selected' value
423 * @see JalviewFileFilter.getDescription
425 String format = getFileFilter().getDescription();
426 int parenPos = format.indexOf("(");
429 format = format.substring(0, parenPos).trim();
432 return FileFormats.getInstance().forName(format);
433 } catch (IllegalArgumentException e)
435 System.err.println("Unexpected format: " + format);
442 public File getSelectedFile()
444 File f = super.getSelectedFile();
445 return f == null ? selectedFile : f;
449 public int showSaveDialog(Component parent) throws HeadlessException
451 this.setAccessory(null);
452 // Java 9,10,11 on OSX - clear selected file so name isn't auto populated
453 this.setSelectedFile(null);
455 return super.showSaveDialog(parent);
459 * If doing a Save, and an existing file is chosen or entered, prompt for
460 * confirmation of overwrite. Proceed if Yes, else leave the file chooser
463 * @see https://stackoverflow.com/questions/8581215/jfilechooser-and-checking-for-overwrite
466 public void approveSelection()
468 if (getDialogType() != SAVE_DIALOG)
470 super.approveSelection();
474 selectedFile = getSelectedFile();
476 if (selectedFile == null)
478 // Workaround for Java 9,10 on OSX - no selected file, but there is a
482 String filename = ((BasicFileChooserUI) getUI()).getFileName();
483 if (filename != null && filename.length() > 0)
485 selectedFile = new File(getCurrentDirectory(), filename);
487 } catch (Throwable x)
490 "Unexpected exception when trying to get filename.");
493 // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND
495 // USER PROMPTED FOR A NEW FILENAME
498 if (selectedFile == null)
503 if (getFileFilter() instanceof JalviewFileFilter)
505 JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
507 if (!jvf.accept(selectedFile))
509 String withExtension = getSelectedFile().getName() + "."
510 + jvf.getAcceptableExtension();
511 selectedFile = (new File(getCurrentDirectory(), withExtension));
512 setSelectedFile(selectedFile);
516 if (selectedFile.exists())
518 int confirm = Cache.getDefault("CONFIRM_OVERWRITE_FILE", true)
519 ? JvOptionPane.showConfirmDialog(this,
521 .getString("label.overwrite_existing_file"),
522 MessageManager.getString("label.file_already_exists"),
523 JvOptionPane.YES_NO_OPTION)
524 : JOptionPane.YES_OPTION;
526 if (confirm != JvOptionPane.YES_OPTION)
532 super.approveSelection();
535 void recentListSelectionChanged(Object selection)
537 setSelectedFile(null);
538 if (selection != null)
540 File file = new File((String) selection);
541 if (getFileFilter() instanceof JalviewFileFilter)
543 JalviewFileFilter jvf = (JalviewFileFilter) this.getFileFilter();
545 if (!jvf.accept(file))
547 setFileFilter(getChoosableFileFilters()[0]);
551 setSelectedFile(file);
555 class RecentlyOpened extends JPanel
557 private static final long serialVersionUID = 1L;
563 setPreferredSize(new Dimension(300, 100));
564 String historyItems = Cache.getProperty("RECENT_FILE");
566 Vector<String> recent = new Vector<>();
568 if (historyItems != null)
570 st = new StringTokenizer(historyItems, "\t");
572 while (st.hasMoreTokens())
574 recent.addElement(st.nextToken());
578 list = new JList<>(recent);
579 list.setCellRenderer(new recentlyOpenedCellRenderer());
581 list.addMouseListener(new MouseAdapter()
584 public void mousePressed(MouseEvent evt)
586 recentListSelectionChanged(list.getSelectedValue());
590 TitledBorder recentlyOpenedBorder = new TitledBorder(
591 MessageManager.getString("label.recently_opened"));
592 recentlyOpenedBorder.setTitleFont(
593 recentlyOpenedBorder.getTitleFont().deriveFont(10f));
594 this.setBorder(recentlyOpenedBorder);
596 final JScrollPane scroller = new JScrollPane(list);
598 SpringLayout layout = new SpringLayout();
599 layout.putConstraint(SpringLayout.WEST, scroller, 5,
600 SpringLayout.WEST, this);
601 layout.putConstraint(SpringLayout.NORTH, scroller, 5,
602 SpringLayout.NORTH, this);
604 // one size okay for all
605 scroller.setPreferredSize(new Dimension(280, 105));
608 SwingUtilities.invokeLater(new Runnable()
613 scroller.getHorizontalScrollBar()
614 .setValue(scroller.getHorizontalScrollBar().getMaximum());
622 class recentlyOpenedCellRenderer extends JLabel
623 implements ListCellRenderer<String>
625 private final static int maxChars = 46;
627 private final static String ellipsis = "...";
630 public Component getListCellRendererComponent(
631 JList<? extends String> list, String value, int index,
632 boolean isSelected, boolean cellHasFocus)
634 String filename = value.toString();
635 String displayFilename;
636 if (filename.length() > maxChars)
638 StringBuilder displayFileSB = new StringBuilder();
639 File file = new File(filename);
640 displayFileSB.append(file.getName());
641 if (file.getParent() != null)
644 boolean spaceleft = true;
645 while (spaceleft && parent.getParent() != null)
647 parent = parent.getParentFile();
648 String name = parent.getName();
649 displayFileSB.insert(0, File.separator);
650 if (displayFileSB.length() + name.length() < maxChars - 1)
652 displayFileSB.insert(0, name);
656 displayFileSB.insert(0, ellipsis);
660 if (spaceleft && filename.startsWith(File.separator)
661 && !(displayFileSB.charAt(0) == File.separatorChar))
663 displayFileSB.insert(0, File.separator);
666 displayFilename = displayFileSB.toString();
670 displayFilename = filename;
672 this.setText(displayFilename.toString());
673 this.setToolTipText(filename);
676 setBackground(list.getSelectionBackground());
677 setForeground(list.getSelectionForeground());
681 setBackground(list.getBackground());
682 setForeground(list.getForeground());
684 this.setHorizontalAlignment(SwingConstants.TRAILING);
685 this.setEnabled(list.isEnabled());
686 this.setFont(list.getFont().deriveFont(12f));
687 this.setOpaque(true);
695 public JalviewFileChooser setResponseHandler(Object response,
698 callbacks.put(response, new Callable<Void>()
712 public DialogRunnerI setResponseHandler(Object response, Runnable action)
714 callbacks.put(response, action);
719 public void handleResponse(Object response)
722 * this test is for NaN in Chrome
724 if (response != null && !response.equals(response))
728 Runnable action = callbacks.get(response);
734 } catch (Exception e)
742 * JalviewJS signals file selection by a property change event for property
743 * "SelectedFile". This methods responds to that by running the response
744 * action for 'OK' in the dialog.
749 public void propertyChange(PropertyChangeEvent evt)
751 // TODO other properties need runners...
752 switch (evt.getPropertyName())
755 * property name here matches that used in JFileChooser.js
758 handleResponse(APPROVE_OPTION);
764 protected JDialog createDialog(Component parent) throws HeadlessException
766 JDialog dialog = super.createDialog(parent);
767 dialog.setIconImages(ChannelProperties.getIconList());