001package apps.startup;
002
003import jmri.util.startup.AbstractStartupModel;
004
005import apps.Apps;
006import apps.gui3.Apps3;
007
008import java.awt.event.ActionEvent;
009import java.io.File;
010import java.io.IOException;
011import java.text.MessageFormat;
012
013import javax.script.ScriptException;
014import javax.swing.AbstractAction;
015import javax.swing.Action;
016import javax.swing.JButton;
017
018import jmri.JmriException;
019import jmri.script.JmriScriptEngineManager;
020
021import org.slf4j.Logger;
022import org.slf4j.LoggerFactory;
023
024/**
025 *
026 * @author Randall Wood
027 */
028public class ScriptButtonModel extends AbstractStartupModel {
029
030    private File script;
031    private final static Logger log = LoggerFactory.getLogger(ScriptButtonModel.class);
032
033    public File getScript() {
034        return this.script;
035    }
036
037    public void setScript(File script) {
038        this.script = script;
039    }
040    
041    @Override
042    public String toString() {
043        return MessageFormat.format("<html>{0}<br>{1}</html>", this.getName(), this.getScript());
044    }
045
046    @Override
047    public void performAction() throws JmriException {
048        if (Apps.buttonSpace() != null) {
049            JButton b = new JButton(new ScriptButtonAction(this));
050            Apps.buttonSpace().add(b);
051        } else if (Apps3.buttonSpace() != null) {
052            JButton b = new JButton(new ScriptButtonAction(this));
053            Apps3.buttonSpace().add(b);
054        }
055    }
056
057    private static class ScriptButtonAction extends AbstractAction {
058
059        ScriptButtonModel model;
060
061        public ScriptButtonAction(ScriptButtonModel model) {
062            this.model = model;
063            super.putValue(Action.NAME, model.getName());
064        }
065
066        @Override
067        public void actionPerformed(ActionEvent e) {
068            try {
069                JmriScriptEngineManager.getDefault().eval(model.getScript());
070            } catch (ScriptException | IOException ex) {
071                log.error("Unable to run script {}.", model.getScript(), ex);
072            }
073        }
074    }
075
076}