import jalview.gui.JvOptionPane;
import jalview.util.MessageManager;
import jalview.util.Platform;
+import jalview.util.dialogrunner.DialogRunnerI;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SpringLayout;
+import javax.swing.filechooser.FileFilter;
import javax.swing.plaf.basic.BasicFileChooserUI;
/**
* @author AMW
*
*/
-public class JalviewFileChooser extends JFileChooser
+public class JalviewFileChooser extends JFileChooser implements DialogRunnerI,
+ PropertyChangeListener
{
+ private static final long serialVersionUID = 1L;
+
+ private Map<Object, Runnable> callbacks = new HashMap<>();
+
+ File selectedFile = null;
+
/**
* backupfilesCheckBox = "Include backup files" checkbox includeBackupfiles =
* flag set by checkbox
public static JalviewFileChooser forRead(String directory,
String selected)
{
+ return JalviewFileChooser.forRead(directory, selected, false);
+ }
+
+ public static JalviewFileChooser forRead(String directory,
+ String selected, boolean allowBackupFiles)
+ {
List<String> extensions = new ArrayList<>();
List<String> descs = new ArrayList<>();
for (FileFormatI format : FileFormats.getInstance().getFormats())
descs.add(format.getName());
}
}
+
return new JalviewFileChooser(directory,
extensions.toArray(new String[extensions.size()]),
- descs.toArray(new String[descs.size()]), selected, true);
+ descs.toArray(new String[descs.size()]), selected, true,
+ allowBackupFiles);
}
/**
}
JalviewFileChooser(String dir, String[] extensions, String[] descs,
- String selected, boolean allFiles)
+ String selected, boolean acceptAny)
{
- this(dir, extensions, descs, selected, allFiles, false);
+ this(dir, extensions, descs, selected, acceptAny, false);
}
public JalviewFileChooser(String dir, String[] extensions, String[] descs,
- String selected, boolean allFiles, boolean allowBackupFiles)
+ String selected, boolean acceptAny, boolean allowBackupFiles)
{
super(safePath(dir));
if (extensions.length == descs.length)
{
formats.add(new String[] { extensions[i], descs[i] });
}
- init(formats, selected, allFiles, allowBackupFiles);
+ init(formats, selected, acceptAny, allowBackupFiles);
}
else
{
}
/**
+ * Overridden for JalviewJS compatibility: only one thread in Javascript,
+ * so we can't wait for user choice in another thread and then perform the
+ * desired action
+ */
+ @Override
+ public int showOpenDialog(Component parent)
+ {
+ int value = super.showOpenDialog(this);
+
+ if (!Platform.isJS())
+ {
+ /*
+ * code here is not run in JalviewJS, instead
+ * propertyChange() is called for dialog action
+ */
+ handleResponse(value);
+ }
+ return value;
+ }
+
+ /**
*
* @param formats
* a list of {extensions, description} for each file format
* @param selected
- * @param allFiles
+ * @param acceptAny
* if true, 'any format' option is included
*/
- void init(List<String[]> formats, String selected, boolean allFiles)
+ void init(List<String[]> formats, String selected, boolean acceptAny)
{
- init(formats, selected, allFiles, false);
+ init(formats, selected, acceptAny, false);
}
- void init(List<String[]> formats, String selected, boolean allFiles,
+ void init(List<String[]> formats, String selected, boolean acceptAny,
boolean allowBackupFiles)
{
// SelectAllFilter needs to be set first before adding further
// file filters to fix bug on Mac OSX
- setAcceptAllFileFilterUsed(allFiles);
+ setAcceptAllFileFilterUsed(acceptAny);
for (String[] format : formats)
{
includeBackupFiles = backupfilesCheckBox.isSelected();
Cache.setProperty(BackupFiles.NS + "_FC_INCLUDE",
String.valueOf(includeBackupFiles));
+
+ FileFilter f = jfc.getFileFilter();
+ // deselect the selected file if it's no longer choosable
+ File selectedFile = jfc.getSelectedFile();
+ if (selectedFile != null && !f.accept(selectedFile))
+ {
+ jfc.setSelectedFile(null);
+ }
+ // fake the OK button changing (to force it to upate)
+ String s = jfc.getApproveButtonText();
+ jfc.firePropertyChange(
+ APPROVE_BUTTON_TEXT_CHANGED_PROPERTY, null, s);
+ // fake the file filter changing (its behaviour actually has)
+ jfc.firePropertyChange(FILE_FILTER_CHANGED_PROPERTY, null, f);
+
jfc.rescanCurrentDirectory();
jfc.revalidate();
jfc.repaint();
- // This is a kludge. Cannot find out how to get the file list to
- // refresh!
- /*
- Object o = jfc.getClientProperty(
- CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY);
- jfc.firePropertyChange(CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY,
- o, o);
- */
}
});
}
return null;
}
- File ourselectedFile = null;
-
@Override
public File getSelectedFile()
{
- File selfile = super.getSelectedFile();
- if (selfile == null && ourselectedFile != null)
- {
- return ourselectedFile;
- }
- return selfile;
+ File f = super.getSelectedFile();
+ return f == null ? selectedFile : f;
}
@Override
public int showSaveDialog(Component parent) throws HeadlessException
{
this.setAccessory(null);
+ // Java 9,10,11 on OSX - clear selected file so name isn't auto populated
+ this.setSelectedFile(null);
- setDialogType(SAVE_DIALOG);
+ return super.showSaveDialog(parent);
+ }
- this.setSelectedFile(null);
- int ret = showDialog(parent, MessageManager.getString("action.save"));
- ourselectedFile = getSelectedFile();
+ /**
+ * If doing a Save, and an existing file is chosen or entered, prompt for
+ * confirmation of overwrite. Proceed if Yes, else leave the file chooser
+ * open.
+ *
+ * @see https://stackoverflow.com/questions/8581215/jfilechooser-and-checking-for-overwrite
+ */
+ @Override
+ public void approveSelection()
+ {
+ if (getDialogType() != SAVE_DIALOG)
+ {
+ super.approveSelection();
+ return;
+ }
+
+ selectedFile = getSelectedFile();
- if (getSelectedFile() == null)
+ if (selectedFile == null)
{
// Workaround for Java 9,10 on OSX - no selected file, but there is a
// filename typed in
String filename = ((BasicFileChooserUI) getUI()).getFileName();
if (filename != null && filename.length() > 0)
{
- ourselectedFile = new File(getCurrentDirectory(), filename);
+ selectedFile = new File(getCurrentDirectory(), filename);
}
} catch (Throwable x)
{
"Unexpected exception when trying to get filename.");
x.printStackTrace();
}
+ // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND
+ // THE
+ // USER PROMPTED FOR A NEW FILENAME
}
- if (ourselectedFile == null)
+
+ if (selectedFile == null)
{
- return JalviewFileChooser.CANCEL_OPTION;
+ return;
}
+
if (getFileFilter() instanceof JalviewFileFilter)
{
JalviewFileFilter jvf = (JalviewFileFilter) getFileFilter();
- if (!jvf.accept(ourselectedFile))
+ if (!jvf.accept(selectedFile))
{
String withExtension = getSelectedFile().getName() + "."
+ jvf.getAcceptableExtension();
- ourselectedFile = (new File(getCurrentDirectory(), withExtension));
- setSelectedFile(ourselectedFile);
+ selectedFile = (new File(getCurrentDirectory(), withExtension));
+ setSelectedFile(selectedFile);
}
}
- // TODO: ENSURE THAT FILES SAVED WITH A ':' IN THE NAME ARE REFUSED AND THE
- // USER PROMPTED FOR A NEW FILENAME.
- // DO NOT need to confirm file overwrite if using backup files (the files
- // aren't being overwritten!)
- if ((ret == JalviewFileChooser.APPROVE_OPTION)
- && ourselectedFile.exists() && (!BackupFiles.getEnabled()))
+ if (selectedFile.exists())
{
- int confirm = JvOptionPane.showConfirmDialog(parent,
+ int confirm = JvOptionPane.showConfirmDialog(this,
MessageManager.getString("label.overwrite_existing_file"),
MessageManager.getString("label.file_already_exists"),
JvOptionPane.YES_NO_OPTION);
if (confirm != JvOptionPane.YES_OPTION)
{
- ret = JalviewFileChooser.CANCEL_OPTION;
+ return;
}
-
}
- return ret;
+ super.approveSelection();
}
void recentListSelectionChanged(Object selection)
class RecentlyOpened extends JPanel
{
- JList list;
+ private static final long serialVersionUID = 1L;
+ JList<String> list;
- public RecentlyOpened()
+ RecentlyOpened()
{
-
- String historyItems = jalview.bin.Cache.getProperty("RECENT_FILE");
+ setPreferredSize(new Dimension(300,100));
+ String historyItems = Cache.getProperty("RECENT_FILE");
StringTokenizer st;
- Vector recent = new Vector();
+ Vector<String> recent = new Vector<>();
if (historyItems != null)
{
while (st.hasMoreTokens())
{
- recent.addElement(st.nextElement());
+ recent.addElement(st.nextToken());
}
}
- list = new JList(recent);
-
+ list = new JList<>(recent);
+
DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
- dlcr.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
+// dlcr.setHorizontalAlignment(DefaultListCellRenderer.RIGHT);
list.setCellRenderer(dlcr);
list.addMouseListener(new MouseAdapter()
layout.putConstraint(SpringLayout.NORTH, scroller, 5,
SpringLayout.NORTH, this);
- if (new Platform().isAMac())
+ if (Platform.isAMacAndNotJS())
{
scroller.setPreferredSize(new Dimension(500, 100));
}
else
{
- scroller.setPreferredSize(new Dimension(130, 200));
+ scroller.setPreferredSize(new Dimension(530, 200));
}
this.add(scroller);
}
}
+
+ @Override
+ public DialogRunnerI setResponseHandler(Object response, Runnable action)
+ {
+ callbacks.put(response, action);
+ return this;
+ }
+
+ @Override
+ public void handleResponse(Object response)
+ {
+ /*
+ * this test is for NaN in Chrome
+ */
+ if (response != null && !response.equals(response))
+ {
+ return;
+ }
+ Runnable action = callbacks.get(response);
+ if (action != null)
+ {
+ action.run();
+ }
+ }
+
+ /**
+ * JalviewJS signals file selection by a property change event
+ * for property "SelectedFile". This methods responds to that by
+ * running the response action for 'OK' in the dialog.
+ *
+ * @param evt
+ */
+ @Override
+ public void propertyChange(PropertyChangeEvent evt)
+ {
+ // TODO other properties need runners...
+ switch (evt.getPropertyName())
+ {
+ /*
+ * property name here matches that used in JFileChooser.js
+ */
+ case "SelectedFile":
+ handleResponse(APPROVE_OPTION);
+ break;
+ }
+ }
}