001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.widgets;
003
004import static org.openstreetmap.josm.tools.I18n.marktr;
005
006import java.awt.Color;
007import java.awt.event.ActionEvent;
008import java.awt.event.ActionListener;
009import java.awt.event.FocusEvent;
010import java.awt.event.FocusListener;
011import java.beans.PropertyChangeEvent;
012import java.beans.PropertyChangeListener;
013import java.util.Objects;
014
015import javax.swing.BorderFactory;
016import javax.swing.UIManager;
017import javax.swing.border.Border;
018import javax.swing.event.DocumentEvent;
019import javax.swing.event.DocumentListener;
020import javax.swing.text.JTextComponent;
021
022import org.openstreetmap.josm.data.preferences.NamedColorProperty;
023import org.openstreetmap.josm.gui.util.ChangeNotifier;
024import org.openstreetmap.josm.tools.CheckParameterUtil;
025
026/**
027 * This is an abstract class for a validator on a text component.
028 *
029 * Subclasses implement {@link #validate()}. {@link #validate()} is invoked whenever
030 * <ul>
031 *   <li>the content of the text component changes (the validator is a {@link DocumentListener})</li>
032 *   <li>the text component loses focus (the validator is a {@link FocusListener})</li>
033 *   <li>the text component is a {@link JosmTextField} and an {@link ActionEvent} is detected</li>
034 * </ul>
035 *
036 * @since 2688
037 */
038public abstract class AbstractTextComponentValidator extends ChangeNotifier
039    implements ActionListener, FocusListener, DocumentListener, PropertyChangeListener {
040
041    protected static final Color ERROR_COLOR = new NamedColorProperty(marktr("Input validation: error"), Color.RED).get();
042    protected static final Border ERROR_BORDER = BorderFactory.createLineBorder(ERROR_COLOR, 1);
043    protected static final Color ERROR_BACKGROUND = new NamedColorProperty(
044            marktr("Input validation: error background"), new Color(0xFFCCCC)).get();
045
046    protected static final Color WARNING_COLOR = new NamedColorProperty(marktr("Input validation: warning"), new Color(0xFFA500)).get();
047    protected static final Border WARNING_BORDER = BorderFactory.createLineBorder(WARNING_COLOR, 1);
048    protected static final Color WARNING_FOREGROUND = new NamedColorProperty(
049            marktr("Input validation: warning foreground"), Color.BLACK).get();
050    protected static final Color WARNING_BACKGROUND = new NamedColorProperty(
051            marktr("Input validation: warning background"), new Color(0xFFEDCC)).get();
052
053    protected static final Color VALID_COLOR = new NamedColorProperty(marktr("Input validation: valid"), new Color(0x008000)).get();
054    protected static final Border VALID_BORDER = BorderFactory.createLineBorder(VALID_COLOR, 1);
055
056    private final JTextComponent tc;
057    // remembers whether the content of the text component is currently valid or not; null means, we don't know yet
058    private Status status;
059    // remember the message
060    private String msg;
061
062    enum Status {
063        INVALID, WARNING, VALID
064    }
065
066    protected void feedbackInvalid(String msg) {
067        if (hasChanged(msg, Status.INVALID)) {
068            // only provide feedback if the validity has changed. This avoids unnecessary UI updates.
069            feedback(ERROR_BORDER, ERROR_BACKGROUND, msg, Status.INVALID, msg);
070        }
071    }
072
073    protected void feedbackWarning(String msg) {
074        if (hasChanged(msg, Status.WARNING)) {
075            // only provide feedback if the validity has changed. This avoids unnecessary UI updates.
076            feedback(WARNING_BORDER, WARNING_BACKGROUND, msg, Status.WARNING, msg);
077        }
078    }
079
080    protected void feedbackDisabled() {
081        feedbackValid(null);
082    }
083
084    protected void feedbackValid(String msg) {
085        if (hasChanged(msg, Status.VALID)) {
086            // only provide feedback if the validity has changed. This avoids unnecessary UI updates.
087            feedback(msg == null ? UIManager.getBorder("TextField.border") : VALID_BORDER,
088                UIManager.getColor("TextField.background"),
089                msg == null ? "" : msg,
090                Status.VALID,
091                msg);
092        }
093    }
094
095    private boolean hasChanged(String msg, Status status) {
096        return !(Objects.equals(status, this.status) && Objects.equals(msg, this.msg));
097    }
098
099    private void feedback(Border border, Color background, String tooltip, Status status, String msg) {
100        tc.setBorder(border);
101        tc.setBackground(background);
102        tc.setToolTipText(tooltip);
103        this.status = status;
104        this.msg = msg;
105        fireStateChanged();
106    }
107
108    /**
109     * Replies the decorated text component
110     *
111     * @return the decorated text component
112     */
113    public JTextComponent getComponent() {
114        return tc;
115    }
116
117    /**
118     * Creates the validator and wires it to the text component <code>tc</code>.
119     *
120     * @param tc the text component. Must not be null.
121     * @throws IllegalArgumentException if tc is null
122     */
123    protected AbstractTextComponentValidator(JTextComponent tc) {
124        this(tc, true);
125    }
126
127    /**
128     * Alternative constructor that allows to turn off the actionListener.
129     * This can be useful if the enter key stroke needs to be forwarded to the default button in a dialog.
130     * @param tc text component
131     * @param addActionListener {@code true} to add the action listener
132     */
133    protected AbstractTextComponentValidator(JTextComponent tc, boolean addActionListener) {
134        this(tc, true, true, addActionListener);
135    }
136
137    /**
138     * Constructs a new {@code AbstractTextComponentValidator}.
139     * @param tc text component
140     * @param addFocusListener {@code true} to add the focus listener
141     * @param addDocumentListener {@code true} to add the document listener
142     * @param addActionListener {@code true} to add the action listener
143     */
144    protected AbstractTextComponentValidator(
145            JTextComponent tc, boolean addFocusListener, boolean addDocumentListener, boolean addActionListener) {
146        CheckParameterUtil.ensureParameterNotNull(tc, "tc");
147        this.tc = tc;
148        if (addFocusListener) {
149            tc.addFocusListener(this);
150        }
151        if (addDocumentListener) {
152            tc.getDocument().addDocumentListener(this);
153        }
154        if (addActionListener && tc instanceof JosmTextField) {
155            ((JosmTextField) tc).addActionListener(this);
156        }
157        tc.addPropertyChangeListener("enabled", this);
158    }
159
160    /**
161     * Implement in subclasses to validate the content of the text component.
162     *
163     */
164    public abstract void validate();
165
166    /**
167     * Replies true if the current content of the decorated text component is valid;
168     * false otherwise
169     *
170     * @return true if the current content of the decorated text component is valid
171     */
172    public abstract boolean isValid();
173
174    /* -------------------------------------------------------------------------------- */
175    /* interface FocusListener                                                          */
176    /* -------------------------------------------------------------------------------- */
177    @Override
178    public void focusGained(FocusEvent e) {}
179
180    @Override
181    public void focusLost(FocusEvent e) {
182        validate();
183    }
184
185    /* -------------------------------------------------------------------------------- */
186    /* interface ActionListener                                                         */
187    /* -------------------------------------------------------------------------------- */
188    @Override
189    public void actionPerformed(ActionEvent e) {
190        validate();
191    }
192
193    /* -------------------------------------------------------------------------------- */
194    /* interface DocumentListener                                                       */
195    /* -------------------------------------------------------------------------------- */
196    @Override
197    public void changedUpdate(DocumentEvent e) {
198        validate();
199    }
200
201    @Override
202    public void insertUpdate(DocumentEvent e) {
203        validate();
204    }
205
206    @Override
207    public void removeUpdate(DocumentEvent e) {
208        validate();
209    }
210
211    /* -------------------------------------------------------------------------------- */
212    /* interface PropertyChangeListener                                                 */
213    /* -------------------------------------------------------------------------------- */
214    @Override
215    public void propertyChange(PropertyChangeEvent evt) {
216        if ("enabled".equals(evt.getPropertyName())) {
217            boolean enabled = (Boolean) evt.getNewValue();
218            if (enabled) {
219                validate();
220            } else {
221                feedbackDisabled();
222            }
223        }
224    }
225}