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

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

fix #11290 - fix width of auto_increment buttons for Aqua & Nimbus look and feels

  • 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 res.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 res.append(getShortDescription(true));
129 res.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) ? 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)) ? 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.length() == 0))
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() {return check.requestFocusInWindow();}
936
937 @Override
938 public MatchType getDefaultMatch() {
939 return MatchType.NONE;
940 }
941
942 @Override
943 public Collection<String> getValues() {
944 return disable_off ? Arrays.asList(value_on) : Arrays.asList(value_on, value_off);
945 }
946
947 @Override
948 public String toString() {
949 return "Check ["
950 + (locale_text != null ? "locale_text=" + locale_text + ", " : "")
951 + (value_on != null ? "value_on=" + value_on + ", " : "")
952 + (value_off != null ? "value_off=" + value_off + ", " : "")
953 + "default_=" + default_ + ", "
954 + (check != null ? "check=" + check + ", " : "")
955 + (initialState != null ? "initialState=" + initialState
956 + ", " : "") + "def=" + def + "]";
957 }
958 }
959
960 /**
961 * Abstract superclass for combo box and multi-select list types.
962 */
963 public abstract static class ComboMultiSelect extends KeyedItem {
964
965 /** The localized version of {@link #text}. */
966 public String locale_text;
967 public String values;
968 public String values_from;
969 /** The context used for translating {@link #values} */
970 public String values_context;
971 public String display_values;
972 /** The localized version of {@link #display_values}. */
973 public String locale_display_values;
974 public String short_descriptions;
975 /** The localized version of {@link #short_descriptions}. */
976 public String locale_short_descriptions;
977 public String default_;
978 public String delimiter = ";";
979 public String use_last_as_default = "false";
980 /** whether to use values for search via {@link TaggingPresetSelector} */
981 public String values_searchable = "false";
982
983 protected JComponent component;
984 protected final Map<String, PresetListEntry> lhm = new LinkedHashMap<>();
985 private boolean initialized = false;
986 protected Usage usage;
987 protected Object originalValue;
988
989 protected abstract Object getSelectedItem();
990 protected abstract void addToPanelAnchor(JPanel p, String def, boolean presetInitiallyMatches);
991
992 protected char getDelChar() {
993 return delimiter.isEmpty() ? ';' : delimiter.charAt(0);
994 }
995
996 @Override
997 public Collection<String> getValues() {
998 initListEntries();
999 return lhm.keySet();
1000 }
1001
1002 public Collection<String> getDisplayValues() {
1003 initListEntries();
1004 return Utils.transform(lhm.values(), new Utils.Function<PresetListEntry, String>() {
1005 @Override
1006 public String apply(PresetListEntry x) {
1007 return x.getDisplayValue(true);
1008 }
1009 });
1010 }
1011
1012 @Override
1013 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
1014
1015 initListEntries();
1016
1017 // find out if our key is already used in the selection.
1018 usage = determineTextUsage(sel, key);
1019 if (!usage.hasUniqueValue() && !usage.unused()) {
1020 lhm.put(DIFFERENT, new PresetListEntry(DIFFERENT));
1021 }
1022
1023 p.add(new JLabel(tr("{0}:", locale_text)), GBC.std().insets(0, 0, 10, 0));
1024 addToPanelAnchor(p, default_, presetInitiallyMatches);
1025
1026 return true;
1027
1028 }
1029
1030 private void initListEntries() {
1031 if (initialized) {
1032 lhm.remove(DIFFERENT); // possibly added in #addToPanel
1033 return;
1034 } else if (lhm.isEmpty()) {
1035 initListEntriesFromAttributes();
1036 } else {
1037 if (values != null) {
1038 Main.warn(tr("Warning in tagging preset \"{0}-{1}\": "
1039 + "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
1040 key, text, "values", "list_entry"));
1041 }
1042 if (display_values != null || locale_display_values != null) {
1043 Main.warn(tr("Warning in tagging preset \"{0}-{1}\": "
1044 + "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
1045 key, text, "display_values", "list_entry"));
1046 }
1047 if (short_descriptions != null || locale_short_descriptions != null) {
1048 Main.warn(tr("Warning in tagging preset \"{0}-{1}\": "
1049 + "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
1050 key, text, "short_descriptions", "list_entry"));
1051 }
1052 for (PresetListEntry e : lhm.values()) {
1053 if (e.value_context == null) {
1054 e.value_context = values_context;
1055 }
1056 }
1057 }
1058 if (locale_text == null) {
1059 locale_text = getLocaleText(text, text_context, null);
1060 }
1061 initialized = true;
1062 }
1063
1064 private String[] initListEntriesFromAttributes() {
1065 char delChar = getDelChar();
1066
1067 String[] value_array = null;
1068
1069 if (values_from != null) {
1070 String[] class_method = values_from.split("#");
1071 if (class_method != null && class_method.length == 2) {
1072 try {
1073 Method method = Class.forName(class_method[0]).getMethod(class_method[1]);
1074 // Check method is public static String[] methodName()
1075 int mod = method.getModifiers();
1076 if (Modifier.isPublic(mod) && Modifier.isStatic(mod)
1077 && method.getReturnType().equals(String[].class) && method.getParameterTypes().length == 0) {
1078 value_array = (String[]) method.invoke(null);
1079 } else {
1080 Main.error(tr("Broken tagging preset \"{0}-{1}\" - Java method given in ''values_from'' is not \"{2}\"", key, text,
1081 "public static String[] methodName()"));
1082 }
1083 } catch (Exception e) {
1084 Main.error(tr("Broken tagging preset \"{0}-{1}\" - Java method given in ''values_from'' threw {2} ({3})", key, text,
1085 e.getClass().getName(), e.getMessage()));
1086 }
1087 }
1088 }
1089
1090 if (value_array == null) {
1091 value_array = splitEscaped(delChar, values);
1092 }
1093
1094 final String displ = Utils.firstNonNull(locale_display_values, display_values);
1095 String[] display_array = displ == null ? value_array : splitEscaped(delChar, displ);
1096
1097 final String descr = Utils.firstNonNull(locale_short_descriptions, short_descriptions);
1098 String[] short_descriptions_array = descr == null ? null : splitEscaped(delChar, descr);
1099
1100 if (display_array.length != value_array.length) {
1101 Main.error(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''display_values'' must be the same as in ''values''", key, text));
1102 display_array = value_array;
1103 }
1104
1105 if (short_descriptions_array != null && short_descriptions_array.length != value_array.length) {
1106 Main.error(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''short_descriptions'' must be the same as in ''values''", key, text));
1107 short_descriptions_array = null;
1108 }
1109
1110 for (int i = 0; i < value_array.length; i++) {
1111 final PresetListEntry e = new PresetListEntry(value_array[i]);
1112 e.locale_display_value = locale_display_values != null
1113 ? display_array[i]
1114 : trc(values_context, fixPresetString(display_array[i]));
1115 if (short_descriptions_array != null) {
1116 e.locale_short_description = locale_short_descriptions != null
1117 ? short_descriptions_array[i]
1118 : tr(fixPresetString(short_descriptions_array[i]));
1119 }
1120 lhm.put(value_array[i], e);
1121 display_array[i] = e.getDisplayValue(true);
1122 }
1123
1124 return display_array;
1125 }
1126
1127 protected String getDisplayIfNull() {
1128 return null;
1129 }
1130
1131 @Override
1132 public void addCommands(List<Tag> changedTags) {
1133 Object obj = getSelectedItem();
1134 String display = (obj == null) ? null : obj.toString();
1135 String value = null;
1136 if (display == null) {
1137 display = getDisplayIfNull();
1138 }
1139
1140 if (display != null) {
1141 for (Entry<String, PresetListEntry> entry : lhm.entrySet()) {
1142 String k = entry.getValue().toString();
1143 if (k != null && k.equals(display)) {
1144 value = entry.getKey();
1145 break;
1146 }
1147 }
1148 if (value == null) {
1149 value = display;
1150 }
1151 } else {
1152 value = "";
1153 }
1154 value = Tag.removeWhiteSpaces(value);
1155
1156 // no change if same as before
1157 if (originalValue == null) {
1158 if (value.length() == 0)
1159 return;
1160 } else if (value.equals(originalValue.toString()))
1161 return;
1162
1163 if (!"false".equals(use_last_as_default)) {
1164 LAST_VALUES.put(key, value);
1165 }
1166 changedTags.add(new Tag(key, value));
1167 }
1168
1169 public void addListEntry(PresetListEntry e) {
1170 lhm.put(e.value, e);
1171 }
1172
1173 public void addListEntries(Collection<PresetListEntry> e) {
1174 for (PresetListEntry i : e) {
1175 addListEntry(i);
1176 }
1177 }
1178
1179 @Override
1180 boolean requestFocusInWindow() {
1181 return component.requestFocusInWindow();
1182 }
1183
1184 private static final ListCellRenderer<PresetListEntry> RENDERER = new ListCellRenderer<PresetListEntry>() {
1185
1186 private JLabel lbl = new JLabel();
1187
1188 @Override
1189 public Component getListCellRendererComponent(
1190 JList<? extends PresetListEntry> list,
1191 PresetListEntry item,
1192 int index,
1193 boolean isSelected,
1194 boolean cellHasFocus) {
1195
1196 // Only return cached size, item is not shown
1197 if (!list.isShowing() && item.prefferedWidth != -1 && item.prefferedHeight != -1) {
1198 if (index == -1) {
1199 lbl.setPreferredSize(new Dimension(item.prefferedWidth, 10));
1200 } else {
1201 lbl.setPreferredSize(new Dimension(item.prefferedWidth, item.prefferedHeight));
1202 }
1203 return lbl;
1204 }
1205
1206 lbl.setPreferredSize(null);
1207
1208
1209 if (isSelected) {
1210 lbl.setBackground(list.getSelectionBackground());
1211 lbl.setForeground(list.getSelectionForeground());
1212 } else {
1213 lbl.setBackground(list.getBackground());
1214 lbl.setForeground(list.getForeground());
1215 }
1216
1217 lbl.setOpaque(true);
1218 lbl.setFont(lbl.getFont().deriveFont(Font.PLAIN));
1219 lbl.setText("<html>" + item.getListDisplay() + "</html>");
1220 lbl.setIcon(item.getIcon());
1221 lbl.setEnabled(list.isEnabled());
1222
1223 // Cache size
1224 item.prefferedWidth = lbl.getPreferredSize().width;
1225 item.prefferedHeight = lbl.getPreferredSize().height;
1226
1227 // We do not want the editor to have the maximum height of all
1228 // entries. Return a dummy with bogus height.
1229 if (index == -1) {
1230 lbl.setPreferredSize(new Dimension(lbl.getPreferredSize().width, 10));
1231 }
1232 return lbl;
1233 }
1234 };
1235
1236 protected ListCellRenderer<PresetListEntry> getListCellRenderer() {
1237 return RENDERER;
1238 }
1239
1240 @Override
1241 public MatchType getDefaultMatch() {
1242 return MatchType.NONE;
1243 }
1244 }
1245
1246 /**
1247 * Combobox type.
1248 */
1249 public static class Combo extends ComboMultiSelect {
1250
1251 public boolean editable = true;
1252 protected JosmComboBox<PresetListEntry> combo;
1253 public String length;
1254
1255 /**
1256 * Constructs a new {@code Combo}.
1257 */
1258 public Combo() {
1259 delimiter = ",";
1260 }
1261
1262 @Override
1263 protected void addToPanelAnchor(JPanel p, String def, boolean presetInitiallyMatches) {
1264 if (!usage.unused()) {
1265 for (String s : usage.values) {
1266 if (!lhm.containsKey(s)) {
1267 lhm.put(s, new PresetListEntry(s));
1268 }
1269 }
1270 }
1271 if (def != null && !lhm.containsKey(def)) {
1272 lhm.put(def, new PresetListEntry(def));
1273 }
1274 lhm.put("", new PresetListEntry(""));
1275
1276 combo = new JosmComboBox<>(lhm.values().toArray(new PresetListEntry[0]));
1277 component = combo;
1278 combo.setRenderer(getListCellRenderer());
1279 combo.setEditable(editable);
1280 combo.reinitialize(lhm.values());
1281 AutoCompletingTextField tf = new AutoCompletingTextField();
1282 initAutoCompletionField(tf, key);
1283 if (Main.pref.getBoolean("taggingpreset.display-keys-as-hint", true)) {
1284 tf.setHint(key);
1285 }
1286 if (length != null && !length.isEmpty()) {
1287 tf.setMaxChars(Integer.valueOf(length));
1288 }
1289 AutoCompletionList acList = tf.getAutoCompletionList();
1290 if (acList != null) {
1291 acList.add(getDisplayValues(), AutoCompletionItemPriority.IS_IN_STANDARD);
1292 }
1293 combo.setEditor(tf);
1294
1295 if (usage.hasUniqueValue()) {
1296 // all items have the same value (and there were no unset items)
1297 originalValue = lhm.get(usage.getFirst());
1298 combo.setSelectedItem(originalValue);
1299 } else if (def != null && usage.unused()) {
1300 // default is set and all items were unset
1301 if (!usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
1302 // selected osm primitives are untagged or filling default feature is enabled
1303 combo.setSelectedItem(lhm.get(def).getDisplayValue(true));
1304 } else {
1305 // selected osm primitives are tagged and filling default feature is disabled
1306 combo.setSelectedItem("");
1307 }
1308 originalValue = lhm.get(DIFFERENT);
1309 } else if (usage.unused()) {
1310 // all items were unset (and so is default)
1311 originalValue = lhm.get("");
1312 if ("force".equals(use_last_as_default) && LAST_VALUES.containsKey(key) && !presetInitiallyMatches) {
1313 combo.setSelectedItem(lhm.get(LAST_VALUES.get(key)));
1314 } else {
1315 combo.setSelectedItem(originalValue);
1316 }
1317 } else {
1318 originalValue = lhm.get(DIFFERENT);
1319 combo.setSelectedItem(originalValue);
1320 }
1321 p.add(combo, GBC.eol().fill(GBC.HORIZONTAL));
1322
1323 }
1324
1325 @Override
1326 protected Object getSelectedItem() {
1327 return combo.getSelectedItem();
1328
1329 }
1330
1331 @Override
1332 protected String getDisplayIfNull() {
1333 if (combo.isEditable())
1334 return combo.getEditor().getItem().toString();
1335 else
1336 return null;
1337 }
1338 }
1339
1340 /**
1341 * Multi-select list type.
1342 */
1343 public static class MultiSelect extends ComboMultiSelect {
1344
1345 /**
1346 * Number of rows to display (positive integer, optional).
1347 */
1348 public String rows;
1349 protected ConcatenatingJList list;
1350
1351 @Override
1352 protected void addToPanelAnchor(JPanel p, String def, boolean presetInitiallyMatches) {
1353 list = new ConcatenatingJList(delimiter, lhm.values().toArray(new PresetListEntry[0]));
1354 component = list;
1355 ListCellRenderer<PresetListEntry> renderer = getListCellRenderer();
1356 list.setCellRenderer(renderer);
1357
1358 if (usage.hasUniqueValue() && !usage.unused()) {
1359 originalValue = usage.getFirst();
1360 list.setSelectedItem(originalValue);
1361 } else if (def != null && !usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
1362 originalValue = DIFFERENT;
1363 list.setSelectedItem(def);
1364 } else if (usage.unused()) {
1365 originalValue = null;
1366 list.setSelectedItem(originalValue);
1367 } else {
1368 originalValue = DIFFERENT;
1369 list.setSelectedItem(originalValue);
1370 }
1371
1372 JScrollPane sp = new JScrollPane(list);
1373 // if a number of rows has been specified in the preset,
1374 // modify preferred height of scroll pane to match that row count.
1375 if (rows != null) {
1376 double height = renderer.getListCellRendererComponent(list,
1377 new PresetListEntry("x"), 0, false, false).getPreferredSize().getHeight() * Integer.valueOf(rows);
1378 sp.setPreferredSize(new Dimension((int) sp.getPreferredSize().getWidth(), (int) height));
1379 }
1380 p.add(sp, GBC.eol().fill(GBC.HORIZONTAL));
1381 }
1382
1383 @Override
1384 protected Object getSelectedItem() {
1385 return list.getSelectedItem();
1386 }
1387
1388 @Override
1389 public void addCommands(List<Tag> changedTags) {
1390 // Do not create any commands if list has been disabled because of an unknown value (fix #8605)
1391 if (list.isEnabled()) {
1392 super.addCommands(changedTags);
1393 }
1394 }
1395 }
1396
1397 /**
1398 * Class that allows list values to be assigned and retrieved as a comma-delimited
1399 * string (extracted from TaggingPreset)
1400 */
1401 private static class ConcatenatingJList extends JList<PresetListEntry> {
1402 private String delimiter;
1403 public ConcatenatingJList(String del, PresetListEntry[] o) {
1404 super(o);
1405 delimiter = del;
1406 }
1407
1408 public void setSelectedItem(Object o) {
1409 if (o == null) {
1410 clearSelection();
1411 } else {
1412 String s = o.toString();
1413 Set<String> parts = new TreeSet<>(Arrays.asList(s.split(delimiter)));
1414 ListModel<PresetListEntry> lm = getModel();
1415 int[] intParts = new int[lm.getSize()];
1416 int j = 0;
1417 for (int i = 0; i < lm.getSize(); i++) {
1418 final String value = lm.getElementAt(i).value;
1419 if (parts.contains(value)) {
1420 intParts[j++]=i;
1421 parts.remove(value);
1422 }
1423 }
1424 setSelectedIndices(Arrays.copyOf(intParts, j));
1425 // check if we have actually managed to represent the full
1426 // value with our presets. if not, cop out; we will not offer
1427 // a selection list that threatens to ruin the value.
1428 setEnabled(parts.isEmpty());
1429 }
1430 }
1431
1432 public String getSelectedItem() {
1433 ListModel<PresetListEntry> lm = getModel();
1434 int[] si = getSelectedIndices();
1435 StringBuilder builder = new StringBuilder();
1436 for (int i=0; i<si.length; i++) {
1437 if (i>0) {
1438 builder.append(delimiter);
1439 }
1440 builder.append(lm.getElementAt(si[i]).value);
1441 }
1442 return builder.toString();
1443 }
1444 }
1445
1446 public static Set<TaggingPresetType> getType(String types) throws SAXException {
1447 if (TYPE_CACHE.containsKey(types))
1448 return TYPE_CACHE.get(types);
1449 Set<TaggingPresetType> result = EnumSet.noneOf(TaggingPresetType.class);
1450 for (String type : Arrays.asList(types.split(","))) {
1451 try {
1452 TaggingPresetType presetType = TaggingPresetType.fromString(type);
1453 result.add(presetType);
1454 } catch (IllegalArgumentException e) {
1455 throw new SAXException(tr("Unknown type: {0}", type), e);
1456 }
1457 }
1458 TYPE_CACHE.put(types, result);
1459 return result;
1460 }
1461
1462 static String fixPresetString(String s) {
1463 return s == null ? s : s.replaceAll("'","''");
1464 }
1465
1466 private static String getLocaleText(String text, String text_context, String defaultText) {
1467 if (text == null) {
1468 return defaultText;
1469 } else if (text_context != null) {
1470 return trc(text_context, fixPresetString(text));
1471 } else {
1472 return tr(fixPresetString(text));
1473 }
1474 }
1475
1476 /**
1477 * allow escaped comma in comma separated list:
1478 * "A\, B\, C,one\, two" --&gt; ["A, B, C", "one, two"]
1479 * @param delimiter the delimiter, e.g. a comma. separates the entries and
1480 * must be escaped within one entry
1481 * @param s the string
1482 */
1483 private static String[] splitEscaped(char delimiter, String s) {
1484 if (s == null)
1485 return new String[0];
1486 List<String> result = new ArrayList<>();
1487 boolean backslash = false;
1488 StringBuilder item = new StringBuilder();
1489 for (int i=0; i<s.length(); i++) {
1490 char ch = s.charAt(i);
1491 if (backslash) {
1492 item.append(ch);
1493 backslash = false;
1494 } else if (ch == '\\') {
1495 backslash = true;
1496 } else if (ch == delimiter) {
1497 result.add(item.toString());
1498 item.setLength(0);
1499 } else {
1500 item.append(ch);
1501 }
1502 }
1503 if (item.length() > 0) {
1504 result.add(item.toString());
1505 }
1506 return result.toArray(new String[result.size()]);
1507 }
1508
1509 static Usage determineTextUsage(Collection<OsmPrimitive> sel, String key) {
1510 Usage returnValue = new Usage();
1511 returnValue.values = new TreeSet<>();
1512 for (OsmPrimitive s : sel) {
1513 String v = s.get(key);
1514 if (v != null) {
1515 returnValue.values.add(v);
1516 } else {
1517 returnValue.hadEmpty = true;
1518 }
1519 if(s.hasKeys()) {
1520 returnValue.hadKeys = true;
1521 }
1522 }
1523 return returnValue;
1524 }
1525
1526 static Usage determineBooleanUsage(Collection<OsmPrimitive> sel, String key) {
1527
1528 Usage returnValue = new Usage();
1529 returnValue.values = new TreeSet<>();
1530 for (OsmPrimitive s : sel) {
1531 String booleanValue = OsmUtils.getNamedOsmBoolean(s.get(key));
1532 if (booleanValue != null) {
1533 returnValue.values.add(booleanValue);
1534 }
1535 }
1536 return returnValue;
1537 }
1538
1539 protected static ImageIcon loadImageIcon(String iconName, File zipIcons, Integer maxSize) {
1540 final Collection<String> s = Main.pref.getCollection("taggingpreset.icon.sources", null);
1541 ImageProvider imgProv = new ImageProvider(iconName).setDirs(s).setId("presets").setArchive(zipIcons).setOptional(true);
1542 if (maxSize != null) {
1543 imgProv.setMaxSize(maxSize);
1544 }
1545 return imgProv.get();
1546 }
1547
1548 protected static Integer parseInteger(String str) {
1549 if (str == null || str.isEmpty())
1550 return null;
1551 try {
1552 return Integer.parseInt(str);
1553 } catch (Exception e) {
1554 if (Main.isTraceEnabled()) {
1555 Main.trace(e.getMessage());
1556 }
1557 }
1558 return null;
1559 }
1560}
Note: See TracBrowser for help on using the repository browser.