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);
201 .errPrintln("JalviewFileChooser arguments mismatch: "
202 + extensions + ", " + descs);
206 private static File safePath(String dir)
213 File f = new File(dir);
214 if (f.getName().indexOf(':') > -1)
222 * Overridden for JalviewJS compatibility: only one thread in Javascript, so
223 * we can't wait for user choice in another thread and then perform the
227 public int showOpenDialog(Component parent)
229 int value = super.showOpenDialog(this);
231 if (!Platform.isJS())
239 * code here is not run in JalviewJS, instead
240 * propertyChange() is called for dialog action
242 handleResponse(value);
250 * a list of {extensions, description} for each file format
253 * if true, 'any format' option is included
255 void init(List<String[]> formats, String selected, boolean acceptAny)
257 init(formats, selected, acceptAny, false);
260 void init(List<String[]> formats, String selected, boolean acceptAny,
261 boolean allowBackupFiles)
264 JalviewFileFilter chosen = null;
266 // SelectAllFilter needs to be set first before adding further
267 // file filters to fix bug on Mac OSX
268 setAcceptAllFileFilterUsed(acceptAny);
270 // add a "All known alignment files" option
271 List<String> allExtensions = new ArrayList<>();
272 for (String[] format : formats)
274 String[] extensions = format[0].split(",");
275 for (String ext : extensions)
277 if (!allExtensions.contains(ext))
279 allExtensions.add(ext);
283 allExtensions.sort(null);
284 JalviewFileFilter alljvf = new JalviewFileFilter(
285 allExtensions.toArray(new String[] {}),
286 MessageManager.getString("label.all_known_alignment_files"));
287 alljvf.setExtensionListInDescription(false);
288 addChoosableFileFilter(alljvf);
290 if (selected == null)
295 for (String[] format : formats)
297 JalviewFileFilter jvf = new JalviewFileFilter(format[0], format[1]);
298 if (allowBackupFiles)
300 jvf.setParentJFC(this);
302 addChoosableFileFilter(jvf);
303 if ((selected != null) && selected.equalsIgnoreCase(format[1]))
311 setFileFilter(chosen);
314 if (allowBackupFiles)
316 JPanel multi = new JPanel();
317 multi.setLayout(new BoxLayout(multi, BoxLayout.PAGE_AXIS));
318 if (backupfilesCheckBox == null)
322 includeBackupFiles = Boolean.parseBoolean(
323 Cache.getProperty(BackupFiles.NS + "_FC_INCLUDE"));
324 } catch (Exception e)
326 includeBackupFiles = false;
328 backupfilesCheckBox = new JCheckBox(
329 MessageManager.getString("label.include_backup_files"),
331 backupfilesCheckBox.setAlignmentX(Component.CENTER_ALIGNMENT);
332 JalviewFileChooser jfc = this;
333 backupfilesCheckBox.addActionListener(new ActionListener()
336 public void actionPerformed(ActionEvent e)
338 includeBackupFiles = backupfilesCheckBox.isSelected();
339 Cache.setProperty(BackupFiles.NS + "_FC_INCLUDE",
340 String.valueOf(includeBackupFiles));
342 FileFilter f = jfc.getFileFilter();
343 // deselect the selected file if it's no longer choosable
344 File selectedFile = jfc.getSelectedFile();
345 if (selectedFile != null && !f.accept(selectedFile))
347 jfc.setSelectedFile(null);
349 // fake the OK button changing (to force it to upate)
350 String s = jfc.getApproveButtonText();
351 jfc.firePropertyChange(APPROVE_BUTTON_TEXT_CHANGED_PROPERTY,
353 // fake the file filter changing (its behaviour actually has)
354 jfc.firePropertyChange(FILE_FILTER_CHANGED_PROPERTY, null, f);
356 jfc.rescanCurrentDirectory();
362 multi.add(new RecentlyOpened());
363 multi.add(backupfilesCheckBox);
368 // set includeBackupFiles=false to avoid other file choosers from picking
369 // up backup files (Just In Case)
370 includeBackupFiles = false;
371 setAccessory(new RecentlyOpened());
376 public void setFileFilter(javax.swing.filechooser.FileFilter filter)
378 super.setFileFilter(filter);
382 if (getUI() instanceof BasicFileChooserUI)
384 final BasicFileChooserUI fcui = (BasicFileChooserUI) getUI();
385 final String name = fcui.getFileName().trim();
387 if ((name == null) || (name.length() == 0))
392 EventQueue.invokeLater(new Thread()
397 String currentName = fcui.getFileName();
398 if ((currentName == null) || (currentName.length() == 0))
400 fcui.setFileName(name);
405 } catch (Exception ex)
407 ex.printStackTrace();
408 // Some platforms do not have BasicFileChooserUI
413 * Returns the selected file format, or null if none selected
417 public FileFormatI getSelectedFormat()
419 if (getFileFilter() == null)
425 * logic here depends on option description being formatted as
426 * formatName (extension, extension...)
427 * or the 'no option selected' value
429 * @see JalviewFileFilter.getDescription
431 String format = getFileFilter().getDescription();
432 int parenPos = format.indexOf("(");
435 format = format.substring(0, parenPos).trim();
438 return FileFormats.getInstance().forName(format);
439 } catch (IllegalArgumentException e)
441 jalview.bin.Console.errPrintln("Unexpected format: " + format);
448 public File getSelectedFile()
450 File f = super.getSelectedFile();
451 return f == null ? selectedFile : f;
455 public int showSaveDialog(Component parent) throws HeadlessException
457 this.setAccessory(null);
458 // Java 9,10,11 on OSX - clear selected file so name isn't auto populated
459 this.setSelectedFile(null);
461 return super.showSaveDialog(parent);
465 * If doing a Save, and an existing file is chosen or entered, prompt for
466 * confirmation of overwrite. Proceed if Yes, else leave the file chooser
469 * @see https://stackoverflow.com/questions/8581215/jfilechooser-and-checking-for-overwrite
472 public void approveSelection()
474 if (getDialogType() != SAVE_DIALOG)
476 super.approveSelection();
480 selectedFile = getSelectedFile();
482 if (selectedFile == null)
484 // Workaround for Java 9,10 on OSX - no selected file, but there is a
488 String filename = ((BasicFileChooserUI) getUI()).getFileName();
489 if (filename != null && filename.length() > 0)
491 selectedFile = new File(getCurrentDirectory(), filename);
493 } catch (Throwable x)
495 jalview.bin.Console.errPrintln(
496 "Unexpected exception when trying to get filename.");
499 // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND
501 // USER PROMPTED FOR A NEW FILENAME
504 if (selectedFile == null)
509 if (getFileFilter() instanceof JalviewFileFilter)
511 JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
513 if (!jvf.accept(selectedFile))
515 String withExtension = getSelectedFile().getName() + "."
516 + jvf.getAcceptableExtension();
517 selectedFile = (new File(getCurrentDirectory(), withExtension));
518 setSelectedFile(selectedFile);
522 if (selectedFile.exists())
524 int confirm = Cache.getDefault("CONFIRM_OVERWRITE_FILE", true)
525 ? JvOptionPane.showConfirmDialog(this,
527 .getString("label.overwrite_existing_file"),
528 MessageManager.getString("label.file_already_exists"),
529 JvOptionPane.YES_NO_OPTION)
530 : JOptionPane.YES_OPTION;
532 if (confirm != JvOptionPane.YES_OPTION)
538 super.approveSelection();
541 void recentListSelectionChanged(Object selection)
543 setSelectedFile(null);
544 if (selection != null)
546 File file = new File((String) selection);
547 if (getFileFilter() instanceof JalviewFileFilter)
549 JalviewFileFilter jvf = (JalviewFileFilter) this.getFileFilter();
551 if (!jvf.accept(file))
553 setFileFilter(getChoosableFileFilters()[0]);
557 if (!file.isAbsolute() && file.exists())
559 file = file.getAbsoluteFile();
562 setSelectedFile(file);
566 class RecentlyOpened extends JPanel
568 private static final long serialVersionUID = 1L;
574 setPreferredSize(new Dimension(300, 100));
575 String historyItems = Cache.getProperty("RECENT_FILE");
577 Vector<String> recent = new Vector<>();
579 if (historyItems != null)
581 st = new StringTokenizer(historyItems, "\t");
583 while (st.hasMoreTokens())
585 recent.addElement(st.nextToken());
589 list = new JList<>(recent);
590 list.setCellRenderer(new recentlyOpenedCellRenderer());
592 list.addMouseListener(new MouseAdapter()
595 public void mousePressed(MouseEvent evt)
597 recentListSelectionChanged(list.getSelectedValue());
601 TitledBorder recentlyOpenedBorder = new TitledBorder(
602 MessageManager.getString("label.recently_opened"));
603 recentlyOpenedBorder.setTitleFont(
604 recentlyOpenedBorder.getTitleFont().deriveFont(10f));
605 this.setBorder(recentlyOpenedBorder);
607 final JScrollPane scroller = new JScrollPane(list);
609 SpringLayout layout = new SpringLayout();
610 layout.putConstraint(SpringLayout.WEST, scroller, 5,
611 SpringLayout.WEST, this);
612 layout.putConstraint(SpringLayout.NORTH, scroller, 5,
613 SpringLayout.NORTH, this);
615 // one size okay for all
616 scroller.setPreferredSize(new Dimension(280, 105));
619 SwingUtilities.invokeLater(new Runnable()
624 scroller.getHorizontalScrollBar()
625 .setValue(scroller.getHorizontalScrollBar().getMaximum());
633 class recentlyOpenedCellRenderer extends JLabel
634 implements ListCellRenderer<String>
636 private final static int maxChars = 46;
638 private final static String ellipsis = "...";
641 public Component getListCellRendererComponent(
642 JList<? extends String> list, String value, int index,
643 boolean isSelected, boolean cellHasFocus)
645 String filename = value.toString();
646 String displayFilename;
647 if (filename.length() > maxChars)
649 StringBuilder displayFileSB = new StringBuilder();
650 File file = new File(filename);
651 displayFileSB.append(file.getName());
652 if (file.getParent() != null)
655 boolean spaceleft = true;
656 while (spaceleft && parent.getParent() != null)
658 parent = parent.getParentFile();
659 String name = parent.getName();
660 displayFileSB.insert(0, File.separator);
661 if (displayFileSB.length() + name.length() < maxChars - 1)
663 displayFileSB.insert(0, name);
667 displayFileSB.insert(0, ellipsis);
671 if (spaceleft && filename.startsWith(File.separator)
672 && !(displayFileSB.charAt(0) == File.separatorChar))
674 displayFileSB.insert(0, File.separator);
677 displayFilename = displayFileSB.toString();
681 displayFilename = filename;
683 this.setText(displayFilename.toString());
684 this.setToolTipText(filename);
687 setBackground(list.getSelectionBackground());
688 setForeground(list.getSelectionForeground());
692 setBackground(list.getBackground());
693 setForeground(list.getForeground());
695 this.setHorizontalAlignment(SwingConstants.TRAILING);
696 this.setEnabled(list.isEnabled());
697 this.setFont(list.getFont().deriveFont(12f));
698 this.setOpaque(true);
706 public JalviewFileChooser setResponseHandler(Object response,
709 callbacks.put(response, new Callable<Void>()
723 public DialogRunnerI setResponseHandler(Object response, Runnable action)
725 callbacks.put(response, action);
730 public void handleResponse(Object response)
733 * this test is for NaN in Chrome
735 if (response != null && !response.equals(response))
739 Runnable action = callbacks.get(response);
745 } catch (Exception e)
753 * JalviewJS signals file selection by a property change event for property
754 * "SelectedFile". This methods responds to that by running the response
755 * action for 'OK' in the dialog.
760 public void propertyChange(PropertyChangeEvent evt)
762 // TODO other properties need runners...
763 switch (evt.getPropertyName())
766 * property name here matches that used in JFileChooser.js
769 handleResponse(APPROVE_OPTION);
775 protected JDialog createDialog(Component parent) throws HeadlessException
777 JDialog dialog = super.createDialog(parent);
778 dialog.setIconImages(ChannelProperties.getIconList());