001package jmri.script.swing;
002
003import java.io.File;
004import java.util.ArrayList;
005import java.util.HashMap;
006import java.util.List;
007import javax.script.ScriptEngineFactory;
008import javax.swing.JFileChooser;
009import javax.swing.filechooser.FileFilter;
010import javax.swing.filechooser.FileNameExtensionFilter;
011import jmri.util.FileUtil;
012import jmri.script.JmriScriptEngineManager;
013
014/**
015 *
016 * @author Randall Wood
017 */
018public class ScriptFileChooser extends jmri.util.swing.JmriJFileChooser {
019
020    public ScriptFileChooser() {
021        super(FileUtil.getScriptsPath());
022        this.init();
023    }
024
025    public ScriptFileChooser(String path) {
026        super(path);
027        this.init();
028    }
029
030    public ScriptFileChooser(File dir) {
031        super(dir);
032        this.init();
033    }
034
035    private void init() {
036        List<String> allExtensions = new ArrayList<>();
037        HashMap<String, FileFilter> filters = new HashMap<>();
038        List<String> filterNames = new ArrayList<>();
039        JmriScriptEngineManager.getDefault().getManager().getEngineFactories().stream().forEach((ScriptEngineFactory factory) -> {
040            log.debug("processing factory {} for {}", factory, factory.getLanguageName());
041            String version = factory.getEngineVersion();
042            if (version != null) {
043                List<String> extensions = factory.getExtensions();
044                allExtensions.addAll(extensions);
045                String name = JmriScriptEngineManager.fileForLanguage(factory.getEngineName(), factory.getLanguageName());
046                filterNames.add(name);
047                if (!extensions.isEmpty()) {
048                    filters.put(name, new FileNameExtensionFilter(name, extensions.toArray(new String[extensions.size()])));
049                } else {
050                    log.warn("Found no valid extensions for language {} version {}", factory.getLanguageName(), version);
051                }
052            }
053        });
054        FileFilter allScripts = new FileNameExtensionFilter(Bundle.getMessage("allScripts"), allExtensions.toArray(new String[allExtensions.size()]));
055        this.addChoosableFileFilter(allScripts);
056        filterNames.stream().sorted().forEach((filter) -> {
057            this.addChoosableFileFilter(filters.get(filter));
058        });
059        this.setFileFilter(allScripts);
060        this.setFileSelectionMode(JFileChooser.FILES_ONLY);
061    }
062
063    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ScriptFileChooser.class);
064}