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

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

fix some Sonar issues

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 =
80 new LinkedHashMap<String, EnumSet<TaggingPresetType>>(16, 1.1f, true);
81
82 /**
83 * Last value of each key used in presets, used for prefilling corresponding fields
84 */
85 private static final Map<String,String> lastValue = new HashMap<String,String>();
86
87 public static class PresetListEntry {
88 public String value;
89 public String value_context;
90 public String display_value;
91 public String short_description;
92 public String icon;
93 public String icon_size;
94 public String locale_display_value;
95 public String locale_short_description;
96 private final File zipIcons = TaggingPresetReader.getZipIcons();
97
98 // Cached size (currently only for Combo) to speed up preset dialog initialization
99 private int prefferedWidth = -1;
100 private int prefferedHeight = -1;
101
102 public String getListDisplay() {
103 if (value.equals(DIFFERENT))
104 return "<b>"+DIFFERENT.replaceAll("<", "&lt;").replaceAll(">", "&gt;")+"</b>";
105
106 if (value.isEmpty())
107 return "&nbsp;";
108
109 final StringBuilder res = new StringBuilder("<b>");
110 res.append(getDisplayValue(true));
111 res.append("</b>");
112 if (getShortDescription(true) != null) {
113 // wrap in table to restrict the text width
114 res.append("<div style=\"width:300px; padding:0 0 5px 5px\">");
115 res.append(getShortDescription(true));
116 res.append("</div>");
117 }
118 return res.toString();
119 }
120
121 public ImageIcon getIcon() {
122 return icon == null ? null : loadImageIcon(icon, zipIcons, parseInteger(icon_size));
123 }
124
125 private Integer parseInteger(String str) {
126 if (str == null || str.isEmpty())
127 return null;
128 try {
129 return Integer.parseInt(str);
130 } catch (Exception e) {
131 //
132 }
133 return null;
134 }
135
136 public PresetListEntry() {
137 }
138
139 public PresetListEntry(String value) {
140 this.value = value;
141 }
142
143 public String getDisplayValue(boolean translated) {
144 return translated
145 ? Utils.firstNonNull(locale_display_value, tr(display_value), trc(value_context, value))
146 : Utils.firstNonNull(display_value, value);
147 }
148
149 public String getShortDescription(boolean translated) {
150 return translated
151 ? Utils.firstNonNull(locale_short_description, tr(short_description))
152 : short_description;
153 }
154
155 // toString is mainly used to initialize the Editor
156 @Override
157 public String toString() {
158 if (value.equals(DIFFERENT))
159 return DIFFERENT;
160 return getDisplayValue(true).replaceAll("<.*>", ""); // remove additional markup, e.g. <br>
161 }
162 }
163
164 public static class Role {
165 public EnumSet<TaggingPresetType> types;
166 public String key;
167 public String text;
168 public String text_context;
169 public String locale_text;
170 public SearchCompiler.Match memberExpression;
171
172 public boolean required = false;
173 public long count = 0;
174
175 public void setType(String types) throws SAXException {
176 this.types = getType(types);
177 }
178
179 public void setRequisite(String str) throws SAXException {
180 if("required".equals(str)) {
181 required = true;
182 } else if(!"optional".equals(str))
183 throw new SAXException(tr("Unknown requisite: {0}", str));
184 }
185
186 public void setMember_expression(String member_expression) throws SAXException {
187 try {
188 this.memberExpression = SearchCompiler.compile(member_expression, true, true);
189 } catch (SearchCompiler.ParseError ex) {
190 throw new SAXException(tr("Illegal member expression: {0}", ex.getMessage()), ex);
191 }
192 }
193
194 /* return either argument, the highest possible value or the lowest
195 allowed value */
196 public long getValidCount(long c)
197 {
198 if(count > 0 && !required)
199 return c != 0 ? count : 0;
200 else if(count > 0)
201 return count;
202 else if(!required)
203 return c != 0 ? c : 0;
204 else
205 return c != 0 ? c : 1;
206 }
207 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel) {
208 String cstring;
209 if(count > 0 && !required) {
210 cstring = "0,"+count;
211 } else if(count > 0) {
212 cstring = String.valueOf(count);
213 } else if(!required) {
214 cstring = "0-...";
215 } else {
216 cstring = "1-...";
217 }
218 if(locale_text == null) {
219 if (text != null) {
220 if(text_context != null) {
221 locale_text = trc(text_context, fixPresetString(text));
222 } else {
223 locale_text = tr(fixPresetString(text));
224 }
225 }
226 }
227 p.add(new JLabel(locale_text+":"), GBC.std().insets(0,0,10,0));
228 p.add(new JLabel(key), GBC.std().insets(0,0,10,0));
229 p.add(new JLabel(cstring), types == null ? GBC.eol() : GBC.std().insets(0,0,10,0));
230 if(types != null){
231 JPanel pp = new JPanel();
232 for(TaggingPresetType t : types) {
233 pp.add(new JLabel(ImageProvider.get(t.getIconName())));
234 }
235 p.add(pp, GBC.eol());
236 }
237 return true;
238 }
239 }
240
241 /**
242 * Enum denoting how a match (see {@link TaggingPresetItem#matches}) is performed.
243 */
244 public static enum MatchType {
245
246 /**
247 * Neutral, i.e., do not consider this item for matching.
248 */
249 NONE("none"),
250 /**
251 * Positive if key matches, neutral otherwise.
252 */
253 KEY("key"),
254 /**
255 * Positive if key matches, negative otherwise.
256 */
257 KEY_REQUIRED("key!"),
258 /**
259 * Positive if key and value matches, negative otherwise.
260 */
261 KEY_VALUE("keyvalue");
262
263 private final String value;
264
265 private MatchType(String value) {
266 this.value = value;
267 }
268
269 public String getValue() {
270 return value;
271 }
272
273 public static MatchType ofString(String type) {
274 for (MatchType i : EnumSet.allOf(MatchType.class)) {
275 if (i.getValue().equals(type))
276 return i;
277 }
278 throw new IllegalArgumentException(type + " is not allowed");
279 }
280 }
281
282 public static class Usage {
283 TreeSet<String> values;
284 boolean hadKeys = false;
285 boolean hadEmpty = false;
286 public boolean hasUniqueValue() {
287 return values.size() == 1 && !hadEmpty;
288 }
289
290 public boolean unused() {
291 return values.isEmpty();
292 }
293 public String getFirst() {
294 return values.first();
295 }
296
297 public boolean hadKeys() {
298 return hadKeys;
299 }
300 }
301
302 /**
303 * A tagging preset item displaying a localizable text.
304 * @since 6190
305 */
306 public abstract static class TaggingPresetTextItem extends TaggingPresetItem {
307
308 /**
309 * The text to display
310 */
311 public String text;
312
313 /**
314 * The context used for translating {@link #text}
315 */
316 public String text_context;
317
318 /**
319 * The localized version of {@link #text}
320 */
321 public String locale_text;
322
323 protected final void initializeLocaleText(String defaultText) {
324 if (locale_text == null) {
325 if (text == null) {
326 locale_text = defaultText;
327 } else if (text_context != null) {
328 locale_text = trc(text_context, fixPresetString(text));
329 } else {
330 locale_text = tr(fixPresetString(text));
331 }
332 }
333 }
334
335 @Override
336 void addCommands(List<Tag> changedTags) {
337 }
338
339 protected String fieldsToString() {
340 return (text != null ? "text=" + text + ", " : "")
341 + (text_context != null ? "text_context=" + text_context + ", " : "")
342 + (locale_text != null ? "locale_text=" + locale_text : "");
343 }
344
345 @Override
346 public String toString() {
347 return getClass().getSimpleName() + " [" + fieldsToString() + "]";
348 }
349 }
350
351 public static class Label extends TaggingPresetTextItem {
352
353 @Override
354 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
355 initializeLocaleText(null);
356 addLabel(p, locale_text);
357 return false;
358 }
359
360 public static void addLabel(JPanel p, String label) {
361 p.add(new JLabel(label), GBC.eol());
362 }
363 }
364
365 public static class Link extends TaggingPresetTextItem {
366
367 /**
368 * The link to display
369 */
370 public String href;
371
372 /**
373 * The localized version of {@link #href}
374 */
375 public String locale_href;
376
377 @Override
378 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
379 initializeLocaleText(tr("More information about this feature"));
380 String url = locale_href;
381 if (url == null) {
382 url = href;
383 }
384 if (url != null) {
385 p.add(new UrlLabel(url, locale_text, 2), GBC.eol().insets(0, 10, 0, 0));
386 }
387 return false;
388 }
389
390 @Override
391 protected String fieldsToString() {
392 return super.fieldsToString()
393 + (href != null ? "href=" + href + ", " : "")
394 + (locale_href != null ? "locale_href=" + locale_href + ", " : "");
395 }
396 }
397
398 public static class PresetLink extends TaggingPresetItem {
399
400 public String preset_name = "";
401
402 @Override
403 boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
404 final String presetName = preset_name;
405 final TaggingPreset t = Utils.filter(TaggingPresetPreference.taggingPresets, new Predicate<TaggingPreset>() {
406 @Override
407 public boolean evaluate(TaggingPreset object) {
408 return presetName.equals(object.name);
409 }
410 }).iterator().next();
411 if (t == null) return false;
412 JLabel lbl = PresetListPanel.createLabelForPreset(t);
413 lbl.addMouseListener(new PresetListPanel.PresetLabelML(lbl, t, null) {
414 @Override
415 public void mouseClicked(MouseEvent arg0) {
416 t.actionPerformed(null);
417 }
418 });
419 p.add(lbl, GBC.eol().fill(GBC.HORIZONTAL));
420 return false;
421 }
422
423 @Override
424 void addCommands(List<Tag> changedTags) {
425 }
426 }
427
428 public static class Roles extends TaggingPresetItem {
429
430 public final List<Role> roles = new LinkedList<Role>();
431
432 @Override
433 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
434 p.add(new JLabel(" "), GBC.eol()); // space
435 if (!roles.isEmpty()) {
436 JPanel proles = new JPanel(new GridBagLayout());
437 proles.add(new JLabel(tr("Available roles")), GBC.std().insets(0, 0, 10, 0));
438 proles.add(new JLabel(tr("role")), GBC.std().insets(0, 0, 10, 0));
439 proles.add(new JLabel(tr("count")), GBC.std().insets(0, 0, 10, 0));
440 proles.add(new JLabel(tr("elements")), GBC.eol());
441 for (Role i : roles) {
442 i.addToPanel(proles, sel);
443 }
444 p.add(proles, GBC.eol());
445 }
446 return false;
447 }
448
449 @Override
450 public void addCommands(List<Tag> changedTags) {
451 }
452 }
453
454 public static class Optional extends TaggingPresetTextItem {
455
456 // TODO: Draw a box around optional stuff
457 @Override
458 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
459 initializeLocaleText(tr("Optional Attributes:"));
460 p.add(new JLabel(" "), GBC.eol()); // space
461 p.add(new JLabel(locale_text), GBC.eol());
462 p.add(new JLabel(" "), GBC.eol()); // space
463 return false;
464 }
465 }
466
467 public static class Space extends TaggingPresetItem {
468
469 @Override
470 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
471 p.add(new JLabel(" "), GBC.eol()); // space
472 return false;
473 }
474
475 @Override
476 public void addCommands(List<Tag> changedTags) {
477 }
478
479 @Override
480 public String toString() {
481 return "Space";
482 }
483 }
484
485 /**
486 * Class used to represent a {@link JSeparator} inside tagging preset window.
487 * @since 6198
488 */
489 public static class ItemSeparator extends TaggingPresetItem {
490
491 @Override
492 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
493 p.add(new JSeparator(), GBC.eol().fill(GBC.HORIZONTAL).insets(0, 5, 0, 5));
494 return false;
495 }
496
497 @Override
498 public void addCommands(List<Tag> changedTags) {
499 }
500
501 @Override
502 public String toString() {
503 return "ItemSeparator";
504 }
505 }
506
507 public abstract static class KeyedItem extends TaggingPresetItem {
508
509 public String key;
510 public String text;
511 public String text_context;
512 public String match = getDefaultMatch().getValue();
513
514 public abstract MatchType getDefaultMatch();
515 public abstract Collection<String> getValues();
516
517 @Override
518 Boolean matches(Map<String, String> tags) {
519 switch (MatchType.ofString(match)) {
520 case NONE:
521 return null;
522 case KEY:
523 return tags.containsKey(key) ? true : null;
524 case KEY_REQUIRED:
525 return tags.containsKey(key);
526 case KEY_VALUE:
527 return tags.containsKey(key) && (getValues().contains(tags.get(key)));
528 default:
529 throw new IllegalStateException();
530 }
531 }
532
533 @Override
534 public String toString() {
535 return "KeyedItem [key=" + key + ", text=" + text
536 + ", text_context=" + text_context + ", match=" + match
537 + "]";
538 }
539 }
540
541 public static class Key extends KeyedItem {
542
543 public String value;
544
545 @Override
546 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
547 return false;
548 }
549
550 @Override
551 public void addCommands(List<Tag> changedTags) {
552 changedTags.add(new Tag(key, value));
553 }
554
555 @Override
556 public MatchType getDefaultMatch() {
557 return MatchType.KEY_VALUE;
558 }
559
560 @Override
561 public Collection<String> getValues() {
562 return Collections.singleton(value);
563 }
564
565 @Override
566 public String toString() {
567 return "Key [key=" + key + ", value=" + value + ", text=" + text
568 + ", text_context=" + text_context + ", match=" + match
569 + "]";
570 }
571 }
572
573 public static class Text extends KeyedItem {
574
575 public String locale_text;
576 public String default_;
577 public String originalValue;
578 public String use_last_as_default = "false";
579 public String auto_increment;
580 public String length;
581
582 private JComponent value;
583
584 @Override public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
585
586 // find out if our key is already used in the selection.
587 Usage usage = determineTextUsage(sel, key);
588 AutoCompletingTextField textField = new AutoCompletingTextField();
589 initAutoCompletionField(textField, key);
590 if (length != null && !length.isEmpty()) {
591 textField.setMaxChars(Integer.valueOf(length));
592 }
593 if (usage.unused()){
594 if (auto_increment_selected != 0 && auto_increment != null) {
595 try {
596 textField.setText(Integer.toString(Integer.parseInt(lastValue.get(key)) + auto_increment_selected));
597 } catch (NumberFormatException ex) {
598 // Ignore - cannot auto-increment if last was non-numeric
599 }
600 }
601 else if (!usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
602 // selected osm primitives are untagged or filling default values feature is enabled
603 if (!"false".equals(use_last_as_default) && lastValue.containsKey(key) && !presetInitiallyMatches) {
604 textField.setText(lastValue.get(key));
605 } else {
606 textField.setText(default_);
607 }
608 } else {
609 // selected osm primitives are tagged and filling default values feature is disabled
610 textField.setText("");
611 }
612 value = textField;
613 originalValue = null;
614 } else if (usage.hasUniqueValue()) {
615 // all objects use the same value
616 textField.setText(usage.getFirst());
617 value = textField;
618 originalValue = usage.getFirst();
619 } else {
620 // the objects have different values
621 JosmComboBox comboBox = new JosmComboBox(usage.values.toArray());
622 comboBox.setEditable(true);
623 comboBox.setEditor(textField);
624 comboBox.getEditor().setItem(DIFFERENT);
625 value=comboBox;
626 originalValue = DIFFERENT;
627 }
628 if (locale_text == null) {
629 if (text != null) {
630 if (text_context != null) {
631 locale_text = trc(text_context, fixPresetString(text));
632 } else {
633 locale_text = tr(fixPresetString(text));
634 }
635 }
636 }
637
638 // if there's an auto_increment setting, then wrap the text field
639 // into a panel, appending a number of buttons.
640 // auto_increment has a format like -2,-1,1,2
641 // the text box being the first component in the panel is relied
642 // on in a rather ugly fashion further down.
643 if (auto_increment != null) {
644 ButtonGroup bg = new ButtonGroup();
645 JPanel pnl = new JPanel(new GridBagLayout());
646 pnl.add(value, GBC.std().fill(GBC.HORIZONTAL));
647
648 // first, one button for each auto_increment value
649 for (final String ai : auto_increment.split(",")) {
650 JToggleButton aibutton = new JToggleButton(ai);
651 aibutton.setToolTipText(tr("Select auto-increment of {0} for this field", ai));
652 aibutton.setMargin(new java.awt.Insets(0,0,0,0));
653 aibutton.setFocusable(false);
654 bg.add(aibutton);
655 try {
656 // TODO there must be a better way to parse a number like "+3" than this.
657 final int buttonvalue = (NumberFormat.getIntegerInstance().parse(ai.replace("+", ""))).intValue();
658 if (auto_increment_selected == buttonvalue) aibutton.setSelected(true);
659 aibutton.addActionListener(new ActionListener() {
660 @Override
661 public void actionPerformed(ActionEvent e) {
662 auto_increment_selected = buttonvalue;
663 }
664 });
665 pnl.add(aibutton, GBC.std());
666 } catch (ParseException x) {
667 Main.error("Cannot parse auto-increment value of '" + ai + "' into an integer");
668 }
669 }
670
671 // an invisible toggle button for "release" of the button group
672 final JToggleButton clearbutton = new JToggleButton("X");
673 clearbutton.setVisible(false);
674 clearbutton.setFocusable(false);
675 bg.add(clearbutton);
676 // and its visible counterpart. - this mechanism allows us to
677 // have *no* button selected after the X is clicked, instead
678 // of the X remaining selected
679 JButton releasebutton = new JButton("X");
680 releasebutton.setToolTipText(tr("Cancel auto-increment for this field"));
681 releasebutton.setMargin(new java.awt.Insets(0,0,0,0));
682 releasebutton.setFocusable(false);
683 releasebutton.addActionListener(new ActionListener() {
684 @Override
685 public void actionPerformed(ActionEvent e) {
686 auto_increment_selected = 0;
687 clearbutton.setSelected(true);
688 }
689 });
690 pnl.add(releasebutton, GBC.eol());
691 value = pnl;
692 }
693 p.add(new JLabel(locale_text+":"), GBC.std().insets(0,0,10,0));
694 p.add(value, GBC.eol().fill(GBC.HORIZONTAL));
695 return true;
696 }
697
698 private static String getValue(Component comp) {
699 if (comp instanceof JosmComboBox) {
700 return ((JosmComboBox) comp).getEditor().getItem().toString();
701 } else if (comp instanceof JosmTextField) {
702 return ((JosmTextField) comp).getText();
703 } else if (comp instanceof JPanel) {
704 return getValue(((JPanel)comp).getComponent(0));
705 } else {
706 return null;
707 }
708 }
709
710 @Override
711 public void addCommands(List<Tag> changedTags) {
712
713 // return if unchanged
714 String v = getValue(value);
715 if (v == null) {
716 Main.error("No 'last value' support for component " + value);
717 return;
718 }
719
720 v = Tag.removeWhiteSpaces(v);
721
722 if (!"false".equals(use_last_as_default) || auto_increment != null) {
723 lastValue.put(key, v);
724 }
725 if (v.equals(originalValue) || (originalValue == null && v.length() == 0))
726 return;
727
728 changedTags.add(new Tag(key, v));
729 }
730
731 @Override
732 boolean requestFocusInWindow() {
733 return value.requestFocusInWindow();
734 }
735
736 @Override
737 public MatchType getDefaultMatch() {
738 return MatchType.NONE;
739 }
740
741 @Override
742 public Collection<String> getValues() {
743 if (default_ == null || default_.isEmpty())
744 return Collections.emptyList();
745 return Collections.singleton(default_);
746 }
747 }
748
749 /**
750 * A group of {@link Check}s.
751 * @since 6114
752 */
753 public static class CheckGroup extends TaggingPresetItem {
754
755 /**
756 * Number of columns (positive integer)
757 */
758 public String columns;
759
760 /**
761 * List of checkboxes
762 */
763 public final List<Check> checks = new LinkedList<Check>();
764
765 @Override
766 boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
767 Integer cols = Integer.valueOf(columns);
768 int rows = (int) Math.ceil(checks.size()/cols.doubleValue());
769 JPanel panel = new JPanel(new GridLayout(rows, cols));
770
771 for (Check check : checks) {
772 check.addToPanel(panel, sel, presetInitiallyMatches);
773 }
774
775 p.add(panel, GBC.eol());
776 return false;
777 }
778
779 @Override
780 void addCommands(List<Tag> changedTags) {
781 for (Check check : checks) {
782 check.addCommands(changedTags);
783 }
784 }
785
786 @Override
787 public String toString() {
788 return "CheckGroup [columns=" + columns + "]";
789 }
790 }
791
792 public static class Check extends KeyedItem {
793
794 public String locale_text;
795 public String value_on = OsmUtils.trueval;
796 public String value_off = OsmUtils.falseval;
797 public boolean default_ = false; // only used for tagless objects
798
799 private QuadStateCheckBox check;
800 private QuadStateCheckBox.State initialState;
801 private boolean def;
802
803 @Override public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
804
805 // find out if our key is already used in the selection.
806 Usage usage = determineBooleanUsage(sel, key);
807 def = default_;
808
809 if(locale_text == null) {
810 if(text_context != null) {
811 locale_text = trc(text_context, fixPresetString(text));
812 } else {
813 locale_text = tr(fixPresetString(text));
814 }
815 }
816
817 String oneValue = null;
818 for (String s : usage.values) {
819 oneValue = s;
820 }
821 if (usage.values.size() < 2 && (oneValue == null || value_on.equals(oneValue) || value_off.equals(oneValue))) {
822 if (def && !PROP_FILL_DEFAULT.get()) {
823 // default is set and filling default values feature is disabled - check if all primitives are untagged
824 for (OsmPrimitive s : sel)
825 if(s.hasKeys()) {
826 def = false;
827 }
828 }
829
830 // all selected objects share the same value which is either true or false or unset,
831 // we can display a standard check box.
832 initialState = value_on.equals(oneValue) ?
833 QuadStateCheckBox.State.SELECTED :
834 value_off.equals(oneValue) ?
835 QuadStateCheckBox.State.NOT_SELECTED :
836 def ? QuadStateCheckBox.State.SELECTED
837 : QuadStateCheckBox.State.UNSET;
838 check = new QuadStateCheckBox(locale_text, initialState,
839 new QuadStateCheckBox.State[] {
840 QuadStateCheckBox.State.SELECTED,
841 QuadStateCheckBox.State.NOT_SELECTED,
842 QuadStateCheckBox.State.UNSET });
843 } else {
844 def = false;
845 // the objects have different values, or one or more objects have something
846 // else than true/false. we display a quad-state check box
847 // in "partial" state.
848 initialState = QuadStateCheckBox.State.PARTIAL;
849 check = new QuadStateCheckBox(locale_text, QuadStateCheckBox.State.PARTIAL,
850 new QuadStateCheckBox.State[] {
851 QuadStateCheckBox.State.PARTIAL,
852 QuadStateCheckBox.State.SELECTED,
853 QuadStateCheckBox.State.NOT_SELECTED,
854 QuadStateCheckBox.State.UNSET });
855 }
856 p.add(check, GBC.eol().fill(GBC.HORIZONTAL));
857 return true;
858 }
859
860 @Override public void addCommands(List<Tag> changedTags) {
861 // if the user hasn't changed anything, don't create a command.
862 if (check.getState() == initialState && !def) return;
863
864 // otherwise change things according to the selected value.
865 changedTags.add(new Tag(key,
866 check.getState() == QuadStateCheckBox.State.SELECTED ? value_on :
867 check.getState() == QuadStateCheckBox.State.NOT_SELECTED ? value_off :
868 null));
869 }
870 @Override boolean requestFocusInWindow() {return check.requestFocusInWindow();}
871
872 @Override
873 public MatchType getDefaultMatch() {
874 return MatchType.NONE;
875 }
876
877 @Override
878 public Collection<String> getValues() {
879 return Arrays.asList(value_on, value_off);
880 }
881
882 @Override
883 public String toString() {
884 return "Check ["
885 + (locale_text != null ? "locale_text=" + locale_text + ", " : "")
886 + (value_on != null ? "value_on=" + value_on + ", " : "")
887 + (value_off != null ? "value_off=" + value_off + ", " : "")
888 + "default_=" + default_ + ", "
889 + (check != null ? "check=" + check + ", " : "")
890 + (initialState != null ? "initialState=" + initialState
891 + ", " : "") + "def=" + def + "]";
892 }
893 }
894
895 public abstract static class ComboMultiSelect extends KeyedItem {
896
897 public String locale_text;
898 public String values;
899 public String values_from;
900 public String values_context;
901 public String display_values;
902 public String locale_display_values;
903 public String short_descriptions;
904 public String locale_short_descriptions;
905 public String default_;
906 public String delimiter = ";";
907 public String use_last_as_default = "false";
908 /** whether to use values for search via {@link TaggingPresetSelector} */
909 public String values_searchable = "false";
910
911 protected JComponent component;
912 protected final Map<String, PresetListEntry> lhm = new LinkedHashMap<String, PresetListEntry>();
913 private boolean initialized = false;
914 protected Usage usage;
915 protected Object originalValue;
916
917 protected abstract Object getSelectedItem();
918 protected abstract void addToPanelAnchor(JPanel p, String def, boolean presetInitiallyMatches);
919
920 protected char getDelChar() {
921 return delimiter.isEmpty() ? ';' : delimiter.charAt(0);
922 }
923
924 @Override
925 public Collection<String> getValues() {
926 initListEntries();
927 return lhm.keySet();
928 }
929
930 public Collection<String> getDisplayValues() {
931 initListEntries();
932 return Utils.transform(lhm.values(), new Utils.Function<PresetListEntry, String>() {
933 @Override
934 public String apply(PresetListEntry x) {
935 return x.getDisplayValue(true);
936 }
937 });
938 }
939
940 @Override
941 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
942
943 initListEntries();
944
945 // find out if our key is already used in the selection.
946 usage = determineTextUsage(sel, key);
947 if (!usage.hasUniqueValue() && !usage.unused()) {
948 lhm.put(DIFFERENT, new PresetListEntry(DIFFERENT));
949 }
950
951 p.add(new JLabel(tr("{0}:", locale_text)), GBC.std().insets(0, 0, 10, 0));
952 addToPanelAnchor(p, default_, presetInitiallyMatches);
953
954 return true;
955
956 }
957
958 private void initListEntries() {
959 if (initialized) {
960 lhm.remove(DIFFERENT); // possibly added in #addToPanel
961 return;
962 } else if (lhm.isEmpty()) {
963 initListEntriesFromAttributes();
964 } else {
965 if (values != null) {
966 Main.warn(tr("Warning in tagging preset \"{0}-{1}\": "
967 + "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
968 key, text, "values", "list_entry"));
969 }
970 if (display_values != null || locale_display_values != null) {
971 Main.warn(tr("Warning in tagging preset \"{0}-{1}\": "
972 + "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
973 key, text, "display_values", "list_entry"));
974 }
975 if (short_descriptions != null || locale_short_descriptions != null) {
976 Main.warn(tr("Warning in tagging preset \"{0}-{1}\": "
977 + "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
978 key, text, "short_descriptions", "list_entry"));
979 }
980 for (PresetListEntry e : lhm.values()) {
981 if (e.value_context == null) {
982 e.value_context = values_context;
983 }
984 }
985 }
986 if (locale_text == null) {
987 locale_text = trc(text_context, fixPresetString(text));
988 }
989 initialized = true;
990 }
991
992 private String[] initListEntriesFromAttributes() {
993 char delChar = getDelChar();
994
995 String[] value_array = null;
996
997 if (values_from != null) {
998 String[] class_method = values_from.split("#");
999 if (class_method != null && class_method.length == 2) {
1000 try {
1001 Method method = Class.forName(class_method[0]).getMethod(class_method[1]);
1002 // Check method is public static String[] methodName()
1003 int mod = method.getModifiers();
1004 if (Modifier.isPublic(mod) && Modifier.isStatic(mod)
1005 && method.getReturnType().equals(String[].class) && method.getParameterTypes().length == 0) {
1006 value_array = (String[]) method.invoke(null);
1007 } else {
1008 Main.error(tr("Broken tagging preset \"{0}-{1}\" - Java method given in ''values_from'' is not \"{2}\"", key, text,
1009 "public static String[] methodName()"));
1010 }
1011 } catch (Exception e) {
1012 Main.error(tr("Broken tagging preset \"{0}-{1}\" - Java method given in ''values_from'' threw {2} ({3})", key, text,
1013 e.getClass().getName(), e.getMessage()));
1014 }
1015 }
1016 }
1017
1018 if (value_array == null) {
1019 value_array = splitEscaped(delChar, values);
1020 }
1021
1022 final String displ = Utils.firstNonNull(locale_display_values, display_values);
1023 String[] display_array = displ == null ? value_array : splitEscaped(delChar, displ);
1024
1025 final String descr = Utils.firstNonNull(locale_short_descriptions, short_descriptions);
1026 String[] short_descriptions_array = descr == null ? null : splitEscaped(delChar, descr);
1027
1028 if (display_array.length != value_array.length) {
1029 Main.error(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''display_values'' must be the same as in ''values''", key, text));
1030 display_array = value_array;
1031 }
1032
1033 if (short_descriptions_array != null && short_descriptions_array.length != value_array.length) {
1034 Main.error(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''short_descriptions'' must be the same as in ''values''", key, text));
1035 short_descriptions_array = null;
1036 }
1037
1038 for (int i = 0; i < value_array.length; i++) {
1039 final PresetListEntry e = new PresetListEntry(value_array[i]);
1040 e.locale_display_value = locale_display_values != null
1041 ? display_array[i]
1042 : trc(values_context, fixPresetString(display_array[i]));
1043 if (short_descriptions_array != null) {
1044 e.locale_short_description = locale_short_descriptions != null
1045 ? short_descriptions_array[i]
1046 : tr(fixPresetString(short_descriptions_array[i]));
1047 }
1048 lhm.put(value_array[i], e);
1049 display_array[i] = e.getDisplayValue(true);
1050 }
1051
1052 return display_array;
1053 }
1054
1055 protected String getDisplayIfNull() {
1056 return null;
1057 }
1058
1059 @Override
1060 public void addCommands(List<Tag> changedTags) {
1061 Object obj = getSelectedItem();
1062 String display = (obj == null) ? null : obj.toString();
1063 String value = null;
1064 if (display == null) {
1065 display = getDisplayIfNull();
1066 }
1067
1068 if (display != null) {
1069 for (String val : lhm.keySet()) {
1070 String k = lhm.get(val).toString();
1071 if (k != null && k.equals(display)) {
1072 value = val;
1073 break;
1074 }
1075 }
1076 if (value == null) {
1077 value = display;
1078 }
1079 } else {
1080 value = "";
1081 }
1082 value = Tag.removeWhiteSpaces(value);
1083
1084 // no change if same as before
1085 if (originalValue == null) {
1086 if (value.length() == 0)
1087 return;
1088 } else if (value.equals(originalValue.toString()))
1089 return;
1090
1091 if (!"false".equals(use_last_as_default)) {
1092 lastValue.put(key, value);
1093 }
1094 changedTags.add(new Tag(key, value));
1095 }
1096
1097 public void addListEntry(PresetListEntry e) {
1098 lhm.put(e.value, e);
1099 }
1100
1101 public void addListEntries(Collection<PresetListEntry> e) {
1102 for (PresetListEntry i : e) {
1103 addListEntry(i);
1104 }
1105 }
1106
1107 @Override
1108 boolean requestFocusInWindow() {
1109 return component.requestFocusInWindow();
1110 }
1111
1112 private static final ListCellRenderer RENDERER = new ListCellRenderer() {
1113
1114 JLabel lbl = new JLabel();
1115
1116 @Override
1117 public Component getListCellRendererComponent(
1118 JList list,
1119 Object value,
1120 int index,
1121 boolean isSelected,
1122 boolean cellHasFocus) {
1123 PresetListEntry item = (PresetListEntry) value;
1124
1125 // Only return cached size, item is not shown
1126 if (!list.isShowing() && item.prefferedWidth != -1 && item.prefferedHeight != -1) {
1127 if (index == -1) {
1128 lbl.setPreferredSize(new Dimension(item.prefferedWidth, 10));
1129 } else {
1130 lbl.setPreferredSize(new Dimension(item.prefferedWidth, item.prefferedHeight));
1131 }
1132 return lbl;
1133 }
1134
1135 lbl.setPreferredSize(null);
1136
1137
1138 if (isSelected) {
1139 lbl.setBackground(list.getSelectionBackground());
1140 lbl.setForeground(list.getSelectionForeground());
1141 } else {
1142 lbl.setBackground(list.getBackground());
1143 lbl.setForeground(list.getForeground());
1144 }
1145
1146 lbl.setOpaque(true);
1147 lbl.setFont(lbl.getFont().deriveFont(Font.PLAIN));
1148 lbl.setText("<html>" + item.getListDisplay() + "</html>");
1149 lbl.setIcon(item.getIcon());
1150 lbl.setEnabled(list.isEnabled());
1151
1152 // Cache size
1153 item.prefferedWidth = lbl.getPreferredSize().width;
1154 item.prefferedHeight = lbl.getPreferredSize().height;
1155
1156 // We do not want the editor to have the maximum height of all
1157 // entries. Return a dummy with bogus height.
1158 if (index == -1) {
1159 lbl.setPreferredSize(new Dimension(lbl.getPreferredSize().width, 10));
1160 }
1161 return lbl;
1162 }
1163 };
1164
1165
1166 protected ListCellRenderer getListCellRenderer() {
1167 return RENDERER;
1168 }
1169
1170 @Override
1171 public MatchType getDefaultMatch() {
1172 return MatchType.NONE;
1173 }
1174 }
1175
1176 public static class Combo extends ComboMultiSelect {
1177
1178 public boolean editable = true;
1179 protected JosmComboBox combo;
1180 public String length;
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<String>(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<String>();
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<String>();
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<String>();
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.