001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.tagging.presets.items;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.Component;
007import java.awt.GridBagLayout;
008import java.awt.Insets;
009import java.text.NumberFormat;
010import java.text.ParseException;
011import java.util.Collection;
012import java.util.Collections;
013import java.util.List;
014
015import javax.swing.AbstractButton;
016import javax.swing.BorderFactory;
017import javax.swing.ButtonGroup;
018import javax.swing.JButton;
019import javax.swing.JComponent;
020import javax.swing.JLabel;
021import javax.swing.JPanel;
022import javax.swing.JToggleButton;
023
024import org.openstreetmap.josm.data.osm.OsmPrimitive;
025import org.openstreetmap.josm.data.osm.Tag;
026import org.openstreetmap.josm.gui.tagging.ac.AutoCompletingTextField;
027import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionManager;
028import org.openstreetmap.josm.gui.widgets.JosmComboBox;
029import org.openstreetmap.josm.gui.widgets.JosmTextField;
030import org.openstreetmap.josm.spi.preferences.Config;
031import org.openstreetmap.josm.tools.GBC;
032import org.openstreetmap.josm.tools.Logging;
033import org.openstreetmap.josm.tools.Utils;
034
035/**
036 * Text field type.
037 */
038public class Text extends KeyedItem {
039
040    private static int auto_increment_selected; // NOSONAR
041
042    /** The localized version of {@link #text}. */
043    public String locale_text; // NOSONAR
044    /** The default value for the item. If not specified, the current value of the key is chosen as default (if applicable). Defaults to "". */
045    public String default_; // NOSONAR
046    /** The original value */
047    public String originalValue; // NOSONAR
048    /** whether the last value is used as default. Using "force" enforces this behaviour also for already tagged objects. Default is "false".*/
049    public String use_last_as_default = "false"; // NOSONAR
050    /**
051     * May contain a comma separated list of integer increments or decrements, e.g. "-2,-1,+1,+2".
052     * A button will be shown next to the text field for each value, allowing the user to select auto-increment with the given stepping.
053     * Auto-increment only happens if the user selects it. There is also a button to deselect auto-increment.
054     * Default is no auto-increment. Mutually exclusive with {@link #use_last_as_default}.
055     */
056    public String auto_increment; // NOSONAR
057    /** The length of the text box (number of characters allowed). */
058    public String length; // NOSONAR
059    /** A comma separated list of alternative keys to use for autocompletion. */
060    public String alternative_autocomplete_keys; // NOSONAR
061
062    private JComponent value;
063
064    @Override
065    public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
066
067        // find out if our key is already used in the selection.
068        Usage usage = determineTextUsage(sel, key);
069        AutoCompletingTextField textField = new AutoCompletingTextField();
070        if (alternative_autocomplete_keys != null) {
071            initAutoCompletionField(textField, (key + ',' + alternative_autocomplete_keys).split(","));
072        } else {
073            initAutoCompletionField(textField, key);
074        }
075        if (Config.getPref().getBoolean("taggingpreset.display-keys-as-hint", true)) {
076            textField.setHint(key);
077        }
078        if (length != null && !length.isEmpty()) {
079            textField.setMaxChars(Integer.valueOf(length));
080        }
081        if (usage.unused()) {
082            if (auto_increment_selected != 0 && auto_increment != null) {
083                try {
084                    textField.setText(Integer.toString(Integer.parseInt(
085                            LAST_VALUES.get(key)) + auto_increment_selected));
086                } catch (NumberFormatException ex) {
087                    // Ignore - cannot auto-increment if last was non-numeric
088                    Logging.trace(ex);
089                }
090            } else if (!usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
091                // selected osm primitives are untagged or filling default values feature is enabled
092                if (!presetInitiallyMatches && !"false".equals(use_last_as_default) && LAST_VALUES.containsKey(key)) {
093                    textField.setText(LAST_VALUES.get(key));
094                } else {
095                    textField.setText(default_);
096                }
097            } else {
098                // selected osm primitives are tagged and filling default values feature is disabled
099                textField.setText("");
100            }
101            value = textField;
102            originalValue = null;
103        } else if (usage.hasUniqueValue()) {
104            // all objects use the same value
105            textField.setText(usage.getFirst());
106            value = textField;
107            originalValue = usage.getFirst();
108        } else {
109            // the objects have different values
110            JosmComboBox<String> comboBox = new JosmComboBox<>(usage.values.toArray(new String[0]));
111            comboBox.setEditable(true);
112            comboBox.setEditor(textField);
113            comboBox.getEditor().setItem(DIFFERENT);
114            value = comboBox;
115            originalValue = DIFFERENT;
116        }
117        if (locale_text == null) {
118            locale_text = getLocaleText(text, text_context, null);
119        }
120
121        // if there's an auto_increment setting, then wrap the text field
122        // into a panel, appending a number of buttons.
123        // auto_increment has a format like -2,-1,1,2
124        // the text box being the first component in the panel is relied
125        // on in a rather ugly fashion further down.
126        if (auto_increment != null) {
127            ButtonGroup bg = new ButtonGroup();
128            JPanel pnl = new JPanel(new GridBagLayout());
129            pnl.add(value, GBC.std().fill(GBC.HORIZONTAL));
130
131            // first, one button for each auto_increment value
132            for (final String ai : auto_increment.split(",")) {
133                JToggleButton aibutton = new JToggleButton(ai);
134                aibutton.setToolTipText(tr("Select auto-increment of {0} for this field", ai));
135                aibutton.setMargin(new Insets(0, 0, 0, 0));
136                aibutton.setFocusable(false);
137                saveHorizontalSpace(aibutton);
138                bg.add(aibutton);
139                try {
140                    // TODO there must be a better way to parse a number like "+3" than this.
141                    final int buttonvalue = (NumberFormat.getIntegerInstance().parse(ai.replace("+", ""))).intValue();
142                    if (auto_increment_selected == buttonvalue) aibutton.setSelected(true);
143                    aibutton.addActionListener(e -> auto_increment_selected = buttonvalue);
144                    pnl.add(aibutton, GBC.std());
145                } catch (ParseException ex) {
146                    Logging.error("Cannot parse auto-increment value of '" + ai + "' into an integer");
147                }
148            }
149
150            // an invisible toggle button for "release" of the button group
151            final JToggleButton clearbutton = new JToggleButton("X");
152            clearbutton.setVisible(false);
153            clearbutton.setFocusable(false);
154            bg.add(clearbutton);
155            // and its visible counterpart. - this mechanism allows us to
156            // have *no* button selected after the X is clicked, instead
157            // of the X remaining selected
158            JButton releasebutton = new JButton("X");
159            releasebutton.setToolTipText(tr("Cancel auto-increment for this field"));
160            releasebutton.setMargin(new Insets(0, 0, 0, 0));
161            releasebutton.setFocusable(false);
162            releasebutton.addActionListener(e -> {
163                auto_increment_selected = 0;
164                clearbutton.setSelected(true);
165            });
166            saveHorizontalSpace(releasebutton);
167            pnl.add(releasebutton, GBC.eol());
168            value = pnl;
169        }
170        final JLabel label = new JLabel(locale_text + ':');
171        label.setToolTipText(getKeyTooltipText());
172        label.setLabelFor(value);
173        p.add(label, GBC.std().insets(0, 0, 10, 0));
174        p.add(value, GBC.eol().fill(GBC.HORIZONTAL));
175        value.setToolTipText(getKeyTooltipText());
176        return true;
177    }
178
179    private static void saveHorizontalSpace(AbstractButton button) {
180        Insets insets = button.getBorder().getBorderInsets(button);
181        // Ensure the current look&feel does not waste horizontal space (as seen in Nimbus & Aqua)
182        if (insets != null && insets.left+insets.right > insets.top+insets.bottom) {
183            int min = Math.min(insets.top, insets.bottom);
184            button.setBorder(BorderFactory.createEmptyBorder(insets.top, min, insets.bottom, min));
185        }
186    }
187
188    private static String getValue(Component comp) {
189        if (comp instanceof JosmComboBox) {
190            return ((JosmComboBox<?>) comp).getEditor().getItem().toString();
191        } else if (comp instanceof JosmTextField) {
192            return ((JosmTextField) comp).getText();
193        } else if (comp instanceof JPanel) {
194            return getValue(((JPanel) comp).getComponent(0));
195        } else {
196            return null;
197        }
198    }
199
200    @Override
201    public void addCommands(List<Tag> changedTags) {
202
203        // return if unchanged
204        String v = getValue(value);
205        if (v == null) {
206            Logging.error("No 'last value' support for component " + value);
207            return;
208        }
209
210        v = Utils.removeWhiteSpaces(v);
211
212        if (!"false".equals(use_last_as_default) || auto_increment != null) {
213            LAST_VALUES.put(key, v);
214        }
215        if (v.equals(originalValue) || (originalValue == null && v.isEmpty()))
216            return;
217
218        changedTags.add(new Tag(key, v));
219        AutoCompletionManager.rememberUserInput(key, v, true);
220    }
221
222    @Override
223    public MatchType getDefaultMatch() {
224        return MatchType.NONE;
225    }
226
227    @Override
228    public Collection<String> getValues() {
229        if (default_ == null || default_.isEmpty())
230            return Collections.emptyList();
231        return Collections.singleton(default_);
232    }
233}