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

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

code style - A close curly brace should be located at the beginning of a line

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