source: josm/trunk/src/org/openstreetmap/josm/gui/tagging/TaggingPresetItems.java@ 8510

Last change on this file since 8510 was 8510, checked in by Don-vip, 9 years ago

checkstyle: enable relevant whitespace checks and fix them

  • Property svn:eol-style set to native
File size: 58.7 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.tagging;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trc;
6
7import java.awt.Component;
8import java.awt.Dimension;
9import java.awt.Font;
10import java.awt.GridBagLayout;
11import java.awt.GridLayout;
12import java.awt.Insets;
13import java.awt.event.ActionEvent;
14import java.awt.event.ActionListener;
15import java.awt.event.MouseAdapter;
16import java.awt.event.MouseEvent;
17import java.io.File;
18import java.lang.reflect.Method;
19import java.lang.reflect.Modifier;
20import java.text.NumberFormat;
21import java.text.ParseException;
22import java.util.ArrayList;
23import java.util.Arrays;
24import java.util.Collection;
25import java.util.Collections;
26import java.util.EnumSet;
27import java.util.HashMap;
28import java.util.LinkedHashMap;
29import java.util.LinkedList;
30import java.util.List;
31import java.util.Map;
32import java.util.Map.Entry;
33import java.util.Set;
34import java.util.SortedSet;
35import java.util.TreeSet;
36
37import javax.swing.AbstractButton;
38import javax.swing.BorderFactory;
39import javax.swing.ButtonGroup;
40import javax.swing.Icon;
41import javax.swing.ImageIcon;
42import javax.swing.JButton;
43import javax.swing.JComponent;
44import javax.swing.JLabel;
45import javax.swing.JList;
46import javax.swing.JPanel;
47import javax.swing.JScrollPane;
48import javax.swing.JSeparator;
49import javax.swing.JToggleButton;
50import javax.swing.ListCellRenderer;
51import javax.swing.ListModel;
52
53import org.openstreetmap.josm.Main;
54import org.openstreetmap.josm.actions.search.SearchCompiler;
55import org.openstreetmap.josm.data.osm.OsmPrimitive;
56import org.openstreetmap.josm.data.osm.OsmUtils;
57import org.openstreetmap.josm.data.osm.Tag;
58import org.openstreetmap.josm.data.preferences.BooleanProperty;
59import org.openstreetmap.josm.gui.tagging.ac.AutoCompletingTextField;
60import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionItemPriority;
61import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionList;
62import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionManager;
63import org.openstreetmap.josm.gui.widgets.JosmComboBox;
64import org.openstreetmap.josm.gui.widgets.JosmTextField;
65import org.openstreetmap.josm.gui.widgets.QuadStateCheckBox;
66import org.openstreetmap.josm.gui.widgets.UrlLabel;
67import org.openstreetmap.josm.tools.AlphanumComparator;
68import org.openstreetmap.josm.tools.GBC;
69import org.openstreetmap.josm.tools.ImageProvider;
70import org.openstreetmap.josm.tools.Predicate;
71import org.openstreetmap.josm.tools.Utils;
72import org.xml.sax.SAXException;
73
74/**
75 * Class that contains all subtypes of TaggingPresetItem, static supplementary data, types and methods
76 * @since 6068
77 */
78public final class TaggingPresetItems {
79 private TaggingPresetItems() {
80 }
81
82 private static int auto_increment_selected = 0;
83 /** Translatation of "<different>". Use in combo boxes to display en entry matching several different values. */
84 public static final String DIFFERENT = tr("<different>");
85
86 private static final BooleanProperty PROP_FILL_DEFAULT = new BooleanProperty("taggingpreset.fill-default-for-tagged-primitives", false);
87
88 // cache the parsing of types using a LRU cache (http://java-planet.blogspot.com/2005/08/how-to-set-up-simple-lru-cache-using.html)
89 private static final Map<String, Set<TaggingPresetType>> TYPE_CACHE = new LinkedHashMap<>(16, 1.1f, true);
90
91 /**
92 * Last value of each key used in presets, used for prefilling corresponding fields
93 */
94 private static final Map<String, String> LAST_VALUES = new HashMap<>();
95
96 public static class PresetListEntry implements Comparable<PresetListEntry> {
97 public String value;
98 /** The context used for translating {@link #value} */
99 public String value_context;
100 public String display_value;
101 public String short_description;
102 /** The location of icon file to display */
103 public String icon;
104 /** The size of displayed icon. If not set, default is size from icon file */
105 public String icon_size;
106 /** The localized version of {@link #display_value}. */
107 public String locale_display_value;
108 /** The localized version of {@link #short_description}. */
109 public String locale_short_description;
110 private final File zipIcons = TaggingPresetReader.getZipIcons();
111
112 // Cached size (currently only for Combo) to speed up preset dialog initialization
113 private int prefferedWidth = -1;
114 private int prefferedHeight = -1;
115
116 public String getListDisplay() {
117 if (value.equals(DIFFERENT))
118 return "<b>"+DIFFERENT.replaceAll("<", "&lt;").replaceAll(">", "&gt;")+"</b>";
119
120 if (value.isEmpty())
121 return "&nbsp;";
122
123 final StringBuilder res = new StringBuilder("<b>");
124 res.append(getDisplayValue(true).replaceAll("<", "&lt;").replaceAll(">", "&gt;"))
125 .append("</b>");
126 if (getShortDescription(true) != null) {
127 // wrap in table to restrict the text width
128 res.append("<div style=\"width:300px; padding:0 0 5px 5px\">")
129 .append(getShortDescription(true))
130 .append("</div>");
131 }
132 return res.toString();
133 }
134
135 /**
136 * Returns the entry icon, if any.
137 * @return the entry icon, or {@code null}
138 */
139 public ImageIcon getIcon() {
140 return icon == null ? null : loadImageIcon(icon, zipIcons, parseInteger(icon_size));
141 }
142
143 /**
144 * Constructs a new {@code PresetListEntry}, uninitialized.
145 */
146 public PresetListEntry() {
147 }
148
149 public PresetListEntry(String value) {
150 this.value = value;
151 }
152
153 public String getDisplayValue(boolean translated) {
154 return translated
155 ? Utils.firstNonNull(locale_display_value, tr(display_value), trc(value_context, value))
156 : Utils.firstNonNull(display_value, value);
157 }
158
159 public String getShortDescription(boolean translated) {
160 return translated
161 ? Utils.firstNonNull(locale_short_description, tr(short_description))
162 : short_description;
163 }
164
165 // toString is mainly used to initialize the Editor
166 @Override
167 public String toString() {
168 if (value.equals(DIFFERENT))
169 return DIFFERENT;
170 return getDisplayValue(true).replaceAll("<.*>", ""); // remove additional markup, e.g. <br>
171 }
172
173 @Override
174 public int compareTo(PresetListEntry o) {
175 return AlphanumComparator.getInstance().compare(this.getDisplayValue(true), o.getDisplayValue(true));
176 }
177 }
178
179 public static class Role {
180 public Set<TaggingPresetType> types;
181 public String key;
182 /** The text to display */
183 public String text;
184 /** The context used for translating {@link #text} */
185 public String text_context;
186 /** The localized version of {@link #text}. */
187 public String locale_text;
188 public SearchCompiler.Match memberExpression;
189
190 public boolean required = false;
191 private long count = 0;
192
193 public void setType(String types) throws SAXException {
194 this.types = getType(types);
195 }
196
197 public void setRequisite(String str) throws SAXException {
198 if ("required".equals(str)) {
199 required = true;
200 } else if (!"optional".equals(str))
201 throw new SAXException(tr("Unknown requisite: {0}", str));
202 }
203
204 public void setMember_expression(String member_expression) throws SAXException {
205 try {
206 this.memberExpression = SearchCompiler.compile(member_expression, true, true);
207 } catch (SearchCompiler.ParseError ex) {
208 throw new SAXException(tr("Illegal member expression: {0}", ex.getMessage()), ex);
209 }
210 }
211
212 public void setCount(String count) {
213 this.count = Long.parseLong(count);
214 }
215
216 /**
217 * Return either argument, the highest possible value or the lowest allowed value
218 */
219 public long getValidCount(long c) {
220 if (count > 0 && !required)
221 return c != 0 ? count : 0;
222 else if (count > 0)
223 return count;
224 else if (!required)
225 return c != 0 ? c : 0;
226 else
227 return c != 0 ? c : 1;
228 }
229
230 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel) {
231 String cstring;
232 if (count > 0 && !required) {
233 cstring = "0,"+count;
234 } else if (count > 0) {
235 cstring = String.valueOf(count);
236 } else if (!required) {
237 cstring = "0-...";
238 } else {
239 cstring = "1-...";
240 }
241 if (locale_text == null) {
242 locale_text = getLocaleText(text, text_context, null);
243 }
244 p.add(new JLabel(locale_text+":"), GBC.std().insets(0, 0, 10, 0));
245 p.add(new JLabel(key), GBC.std().insets(0, 0, 10, 0));
246 p.add(new JLabel(cstring), types == null ? GBC.eol() : GBC.std().insets(0, 0, 10, 0));
247 if (types != null) {
248 JPanel pp = new JPanel();
249 for (TaggingPresetType t : types) {
250 pp.add(new JLabel(ImageProvider.get(t.getIconName())));
251 }
252 p.add(pp, GBC.eol());
253 }
254 return true;
255 }
256 }
257
258 /**
259 * Enum denoting how a match (see {@link TaggingPresetItem#matches}) is performed.
260 */
261 public static enum MatchType {
262
263 /** Neutral, i.e., do not consider this item for matching. */
264 NONE("none"),
265 /** Positive if key matches, neutral otherwise. */
266 KEY("key"),
267 /** Positive if key matches, negative otherwise. */
268 KEY_REQUIRED("key!"),
269 /** Positive if key and value matches, neutral otherwise. */
270 KEY_VALUE("keyvalue"),
271 /** Positive if key and value matches, negative otherwise. */
272 KEY_VALUE_REQUIRED("keyvalue!");
273
274 private final String value;
275
276 private MatchType(String value) {
277 this.value = value;
278 }
279
280 /**
281 * Replies the associated textual value.
282 * @return the associated textual value
283 */
284 public String getValue() {
285 return value;
286 }
287
288 /**
289 * Determines the {@code MatchType} for the given textual value.
290 * @param type the textual value
291 * @return the {@code MatchType} for the given textual value
292 */
293 public static MatchType ofString(String type) {
294 for (MatchType i : EnumSet.allOf(MatchType.class)) {
295 if (i.getValue().equals(type))
296 return i;
297 }
298 throw new IllegalArgumentException(type + " is not allowed");
299 }
300 }
301
302 public static class Usage {
303 private SortedSet<String> values;
304 private boolean hadKeys = false;
305 private boolean hadEmpty = false;
306
307 public boolean hasUniqueValue() {
308 return values.size() == 1 && !hadEmpty;
309 }
310
311 public boolean unused() {
312 return values.isEmpty();
313 }
314
315 public String getFirst() {
316 return values.first();
317 }
318
319 public boolean hadKeys() {
320 return hadKeys;
321 }
322 }
323
324 /**
325 * A tagging preset item displaying a localizable text.
326 * @since 6190
327 */
328 public abstract static class TaggingPresetTextItem extends TaggingPresetItem {
329
330 /** The text to display */
331 public String text;
332
333 /** The context used for translating {@link #text} */
334 public String text_context;
335
336 /** The localized version of {@link #text} */
337 public String locale_text;
338
339 protected final void initializeLocaleText(String defaultText) {
340 if (locale_text == null) {
341 locale_text = getLocaleText(text, text_context, defaultText);
342 }
343 }
344
345 @Override
346 void addCommands(List<Tag> changedTags) {
347 }
348
349 protected String fieldsToString() {
350 return (text != null ? "text=" + text + ", " : "")
351 + (text_context != null ? "text_context=" + text_context + ", " : "")
352 + (locale_text != null ? "locale_text=" + locale_text : "");
353 }
354
355 @Override
356 public String toString() {
357 return getClass().getSimpleName() + " [" + fieldsToString() + "]";
358 }
359 }
360
361 /**
362 * Label type.
363 */
364 public static class Label extends TaggingPresetTextItem {
365
366 /** The location of icon file to display (optional) */
367 public String icon;
368 /** The size of displayed icon. If not set, default is 16px */
369 public String icon_size;
370
371 @Override
372 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
373 initializeLocaleText(null);
374 addLabel(p, getIcon(), locale_text);
375 return true;
376 }
377
378 /**
379 * Adds a new {@code JLabel} to the given panel.
380 * @param p The panel
381 * @param icon the icon (optional, can be null)
382 * @param label The text label
383 */
384 public static void addLabel(JPanel p, Icon icon, String label) {
385 p.add(new JLabel(label, icon, JLabel.LEADING), GBC.eol().fill(GBC.HORIZONTAL));
386 }
387
388 /**
389 * Returns the label icon, if any.
390 * @return the label icon, or {@code null}
391 */
392 public ImageIcon getIcon() {
393 Integer size = parseInteger(icon_size);
394 return icon == null ? null : loadImageIcon(icon, TaggingPresetReader.getZipIcons(), size != null ? size : 16);
395 }
396 }
397
398 /**
399 * Hyperlink type.
400 */
401 public static class Link extends TaggingPresetTextItem {
402
403 /** The link to display. */
404 public String href;
405
406 /** The localized version of {@link #href}. */
407 public String locale_href;
408
409 @Override
410 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
411 initializeLocaleText(tr("More information about this feature"));
412 String url = locale_href;
413 if (url == null) {
414 url = href;
415 }
416 if (url != null) {
417 p.add(new UrlLabel(url, locale_text, 2), GBC.eol().insets(0, 10, 0, 0).fill(GBC.HORIZONTAL));
418 }
419 return false;
420 }
421
422 @Override
423 protected String fieldsToString() {
424 return super.fieldsToString()
425 + (href != null ? "href=" + href + ", " : "")
426 + (locale_href != null ? "locale_href=" + locale_href + ", " : "");
427 }
428 }
429
430 public static class PresetLink extends TaggingPresetItem {
431
432 public String preset_name = "";
433
434 @Override
435 boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
436 final String presetName = preset_name;
437 final TaggingPreset t = Utils.filter(TaggingPresets.getTaggingPresets(), new Predicate<TaggingPreset>() {
438 @Override
439 public boolean evaluate(TaggingPreset object) {
440 return presetName.equals(object.name);
441 }
442 }).iterator().next();
443 if (t == null) return false;
444 JLabel lbl = new PresetLabel(t);
445 lbl.addMouseListener(new MouseAdapter() {
446 @Override
447 public void mouseClicked(MouseEvent arg0) {
448 t.actionPerformed(null);
449 }
450 });
451 p.add(lbl, GBC.eol().fill(GBC.HORIZONTAL));
452 return false;
453 }
454
455 @Override
456 void addCommands(List<Tag> changedTags) {
457 }
458 }
459
460 public static class Roles extends TaggingPresetItem {
461
462 public final List<Role> roles = new LinkedList<>();
463
464 @Override
465 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
466 p.add(new JLabel(" "), GBC.eol()); // space
467 if (!roles.isEmpty()) {
468 JPanel proles = new JPanel(new GridBagLayout());
469 proles.add(new JLabel(tr("Available roles")), GBC.std().insets(0, 0, 10, 0));
470 proles.add(new JLabel(tr("role")), GBC.std().insets(0, 0, 10, 0));
471 proles.add(new JLabel(tr("count")), GBC.std().insets(0, 0, 10, 0));
472 proles.add(new JLabel(tr("elements")), GBC.eol());
473 for (Role i : roles) {
474 i.addToPanel(proles, sel);
475 }
476 p.add(proles, GBC.eol());
477 }
478 return false;
479 }
480
481 @Override
482 public void addCommands(List<Tag> changedTags) {
483 }
484 }
485
486 public static class Optional extends TaggingPresetTextItem {
487
488 // TODO: Draw a box around optional stuff
489 @Override
490 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
491 initializeLocaleText(tr("Optional Attributes:"));
492 p.add(new JLabel(" "), GBC.eol()); // space
493 p.add(new JLabel(locale_text), GBC.eol());
494 p.add(new JLabel(" "), GBC.eol()); // space
495 return false;
496 }
497 }
498
499 /**
500 * Horizontal separator type.
501 */
502 public static class Space extends TaggingPresetItem {
503
504 @Override
505 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
506 p.add(new JLabel(" "), GBC.eol()); // space
507 return false;
508 }
509
510 @Override
511 public void addCommands(List<Tag> changedTags) {
512 }
513
514 @Override
515 public String toString() {
516 return "Space";
517 }
518 }
519
520 /**
521 * Class used to represent a {@link JSeparator} inside tagging preset window.
522 * @since 6198
523 */
524 public static class ItemSeparator extends TaggingPresetItem {
525
526 @Override
527 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
528 p.add(new JSeparator(), GBC.eol().fill(GBC.HORIZONTAL).insets(0, 5, 0, 5));
529 return false;
530 }
531
532 @Override
533 public void addCommands(List<Tag> changedTags) {
534 }
535
536 @Override
537 public String toString() {
538 return "ItemSeparator";
539 }
540 }
541
542 /**
543 * Preset item associated to an OSM key.
544 */
545 public abstract static class KeyedItem extends TaggingPresetItem {
546
547 public String key;
548 /** The text to display */
549 public String text;
550 /** The context used for translating {@link #text} */
551 public String text_context;
552 public String match = getDefaultMatch().getValue();
553
554 public abstract MatchType getDefaultMatch();
555
556 public abstract Collection<String> getValues();
557
558 @Override
559 Boolean matches(Map<String, String> tags) {
560 switch (MatchType.ofString(match)) {
561 case NONE:
562 return null;
563 case KEY:
564 return tags.containsKey(key) ? Boolean.TRUE : null;
565 case KEY_REQUIRED:
566 return tags.containsKey(key);
567 case KEY_VALUE:
568 return tags.containsKey(key) && getValues().contains(tags.get(key)) ? Boolean.TRUE : null;
569 case KEY_VALUE_REQUIRED:
570 return tags.containsKey(key) && getValues().contains(tags.get(key));
571 default:
572 throw new IllegalStateException();
573 }
574 }
575
576 @Override
577 public String toString() {
578 return "KeyedItem [key=" + key + ", text=" + text
579 + ", text_context=" + text_context + ", match=" + match
580 + "]";
581 }
582 }
583
584 /**
585 * Invisible type allowing to hardcode an OSM key/value from the preset definition.
586 */
587 public static class Key extends KeyedItem {
588
589 /** The hardcoded value for key */
590 public String value;
591
592 @Override
593 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
594 return false;
595 }
596
597 @Override
598 public void addCommands(List<Tag> changedTags) {
599 changedTags.add(new Tag(key, value));
600 }
601
602 @Override
603 public MatchType getDefaultMatch() {
604 return MatchType.KEY_VALUE_REQUIRED;
605 }
606
607 @Override
608 public Collection<String> getValues() {
609 return Collections.singleton(value);
610 }
611
612 @Override
613 public String toString() {
614 return "Key [key=" + key + ", value=" + value + ", text=" + text
615 + ", text_context=" + text_context + ", match=" + match
616 + "]";
617 }
618 }
619
620 /**
621 * Text field type.
622 */
623 public static class Text extends KeyedItem {
624
625 /** The localized version of {@link #text}. */
626 public String locale_text;
627 public String default_;
628 public String originalValue;
629 public String use_last_as_default = "false";
630 public String auto_increment;
631 public String length;
632 public String alternative_autocomplete_keys;
633
634 private JComponent value;
635
636 @Override
637 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
638
639 // find out if our key is already used in the selection.
640 Usage usage = determineTextUsage(sel, key);
641 AutoCompletingTextField textField = new AutoCompletingTextField();
642 if (alternative_autocomplete_keys != null) {
643 initAutoCompletionField(textField, (key + "," + alternative_autocomplete_keys).split(","));
644 } else {
645 initAutoCompletionField(textField, key);
646 }
647 if (Main.pref.getBoolean("taggingpreset.display-keys-as-hint", true)) {
648 textField.setHint(key);
649 }
650 if (length != null && !length.isEmpty()) {
651 textField.setMaxChars(Integer.valueOf(length));
652 }
653 if (usage.unused()) {
654 if (auto_increment_selected != 0 && auto_increment != null) {
655 try {
656 textField.setText(Integer.toString(Integer.parseInt(LAST_VALUES.get(key)) + auto_increment_selected));
657 } catch (NumberFormatException ex) {
658 // Ignore - cannot auto-increment if last was non-numeric
659 }
660 } else if (!usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
661 // selected osm primitives are untagged or filling default values feature is enabled
662 if (!"false".equals(use_last_as_default) && LAST_VALUES.containsKey(key) && !presetInitiallyMatches) {
663 textField.setText(LAST_VALUES.get(key));
664 } else {
665 textField.setText(default_);
666 }
667 } else {
668 // selected osm primitives are tagged and filling default values feature is disabled
669 textField.setText("");
670 }
671 value = textField;
672 originalValue = null;
673 } else if (usage.hasUniqueValue()) {
674 // all objects use the same value
675 textField.setText(usage.getFirst());
676 value = textField;
677 originalValue = usage.getFirst();
678 } else {
679 // the objects have different values
680 JosmComboBox<String> comboBox = new JosmComboBox<>(usage.values.toArray(new String[0]));
681 comboBox.setEditable(true);
682 comboBox.setEditor(textField);
683 comboBox.getEditor().setItem(DIFFERENT);
684 value = comboBox;
685 originalValue = DIFFERENT;
686 }
687 if (locale_text == null) {
688 locale_text = getLocaleText(text, text_context, null);
689 }
690
691 // if there's an auto_increment setting, then wrap the text field
692 // into a panel, appending a number of buttons.
693 // auto_increment has a format like -2,-1,1,2
694 // the text box being the first component in the panel is relied
695 // on in a rather ugly fashion further down.
696 if (auto_increment != null) {
697 ButtonGroup bg = new ButtonGroup();
698 JPanel pnl = new JPanel(new GridBagLayout());
699 pnl.add(value, GBC.std().fill(GBC.HORIZONTAL));
700
701 // first, one button for each auto_increment value
702 for (final String ai : auto_increment.split(",")) {
703 JToggleButton aibutton = new JToggleButton(ai);
704 aibutton.setToolTipText(tr("Select auto-increment of {0} for this field", ai));
705 aibutton.setMargin(new java.awt.Insets(0, 0, 0, 0));
706 aibutton.setFocusable(false);
707 saveHorizontalSpace(aibutton);
708 bg.add(aibutton);
709 try {
710 // TODO there must be a better way to parse a number like "+3" than this.
711 final int buttonvalue = (NumberFormat.getIntegerInstance().parse(ai.replace("+", ""))).intValue();
712 if (auto_increment_selected == buttonvalue) aibutton.setSelected(true);
713 aibutton.addActionListener(new ActionListener() {
714 @Override
715 public void actionPerformed(ActionEvent e) {
716 auto_increment_selected = buttonvalue;
717 }
718 });
719 pnl.add(aibutton, GBC.std());
720 } catch (ParseException x) {
721 Main.error("Cannot parse auto-increment value of '" + ai + "' into an integer");
722 }
723 }
724
725 // an invisible toggle button for "release" of the button group
726 final JToggleButton clearbutton = new JToggleButton("X");
727 clearbutton.setVisible(false);
728 clearbutton.setFocusable(false);
729 bg.add(clearbutton);
730 // and its visible counterpart. - this mechanism allows us to
731 // have *no* button selected after the X is clicked, instead
732 // of the X remaining selected
733 JButton releasebutton = new JButton("X");
734 releasebutton.setToolTipText(tr("Cancel auto-increment for this field"));
735 releasebutton.setMargin(new java.awt.Insets(0, 0, 0, 0));
736 releasebutton.setFocusable(false);
737 releasebutton.addActionListener(new ActionListener() {
738 @Override
739 public void actionPerformed(ActionEvent e) {
740 auto_increment_selected = 0;
741 clearbutton.setSelected(true);
742 }
743 });
744 saveHorizontalSpace(releasebutton);
745 pnl.add(releasebutton, GBC.eol());
746 value = pnl;
747 }
748 p.add(new JLabel(locale_text+":"), GBC.std().insets(0, 0, 10, 0));
749 p.add(value, GBC.eol().fill(GBC.HORIZONTAL));
750 return true;
751 }
752
753 private static void saveHorizontalSpace(AbstractButton button) {
754 Insets insets = button.getBorder().getBorderInsets(button);
755 // Ensure the current look&feel does not waste horizontal space (as seen in Nimbus & Aqua)
756 if (insets != null && insets.left+insets.right > insets.top+insets.bottom) {
757 int min = Math.min(insets.top, insets.bottom);
758 button.setBorder(BorderFactory.createEmptyBorder(insets.top, min, insets.bottom, min));
759 }
760 }
761
762 private static String getValue(Component comp) {
763 if (comp instanceof JosmComboBox) {
764 return ((JosmComboBox<?>) comp).getEditor().getItem().toString();
765 } else if (comp instanceof JosmTextField) {
766 return ((JosmTextField) comp).getText();
767 } else if (comp instanceof JPanel) {
768 return getValue(((JPanel) comp).getComponent(0));
769 } else {
770 return null;
771 }
772 }
773
774 @Override
775 public void addCommands(List<Tag> changedTags) {
776
777 // return if unchanged
778 String v = getValue(value);
779 if (v == null) {
780 Main.error("No 'last value' support for component " + value);
781 return;
782 }
783
784 v = Tag.removeWhiteSpaces(v);
785
786 if (!"false".equals(use_last_as_default) || auto_increment != null) {
787 LAST_VALUES.put(key, v);
788 }
789 if (v.equals(originalValue) || (originalValue == null && v.isEmpty()))
790 return;
791
792 changedTags.add(new Tag(key, v));
793 AutoCompletionManager.rememberUserInput(key, v, true);
794 }
795
796 @Override
797 boolean requestFocusInWindow() {
798 return value.requestFocusInWindow();
799 }
800
801 @Override
802 public MatchType getDefaultMatch() {
803 return MatchType.NONE;
804 }
805
806 @Override
807 public Collection<String> getValues() {
808 if (default_ == null || default_.isEmpty())
809 return Collections.emptyList();
810 return Collections.singleton(default_);
811 }
812 }
813
814 /**
815 * A group of {@link Check}s.
816 * @since 6114
817 */
818 public static class CheckGroup extends TaggingPresetItem {
819
820 /**
821 * Number of columns (positive integer)
822 */
823 public String columns;
824
825 /**
826 * List of checkboxes
827 */
828 public final List<Check> checks = new LinkedList<>();
829
830 @Override
831 boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
832 Integer cols = Integer.valueOf(columns);
833 int rows = (int) Math.ceil(checks.size()/cols.doubleValue());
834 JPanel panel = new JPanel(new GridLayout(rows, cols));
835
836 for (Check check : checks) {
837 check.addToPanel(panel, sel, presetInitiallyMatches);
838 }
839
840 p.add(panel, GBC.eol());
841 return false;
842 }
843
844 @Override
845 void addCommands(List<Tag> changedTags) {
846 for (Check check : checks) {
847 check.addCommands(changedTags);
848 }
849 }
850
851 @Override
852 public String toString() {
853 return "CheckGroup [columns=" + columns + "]";
854 }
855 }
856
857 /**
858 * Checkbox type.
859 */
860 public static class Check extends KeyedItem {
861
862 /** The localized version of {@link #text}. */
863 public String locale_text;
864 /** the value to set when checked (default is "yes") */
865 public String value_on = OsmUtils.trueval;
866 /** the value to set when unchecked (default is "no") */
867 public String value_off = OsmUtils.falseval;
868 /** whether the off value is disabled in the dialog, i.e., only unset or yes are provided */
869 public boolean disable_off = false;
870 /** ticked on/off (default is "off") */
871 public boolean default_ = false; // only used for tagless objects
872
873 private QuadStateCheckBox check;
874 private QuadStateCheckBox.State initialState;
875 private boolean def;
876
877 @Override
878 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
879
880 // find out if our key is already used in the selection.
881 final Usage usage = determineBooleanUsage(sel, key);
882 final String oneValue = usage.values.isEmpty() ? null : usage.values.last();
883 def = default_;
884
885 if (locale_text == null) {
886 locale_text = getLocaleText(text, text_context, null);
887 }
888
889 if (usage.values.size() < 2 && (oneValue == null || value_on.equals(oneValue) || value_off.equals(oneValue))) {
890 if (def && !PROP_FILL_DEFAULT.get()) {
891 // default is set and filling default values feature is disabled - check if all primitives are untagged
892 for (OsmPrimitive s : sel)
893 if (s.hasKeys()) {
894 def = false;
895 }
896 }
897
898 // all selected objects share the same value which is either true or false or unset,
899 // we can display a standard check box.
900 initialState = value_on.equals(oneValue)
901 ? QuadStateCheckBox.State.SELECTED
902 : value_off.equals(oneValue)
903 ? QuadStateCheckBox.State.NOT_SELECTED
904 : def
905 ? QuadStateCheckBox.State.SELECTED
906 : QuadStateCheckBox.State.UNSET;
907 } else {
908 def = false;
909 // the objects have different values, or one or more objects have something
910 // else than true/false. we display a quad-state check box
911 // in "partial" state.
912 initialState = QuadStateCheckBox.State.PARTIAL;
913 }
914
915 final List<QuadStateCheckBox.State> allowedStates = new ArrayList<>(4);
916 if (QuadStateCheckBox.State.PARTIAL.equals(initialState))
917 allowedStates.add(QuadStateCheckBox.State.PARTIAL);
918 allowedStates.add(QuadStateCheckBox.State.SELECTED);
919 if (!disable_off || value_off.equals(oneValue))
920 allowedStates.add(QuadStateCheckBox.State.NOT_SELECTED);
921 allowedStates.add(QuadStateCheckBox.State.UNSET);
922 check = new QuadStateCheckBox(locale_text, initialState,
923 allowedStates.toArray(new QuadStateCheckBox.State[allowedStates.size()]));
924
925 p.add(check, GBC.eol().fill(GBC.HORIZONTAL));
926 return true;
927 }
928
929 @Override
930 public void addCommands(List<Tag> changedTags) {
931 // if the user hasn't changed anything, don't create a command.
932 if (check.getState() == initialState && !def) return;
933
934 // otherwise change things according to the selected value.
935 changedTags.add(new Tag(key,
936 check.getState() == QuadStateCheckBox.State.SELECTED ? value_on :
937 check.getState() == QuadStateCheckBox.State.NOT_SELECTED ? value_off :
938 null));
939 }
940
941 @Override
942 boolean requestFocusInWindow() {
943 return check.requestFocusInWindow();
944 }
945
946 @Override
947 public MatchType getDefaultMatch() {
948 return MatchType.NONE;
949 }
950
951 @Override
952 public Collection<String> getValues() {
953 return disable_off ? Arrays.asList(value_on) : Arrays.asList(value_on, value_off);
954 }
955
956 @Override
957 public String toString() {
958 return "Check ["
959 + (locale_text != null ? "locale_text=" + locale_text + ", " : "")
960 + (value_on != null ? "value_on=" + value_on + ", " : "")
961 + (value_off != null ? "value_off=" + value_off + ", " : "")
962 + "default_=" + default_ + ", "
963 + (check != null ? "check=" + check + ", " : "")
964 + (initialState != null ? "initialState=" + initialState
965 + ", " : "") + "def=" + def + "]";
966 }
967 }
968
969 /**
970 * Abstract superclass for combo box and multi-select list types.
971 */
972 public abstract static class ComboMultiSelect extends KeyedItem {
973
974 /** The localized version of {@link #text}. */
975 public String locale_text;
976 public String values;
977 public String values_from;
978 /** The context used for translating {@link #values} */
979 public String values_context;
980 public String display_values;
981 /** The localized version of {@link #display_values}. */
982 public String locale_display_values;
983 public String short_descriptions;
984 /** The localized version of {@link #short_descriptions}. */
985 public String locale_short_descriptions;
986 public String default_;
987 public String delimiter = ";";
988 public String use_last_as_default = "false";
989 /** whether to use values for search via {@link TaggingPresetSelector} */
990 public String values_searchable = "false";
991
992 protected JComponent component;
993 protected final Map<String, PresetListEntry> lhm = new LinkedHashMap<>();
994 private boolean initialized = false;
995 protected Usage usage;
996 protected Object originalValue;
997
998 protected abstract Object getSelectedItem();
999
1000 protected abstract void addToPanelAnchor(JPanel p, String def, boolean presetInitiallyMatches);
1001
1002 protected char getDelChar() {
1003 return delimiter.isEmpty() ? ';' : delimiter.charAt(0);
1004 }
1005
1006 @Override
1007 public Collection<String> getValues() {
1008 initListEntries();
1009 return lhm.keySet();
1010 }
1011
1012 public Collection<String> getDisplayValues() {
1013 initListEntries();
1014 return Utils.transform(lhm.values(), new Utils.Function<PresetListEntry, String>() {
1015 @Override
1016 public String apply(PresetListEntry x) {
1017 return x.getDisplayValue(true);
1018 }
1019 });
1020 }
1021
1022 @Override
1023 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
1024
1025 initListEntries();
1026
1027 // find out if our key is already used in the selection.
1028 usage = determineTextUsage(sel, key);
1029 if (!usage.hasUniqueValue() && !usage.unused()) {
1030 lhm.put(DIFFERENT, new PresetListEntry(DIFFERENT));
1031 }
1032
1033 p.add(new JLabel(tr("{0}:", locale_text)), GBC.std().insets(0, 0, 10, 0));
1034 addToPanelAnchor(p, default_, presetInitiallyMatches);
1035
1036 return true;
1037
1038 }
1039
1040 private void initListEntries() {
1041 if (initialized) {
1042 lhm.remove(DIFFERENT); // possibly added in #addToPanel
1043 return;
1044 } else if (lhm.isEmpty()) {
1045 initListEntriesFromAttributes();
1046 } else {
1047 if (values != null) {
1048 Main.warn(tr("Warning in tagging preset \"{0}-{1}\": "
1049 + "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
1050 key, text, "values", "list_entry"));
1051 }
1052 if (display_values != null || locale_display_values != null) {
1053 Main.warn(tr("Warning in tagging preset \"{0}-{1}\": "
1054 + "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
1055 key, text, "display_values", "list_entry"));
1056 }
1057 if (short_descriptions != null || locale_short_descriptions != null) {
1058 Main.warn(tr("Warning in tagging preset \"{0}-{1}\": "
1059 + "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
1060 key, text, "short_descriptions", "list_entry"));
1061 }
1062 for (PresetListEntry e : lhm.values()) {
1063 if (e.value_context == null) {
1064 e.value_context = values_context;
1065 }
1066 }
1067 }
1068 if (locale_text == null) {
1069 locale_text = getLocaleText(text, text_context, null);
1070 }
1071 initialized = true;
1072 }
1073
1074 private void initListEntriesFromAttributes() {
1075 char delChar = getDelChar();
1076
1077 String[] value_array = null;
1078
1079 if (values_from != null) {
1080 String[] class_method = values_from.split("#");
1081 if (class_method != null && class_method.length == 2) {
1082 try {
1083 Method method = Class.forName(class_method[0]).getMethod(class_method[1]);
1084 // Check method is public static String[] methodName()
1085 int mod = method.getModifiers();
1086 if (Modifier.isPublic(mod) && Modifier.isStatic(mod)
1087 && method.getReturnType().equals(String[].class) && method.getParameterTypes().length == 0) {
1088 value_array = (String[]) method.invoke(null);
1089 } else {
1090 Main.error(tr("Broken tagging preset \"{0}-{1}\" - Java method given in ''values_from'' is not \"{2}\"", key, text,
1091 "public static String[] methodName()"));
1092 }
1093 } catch (Exception e) {
1094 Main.error(tr("Broken tagging preset \"{0}-{1}\" - Java method given in ''values_from'' threw {2} ({3})", key, text,
1095 e.getClass().getName(), e.getMessage()));
1096 }
1097 }
1098 }
1099
1100 if (value_array == null) {
1101 value_array = splitEscaped(delChar, values);
1102 }
1103
1104 final String displ = Utils.firstNonNull(locale_display_values, display_values);
1105 String[] display_array = displ == null ? value_array : splitEscaped(delChar, displ);
1106
1107 final String descr = Utils.firstNonNull(locale_short_descriptions, short_descriptions);
1108 String[] short_descriptions_array = descr == null ? null : splitEscaped(delChar, descr);
1109
1110 if (display_array.length != value_array.length) {
1111 Main.error(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''display_values'' must be the same as in ''values''",
1112 key, text));
1113 display_array = value_array;
1114 }
1115
1116 if (short_descriptions_array != null && short_descriptions_array.length != value_array.length) {
1117 Main.error(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''short_descriptions'' must be the same as in ''values''",
1118 key, text));
1119 short_descriptions_array = null;
1120 }
1121
1122 final List<PresetListEntry> entries = new ArrayList<>(value_array.length);
1123 for (int i = 0; i < value_array.length; i++) {
1124 final PresetListEntry e = new PresetListEntry(value_array[i]);
1125 e.locale_display_value = locale_display_values != null
1126 ? display_array[i]
1127 : trc(values_context, fixPresetString(display_array[i]));
1128 if (short_descriptions_array != null) {
1129 e.locale_short_description = locale_short_descriptions != null
1130 ? short_descriptions_array[i]
1131 : tr(fixPresetString(short_descriptions_array[i]));
1132 }
1133
1134 entries.add(e);
1135 }
1136
1137 if (Main.pref.getBoolean("taggingpreset.sortvalues", true)) {
1138 Collections.sort(entries);
1139 }
1140
1141 for (PresetListEntry i : entries) {
1142 lhm.put(i.value, i);
1143 }
1144
1145 }
1146
1147 protected String getDisplayIfNull() {
1148 return null;
1149 }
1150
1151 @Override
1152 public void addCommands(List<Tag> changedTags) {
1153 Object obj = getSelectedItem();
1154 String display = (obj == null) ? null : obj.toString();
1155 String value = null;
1156 if (display == null) {
1157 display = getDisplayIfNull();
1158 }
1159
1160 if (display != null) {
1161 for (Entry<String, PresetListEntry> entry : lhm.entrySet()) {
1162 String k = entry.getValue().toString();
1163 if (k != null && k.equals(display)) {
1164 value = entry.getKey();
1165 break;
1166 }
1167 }
1168 if (value == null) {
1169 value = display;
1170 }
1171 } else {
1172 value = "";
1173 }
1174 value = Tag.removeWhiteSpaces(value);
1175
1176 // no change if same as before
1177 if (originalValue == null) {
1178 if (value.isEmpty())
1179 return;
1180 } else if (value.equals(originalValue.toString()))
1181 return;
1182
1183 if (!"false".equals(use_last_as_default)) {
1184 LAST_VALUES.put(key, value);
1185 }
1186 changedTags.add(new Tag(key, value));
1187 }
1188
1189 public void addListEntry(PresetListEntry e) {
1190 lhm.put(e.value, e);
1191 }
1192
1193 public void addListEntries(Collection<PresetListEntry> e) {
1194 for (PresetListEntry i : e) {
1195 addListEntry(i);
1196 }
1197 }
1198
1199 @Override
1200 boolean requestFocusInWindow() {
1201 return component.requestFocusInWindow();
1202 }
1203
1204 private static final ListCellRenderer<PresetListEntry> RENDERER = new ListCellRenderer<PresetListEntry>() {
1205
1206 private final JLabel lbl = new JLabel();
1207
1208 @Override
1209 public Component getListCellRendererComponent(JList<? extends PresetListEntry> list, PresetListEntry item, int index,
1210 boolean isSelected, boolean cellHasFocus) {
1211
1212 // Only return cached size, item is not shown
1213 if (!list.isShowing() && item.prefferedWidth != -1 && item.prefferedHeight != -1) {
1214 if (index == -1) {
1215 lbl.setPreferredSize(new Dimension(item.prefferedWidth, 10));
1216 } else {
1217 lbl.setPreferredSize(new Dimension(item.prefferedWidth, item.prefferedHeight));
1218 }
1219 return lbl;
1220 }
1221
1222 lbl.setPreferredSize(null);
1223
1224 if (isSelected) {
1225 lbl.setBackground(list.getSelectionBackground());
1226 lbl.setForeground(list.getSelectionForeground());
1227 } else {
1228 lbl.setBackground(list.getBackground());
1229 lbl.setForeground(list.getForeground());
1230 }
1231
1232 lbl.setOpaque(true);
1233 lbl.setFont(lbl.getFont().deriveFont(Font.PLAIN));
1234 lbl.setText("<html>" + item.getListDisplay() + "</html>");
1235 lbl.setIcon(item.getIcon());
1236 lbl.setEnabled(list.isEnabled());
1237
1238 // Cache size
1239 item.prefferedWidth = lbl.getPreferredSize().width;
1240 item.prefferedHeight = lbl.getPreferredSize().height;
1241
1242 // We do not want the editor to have the maximum height of all
1243 // entries. Return a dummy with bogus height.
1244 if (index == -1) {
1245 lbl.setPreferredSize(new Dimension(lbl.getPreferredSize().width, 10));
1246 }
1247 return lbl;
1248 }
1249 };
1250
1251 protected ListCellRenderer<PresetListEntry> getListCellRenderer() {
1252 return RENDERER;
1253 }
1254
1255 @Override
1256 public MatchType getDefaultMatch() {
1257 return MatchType.NONE;
1258 }
1259 }
1260
1261 /**
1262 * Combobox type.
1263 */
1264 public static class Combo extends ComboMultiSelect {
1265
1266 public boolean editable = true;
1267 protected JosmComboBox<PresetListEntry> combo;
1268 public String length;
1269
1270 /**
1271 * Constructs a new {@code Combo}.
1272 */
1273 public Combo() {
1274 delimiter = ",";
1275 }
1276
1277 @Override
1278 protected void addToPanelAnchor(JPanel p, String def, boolean presetInitiallyMatches) {
1279 if (!usage.unused()) {
1280 for (String s : usage.values) {
1281 if (!lhm.containsKey(s)) {
1282 lhm.put(s, new PresetListEntry(s));
1283 }
1284 }
1285 }
1286 if (def != null && !lhm.containsKey(def)) {
1287 lhm.put(def, new PresetListEntry(def));
1288 }
1289 lhm.put("", new PresetListEntry(""));
1290
1291 combo = new JosmComboBox<>(lhm.values().toArray(new PresetListEntry[0]));
1292 component = combo;
1293 combo.setRenderer(getListCellRenderer());
1294 combo.setEditable(editable);
1295 combo.reinitialize(lhm.values());
1296 AutoCompletingTextField tf = new AutoCompletingTextField();
1297 initAutoCompletionField(tf, key);
1298 if (Main.pref.getBoolean("taggingpreset.display-keys-as-hint", true)) {
1299 tf.setHint(key);
1300 }
1301 if (length != null && !length.isEmpty()) {
1302 tf.setMaxChars(Integer.valueOf(length));
1303 }
1304 AutoCompletionList acList = tf.getAutoCompletionList();
1305 if (acList != null) {
1306 acList.add(getDisplayValues(), AutoCompletionItemPriority.IS_IN_STANDARD);
1307 }
1308 combo.setEditor(tf);
1309
1310 if (usage.hasUniqueValue()) {
1311 // all items have the same value (and there were no unset items)
1312 originalValue = lhm.get(usage.getFirst());
1313 combo.setSelectedItem(originalValue);
1314 } else if (def != null && usage.unused()) {
1315 // default is set and all items were unset
1316 if (!usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
1317 // selected osm primitives are untagged or filling default feature is enabled
1318 combo.setSelectedItem(lhm.get(def).getDisplayValue(true));
1319 } else {
1320 // selected osm primitives are tagged and filling default feature is disabled
1321 combo.setSelectedItem("");
1322 }
1323 originalValue = lhm.get(DIFFERENT);
1324 } else if (usage.unused()) {
1325 // all items were unset (and so is default)
1326 originalValue = lhm.get("");
1327 if ("force".equals(use_last_as_default) && LAST_VALUES.containsKey(key) && !presetInitiallyMatches) {
1328 combo.setSelectedItem(lhm.get(LAST_VALUES.get(key)));
1329 } else {
1330 combo.setSelectedItem(originalValue);
1331 }
1332 } else {
1333 originalValue = lhm.get(DIFFERENT);
1334 combo.setSelectedItem(originalValue);
1335 }
1336 p.add(combo, GBC.eol().fill(GBC.HORIZONTAL));
1337
1338 }
1339
1340 @Override
1341 protected Object getSelectedItem() {
1342 return combo.getSelectedItem();
1343
1344 }
1345
1346 @Override
1347 protected String getDisplayIfNull() {
1348 if (combo.isEditable())
1349 return combo.getEditor().getItem().toString();
1350 else
1351 return null;
1352 }
1353 }
1354
1355 /**
1356 * Multi-select list type.
1357 */
1358 public static class MultiSelect extends ComboMultiSelect {
1359
1360 /**
1361 * Number of rows to display (positive integer, optional).
1362 */
1363 public String rows;
1364 protected ConcatenatingJList list;
1365
1366 @Override
1367 protected void addToPanelAnchor(JPanel p, String def, boolean presetInitiallyMatches) {
1368 list = new ConcatenatingJList(delimiter, lhm.values().toArray(new PresetListEntry[0]));
1369 component = list;
1370 ListCellRenderer<PresetListEntry> renderer = getListCellRenderer();
1371 list.setCellRenderer(renderer);
1372
1373 if (usage.hasUniqueValue() && !usage.unused()) {
1374 originalValue = usage.getFirst();
1375 list.setSelectedItem(originalValue);
1376 } else if (def != null && !usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
1377 originalValue = DIFFERENT;
1378 list.setSelectedItem(def);
1379 } else if (usage.unused()) {
1380 originalValue = null;
1381 list.setSelectedItem(originalValue);
1382 } else {
1383 originalValue = DIFFERENT;
1384 list.setSelectedItem(originalValue);
1385 }
1386
1387 JScrollPane sp = new JScrollPane(list);
1388 // if a number of rows has been specified in the preset,
1389 // modify preferred height of scroll pane to match that row count.
1390 if (rows != null) {
1391 double height = renderer.getListCellRendererComponent(list,
1392 new PresetListEntry("x"), 0, false, false).getPreferredSize().getHeight() * Integer.parseInt(rows);
1393 sp.setPreferredSize(new Dimension((int) sp.getPreferredSize().getWidth(), (int) height));
1394 }
1395 p.add(sp, GBC.eol().fill(GBC.HORIZONTAL));
1396 }
1397
1398 @Override
1399 protected Object getSelectedItem() {
1400 return list.getSelectedItem();
1401 }
1402
1403 @Override
1404 public void addCommands(List<Tag> changedTags) {
1405 // Do not create any commands if list has been disabled because of an unknown value (fix #8605)
1406 if (list.isEnabled()) {
1407 super.addCommands(changedTags);
1408 }
1409 }
1410 }
1411
1412 /**
1413 * Class that allows list values to be assigned and retrieved as a comma-delimited
1414 * string (extracted from TaggingPreset)
1415 */
1416 private static class ConcatenatingJList extends JList<PresetListEntry> {
1417 private String delimiter;
1418
1419 public ConcatenatingJList(String del, PresetListEntry[] o) {
1420 super(o);
1421 delimiter = del;
1422 }
1423
1424 public void setSelectedItem(Object o) {
1425 if (o == null) {
1426 clearSelection();
1427 } else {
1428 String s = o.toString();
1429 Set<String> parts = new TreeSet<>(Arrays.asList(s.split(delimiter)));
1430 ListModel<PresetListEntry> lm = getModel();
1431 int[] intParts = new int[lm.getSize()];
1432 int j = 0;
1433 for (int i = 0; i < lm.getSize(); i++) {
1434 final String value = lm.getElementAt(i).value;
1435 if (parts.contains(value)) {
1436 intParts[j++] = i;
1437 parts.remove(value);
1438 }
1439 }
1440 setSelectedIndices(Arrays.copyOf(intParts, j));
1441 // check if we have actually managed to represent the full
1442 // value with our presets. if not, cop out; we will not offer
1443 // a selection list that threatens to ruin the value.
1444 setEnabled(parts.isEmpty());
1445 }
1446 }
1447
1448 public String getSelectedItem() {
1449 ListModel<PresetListEntry> lm = getModel();
1450 int[] si = getSelectedIndices();
1451 StringBuilder builder = new StringBuilder();
1452 for (int i = 0; i < si.length; i++) {
1453 if (i > 0) {
1454 builder.append(delimiter);
1455 }
1456 builder.append(lm.getElementAt(si[i]).value);
1457 }
1458 return builder.toString();
1459 }
1460 }
1461
1462 public static Set<TaggingPresetType> getType(String types) throws SAXException {
1463 if (TYPE_CACHE.containsKey(types))
1464 return TYPE_CACHE.get(types);
1465 Set<TaggingPresetType> result = EnumSet.noneOf(TaggingPresetType.class);
1466 for (String type : Arrays.asList(types.split(","))) {
1467 try {
1468 TaggingPresetType presetType = TaggingPresetType.fromString(type);
1469 result.add(presetType);
1470 } catch (IllegalArgumentException e) {
1471 throw new SAXException(tr("Unknown type: {0}", type), e);
1472 }
1473 }
1474 TYPE_CACHE.put(types, result);
1475 return result;
1476 }
1477
1478 static String fixPresetString(String s) {
1479 return s == null ? s : s.replaceAll("'", "''");
1480 }
1481
1482 private static String getLocaleText(String text, String text_context, String defaultText) {
1483 if (text == null) {
1484 return defaultText;
1485 } else if (text_context != null) {
1486 return trc(text_context, fixPresetString(text));
1487 } else {
1488 return tr(fixPresetString(text));
1489 }
1490 }
1491
1492 /**
1493 * allow escaped comma in comma separated list:
1494 * "A\, B\, C,one\, two" --&gt; ["A, B, C", "one, two"]
1495 * @param delimiter the delimiter, e.g. a comma. separates the entries and
1496 * must be escaped within one entry
1497 * @param s the string
1498 */
1499 private static String[] splitEscaped(char delimiter, String s) {
1500 if (s == null)
1501 return new String[0];
1502 List<String> result = new ArrayList<>();
1503 boolean backslash = false;
1504 StringBuilder item = new StringBuilder();
1505 for (int i = 0; i < s.length(); i++) {
1506 char ch = s.charAt(i);
1507 if (backslash) {
1508 item.append(ch);
1509 backslash = false;
1510 } else if (ch == '\\') {
1511 backslash = true;
1512 } else if (ch == delimiter) {
1513 result.add(item.toString());
1514 item.setLength(0);
1515 } else {
1516 item.append(ch);
1517 }
1518 }
1519 if (item.length() > 0) {
1520 result.add(item.toString());
1521 }
1522 return result.toArray(new String[result.size()]);
1523 }
1524
1525 static Usage determineTextUsage(Collection<OsmPrimitive> sel, String key) {
1526 Usage returnValue = new Usage();
1527 returnValue.values = new TreeSet<>();
1528 for (OsmPrimitive s : sel) {
1529 String v = s.get(key);
1530 if (v != null) {
1531 returnValue.values.add(v);
1532 } else {
1533 returnValue.hadEmpty = true;
1534 }
1535 if (s.hasKeys()) {
1536 returnValue.hadKeys = true;
1537 }
1538 }
1539 return returnValue;
1540 }
1541
1542 static Usage determineBooleanUsage(Collection<OsmPrimitive> sel, String key) {
1543
1544 Usage returnValue = new Usage();
1545 returnValue.values = new TreeSet<>();
1546 for (OsmPrimitive s : sel) {
1547 String booleanValue = OsmUtils.getNamedOsmBoolean(s.get(key));
1548 if (booleanValue != null) {
1549 returnValue.values.add(booleanValue);
1550 }
1551 }
1552 return returnValue;
1553 }
1554
1555 protected static ImageIcon loadImageIcon(String iconName, File zipIcons, Integer maxSize) {
1556 final Collection<String> s = Main.pref.getCollection("taggingpreset.icon.sources", null);
1557 ImageProvider imgProv = new ImageProvider(iconName).setDirs(s).setId("presets").setArchive(zipIcons).setOptional(true);
1558 if (maxSize != null) {
1559 imgProv.setMaxSize(maxSize);
1560 }
1561 return imgProv.get();
1562 }
1563
1564 protected static Integer parseInteger(String str) {
1565 if (str == null || str.isEmpty())
1566 return null;
1567 try {
1568 return Integer.valueOf(str);
1569 } catch (Exception e) {
1570 if (Main.isTraceEnabled()) {
1571 Main.trace(e.getMessage());
1572 }
1573 }
1574 return null;
1575 }
1576}
Note: See TracBrowser for help on using the repository browser.