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

Last change on this file since 8493 was 8493, checked in by simon04, 9 years ago

fix #5509 - Presets: sort property lists by display name

Sorting is on by default and can be controlled with preference key
taggingpreset.sortvalues.

  • 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 public abstract Collection<String> getValues();
556
557 @Override
558 Boolean matches(Map<String, String> tags) {
559 switch (MatchType.ofString(match)) {
560 case NONE:
561 return null;
562 case KEY:
563 return tags.containsKey(key) ? Boolean.TRUE : null;
564 case KEY_REQUIRED:
565 return tags.containsKey(key);
566 case KEY_VALUE:
567 return tags.containsKey(key) && getValues().contains(tags.get(key)) ? Boolean.TRUE : null;
568 case KEY_VALUE_REQUIRED:
569 return tags.containsKey(key) && getValues().contains(tags.get(key));
570 default:
571 throw new IllegalStateException();
572 }
573 }
574
575 @Override
576 public String toString() {
577 return "KeyedItem [key=" + key + ", text=" + text
578 + ", text_context=" + text_context + ", match=" + match
579 + "]";
580 }
581 }
582
583 /**
584 * Invisible type allowing to hardcode an OSM key/value from the preset definition.
585 */
586 public static class Key extends KeyedItem {
587
588 /** The hardcoded value for key */
589 public String value;
590
591 @Override
592 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
593 return false;
594 }
595
596 @Override
597 public void addCommands(List<Tag> changedTags) {
598 changedTags.add(new Tag(key, value));
599 }
600
601 @Override
602 public MatchType getDefaultMatch() {
603 return MatchType.KEY_VALUE_REQUIRED;
604 }
605
606 @Override
607 public Collection<String> getValues() {
608 return Collections.singleton(value);
609 }
610
611 @Override
612 public String toString() {
613 return "Key [key=" + key + ", value=" + value + ", text=" + text
614 + ", text_context=" + text_context + ", match=" + match
615 + "]";
616 }
617 }
618
619 /**
620 * Text field type.
621 */
622 public static class Text extends KeyedItem {
623
624 /** The localized version of {@link #text}. */
625 public String locale_text;
626 public String default_;
627 public String originalValue;
628 public String use_last_as_default = "false";
629 public String auto_increment;
630 public String length;
631 public String alternative_autocomplete_keys;
632
633 private JComponent value;
634
635 @Override
636 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
637
638 // find out if our key is already used in the selection.
639 Usage usage = determineTextUsage(sel, key);
640 AutoCompletingTextField textField = new AutoCompletingTextField();
641 if (alternative_autocomplete_keys != null) {
642 initAutoCompletionField(textField, (key + "," + alternative_autocomplete_keys).split(","));
643 } else {
644 initAutoCompletionField(textField, key);
645 }
646 if (Main.pref.getBoolean("taggingpreset.display-keys-as-hint", true)) {
647 textField.setHint(key);
648 }
649 if (length != null && !length.isEmpty()) {
650 textField.setMaxChars(Integer.valueOf(length));
651 }
652 if (usage.unused()){
653 if (auto_increment_selected != 0 && auto_increment != null) {
654 try {
655 textField.setText(Integer.toString(Integer.parseInt(LAST_VALUES.get(key)) + auto_increment_selected));
656 } catch (NumberFormatException ex) {
657 // Ignore - cannot auto-increment if last was non-numeric
658 }
659 } else if (!usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
660 // selected osm primitives are untagged or filling default values feature is enabled
661 if (!"false".equals(use_last_as_default) && LAST_VALUES.containsKey(key) && !presetInitiallyMatches) {
662 textField.setText(LAST_VALUES.get(key));
663 } else {
664 textField.setText(default_);
665 }
666 } else {
667 // selected osm primitives are tagged and filling default values feature is disabled
668 textField.setText("");
669 }
670 value = textField;
671 originalValue = null;
672 } else if (usage.hasUniqueValue()) {
673 // all objects use the same value
674 textField.setText(usage.getFirst());
675 value = textField;
676 originalValue = usage.getFirst();
677 } else {
678 // the objects have different values
679 JosmComboBox<String> comboBox = new JosmComboBox<>(usage.values.toArray(new String[0]));
680 comboBox.setEditable(true);
681 comboBox.setEditor(textField);
682 comboBox.getEditor().setItem(DIFFERENT);
683 value=comboBox;
684 originalValue = DIFFERENT;
685 }
686 if (locale_text == null) {
687 locale_text = getLocaleText(text, text_context, null);
688 }
689
690 // if there's an auto_increment setting, then wrap the text field
691 // into a panel, appending a number of buttons.
692 // auto_increment has a format like -2,-1,1,2
693 // the text box being the first component in the panel is relied
694 // on in a rather ugly fashion further down.
695 if (auto_increment != null) {
696 ButtonGroup bg = new ButtonGroup();
697 JPanel pnl = new JPanel(new GridBagLayout());
698 pnl.add(value, GBC.std().fill(GBC.HORIZONTAL));
699
700 // first, one button for each auto_increment value
701 for (final String ai : auto_increment.split(",")) {
702 JToggleButton aibutton = new JToggleButton(ai);
703 aibutton.setToolTipText(tr("Select auto-increment of {0} for this field", ai));
704 aibutton.setMargin(new java.awt.Insets(0,0,0,0));
705 aibutton.setFocusable(false);
706 saveHorizontalSpace(aibutton);
707 bg.add(aibutton);
708 try {
709 // TODO there must be a better way to parse a number like "+3" than this.
710 final int buttonvalue = (NumberFormat.getIntegerInstance().parse(ai.replace("+", ""))).intValue();
711 if (auto_increment_selected == buttonvalue) aibutton.setSelected(true);
712 aibutton.addActionListener(new ActionListener() {
713 @Override
714 public void actionPerformed(ActionEvent e) {
715 auto_increment_selected = buttonvalue;
716 }
717 });
718 pnl.add(aibutton, GBC.std());
719 } catch (ParseException x) {
720 Main.error("Cannot parse auto-increment value of '" + ai + "' into an integer");
721 }
722 }
723
724 // an invisible toggle button for "release" of the button group
725 final JToggleButton clearbutton = new JToggleButton("X");
726 clearbutton.setVisible(false);
727 clearbutton.setFocusable(false);
728 bg.add(clearbutton);
729 // and its visible counterpart. - this mechanism allows us to
730 // have *no* button selected after the X is clicked, instead
731 // of the X remaining selected
732 JButton releasebutton = new JButton("X");
733 releasebutton.setToolTipText(tr("Cancel auto-increment for this field"));
734 releasebutton.setMargin(new java.awt.Insets(0,0,0,0));
735 releasebutton.setFocusable(false);
736 releasebutton.addActionListener(new ActionListener() {
737 @Override
738 public void actionPerformed(ActionEvent e) {
739 auto_increment_selected = 0;
740 clearbutton.setSelected(true);
741 }
742 });
743 saveHorizontalSpace(releasebutton);
744 pnl.add(releasebutton, GBC.eol());
745 value = pnl;
746 }
747 p.add(new JLabel(locale_text+":"), GBC.std().insets(0,0,10,0));
748 p.add(value, GBC.eol().fill(GBC.HORIZONTAL));
749 return true;
750 }
751
752 private static void saveHorizontalSpace(AbstractButton button) {
753 Insets insets = button.getBorder().getBorderInsets(button);
754 // Ensure the current look&feel does not waste horizontal space (as seen in Nimbus & Aqua)
755 if (insets != null && insets.left+insets.right > insets.top+insets.bottom) {
756 int min = Math.min(insets.top, insets.bottom);
757 button.setBorder(BorderFactory.createEmptyBorder(insets.top, min, insets.bottom, min));
758 }
759 }
760
761 private static String getValue(Component comp) {
762 if (comp instanceof JosmComboBox) {
763 return ((JosmComboBox<?>) comp).getEditor().getItem().toString();
764 } else if (comp instanceof JosmTextField) {
765 return ((JosmTextField) comp).getText();
766 } else if (comp instanceof JPanel) {
767 return getValue(((JPanel)comp).getComponent(0));
768 } else {
769 return null;
770 }
771 }
772
773 @Override
774 public void addCommands(List<Tag> changedTags) {
775
776 // return if unchanged
777 String v = getValue(value);
778 if (v == null) {
779 Main.error("No 'last value' support for component " + value);
780 return;
781 }
782
783 v = Tag.removeWhiteSpaces(v);
784
785 if (!"false".equals(use_last_as_default) || auto_increment != null) {
786 LAST_VALUES.put(key, v);
787 }
788 if (v.equals(originalValue) || (originalValue == null && v.isEmpty()))
789 return;
790
791 changedTags.add(new Tag(key, v));
792 AutoCompletionManager.rememberUserInput(key, v, true);
793 }
794
795 @Override
796 boolean requestFocusInWindow() {
797 return value.requestFocusInWindow();
798 }
799
800 @Override
801 public MatchType getDefaultMatch() {
802 return MatchType.NONE;
803 }
804
805 @Override
806 public Collection<String> getValues() {
807 if (default_ == null || default_.isEmpty())
808 return Collections.emptyList();
809 return Collections.singleton(default_);
810 }
811 }
812
813 /**
814 * A group of {@link Check}s.
815 * @since 6114
816 */
817 public static class CheckGroup extends TaggingPresetItem {
818
819 /**
820 * Number of columns (positive integer)
821 */
822 public String columns;
823
824 /**
825 * List of checkboxes
826 */
827 public final List<Check> checks = new LinkedList<>();
828
829 @Override
830 boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
831 Integer cols = Integer.valueOf(columns);
832 int rows = (int) Math.ceil(checks.size()/cols.doubleValue());
833 JPanel panel = new JPanel(new GridLayout(rows, cols));
834
835 for (Check check : checks) {
836 check.addToPanel(panel, sel, presetInitiallyMatches);
837 }
838
839 p.add(panel, GBC.eol());
840 return false;
841 }
842
843 @Override
844 void addCommands(List<Tag> changedTags) {
845 for (Check check : checks) {
846 check.addCommands(changedTags);
847 }
848 }
849
850 @Override
851 public String toString() {
852 return "CheckGroup [columns=" + columns + "]";
853 }
854 }
855
856 /**
857 * Checkbox type.
858 */
859 public static class Check extends KeyedItem {
860
861 /** The localized version of {@link #text}. */
862 public String locale_text;
863 /** the value to set when checked (default is "yes") */
864 public String value_on = OsmUtils.trueval;
865 /** the value to set when unchecked (default is "no") */
866 public String value_off = OsmUtils.falseval;
867 /** whether the off value is disabled in the dialog, i.e., only unset or yes are provided */
868 public boolean disable_off = false;
869 /** ticked on/off (default is "off") */
870 public boolean default_ = false; // only used for tagless objects
871
872 private QuadStateCheckBox check;
873 private QuadStateCheckBox.State initialState;
874 private boolean def;
875
876 @Override
877 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
878
879 // find out if our key is already used in the selection.
880 final Usage usage = determineBooleanUsage(sel, key);
881 final String oneValue = usage.values.isEmpty() ? null : usage.values.last();
882 def = default_;
883
884 if (locale_text == null) {
885 locale_text = getLocaleText(text, text_context, null);
886 }
887
888 if (usage.values.size() < 2 && (oneValue == null || value_on.equals(oneValue) || value_off.equals(oneValue))) {
889 if (def && !PROP_FILL_DEFAULT.get()) {
890 // default is set and filling default values feature is disabled - check if all primitives are untagged
891 for (OsmPrimitive s : sel)
892 if (s.hasKeys()) {
893 def = false;
894 }
895 }
896
897 // all selected objects share the same value which is either true or false or unset,
898 // we can display a standard check box.
899 initialState = value_on.equals(oneValue)
900 ? QuadStateCheckBox.State.SELECTED
901 : value_off.equals(oneValue)
902 ? QuadStateCheckBox.State.NOT_SELECTED
903 : def
904 ? QuadStateCheckBox.State.SELECTED
905 : QuadStateCheckBox.State.UNSET;
906 } else {
907 def = false;
908 // the objects have different values, or one or more objects have something
909 // else than true/false. we display a quad-state check box
910 // in "partial" state.
911 initialState = QuadStateCheckBox.State.PARTIAL;
912 }
913
914 final List<QuadStateCheckBox.State> allowedStates = new ArrayList<>(4);
915 if (QuadStateCheckBox.State.PARTIAL.equals(initialState))
916 allowedStates.add(QuadStateCheckBox.State.PARTIAL);
917 allowedStates.add(QuadStateCheckBox.State.SELECTED);
918 if (!disable_off || value_off.equals(oneValue))
919 allowedStates.add(QuadStateCheckBox.State.NOT_SELECTED);
920 allowedStates.add(QuadStateCheckBox.State.UNSET);
921 check = new QuadStateCheckBox(locale_text, initialState,
922 allowedStates.toArray(new QuadStateCheckBox.State[allowedStates.size()]));
923
924 p.add(check, GBC.eol().fill(GBC.HORIZONTAL));
925 return true;
926 }
927
928 @Override
929 public void addCommands(List<Tag> changedTags) {
930 // if the user hasn't changed anything, don't create a command.
931 if (check.getState() == initialState && !def) return;
932
933 // otherwise change things according to the selected value.
934 changedTags.add(new Tag(key,
935 check.getState() == QuadStateCheckBox.State.SELECTED ? value_on :
936 check.getState() == QuadStateCheckBox.State.NOT_SELECTED ? value_off :
937 null));
938 }
939
940 @Override
941 boolean requestFocusInWindow() {
942 return check.requestFocusInWindow();
943 }
944
945 @Override
946 public MatchType getDefaultMatch() {
947 return MatchType.NONE;
948 }
949
950 @Override
951 public Collection<String> getValues() {
952 return disable_off ? Arrays.asList(value_on) : Arrays.asList(value_on, value_off);
953 }
954
955 @Override
956 public String toString() {
957 return "Check ["
958 + (locale_text != null ? "locale_text=" + locale_text + ", " : "")
959 + (value_on != null ? "value_on=" + value_on + ", " : "")
960 + (value_off != null ? "value_off=" + value_off + ", " : "")
961 + "default_=" + default_ + ", "
962 + (check != null ? "check=" + check + ", " : "")
963 + (initialState != null ? "initialState=" + initialState
964 + ", " : "") + "def=" + def + "]";
965 }
966 }
967
968 /**
969 * Abstract superclass for combo box and multi-select list types.
970 */
971 public abstract static class ComboMultiSelect extends KeyedItem {
972
973 /** The localized version of {@link #text}. */
974 public String locale_text;
975 public String values;
976 public String values_from;
977 /** The context used for translating {@link #values} */
978 public String values_context;
979 public String display_values;
980 /** The localized version of {@link #display_values}. */
981 public String locale_display_values;
982 public String short_descriptions;
983 /** The localized version of {@link #short_descriptions}. */
984 public String locale_short_descriptions;
985 public String default_;
986 public String delimiter = ";";
987 public String use_last_as_default = "false";
988 /** whether to use values for search via {@link TaggingPresetSelector} */
989 public String values_searchable = "false";
990
991 protected JComponent component;
992 protected final Map<String, PresetListEntry> lhm = new LinkedHashMap<>();
993 private boolean initialized = false;
994 protected Usage usage;
995 protected Object originalValue;
996
997 protected abstract Object getSelectedItem();
998 protected abstract void addToPanelAnchor(JPanel p, String def, boolean presetInitiallyMatches);
999
1000 protected char getDelChar() {
1001 return delimiter.isEmpty() ? ';' : delimiter.charAt(0);
1002 }
1003
1004 @Override
1005 public Collection<String> getValues() {
1006 initListEntries();
1007 return lhm.keySet();
1008 }
1009
1010 public Collection<String> getDisplayValues() {
1011 initListEntries();
1012 return Utils.transform(lhm.values(), new Utils.Function<PresetListEntry, String>() {
1013 @Override
1014 public String apply(PresetListEntry x) {
1015 return x.getDisplayValue(true);
1016 }
1017 });
1018 }
1019
1020 @Override
1021 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
1022
1023 initListEntries();
1024
1025 // find out if our key is already used in the selection.
1026 usage = determineTextUsage(sel, key);
1027 if (!usage.hasUniqueValue() && !usage.unused()) {
1028 lhm.put(DIFFERENT, new PresetListEntry(DIFFERENT));
1029 }
1030
1031 p.add(new JLabel(tr("{0}:", locale_text)), GBC.std().insets(0, 0, 10, 0));
1032 addToPanelAnchor(p, default_, presetInitiallyMatches);
1033
1034 return true;
1035
1036 }
1037
1038 private void initListEntries() {
1039 if (initialized) {
1040 lhm.remove(DIFFERENT); // possibly added in #addToPanel
1041 return;
1042 } else if (lhm.isEmpty()) {
1043 initListEntriesFromAttributes();
1044 } else {
1045 if (values != null) {
1046 Main.warn(tr("Warning in tagging preset \"{0}-{1}\": "
1047 + "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
1048 key, text, "values", "list_entry"));
1049 }
1050 if (display_values != null || locale_display_values != null) {
1051 Main.warn(tr("Warning in tagging preset \"{0}-{1}\": "
1052 + "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
1053 key, text, "display_values", "list_entry"));
1054 }
1055 if (short_descriptions != null || locale_short_descriptions != null) {
1056 Main.warn(tr("Warning in tagging preset \"{0}-{1}\": "
1057 + "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
1058 key, text, "short_descriptions", "list_entry"));
1059 }
1060 for (PresetListEntry e : lhm.values()) {
1061 if (e.value_context == null) {
1062 e.value_context = values_context;
1063 }
1064 }
1065 }
1066 if (locale_text == null) {
1067 locale_text = getLocaleText(text, text_context, null);
1068 }
1069 initialized = true;
1070 }
1071
1072 private void initListEntriesFromAttributes() {
1073 char delChar = getDelChar();
1074
1075 String[] value_array = null;
1076
1077 if (values_from != null) {
1078 String[] class_method = values_from.split("#");
1079 if (class_method != null && class_method.length == 2) {
1080 try {
1081 Method method = Class.forName(class_method[0]).getMethod(class_method[1]);
1082 // Check method is public static String[] methodName()
1083 int mod = method.getModifiers();
1084 if (Modifier.isPublic(mod) && Modifier.isStatic(mod)
1085 && method.getReturnType().equals(String[].class) && method.getParameterTypes().length == 0) {
1086 value_array = (String[]) method.invoke(null);
1087 } else {
1088 Main.error(tr("Broken tagging preset \"{0}-{1}\" - Java method given in ''values_from'' is not \"{2}\"", key, text,
1089 "public static String[] methodName()"));
1090 }
1091 } catch (Exception e) {
1092 Main.error(tr("Broken tagging preset \"{0}-{1}\" - Java method given in ''values_from'' threw {2} ({3})", key, text,
1093 e.getClass().getName(), e.getMessage()));
1094 }
1095 }
1096 }
1097
1098 if (value_array == null) {
1099 value_array = splitEscaped(delChar, values);
1100 }
1101
1102 final String displ = Utils.firstNonNull(locale_display_values, display_values);
1103 String[] display_array = displ == null ? value_array : splitEscaped(delChar, displ);
1104
1105 final String descr = Utils.firstNonNull(locale_short_descriptions, short_descriptions);
1106 String[] short_descriptions_array = descr == null ? null : splitEscaped(delChar, descr);
1107
1108 if (display_array.length != value_array.length) {
1109 Main.error(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''display_values'' must be the same as in ''values''", key, text));
1110 display_array = value_array;
1111 }
1112
1113 if (short_descriptions_array != null && short_descriptions_array.length != value_array.length) {
1114 Main.error(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''short_descriptions'' must be the same as in ''values''", key, text));
1115 short_descriptions_array = null;
1116 }
1117
1118 final List<PresetListEntry> entries = new ArrayList<>(value_array.length);
1119 for (int i = 0; i < value_array.length; i++) {
1120 final PresetListEntry e = new PresetListEntry(value_array[i]);
1121 e.locale_display_value = locale_display_values != null
1122 ? display_array[i]
1123 : trc(values_context, fixPresetString(display_array[i]));
1124 if (short_descriptions_array != null) {
1125 e.locale_short_description = locale_short_descriptions != null
1126 ? short_descriptions_array[i]
1127 : tr(fixPresetString(short_descriptions_array[i]));
1128 }
1129
1130 entries.add(e);
1131 }
1132
1133 if (Main.pref.getBoolean("taggingpreset.sortvalues", true)) {
1134 Collections.sort(entries);
1135 }
1136
1137 for (PresetListEntry i : entries) {
1138 lhm.put(i.value, i);
1139 }
1140
1141 }
1142
1143 protected String getDisplayIfNull() {
1144 return null;
1145 }
1146
1147 @Override
1148 public void addCommands(List<Tag> changedTags) {
1149 Object obj = getSelectedItem();
1150 String display = (obj == null) ? null : obj.toString();
1151 String value = null;
1152 if (display == null) {
1153 display = getDisplayIfNull();
1154 }
1155
1156 if (display != null) {
1157 for (Entry<String, PresetListEntry> entry : lhm.entrySet()) {
1158 String k = entry.getValue().toString();
1159 if (k != null && k.equals(display)) {
1160 value = entry.getKey();
1161 break;
1162 }
1163 }
1164 if (value == null) {
1165 value = display;
1166 }
1167 } else {
1168 value = "";
1169 }
1170 value = Tag.removeWhiteSpaces(value);
1171
1172 // no change if same as before
1173 if (originalValue == null) {
1174 if (value.isEmpty())
1175 return;
1176 } else if (value.equals(originalValue.toString()))
1177 return;
1178
1179 if (!"false".equals(use_last_as_default)) {
1180 LAST_VALUES.put(key, value);
1181 }
1182 changedTags.add(new Tag(key, value));
1183 }
1184
1185 public void addListEntry(PresetListEntry e) {
1186 lhm.put(e.value, e);
1187 }
1188
1189 public void addListEntries(Collection<PresetListEntry> e) {
1190 for (PresetListEntry i : e) {
1191 addListEntry(i);
1192 }
1193 }
1194
1195 @Override
1196 boolean requestFocusInWindow() {
1197 return component.requestFocusInWindow();
1198 }
1199
1200 private static final ListCellRenderer<PresetListEntry> RENDERER = new ListCellRenderer<PresetListEntry>() {
1201
1202 private JLabel lbl = new JLabel();
1203
1204 @Override
1205 public Component getListCellRendererComponent(
1206 JList<? extends PresetListEntry> list,
1207 PresetListEntry item,
1208 int index,
1209 boolean isSelected,
1210 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
1225 if (isSelected) {
1226 lbl.setBackground(list.getSelectionBackground());
1227 lbl.setForeground(list.getSelectionForeground());
1228 } else {
1229 lbl.setBackground(list.getBackground());
1230 lbl.setForeground(list.getForeground());
1231 }
1232
1233 lbl.setOpaque(true);
1234 lbl.setFont(lbl.getFont().deriveFont(Font.PLAIN));
1235 lbl.setText("<html>" + item.getListDisplay() + "</html>");
1236 lbl.setIcon(item.getIcon());
1237 lbl.setEnabled(list.isEnabled());
1238
1239 // Cache size
1240 item.prefferedWidth = lbl.getPreferredSize().width;
1241 item.prefferedHeight = lbl.getPreferredSize().height;
1242
1243 // We do not want the editor to have the maximum height of all
1244 // entries. Return a dummy with bogus height.
1245 if (index == -1) {
1246 lbl.setPreferredSize(new Dimension(lbl.getPreferredSize().width, 10));
1247 }
1248 return lbl;
1249 }
1250 };
1251
1252 protected ListCellRenderer<PresetListEntry> getListCellRenderer() {
1253 return RENDERER;
1254 }
1255
1256 @Override
1257 public MatchType getDefaultMatch() {
1258 return MatchType.NONE;
1259 }
1260 }
1261
1262 /**
1263 * Combobox type.
1264 */
1265 public static class Combo extends ComboMultiSelect {
1266
1267 public boolean editable = true;
1268 protected JosmComboBox<PresetListEntry> combo;
1269 public String length;
1270
1271 /**
1272 * Constructs a new {@code Combo}.
1273 */
1274 public Combo() {
1275 delimiter = ",";
1276 }
1277
1278 @Override
1279 protected void addToPanelAnchor(JPanel p, String def, boolean presetInitiallyMatches) {
1280 if (!usage.unused()) {
1281 for (String s : usage.values) {
1282 if (!lhm.containsKey(s)) {
1283 lhm.put(s, new PresetListEntry(s));
1284 }
1285 }
1286 }
1287 if (def != null && !lhm.containsKey(def)) {
1288 lhm.put(def, new PresetListEntry(def));
1289 }
1290 lhm.put("", new PresetListEntry(""));
1291
1292 combo = new JosmComboBox<>(lhm.values().toArray(new PresetListEntry[0]));
1293 component = combo;
1294 combo.setRenderer(getListCellRenderer());
1295 combo.setEditable(editable);
1296 combo.reinitialize(lhm.values());
1297 AutoCompletingTextField tf = new AutoCompletingTextField();
1298 initAutoCompletionField(tf, key);
1299 if (Main.pref.getBoolean("taggingpreset.display-keys-as-hint", true)) {
1300 tf.setHint(key);
1301 }
1302 if (length != null && !length.isEmpty()) {
1303 tf.setMaxChars(Integer.valueOf(length));
1304 }
1305 AutoCompletionList acList = tf.getAutoCompletionList();
1306 if (acList != null) {
1307 acList.add(getDisplayValues(), AutoCompletionItemPriority.IS_IN_STANDARD);
1308 }
1309 combo.setEditor(tf);
1310
1311 if (usage.hasUniqueValue()) {
1312 // all items have the same value (and there were no unset items)
1313 originalValue = lhm.get(usage.getFirst());
1314 combo.setSelectedItem(originalValue);
1315 } else if (def != null && usage.unused()) {
1316 // default is set and all items were unset
1317 if (!usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
1318 // selected osm primitives are untagged or filling default feature is enabled
1319 combo.setSelectedItem(lhm.get(def).getDisplayValue(true));
1320 } else {
1321 // selected osm primitives are tagged and filling default feature is disabled
1322 combo.setSelectedItem("");
1323 }
1324 originalValue = lhm.get(DIFFERENT);
1325 } else if (usage.unused()) {
1326 // all items were unset (and so is default)
1327 originalValue = lhm.get("");
1328 if ("force".equals(use_last_as_default) && LAST_VALUES.containsKey(key) && !presetInitiallyMatches) {
1329 combo.setSelectedItem(lhm.get(LAST_VALUES.get(key)));
1330 } else {
1331 combo.setSelectedItem(originalValue);
1332 }
1333 } else {
1334 originalValue = lhm.get(DIFFERENT);
1335 combo.setSelectedItem(originalValue);
1336 }
1337 p.add(combo, GBC.eol().fill(GBC.HORIZONTAL));
1338
1339 }
1340
1341 @Override
1342 protected Object getSelectedItem() {
1343 return combo.getSelectedItem();
1344
1345 }
1346
1347 @Override
1348 protected String getDisplayIfNull() {
1349 if (combo.isEditable())
1350 return combo.getEditor().getItem().toString();
1351 else
1352 return null;
1353 }
1354 }
1355
1356 /**
1357 * Multi-select list type.
1358 */
1359 public static class MultiSelect extends ComboMultiSelect {
1360
1361 /**
1362 * Number of rows to display (positive integer, optional).
1363 */
1364 public String rows;
1365 protected ConcatenatingJList list;
1366
1367 @Override
1368 protected void addToPanelAnchor(JPanel p, String def, boolean presetInitiallyMatches) {
1369 list = new ConcatenatingJList(delimiter, lhm.values().toArray(new PresetListEntry[0]));
1370 component = list;
1371 ListCellRenderer<PresetListEntry> renderer = getListCellRenderer();
1372 list.setCellRenderer(renderer);
1373
1374 if (usage.hasUniqueValue() && !usage.unused()) {
1375 originalValue = usage.getFirst();
1376 list.setSelectedItem(originalValue);
1377 } else if (def != null && !usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
1378 originalValue = DIFFERENT;
1379 list.setSelectedItem(def);
1380 } else if (usage.unused()) {
1381 originalValue = null;
1382 list.setSelectedItem(originalValue);
1383 } else {
1384 originalValue = DIFFERENT;
1385 list.setSelectedItem(originalValue);
1386 }
1387
1388 JScrollPane sp = new JScrollPane(list);
1389 // if a number of rows has been specified in the preset,
1390 // modify preferred height of scroll pane to match that row count.
1391 if (rows != null) {
1392 double height = renderer.getListCellRendererComponent(list,
1393 new PresetListEntry("x"), 0, false, false).getPreferredSize().getHeight() * Integer.parseInt(rows);
1394 sp.setPreferredSize(new Dimension((int) sp.getPreferredSize().getWidth(), (int) height));
1395 }
1396 p.add(sp, GBC.eol().fill(GBC.HORIZONTAL));
1397 }
1398
1399 @Override
1400 protected Object getSelectedItem() {
1401 return list.getSelectedItem();
1402 }
1403
1404 @Override
1405 public void addCommands(List<Tag> changedTags) {
1406 // Do not create any commands if list has been disabled because of an unknown value (fix #8605)
1407 if (list.isEnabled()) {
1408 super.addCommands(changedTags);
1409 }
1410 }
1411 }
1412
1413 /**
1414 * Class that allows list values to be assigned and retrieved as a comma-delimited
1415 * string (extracted from TaggingPreset)
1416 */
1417 private static class ConcatenatingJList extends JList<PresetListEntry> {
1418 private String delimiter;
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.