001package jmri.jmrit.logixng.actions.swing; 002 003import java.util.*; 004 005import javax.annotation.CheckForNull; 006import javax.annotation.Nonnull; 007import javax.swing.*; 008 009import jmri.InstanceManager; 010import jmri.jmrit.logixng.*; 011import jmri.jmrit.logixng.actions.DigitalFormula; 012import jmri.jmrit.logixng.util.parser.*; 013 014/** 015 * Configures an Formula object with a Swing JPanel. 016 * 017 * @author Daniel Bergqvist Copyright 2021 018 */ 019public class DigitalFormulaSwing extends AbstractDigitalActionSwing { 020 021 private JTextField _formula; 022 023 @Override 024 protected void createPanel(@CheckForNull Base object, @Nonnull JPanel buttonPanel) { 025 DigitalFormula action = (DigitalFormula)object; 026 panel = new JPanel(); 027 JLabel label = new JLabel(Bundle.getMessage("DigitalFormula_Formula")); 028 _formula = new JTextField(); 029 _formula.setColumns(40); 030 if (action != null) _formula.setText(action.getFormula()); 031 panel.add(label); 032 panel.add(_formula); 033 } 034 035 /** {@inheritDoc} */ 036 @Override 037 public boolean validate(@Nonnull List<String> errorMessages) { 038 if (_formula.getText().isEmpty()) return true; 039 040 try { 041 Map<String, Variable> variables = new HashMap<>(); 042 RecursiveDescentParser parser = new RecursiveDescentParser(variables); 043 parser.parseExpression(_formula.getText()); 044 } catch (ParserException ex) { 045 errorMessages.add(Bundle.getMessage("DigitalFormula_InvalidFormula", _formula.getText())); 046 log.error("Invalid formula '{}'. Error: ", _formula.getText(), ex); 047 return false; 048 } 049 return true; 050 } 051 052 /** {@inheritDoc} */ 053 @Override 054 public MaleSocket createNewObject(@Nonnull String systemName, @CheckForNull String userName) { 055 DigitalFormula action = new DigitalFormula(systemName, userName); 056 updateObject(action); 057 return InstanceManager.getDefault(DigitalActionManager.class).registerAction(action); 058 } 059 060 /** {@inheritDoc} */ 061 @Override 062 public void updateObject(@Nonnull Base object) { 063 if (!(object instanceof DigitalFormula)) { 064 throw new IllegalArgumentException("object must be an DigitalFormula but is a: "+object.getClass().getName()); 065 } 066 067 DigitalFormula action = (DigitalFormula)object; 068 069 try { 070 action.setFormula(_formula.getText()); 071 } catch (ParserException ex) { 072 log.error("Error when parsing formula", ex); 073 } 074 } 075 076 /** {@inheritDoc} */ 077 @Override 078 public String toString() { 079 return Bundle.getMessage("DigitalFormula_Short"); 080 } 081 082 @Override 083 public void dispose() { 084 } 085 086 087 private final static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(DigitalFormulaSwing.class); 088 089}