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.bin.Jalview;
26 import jalview.gui.JvOptionPane;
27 import jalview.util.MessageManager;
28 import jalview.util.Platform;
29 import jalview.util.dialogrunner.DialogRunner;
30 import jalview.util.dialogrunner.DialogRunnerI;
31 import jalview.util.dialogrunner.RunResponse;
33 import java.awt.Component;
34 import java.awt.Dimension;
35 import java.awt.EventQueue;
36 import java.awt.HeadlessException;
37 import java.awt.event.MouseAdapter;
38 import java.awt.event.MouseEvent;
39 import java.beans.PropertyChangeEvent;
40 import java.beans.PropertyChangeListener;
42 import java.util.ArrayList;
43 import java.util.List;
44 import java.util.StringTokenizer;
45 import java.util.Vector;
47 import javax.swing.DefaultListCellRenderer;
48 import javax.swing.JFileChooser;
49 import javax.swing.JList;
50 import javax.swing.JPanel;
51 import javax.swing.JScrollPane;
52 import javax.swing.SpringLayout;
53 import javax.swing.SwingUtilities;
54 import javax.swing.border.TitledBorder;
55 import javax.swing.plaf.basic.BasicFileChooserUI;
58 * Enhanced file chooser dialog box.
60 * NOTE: bug on Windows systems when filechooser opened on directory to view
61 * files with colons in title.
66 public class JalviewFileChooser extends JFileChooser implements DialogRunnerI,
67 PropertyChangeListener
69 private static final long serialVersionUID = 1L;
71 private DialogRunnerI runner = new DialogRunner();
73 File selectedFile = null;
76 * Factory method to return a file chooser that offers readable alignment file
83 public static JalviewFileChooser forRead(String directory,
86 List<String> extensions = new ArrayList<>();
87 List<String> descs = new ArrayList<>();
88 for (FileFormatI format : FileFormats.getInstance().getFormats())
90 if (format.isReadable())
92 extensions.add(format.getExtensions());
93 descs.add(format.getName());
96 return new JalviewFileChooser(directory,
97 extensions.toArray(new String[extensions.size()]),
98 descs.toArray(new String[descs.size()]), selected, true);
102 * Factory method to return a file chooser that offers writable alignment file
109 public static JalviewFileChooser forWrite(String directory,
112 // TODO in Java 8, forRead and forWrite can be a single method
113 // with a lambda expression parameter for isReadable/isWritable
114 List<String> extensions = new ArrayList<>();
115 List<String> descs = new ArrayList<>();
116 for (FileFormatI format : FileFormats.getInstance().getFormats())
118 if (format.isWritable())
120 extensions.add(format.getExtensions());
121 descs.add(format.getName());
124 return new JalviewFileChooser(directory,
125 extensions.toArray(new String[extensions.size()]),
126 descs.toArray(new String[descs.size()]), selected, false);
129 public JalviewFileChooser(String dir)
131 super(safePath(dir));
132 setAccessory(new RecentlyOpened());
135 public JalviewFileChooser(String dir, String[] suffix, String[] desc,
138 this(dir, suffix, desc, selected, true);
142 * Constructor for a single choice of file extension and description
147 public JalviewFileChooser(String extension, String desc)
149 this(Cache.getProperty("LAST_DIRECTORY"), new String[] { extension },
151 { desc }, desc, true);
154 JalviewFileChooser(String dir, String[] extensions, String[] descs,
155 String selected, boolean acceptAny)
157 super(safePath(dir));
158 if (extensions.length == descs.length)
160 List<String[]> formats = new ArrayList<>();
161 for (int i = 0; i < extensions.length; i++)
163 formats.add(new String[] { extensions[i], descs[i] });
165 init(formats, selected, acceptAny);
169 System.err.println("JalviewFileChooser arguments mismatch: "
170 + extensions + ", " + descs);
174 private static File safePath(String dir)
181 File f = new File(dir);
182 if (f.getName().indexOf(':') > -1)
190 * Overridden for JalviewJS compatibility: only one thread in Javascript,
191 * so we can't wait for user choice in another thread and then perform the
195 public int showOpenDialog(Component parent)
197 // runner.resetResponses();
198 int value = super.showOpenDialog(this);
201 runner.handleResponse(value);
209 * a list of {extensions, description} for each file format
212 * if true, 'any format' option is included
214 void init(List<String[]> formats, String selected, boolean acceptAny)
217 JalviewFileFilter chosen = null;
219 // SelectAllFilter needs to be set first before adding further
220 // file filters to fix bug on Mac OSX
221 setAcceptAllFileFilterUsed(acceptAny);
223 for (String[] format : formats)
225 JalviewFileFilter jvf = new JalviewFileFilter(format[0], format[1]);
226 addChoosableFileFilter(jvf);
227 if ((selected != null) && selected.equalsIgnoreCase(format[1]))
235 setFileFilter(chosen);
238 setAccessory(new RecentlyOpened());
242 public void setFileFilter(javax.swing.filechooser.FileFilter filter)
244 super.setFileFilter(filter);
248 if (getUI() instanceof BasicFileChooserUI)
250 final BasicFileChooserUI fcui = (BasicFileChooserUI) getUI();
251 final String name = fcui.getFileName().trim();
253 if ((name == null) || (name.length() == 0))
258 EventQueue.invokeLater(new Thread()
263 String currentName = fcui.getFileName();
264 if ((currentName == null) || (currentName.length() == 0))
266 fcui.setFileName(name);
271 } catch (Exception ex)
273 ex.printStackTrace();
274 // Some platforms do not have BasicFileChooserUI
279 * Returns the selected file format, or null if none selected
283 public FileFormatI getSelectedFormat()
285 if (getFileFilter() == null)
291 * logic here depends on option description being formatted as
292 * formatName (extension, extension...)
293 * or the 'no option selected' value
295 * @see JalviewFileFilter.getDescription
297 String format = getFileFilter().getDescription();
298 int parenPos = format.indexOf("(");
301 format = format.substring(0, parenPos).trim();
304 return FileFormats.getInstance().forName(format);
305 } catch (IllegalArgumentException e)
307 System.err.println("Unexpected format: " + format);
314 public File getSelectedFile()
316 File f = super.getSelectedFile();
317 return f == null ? selectedFile : f;
321 * Overridden for JalviewJS compatibility: only one thread in Javascript,
322 * so we can't wait for user choice in another thread and then perform the
326 public int showSaveDialog(Component parent) throws HeadlessException
328 this.setAccessory(null);
329 this.setSelectedFile(null);
330 return super.showSaveDialog(parent);
334 * If doing a Save, and an existing file is chosen or entered, prompt for
335 * confirmation of overwrite. Proceed if Yes, else leave the file chooser
338 * @see https://stackoverflow.com/questions/8581215/jfilechooser-and-checking-for-overwrite
341 public void approveSelection()
343 if (getDialogType() != SAVE_DIALOG)
345 super.approveSelection();
349 selectedFile = getSelectedFile();
351 if (selectedFile == null)
353 // Workaround for Java 9,10 on OSX - no selected file, but there is a
357 String filename = ((BasicFileChooserUI) getUI()).getFileName();
358 if (filename != null && filename.length() > 0)
360 selectedFile = new File(getCurrentDirectory(), filename);
362 } catch (Throwable x)
365 "Unexpected exception when trying to get filename.");
368 // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND
370 // USER PROMPTED FOR A NEW FILENAME
373 if (selectedFile == null)
378 if (getFileFilter() instanceof JalviewFileFilter)
380 JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
382 if (!jvf.accept(selectedFile))
384 String withExtension = getSelectedFile().getName() + "."
385 + jvf.getAcceptableExtension();
386 selectedFile = (new File(getCurrentDirectory(), withExtension));
387 setSelectedFile(selectedFile);
391 if (selectedFile.exists())
393 int confirm = JvOptionPane.showConfirmDialog(this,
394 MessageManager.getString("label.overwrite_existing_file"),
395 MessageManager.getString("label.file_already_exists"),
396 JvOptionPane.YES_NO_OPTION);
397 if (confirm != JvOptionPane.YES_OPTION)
403 super.approveSelection();
406 void recentListSelectionChanged(Object selection)
408 setSelectedFile(null);
409 if (selection != null)
411 File file = new File((String) selection);
412 if (getFileFilter() instanceof JalviewFileFilter)
414 JalviewFileFilter jvf = (JalviewFileFilter) this.getFileFilter();
416 if (!jvf.accept(file))
418 setFileFilter(getChoosableFileFilters()[0]);
422 setSelectedFile(file);
427 * A panel to set as the 'accessory' component to the file chooser dialog,
428 * holding a list of recently opened files (if any). These are held as a
429 * tab-separated list of file paths under key <code>RECENT_FILE</code> in
430 * <code>.jalview_properties</code>. A click in the list calls a method in
431 * JalviewFileChooser to set the chosen file as the selection.
433 class RecentlyOpened extends JPanel
435 private static final long serialVersionUID = 1L;
441 setPreferredSize(new Dimension(300,100));
442 String historyItems = Cache.getProperty("RECENT_FILE");
444 Vector<String> recent = new Vector<>();
446 if (historyItems != null)
448 st = new StringTokenizer(historyItems, "\t");
449 while (st.hasMoreTokens())
451 recent.addElement(st.nextToken());
455 list = new JList<>(recent);
457 DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
458 // dlcr.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
459 list.setCellRenderer(dlcr);
461 list.addMouseListener(new MouseAdapter()
464 public void mousePressed(MouseEvent evt)
466 recentListSelectionChanged(list.getSelectedValue());
470 this.setBorder(new TitledBorder(
471 MessageManager.getString("label.recently_opened")));
473 final JScrollPane scroller = new JScrollPane(list);
475 SpringLayout layout = new SpringLayout();
476 layout.putConstraint(SpringLayout.WEST, scroller, 5,
477 SpringLayout.WEST, this);
478 layout.putConstraint(SpringLayout.NORTH, scroller, 5,
479 SpringLayout.NORTH, this);
481 if (Platform.isAMac())
483 scroller.setPreferredSize(new Dimension(500, 100));
487 scroller.setPreferredSize(new Dimension(530, 200));
492 SwingUtilities.invokeLater(new Runnable()
497 scroller.getHorizontalScrollBar()
498 .setValue(scroller.getHorizontalScrollBar().getMaximum());
505 public DialogRunnerI addResponse(Object response, RunResponse action)
507 return runner.addResponse(response, action);
511 * JalviewJS signals file selection by a property change event
512 * for property "SelectedFile". This methods responds to that by
513 * running the response action for 'OK' in the dialog.
518 public void propertyChange(PropertyChangeEvent evt)
520 // TODO other properties need runners...
521 switch (evt.getPropertyName())
524 runner.handleResponse(APPROVE_OPTION);