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

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

see #8465 - use diamond operator where applicable

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