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())
226 * code here is not run in JalviewJS, instead
227 * propertyChange() is called for dialog action
229 handleResponse(value);
237 * a list of {extensions, description} for each file format
240 * if true, 'any format' option is included
242 void init(List<String[]> formats, String selected, boolean acceptAny)
244 init(formats, selected, acceptAny, false);
247 void init(List<String[]> formats, String selected, boolean acceptAny,
248 boolean allowBackupFiles)
251 JalviewFileFilter chosen = null;
253 // SelectAllFilter needs to be set first before adding further
254 // file filters to fix bug on Mac OSX
255 setAcceptAllFileFilterUsed(acceptAny);
257 for (String[] format : formats)
259 JalviewFileFilter jvf = new JalviewFileFilter(format[0], format[1]);
260 if (allowBackupFiles)
262 jvf.setParentJFC(this);
264 addChoosableFileFilter(jvf);
265 if ((selected != null) && selected.equalsIgnoreCase(format[1]))
273 setFileFilter(chosen);
276 if (allowBackupFiles)
278 JPanel multi = new JPanel();
279 multi.setLayout(new BoxLayout(multi, BoxLayout.PAGE_AXIS));
280 if (backupfilesCheckBox == null)
283 includeBackupFiles = Boolean.parseBoolean(
284 Cache.getProperty(BackupFiles.NS + "_FC_INCLUDE"));
285 } catch (Exception e)
287 includeBackupFiles = false;
289 backupfilesCheckBox = new JCheckBox(
290 MessageManager.getString("label.include_backup_files"),
292 backupfilesCheckBox.setAlignmentX(Component.CENTER_ALIGNMENT);
293 JalviewFileChooser jfc = this;
294 backupfilesCheckBox.addActionListener(new ActionListener()
297 public void actionPerformed(ActionEvent e)
299 includeBackupFiles = backupfilesCheckBox.isSelected();
300 Cache.setProperty(BackupFiles.NS + "_FC_INCLUDE",
301 String.valueOf(includeBackupFiles));
303 FileFilter f = jfc.getFileFilter();
304 // deselect the selected file if it's no longer choosable
305 File selectedFile = jfc.getSelectedFile();
306 if (selectedFile != null && !f.accept(selectedFile))
308 jfc.setSelectedFile(null);
310 // fake the OK button changing (to force it to upate)
311 String s = jfc.getApproveButtonText();
312 jfc.firePropertyChange(
313 APPROVE_BUTTON_TEXT_CHANGED_PROPERTY, null, s);
314 // fake the file filter changing (its behaviour actually has)
315 jfc.firePropertyChange(FILE_FILTER_CHANGED_PROPERTY, null, f);
317 jfc.rescanCurrentDirectory();
323 multi.add(new RecentlyOpened());
324 multi.add(backupfilesCheckBox);
329 // set includeBackupFiles=false to avoid other file choosers from picking
330 // up backup files (Just In Case)
331 includeBackupFiles = false;
332 setAccessory(new RecentlyOpened());
337 public void setFileFilter(javax.swing.filechooser.FileFilter filter)
339 super.setFileFilter(filter);
343 if (getUI() instanceof BasicFileChooserUI)
345 final BasicFileChooserUI fcui = (BasicFileChooserUI) getUI();
346 final String name = fcui.getFileName().trim();
348 if ((name == null) || (name.length() == 0))
353 EventQueue.invokeLater(new Thread()
358 String currentName = fcui.getFileName();
359 if ((currentName == null) || (currentName.length() == 0))
361 fcui.setFileName(name);
366 } catch (Exception ex)
368 ex.printStackTrace();
369 // Some platforms do not have BasicFileChooserUI
374 * Returns the selected file format, or null if none selected
378 public FileFormatI getSelectedFormat()
380 if (getFileFilter() == null)
386 * logic here depends on option description being formatted as
387 * formatName (extension, extension...)
388 * or the 'no option selected' value
390 * @see JalviewFileFilter.getDescription
392 String format = getFileFilter().getDescription();
393 int parenPos = format.indexOf("(");
396 format = format.substring(0, parenPos).trim();
399 return FileFormats.getInstance().forName(format);
400 } catch (IllegalArgumentException e)
402 System.err.println("Unexpected format: " + format);
409 public File getSelectedFile()
411 File f = super.getSelectedFile();
412 return f == null ? selectedFile : f;
416 public int showSaveDialog(Component parent) throws HeadlessException
418 this.setAccessory(null);
419 // Java 9,10,11 on OSX - clear selected file so name isn't auto populated
420 this.setSelectedFile(null);
422 return super.showSaveDialog(parent);
426 * If doing a Save, and an existing file is chosen or entered, prompt for
427 * confirmation of overwrite. Proceed if Yes, else leave the file chooser
430 * @see https://stackoverflow.com/questions/8581215/jfilechooser-and-checking-for-overwrite
433 public void approveSelection()
435 if (getDialogType() != SAVE_DIALOG)
437 super.approveSelection();
441 selectedFile = getSelectedFile();
443 if (selectedFile == null)
445 // Workaround for Java 9,10 on OSX - no selected file, but there is a
449 String filename = ((BasicFileChooserUI) getUI()).getFileName();
450 if (filename != null && filename.length() > 0)
452 selectedFile = new File(getCurrentDirectory(), filename);
454 } catch (Throwable x)
457 "Unexpected exception when trying to get filename.");
460 // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND
462 // USER PROMPTED FOR A NEW FILENAME
465 if (selectedFile == null)
470 if (getFileFilter() instanceof JalviewFileFilter)
472 JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
474 if (!jvf.accept(selectedFile))
476 String withExtension = getSelectedFile().getName() + "."
477 + jvf.getAcceptableExtension();
478 selectedFile = (new File(getCurrentDirectory(), withExtension));
479 setSelectedFile(selectedFile);
483 if (selectedFile.exists())
485 int confirm = JvOptionPane.showConfirmDialog(this,
486 MessageManager.getString("label.overwrite_existing_file"),
487 MessageManager.getString("label.file_already_exists"),
488 JvOptionPane.YES_NO_OPTION);
490 if (confirm != JvOptionPane.YES_OPTION)
496 super.approveSelection();
499 void recentListSelectionChanged(Object selection)
501 setSelectedFile(null);
502 if (selection != null)
504 File file = new File((String) selection);
505 if (getFileFilter() instanceof JalviewFileFilter)
507 JalviewFileFilter jvf = (JalviewFileFilter) this.getFileFilter();
509 if (!jvf.accept(file))
511 setFileFilter(getChoosableFileFilters()[0]);
515 setSelectedFile(file);
519 class RecentlyOpened extends JPanel
521 private static final long serialVersionUID = 1L;
526 setPreferredSize(new Dimension(300,100));
527 String historyItems = Cache.getProperty("RECENT_FILE");
529 Vector<String> recent = new Vector<>();
531 if (historyItems != null)
533 st = new StringTokenizer(historyItems, "\t");
535 while (st.hasMoreTokens())
537 recent.addElement(st.nextToken());
541 list = new JList<>(recent);
543 DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
544 dlcr.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
545 list.setCellRenderer(dlcr);
547 list.addMouseListener(new MouseAdapter()
550 public void mousePressed(MouseEvent evt)
552 recentListSelectionChanged(list.getSelectedValue());
556 this.setBorder(new javax.swing.border.TitledBorder(
557 MessageManager.getString("label.recently_opened")));
559 final JScrollPane scroller = new JScrollPane(list);
561 SpringLayout layout = new SpringLayout();
562 layout.putConstraint(SpringLayout.WEST, scroller, 5,
563 SpringLayout.WEST, this);
564 layout.putConstraint(SpringLayout.NORTH, scroller, 5,
565 SpringLayout.NORTH, this);
567 if (Platform.isAMacAndNotJS())
569 scroller.setPreferredSize(new Dimension(500, 100));
573 scroller.setPreferredSize(new Dimension(530, 200));
578 javax.swing.SwingUtilities.invokeLater(new Runnable()
583 scroller.getHorizontalScrollBar()
584 .setValue(scroller.getHorizontalScrollBar().getMaximum());
593 public DialogRunnerI setResponseHandler(Object response, Runnable action)
595 callbacks.put(response, action);
600 public void handleResponse(Object response)
603 * this test is for NaN in Chrome
605 if (response != null && !response.equals(response))
609 Runnable action = callbacks.get(response);
617 * JalviewJS signals file selection by a property change event
618 * for property "SelectedFile". This methods responds to that by
619 * running the response action for 'OK' in the dialog.
624 public void propertyChange(PropertyChangeEvent evt)
626 // TODO other properties need runners...
627 switch (evt.getPropertyName())
630 * property name here matches that used in JFileChooser.js
633 handleResponse(APPROVE_OPTION);