001package jmri.jmrix.dccpp.swing;
002
003import java.awt.event.ActionEvent;
004import javax.swing.AbstractAction;
005
006import java.io.*;
007import java.nio.charset.StandardCharsets;
008
009import javax.script.ScriptException;
010
011import jmri.script.ScriptEngineSelector;
012import jmri.util.swing.JmriJOptionPane;
013
014/**
015 * Menu action to Export all JMRI Roster Entries as ROSTER() macro calls
016 *  This adds a menu item to the "DCC++" menu. Taking this option opens a 
017 *  window where the ROSTER() lines can be copied into your myAutomation.h 
018 *  Syntax: ROSTER(999,"Loco Name","F0/F1/*F2/F3/F4/F5/F6/F7/F8")
019 * NOTE: calls existing script for compatibility
020 * @author MSteveTodd Copyright (C) 2023
021 */
022public class DCCppRosterExportAction extends AbstractAction {
023
024    private final ScriptEngineSelector _scriptEngineSelector = new ScriptEngineSelector();
025    private final String scriptFilename = "program:jython"+File.separator+"DCC-EX"+File.separator+"RosterExportToDCC-EX.py";
026    
027    public DCCppRosterExportAction(String s) {
028        super(s);
029    }
030
031    public DCCppRosterExportAction() {
032        this("Roster Export to DCC-EX");
033    }
034
035    @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( value="SLF4J_FORMAT_SHOULD_BE_CONST",
036            justification="Same message is used in dialog")
037    @Override
038    public void actionPerformed(ActionEvent e) {
039        log.debug("in actionPerformed");
040        ScriptEngineSelector.Engine engine =
041                    _scriptEngineSelector.getSelectedEngine();
042        if (engine == null) {
043            String em = "Script engine is null";
044            log.error(em);
045            JmriJOptionPane.showMessageDialog(null,
046                    em, "Script Error",
047                    JmriJOptionPane.ERROR_MESSAGE);
048            return;
049        }
050        try (InputStreamReader reader = new InputStreamReader(
051                    new FileInputStream(jmri.util.FileUtil.getExternalFilename(scriptFilename)),
052                    StandardCharsets.UTF_8)) {
053            engine.getScriptEngine().eval(reader);
054        } catch (IOException | ScriptException ex) {
055            String em = "Cannot execute script: " + ex;
056            log.error(em);
057            JmriJOptionPane.showMessageDialog(null,
058                    em, "Script Error",
059                    JmriJOptionPane.ERROR_MESSAGE);
060        }
061    }
062
063    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(DCCppRosterExportAction.class);
064
065}