source: josm/trunk/src/org/openstreetmap/josm/gui/tagging/TaggingPreset.java@ 5964

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

fix #5618 - Use full list of ISO 3166 country codes from JDK for addr:country in presets with new preset attribute values_from

  • Property svn:eol-style set to native
File size: 72.2 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.gui.tagging;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trc;
6import static org.openstreetmap.josm.tools.I18n.trn;
7
8import java.awt.Component;
9import java.awt.Dimension;
10import java.awt.Font;
11import java.awt.GridBagLayout;
12import java.awt.Insets;
13import java.awt.event.ActionEvent;
14import java.awt.event.ActionListener;
15import java.io.BufferedReader;
16import java.io.File;
17import java.io.IOException;
18import java.io.InputStream;
19import java.io.InputStreamReader;
20import java.io.Reader;
21import java.io.UnsupportedEncodingException;
22import java.lang.reflect.Method;
23import java.lang.reflect.Modifier;
24import java.text.NumberFormat;
25import java.text.ParseException;
26import java.util.ArrayList;
27import java.util.Arrays;
28import java.util.Collection;
29import java.util.Collections;
30import java.util.EnumSet;
31import java.util.HashMap;
32import java.util.HashSet;
33import java.util.LinkedHashMap;
34import java.util.LinkedList;
35import java.util.List;
36import java.util.Map;
37import java.util.TreeSet;
38
39import javax.swing.AbstractAction;
40import javax.swing.Action;
41import javax.swing.ButtonGroup;
42import javax.swing.ImageIcon;
43import javax.swing.JButton;
44import javax.swing.JComponent;
45import javax.swing.JLabel;
46import javax.swing.JList;
47import javax.swing.JOptionPane;
48import javax.swing.JPanel;
49import javax.swing.JScrollPane;
50import javax.swing.JToggleButton;
51import javax.swing.ListCellRenderer;
52import javax.swing.ListModel;
53import javax.swing.SwingUtilities;
54
55import org.openstreetmap.josm.Main;
56import org.openstreetmap.josm.actions.search.SearchCompiler;
57import org.openstreetmap.josm.actions.search.SearchCompiler.Match;
58import org.openstreetmap.josm.command.ChangePropertyCommand;
59import org.openstreetmap.josm.command.Command;
60import org.openstreetmap.josm.command.SequenceCommand;
61import org.openstreetmap.josm.data.osm.Node;
62import org.openstreetmap.josm.data.osm.OsmPrimitive;
63import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
64import org.openstreetmap.josm.data.osm.OsmUtils;
65import org.openstreetmap.josm.data.osm.Relation;
66import org.openstreetmap.josm.data.osm.RelationMember;
67import org.openstreetmap.josm.data.osm.Tag;
68import org.openstreetmap.josm.data.osm.Way;
69import org.openstreetmap.josm.data.preferences.BooleanProperty;
70import org.openstreetmap.josm.gui.ExtendedDialog;
71import org.openstreetmap.josm.gui.MapView;
72import org.openstreetmap.josm.gui.QuadStateCheckBox;
73import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor;
74import org.openstreetmap.josm.gui.layer.Layer;
75import org.openstreetmap.josm.gui.layer.OsmDataLayer;
76import org.openstreetmap.josm.gui.preferences.SourceEntry;
77import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
78import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference.PresetPrefHelper;
79import org.openstreetmap.josm.gui.tagging.ac.AutoCompletingTextField;
80import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionItemPritority;
81import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionList;
82import org.openstreetmap.josm.gui.util.GuiHelper;
83import org.openstreetmap.josm.gui.widgets.JosmComboBox;
84import org.openstreetmap.josm.gui.widgets.JosmTextField;
85import org.openstreetmap.josm.io.MirroredInputStream;
86import org.openstreetmap.josm.tools.GBC;
87import org.openstreetmap.josm.tools.ImageProvider;
88import org.openstreetmap.josm.tools.Predicate;
89import org.openstreetmap.josm.tools.UrlLabel;
90import org.openstreetmap.josm.tools.Utils;
91import org.openstreetmap.josm.tools.XmlObjectParser;
92import org.openstreetmap.josm.tools.template_engine.ParseError;
93import org.openstreetmap.josm.tools.template_engine.TemplateEntry;
94import org.openstreetmap.josm.tools.template_engine.TemplateParser;
95import org.xml.sax.SAXException;
96
97
98/**
99 * This class read encapsulate one tagging preset. A class method can
100 * read in all predefined presets, either shipped with JOSM or that are
101 * in the config directory.
102 *
103 * It is also able to construct dialogs out of preset definitions.
104 */
105public class TaggingPreset extends AbstractAction implements MapView.LayerChangeListener {
106
107 public enum PresetType {
108 NODE(/* ICON */"Mf_node", "node"),
109 WAY(/* ICON */"Mf_way", "way"),
110 RELATION(/* ICON */"Mf_relation", "relation"),
111 CLOSEDWAY(/* ICON */"Mf_closedway", "closedway");
112
113 private final String iconName;
114 private final String name;
115
116 PresetType(String iconName, String name) {
117 this.iconName = iconName;
118 this.name = name;
119 }
120
121 public String getIconName() {
122 return iconName;
123 }
124
125 public String getName() {
126 return name;
127 }
128
129 public static PresetType forPrimitive(OsmPrimitive p) {
130 return forPrimitiveType(p.getDisplayType());
131 }
132
133 public static PresetType forPrimitiveType(OsmPrimitiveType type) {
134 switch (type) {
135 case NODE:
136 return NODE;
137 case WAY:
138 return WAY;
139 case CLOSEDWAY:
140 return CLOSEDWAY;
141 case RELATION:
142 case MULTIPOLYGON:
143 return RELATION;
144 default:
145 throw new IllegalArgumentException("Unexpected primitive type: " + type);
146 }
147 }
148
149 public static PresetType fromString(String type) {
150 for (PresetType t : PresetType.values()) {
151 if (t.getName().equals(type))
152 return t;
153 }
154 return null;
155 }
156 }
157
158 /**
159 * Enum denoting how a match (see {@link Item#matches}) is performed.
160 */
161 private enum MatchType {
162
163 /**
164 * Neutral, i.e., do not consider this item for matching.
165 */
166 NONE("none"),
167 /**
168 * Positive if key matches, neutral otherwise.
169 */
170 KEY("key"),
171 /**
172 * Positive if key matches, negative otherwise.
173 */
174 KEY_REQUIRED("key!"),
175 /**
176 * Positive if key and value matches, negative otherwise.
177 */
178 KEY_VALUE("keyvalue");
179
180 private final String value;
181
182 private MatchType(String value) {
183 this.value = value;
184 }
185
186 public String getValue() {
187 return value;
188 }
189
190 public static MatchType ofString(String type) {
191 for (MatchType i : EnumSet.allOf(MatchType.class)) {
192 if (i.getValue().equals(type))
193 return i;
194 }
195 throw new IllegalArgumentException(type + " is not allowed");
196 }
197 }
198
199 public static final int DIALOG_ANSWER_APPLY = 1;
200 public static final int DIALOG_ANSWER_NEW_RELATION = 2;
201 public static final int DIALOG_ANSWER_CANCEL = 3;
202
203 public TaggingPresetMenu group = null;
204 public String name;
205 public String name_context;
206 public String locale_name;
207 public final static String OPTIONAL_TOOLTIP_TEXT = "Optional tooltip text";
208 private static File zipIcons = null;
209 private static final BooleanProperty PROP_FILL_DEFAULT = new BooleanProperty("taggingpreset.fill-default-for-tagged-primitives", false);
210
211 public static abstract class Item {
212
213 protected void initAutoCompletionField(AutoCompletingTextField field, String key) {
214 OsmDataLayer layer = Main.main.getEditLayer();
215 if (layer == null)
216 return;
217 AutoCompletionList list = new AutoCompletionList();
218 Main.main.getEditLayer().data.getAutoCompletionManager().populateWithTagValues(list, key);
219 field.setAutoCompletionList(list);
220 }
221
222 abstract boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel);
223
224 abstract void addCommands(List<Tag> changedTags);
225
226 boolean requestFocusInWindow() {
227 return false;
228 }
229
230 /**
231 * Tests whether the tags match this item.
232 * Note that for a match, at least one positive and no negative is required.
233 * @param tags the tags of an {@link OsmPrimitive}
234 * @return {@code true} if matches (positive), {@code null} if neutral, {@code false} if mismatches (negative).
235 */
236 Boolean matches(Map<String, String> tags) {
237 return null;
238 }
239 }
240
241 public static abstract class KeyedItem extends Item {
242
243 public String key;
244 public String text;
245 public String text_context;
246 public String match = getDefaultMatch().getValue();
247
248 public abstract MatchType getDefaultMatch();
249 public abstract Collection<String> getValues();
250
251 @Override
252 Boolean matches(Map<String, String> tags) {
253 switch (MatchType.ofString(match)) {
254 case NONE:
255 return null;
256 case KEY:
257 return tags.containsKey(key) ? true : null;
258 case KEY_REQUIRED:
259 return tags.containsKey(key);
260 case KEY_VALUE:
261 return tags.containsKey(key) && (getValues().contains(tags.get(key)));
262 default:
263 throw new IllegalStateException();
264 }
265 }
266
267 @Override
268 public String toString() {
269 return "KeyedItem [key=" + key + ", text=" + text
270 + ", text_context=" + text_context + ", match=" + match
271 + "]";
272 }
273 }
274
275 public static class Usage {
276 TreeSet<String> values;
277 boolean hadKeys = false;
278 boolean hadEmpty = false;
279 public boolean hasUniqueValue() {
280 return values.size() == 1 && !hadEmpty;
281 }
282
283 public boolean unused() {
284 return values.isEmpty();
285 }
286 public String getFirst() {
287 return values.first();
288 }
289
290 public boolean hadKeys() {
291 return hadKeys;
292 }
293 }
294
295 public static final String DIFFERENT = tr("<different>");
296
297 static Usage determineTextUsage(Collection<OsmPrimitive> sel, String key) {
298 Usage returnValue = new Usage();
299 returnValue.values = new TreeSet<String>();
300 for (OsmPrimitive s : sel) {
301 String v = s.get(key);
302 if (v != null) {
303 returnValue.values.add(v);
304 } else {
305 returnValue.hadEmpty = true;
306 }
307 if(s.hasKeys()) {
308 returnValue.hadKeys = true;
309 }
310 }
311 return returnValue;
312 }
313
314 static Usage determineBooleanUsage(Collection<OsmPrimitive> sel, String key) {
315
316 Usage returnValue = new Usage();
317 returnValue.values = new TreeSet<String>();
318 for (OsmPrimitive s : sel) {
319 String booleanValue = OsmUtils.getNamedOsmBoolean(s.get(key));
320 if (booleanValue != null) {
321 returnValue.values.add(booleanValue);
322 }
323 }
324 return returnValue;
325 }
326
327 public static class PresetListEntry {
328 public String value;
329 public String value_context;
330 public String display_value;
331 public String short_description;
332 public String icon;
333 public String icon_size;
334 public String locale_display_value;
335 public String locale_short_description;
336 private final File zipIcons = TaggingPreset.zipIcons;
337
338 // Cached size (currently only for Combo) to speed up preset dialog initialization
339 private int prefferedWidth = -1;
340 private int prefferedHeight = -1;
341
342 public String getListDisplay() {
343 if (value.equals(DIFFERENT))
344 return "<b>"+DIFFERENT.replaceAll("<", "&lt;").replaceAll(">", "&gt;")+"</b>";
345
346 if (value.equals(""))
347 return "&nbsp;";
348
349 final StringBuilder res = new StringBuilder("<b>");
350 res.append(getDisplayValue(true));
351 res.append("</b>");
352 if (getShortDescription(true) != null) {
353 // wrap in table to restrict the text width
354 res.append("<div style=\"width:300px; padding:0 0 5px 5px\">");
355 res.append(getShortDescription(true));
356 res.append("</div>");
357 }
358 return res.toString();
359 }
360
361 public ImageIcon getIcon() {
362 return icon == null ? null : loadImageIcon(icon, zipIcons, parseInteger(icon_size));
363 }
364
365 private Integer parseInteger(String str) {
366 if (str == null || "".equals(str))
367 return null;
368 try {
369 return Integer.parseInt(str);
370 } catch (Exception e) {
371 //
372 }
373 return null;
374 }
375
376 public PresetListEntry() {
377 }
378
379 public PresetListEntry(String value) {
380 this.value = value;
381 }
382
383 public String getDisplayValue(boolean translated) {
384 return translated
385 ? Utils.firstNonNull(locale_display_value, tr(display_value), trc(value_context, value))
386 : Utils.firstNonNull(display_value, value);
387 }
388
389 public String getShortDescription(boolean translated) {
390 return translated
391 ? Utils.firstNonNull(locale_short_description, tr(short_description))
392 : short_description;
393 }
394
395 // toString is mainly used to initialize the Editor
396 @Override
397 public String toString() {
398 if (value.equals(DIFFERENT))
399 return DIFFERENT;
400 return getDisplayValue(true).replaceAll("<.*>", ""); // remove additional markup, e.g. <br>
401 }
402 }
403
404 public static class Text extends KeyedItem {
405
406 public String locale_text;
407 public String default_;
408 public String originalValue;
409 public String use_last_as_default = "false";
410 public String auto_increment;
411 public String length;
412
413 private JComponent value;
414
415 @Override public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel) {
416
417 // find out if our key is already used in the selection.
418 Usage usage = determineTextUsage(sel, key);
419 AutoCompletingTextField textField = new AutoCompletingTextField();
420 initAutoCompletionField(textField, key);
421 if (length != null && !length.isEmpty()) {
422 textField.setMaxChars(new Integer(length));
423 }
424 if (usage.unused()){
425 if (auto_increment_selected != 0 && auto_increment != null) {
426 try {
427 textField.setText(Integer.toString(Integer.parseInt(lastValue.get(key)) + auto_increment_selected));
428 } catch (NumberFormatException ex) {
429 // Ignore - cannot auto-increment if last was non-numeric
430 }
431 }
432 else if (!usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
433 // selected osm primitives are untagged or filling default values feature is enabled
434 if (!"false".equals(use_last_as_default) && lastValue.containsKey(key)) {
435 textField.setText(lastValue.get(key));
436 } else {
437 textField.setText(default_);
438 }
439 } else {
440 // selected osm primitives are tagged and filling default values feature is disabled
441 textField.setText("");
442 }
443 value = textField;
444 originalValue = null;
445 } else if (usage.hasUniqueValue()) {
446 // all objects use the same value
447 textField.setText(usage.getFirst());
448 value = textField;
449 originalValue = usage.getFirst();
450 } else {
451 // the objects have different values
452 JosmComboBox comboBox = new JosmComboBox(usage.values.toArray());
453 comboBox.setEditable(true);
454 comboBox.setEditor(textField);
455 comboBox.getEditor().setItem(DIFFERENT);
456 value=comboBox;
457 originalValue = DIFFERENT;
458 }
459 if (locale_text == null) {
460 if (text != null) {
461 if (text_context != null) {
462 locale_text = trc(text_context, fixPresetString(text));
463 } else {
464 locale_text = tr(fixPresetString(text));
465 }
466 }
467 }
468
469 // if there's an auto_increment setting, then wrap the text field
470 // into a panel, appending a number of buttons.
471 // auto_increment has a format like -2,-1,1,2
472 // the text box being the first component in the panel is relied
473 // on in a rather ugly fashion further down.
474 if (auto_increment != null) {
475 ButtonGroup bg = new ButtonGroup();
476 JPanel pnl = new JPanel(new GridBagLayout());
477 pnl.add(value, GBC.std().fill(GBC.HORIZONTAL));
478
479 // first, one button for each auto_increment value
480 for (final String ai : auto_increment.split(",")) {
481 JToggleButton aibutton = new JToggleButton(ai);
482 aibutton.setToolTipText(tr("Select auto-increment of {0} for this field", ai));
483 aibutton.setMargin(new java.awt.Insets(0,0,0,0));
484 bg.add(aibutton);
485 try {
486 // TODO there must be a better way to parse a number like "+3" than this.
487 final int buttonvalue = ((Number)NumberFormat.getIntegerInstance().parse(ai.replace("+", ""))).intValue();
488 if (auto_increment_selected == buttonvalue) aibutton.setSelected(true);
489 aibutton.addActionListener(new ActionListener() {
490 public void actionPerformed(ActionEvent e) {
491 auto_increment_selected = buttonvalue;
492 }
493 });
494 pnl.add(aibutton, GBC.std());
495 } catch (ParseException x) {
496 System.err.println("Cannot parse auto-increment value of '" + ai + "' into an integer");
497 }
498 }
499
500 // an invisible toggle button for "release" of the button group
501 final JToggleButton clearbutton = new JToggleButton("X");
502 clearbutton.setVisible(false);
503 bg.add(clearbutton);
504 // and its visible counterpart. - this mechanism allows us to
505 // have *no* button selected after the X is clicked, instead
506 // of the X remaining selected
507 JButton releasebutton = new JButton("X");
508 releasebutton.setToolTipText(tr("Cancel auto-increment for this field"));
509 releasebutton.setMargin(new java.awt.Insets(0,0,0,0));
510 releasebutton.addActionListener(new ActionListener() {
511 public void actionPerformed(ActionEvent e) {
512 auto_increment_selected = 0;
513 clearbutton.setSelected(true);
514 }
515 });
516 pnl.add(releasebutton, GBC.eol());
517 value = pnl;
518 }
519 p.add(new JLabel(locale_text+":"), GBC.std().insets(0,0,10,0));
520 p.add(value, GBC.eol().fill(GBC.HORIZONTAL));
521 return true;
522 }
523
524 private static String getValue(Component comp) {
525 if (comp instanceof JosmComboBox) {
526 return ((JosmComboBox) comp).getEditor().getItem().toString();
527 } else if (comp instanceof JosmTextField) {
528 return ((JosmTextField) comp).getText();
529 } else if (comp instanceof JPanel) {
530 return getValue(((JPanel)comp).getComponent(0));
531 } else {
532 return null;
533 }
534 }
535
536 @Override
537 public void addCommands(List<Tag> changedTags) {
538
539 // return if unchanged
540 String v = getValue(value);
541 if (v == null) {
542 System.err.println("No 'last value' support for component " + value);
543 return;
544 }
545
546 v = v.trim();
547
548 if (!"false".equals(use_last_as_default) || auto_increment != null) {
549 lastValue.put(key, v);
550 }
551 if (v.equals(originalValue) || (originalValue == null && v.length() == 0))
552 return;
553
554 changedTags.add(new Tag(key, v));
555 }
556
557 @Override
558 boolean requestFocusInWindow() {
559 return value.requestFocusInWindow();
560 }
561
562 @Override
563 public MatchType getDefaultMatch() {
564 return MatchType.NONE;
565 }
566
567 @Override
568 public Collection<String> getValues() {
569 if (default_ == null || default_.isEmpty())
570 return Collections.emptyList();
571 return Collections.singleton(default_);
572 }
573 }
574
575 public static class Check extends KeyedItem {
576
577 public String locale_text;
578 public String value_on = OsmUtils.trueval;
579 public String value_off = OsmUtils.falseval;
580 public boolean default_ = false; // only used for tagless objects
581
582 private QuadStateCheckBox check;
583 private QuadStateCheckBox.State initialState;
584 private boolean def;
585
586 @Override public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel) {
587
588 // find out if our key is already used in the selection.
589 Usage usage = determineBooleanUsage(sel, key);
590 def = default_;
591
592 if(locale_text == null) {
593 if(text_context != null) {
594 locale_text = trc(text_context, fixPresetString(text));
595 } else {
596 locale_text = tr(fixPresetString(text));
597 }
598 }
599
600 String oneValue = null;
601 for (String s : usage.values) {
602 oneValue = s;
603 }
604 if (usage.values.size() < 2 && (oneValue == null || value_on.equals(oneValue) || value_off.equals(oneValue))) {
605 if (def && !PROP_FILL_DEFAULT.get()) {
606 // default is set and filling default values feature is disabled - check if all primitives are untagged
607 for (OsmPrimitive s : sel)
608 if(s.hasKeys()) {
609 def = false;
610 }
611 }
612
613 // all selected objects share the same value which is either true or false or unset,
614 // we can display a standard check box.
615 initialState = value_on.equals(oneValue) ?
616 QuadStateCheckBox.State.SELECTED :
617 value_off.equals(oneValue) ?
618 QuadStateCheckBox.State.NOT_SELECTED :
619 def ? QuadStateCheckBox.State.SELECTED
620 : QuadStateCheckBox.State.UNSET;
621 check = new QuadStateCheckBox(locale_text, initialState,
622 new QuadStateCheckBox.State[] {
623 QuadStateCheckBox.State.SELECTED,
624 QuadStateCheckBox.State.NOT_SELECTED,
625 QuadStateCheckBox.State.UNSET });
626 } else {
627 def = false;
628 // the objects have different values, or one or more objects have something
629 // else than true/false. we display a quad-state check box
630 // in "partial" state.
631 initialState = QuadStateCheckBox.State.PARTIAL;
632 check = new QuadStateCheckBox(locale_text, QuadStateCheckBox.State.PARTIAL,
633 new QuadStateCheckBox.State[] {
634 QuadStateCheckBox.State.PARTIAL,
635 QuadStateCheckBox.State.SELECTED,
636 QuadStateCheckBox.State.NOT_SELECTED,
637 QuadStateCheckBox.State.UNSET });
638 }
639 p.add(check, GBC.eol().fill(GBC.HORIZONTAL));
640 return true;
641 }
642
643 @Override public void addCommands(List<Tag> changedTags) {
644 // if the user hasn't changed anything, don't create a command.
645 if (check.getState() == initialState && !def) return;
646
647 // otherwise change things according to the selected value.
648 changedTags.add(new Tag(key,
649 check.getState() == QuadStateCheckBox.State.SELECTED ? value_on :
650 check.getState() == QuadStateCheckBox.State.NOT_SELECTED ? value_off :
651 null));
652 }
653 @Override boolean requestFocusInWindow() {return check.requestFocusInWindow();}
654
655 @Override
656 public MatchType getDefaultMatch() {
657 return MatchType.NONE;
658 }
659
660 @Override
661 public Collection<String> getValues() {
662 return Arrays.asList(value_on, value_off);
663 }
664 }
665
666 public static abstract class ComboMultiSelect extends KeyedItem {
667
668 public String locale_text;
669 public String values;
670 public String values_from;
671 public String values_context;
672 public String display_values;
673 public String locale_display_values;
674 public String short_descriptions;
675 public String locale_short_descriptions;
676 public String default_;
677 public String delimiter = ";";
678 public String use_last_as_default = "false";
679
680 protected JComponent component;
681 protected final Map<String, PresetListEntry> lhm = new LinkedHashMap<String, PresetListEntry>();
682 private boolean initialized = false;
683 protected Usage usage;
684 protected Object originalValue;
685
686 protected abstract Object getSelectedItem();
687 protected abstract void addToPanelAnchor(JPanel p, String def);
688
689 protected char getDelChar() {
690 return delimiter.isEmpty() ? ';' : delimiter.charAt(0);
691 }
692
693 @Override
694 public Collection<String> getValues() {
695 initListEntries();
696 return lhm.keySet();
697 }
698
699 public Collection<String> getDisplayValues() {
700 initListEntries();
701 return Utils.transform(lhm.values(), new Utils.Function<PresetListEntry, String>() {
702
703 @Override
704 public String apply(PresetListEntry x) {
705 return x.getDisplayValue(true);
706 }
707 });
708 }
709
710 @Override
711 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel) {
712
713 initListEntries();
714
715 // find out if our key is already used in the selection.
716 usage = determineTextUsage(sel, key);
717 if (!usage.hasUniqueValue() && !usage.unused()) {
718 lhm.put(DIFFERENT, new PresetListEntry(DIFFERENT));
719 }
720
721 p.add(new JLabel(tr("{0}:", locale_text)), GBC.std().insets(0, 0, 10, 0));
722 addToPanelAnchor(p, default_);
723
724 return true;
725
726 }
727
728 private void initListEntries() {
729 if (initialized) {
730 lhm.remove(DIFFERENT); // possibly added in #addToPanel
731 return;
732 } else if (lhm.isEmpty()) {
733 initListEntriesFromAttributes();
734 } else {
735 if (values != null) {
736 System.err.println(tr("Warning in tagging preset \"{0}-{1}\": "
737 + "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
738 key, text, "values", "list_entry"));
739 }
740 if (display_values != null || locale_display_values != null) {
741 System.err.println(tr("Warning in tagging preset \"{0}-{1}\": "
742 + "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
743 key, text, "display_values", "list_entry"));
744 }
745 if (short_descriptions != null || locale_short_descriptions != null) {
746 System.err.println(tr("Warning in tagging preset \"{0}-{1}\": "
747 + "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
748 key, text, "short_descriptions", "list_entry"));
749 }
750 for (PresetListEntry e : lhm.values()) {
751 if (e.value_context == null) {
752 e.value_context = values_context;
753 }
754 }
755 }
756 if (locale_text == null) {
757 locale_text = trc(text_context, fixPresetString(text));
758 }
759 initialized = true;
760 }
761
762 private String[] initListEntriesFromAttributes() {
763 char delChar = getDelChar();
764
765 String[] value_array = null;
766
767 if (values_from != null) {
768 String[] class_method = values_from.split("#");
769 if (class_method != null && class_method.length == 2) {
770 try {
771 Method method = Class.forName(class_method[0]).getMethod(class_method[1]);
772 // Check method is public static String[] methodName();
773 int mod = method.getModifiers();
774 if (Modifier.isPublic(mod) && Modifier.isStatic(mod)
775 && method.getReturnType().equals(String[].class) && method.getParameterTypes().length == 0) {
776 value_array = (String[]) method.invoke(null);
777 } else {
778 System.err.println(tr("Broken tagging preset \"{0}-{1}\" - Java method given in ''values_from'' is not \"{2}\"", key, text,
779 "public static String[] methodName()"));
780 }
781 } catch (Exception e) {
782 System.err.println(tr("Broken tagging preset \"{0}-{1}\" - Java method given in ''values_from'' threw {2} ({3})", key, text,
783 e.getClass().getName(), e.getMessage()));
784 }
785 }
786 }
787
788 if (value_array == null) {
789 value_array = splitEscaped(delChar, values);
790 }
791
792 final String displ = Utils.firstNonNull(locale_display_values, display_values);
793 String[] display_array = displ == null ? value_array : splitEscaped(delChar, displ);
794
795 final String descr = Utils.firstNonNull(locale_short_descriptions, short_descriptions);
796 String[] short_descriptions_array = descr == null ? null : splitEscaped(delChar, descr);
797
798 if (display_array.length != value_array.length) {
799 System.err.println(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''display_values'' must be the same as in ''values''", key, text));
800 display_array = value_array;
801 }
802
803 if (short_descriptions_array != null && short_descriptions_array.length != value_array.length) {
804 System.err.println(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''short_descriptions'' must be the same as in ''values''", key, text));
805 short_descriptions_array = null;
806 }
807
808 for (int i = 0; i < value_array.length; i++) {
809 final PresetListEntry e = new PresetListEntry(value_array[i]);
810 e.locale_display_value = locale_display_values != null
811 ? display_array[i]
812 : trc(values_context, fixPresetString(display_array[i]));
813 if (short_descriptions_array != null) {
814 e.locale_short_description = locale_short_descriptions != null
815 ? short_descriptions_array[i]
816 : tr(fixPresetString(short_descriptions_array[i]));
817 }
818 lhm.put(value_array[i], e);
819 display_array[i] = e.getDisplayValue(true);
820 }
821
822 return display_array;
823 }
824
825 protected String getDisplayIfNull(String display) {
826 return display;
827 }
828
829 @Override
830 public void addCommands(List<Tag> changedTags) {
831 Object obj = getSelectedItem();
832 String display = (obj == null) ? null : obj.toString();
833 String value = null;
834 if (display == null) {
835 display = getDisplayIfNull(display);
836 }
837
838 if (display != null) {
839 for (String key : lhm.keySet()) {
840 String k = lhm.get(key).toString();
841 if (k != null && k.equals(display)) {
842 value = key;
843 break;
844 }
845 }
846 if (value == null) {
847 value = display;
848 }
849 } else {
850 value = "";
851 }
852 value = value.trim();
853
854 // no change if same as before
855 if (originalValue == null) {
856 if (value.length() == 0)
857 return;
858 } else if (value.equals(originalValue.toString()))
859 return;
860
861 if (!"false".equals(use_last_as_default)) {
862 lastValue.put(key, value);
863 }
864 changedTags.add(new Tag(key, value));
865 }
866
867 public void addListEntry(PresetListEntry e) {
868 lhm.put(e.value, e);
869 }
870
871 public void addListEntries(Collection<PresetListEntry> e) {
872 for (PresetListEntry i : e) {
873 addListEntry(i);
874 }
875 }
876
877 @Override
878 boolean requestFocusInWindow() {
879 return component.requestFocusInWindow();
880 }
881
882 private static ListCellRenderer RENDERER = new ListCellRenderer() {
883
884 JLabel lbl = new JLabel();
885
886 public Component getListCellRendererComponent(
887 JList list,
888 Object value,
889 int index,
890 boolean isSelected,
891 boolean cellHasFocus) {
892 PresetListEntry item = (PresetListEntry) value;
893
894 // Only return cached size, item is not shown
895 if (!list.isShowing() && item.prefferedWidth != -1 && item.prefferedHeight != -1) {
896 if (index == -1) {
897 lbl.setPreferredSize(new Dimension(item.prefferedWidth, 10));
898 } else {
899 lbl.setPreferredSize(new Dimension(item.prefferedWidth, item.prefferedHeight));
900 }
901 return lbl;
902 }
903
904 lbl.setPreferredSize(null);
905
906
907 if (isSelected) {
908 lbl.setBackground(list.getSelectionBackground());
909 lbl.setForeground(list.getSelectionForeground());
910 } else {
911 lbl.setBackground(list.getBackground());
912 lbl.setForeground(list.getForeground());
913 }
914
915 lbl.setOpaque(true);
916 lbl.setFont(lbl.getFont().deriveFont(Font.PLAIN));
917 lbl.setText("<html>" + item.getListDisplay() + "</html>");
918 lbl.setIcon(item.getIcon());
919 lbl.setEnabled(list.isEnabled());
920
921 // Cache size
922 item.prefferedWidth = lbl.getPreferredSize().width;
923 item.prefferedHeight = lbl.getPreferredSize().height;
924
925 // We do not want the editor to have the maximum height of all
926 // entries. Return a dummy with bogus height.
927 if (index == -1) {
928 lbl.setPreferredSize(new Dimension(lbl.getPreferredSize().width, 10));
929 }
930 return lbl;
931 }
932 };
933
934
935 protected ListCellRenderer getListCellRenderer() {
936 return RENDERER;
937 }
938
939 @Override
940 public MatchType getDefaultMatch() {
941 return MatchType.NONE;
942 }
943 }
944
945 public static class Combo extends ComboMultiSelect {
946
947 public boolean editable = true;
948 protected JosmComboBox combo;
949
950 public Combo() {
951 delimiter = ",";
952 }
953
954 @Override
955 protected void addToPanelAnchor(JPanel p, String def) {
956 if (!usage.unused()) {
957 for (String s : usage.values) {
958 if (!lhm.containsKey(s)) {
959 lhm.put(s, new PresetListEntry(s));
960 }
961 }
962 }
963 if (def != null && !lhm.containsKey(def)) {
964 lhm.put(def, new PresetListEntry(def));
965 }
966 lhm.put("", new PresetListEntry(""));
967
968 combo = new JosmComboBox(lhm.values().toArray());
969 component = combo;
970 combo.setRenderer(getListCellRenderer());
971 combo.setEditable(editable);
972 combo.reinitialize(lhm.values());
973 AutoCompletingTextField tf = new AutoCompletingTextField();
974 initAutoCompletionField(tf, key);
975 AutoCompletionList acList = tf.getAutoCompletionList();
976 if (acList != null) {
977 acList.add(getDisplayValues(), AutoCompletionItemPritority.IS_IN_STANDARD);
978 }
979 combo.setEditor(tf);
980
981 if (usage.hasUniqueValue()) {
982 // all items have the same value (and there were no unset items)
983 originalValue = lhm.get(usage.getFirst());
984 combo.setSelectedItem(originalValue);
985 } else if (def != null && usage.unused()) {
986 // default is set and all items were unset
987 if (!usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
988 // selected osm primitives are untagged or filling default feature is enabled
989 combo.setSelectedItem(lhm.get(def).getDisplayValue(true));
990 } else {
991 // selected osm primitives are tagged and filling default feature is disabled
992 combo.setSelectedItem("");
993 }
994 originalValue = lhm.get(DIFFERENT);
995 } else if (usage.unused()) {
996 // all items were unset (and so is default)
997 originalValue = lhm.get("");
998 if ("force".equals(use_last_as_default) && lastValue.containsKey(key)) {
999 combo.setSelectedItem(lhm.get(lastValue.get(key)));
1000 } else {
1001 combo.setSelectedItem(originalValue);
1002 }
1003 } else {
1004 originalValue = lhm.get(DIFFERENT);
1005 combo.setSelectedItem(originalValue);
1006 }
1007 p.add(combo, GBC.eol().fill(GBC.HORIZONTAL));
1008
1009 }
1010
1011 @Override
1012 protected Object getSelectedItem() {
1013 return combo.getSelectedItem();
1014
1015 }
1016
1017 @Override
1018 protected String getDisplayIfNull(String display) {
1019 if (combo.isEditable())
1020 return combo.getEditor().getItem().toString();
1021 else
1022 return display;
1023
1024 }
1025 }
1026
1027 /**
1028 * Class that allows list values to be assigned and retrieved as a comma-delimited
1029 * string.
1030 */
1031 public static class ConcatenatingJList extends JList {
1032 private String delimiter;
1033 public ConcatenatingJList(String del, Object[] o) {
1034 super(o);
1035 delimiter = del;
1036 }
1037 public void setSelectedItem(Object o) {
1038 if (o == null) {
1039 clearSelection();
1040 } else {
1041 String s = o.toString();
1042 TreeSet<String> parts = new TreeSet<String>(Arrays.asList(s.split(delimiter)));
1043 ListModel lm = getModel();
1044 int[] intParts = new int[lm.getSize()];
1045 int j = 0;
1046 for (int i = 0; i < lm.getSize(); i++) {
1047 if (parts.contains((((PresetListEntry)lm.getElementAt(i)).value))) {
1048 intParts[j++]=i;
1049 }
1050 }
1051 setSelectedIndices(Arrays.copyOf(intParts, j));
1052 // check if we have actually managed to represent the full
1053 // value with our presets. if not, cop out; we will not offer
1054 // a selection list that threatens to ruin the value.
1055 setEnabled(Utils.join(delimiter, parts).equals(getSelectedItem()));
1056 }
1057 }
1058 public String getSelectedItem() {
1059 ListModel lm = getModel();
1060 int[] si = getSelectedIndices();
1061 StringBuilder builder = new StringBuilder();
1062 for (int i=0; i<si.length; i++) {
1063 if (i>0) {
1064 builder.append(delimiter);
1065 }
1066 builder.append(((PresetListEntry)lm.getElementAt(si[i])).value);
1067 }
1068 return builder.toString();
1069 }
1070 }
1071
1072 public static class MultiSelect extends ComboMultiSelect {
1073
1074 public long rows = -1;
1075 protected ConcatenatingJList list;
1076
1077 @Override
1078 protected void addToPanelAnchor(JPanel p, String def) {
1079 list = new ConcatenatingJList(delimiter, lhm.values().toArray());
1080 component = list;
1081 ListCellRenderer renderer = getListCellRenderer();
1082 list.setCellRenderer(renderer);
1083
1084 if (usage.hasUniqueValue() && !usage.unused()) {
1085 originalValue = usage.getFirst();
1086 list.setSelectedItem(originalValue);
1087 } else if (def != null && !usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
1088 originalValue = DIFFERENT;
1089 list.setSelectedItem(def);
1090 } else if (usage.unused()) {
1091 originalValue = null;
1092 list.setSelectedItem(originalValue);
1093 } else {
1094 originalValue = DIFFERENT;
1095 list.setSelectedItem(originalValue);
1096 }
1097
1098 JScrollPane sp = new JScrollPane(list);
1099 // if a number of rows has been specified in the preset,
1100 // modify preferred height of scroll pane to match that row count.
1101 if (rows != -1) {
1102 double height = renderer.getListCellRendererComponent(list,
1103 new PresetListEntry("x"), 0, false, false).getPreferredSize().getHeight() * rows;
1104 sp.setPreferredSize(new Dimension((int) sp.getPreferredSize().getWidth(), (int) height));
1105 }
1106 p.add(sp, GBC.eol().fill(GBC.HORIZONTAL));
1107
1108
1109 }
1110
1111 @Override
1112 protected Object getSelectedItem() {
1113 return list.getSelectedItem();
1114 }
1115
1116 @Override
1117 public void addCommands(List<Tag> changedTags) {
1118 // Do not create any commands if list has been disabled because of an unknown value (fix #8605)
1119 if (list.isEnabled()) {
1120 super.addCommands(changedTags);
1121 }
1122 }
1123 }
1124
1125 /**
1126 * allow escaped comma in comma separated list:
1127 * "A\, B\, C,one\, two" --> ["A, B, C", "one, two"]
1128 * @param delimiter the delimiter, e.g. a comma. separates the entries and
1129 * must be escaped within one entry
1130 * @param s the string
1131 */
1132 private static String[] splitEscaped(char delimiter, String s) {
1133 if (s == null)
1134 return new String[0];
1135 List<String> result = new ArrayList<String>();
1136 boolean backslash = false;
1137 StringBuilder item = new StringBuilder();
1138 for (int i=0; i<s.length(); i++) {
1139 char ch = s.charAt(i);
1140 if (backslash) {
1141 item.append(ch);
1142 backslash = false;
1143 } else if (ch == '\\') {
1144 backslash = true;
1145 } else if (ch == delimiter) {
1146 result.add(item.toString());
1147 item.setLength(0);
1148 } else {
1149 item.append(ch);
1150 }
1151 }
1152 if (item.length() > 0) {
1153 result.add(item.toString());
1154 }
1155 return result.toArray(new String[result.size()]);
1156 }
1157
1158 public static class Label extends Item {
1159
1160 public String text;
1161 public String text_context;
1162 public String locale_text;
1163
1164 @Override
1165 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel) {
1166 if (locale_text == null) {
1167 if (text_context != null) {
1168 locale_text = trc(text_context, fixPresetString(text));
1169 } else {
1170 locale_text = tr(fixPresetString(text));
1171 }
1172 }
1173 p.add(new JLabel(locale_text), GBC.eol());
1174 return false;
1175 }
1176
1177 @Override
1178 public void addCommands(List<Tag> changedTags) {
1179 }
1180 }
1181
1182 public static class Link extends Item {
1183
1184 public String href;
1185 public String text;
1186 public String text_context;
1187 public String locale_text;
1188 public String locale_href;
1189
1190 @Override
1191 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel) {
1192 if (locale_text == null) {
1193 if (text == null) {
1194 locale_text = tr("More information about this feature");
1195 } else if (text_context != null) {
1196 locale_text = trc(text_context, fixPresetString(text));
1197 } else {
1198 locale_text = tr(fixPresetString(text));
1199 }
1200 }
1201 String url = locale_href;
1202 if (url == null) {
1203 url = href;
1204 }
1205 if (url != null) {
1206 p.add(new UrlLabel(url, locale_text, 2), GBC.eol().anchor(GBC.WEST));
1207 }
1208 return false;
1209 }
1210
1211 @Override
1212 public void addCommands(List<Tag> changedTags) {
1213 }
1214 }
1215
1216 public static class Role {
1217 public EnumSet<PresetType> types;
1218 public String key;
1219 public String text;
1220 public String text_context;
1221 public String locale_text;
1222 public Match memberExpression;
1223
1224 public boolean required = false;
1225 public long count = 0;
1226
1227 public void setType(String types) throws SAXException {
1228 this.types = TaggingPreset.getType(types);
1229 }
1230
1231 public void setRequisite(String str) throws SAXException {
1232 if("required".equals(str)) {
1233 required = true;
1234 } else if(!"optional".equals(str))
1235 throw new SAXException(tr("Unknown requisite: {0}", str));
1236 }
1237
1238 public void setMember_expression(String member_expression) throws SAXException {
1239 try {
1240 this.memberExpression = SearchCompiler.compile(member_expression, true, true);
1241 } catch (SearchCompiler.ParseError ex) {
1242 throw new SAXException(tr("Illegal member expression: {0}", ex.getMessage()), ex);
1243 }
1244 }
1245
1246 /* return either argument, the highest possible value or the lowest
1247 allowed value */
1248 public long getValidCount(long c)
1249 {
1250 if(count > 0 && !required)
1251 return c != 0 ? count : 0;
1252 else if(count > 0)
1253 return count;
1254 else if(!required)
1255 return c != 0 ? c : 0;
1256 else
1257 return c != 0 ? c : 1;
1258 }
1259 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel) {
1260 String cstring;
1261 if(count > 0 && !required) {
1262 cstring = "0,"+String.valueOf(count);
1263 } else if(count > 0) {
1264 cstring = String.valueOf(count);
1265 } else if(!required) {
1266 cstring = "0-...";
1267 } else {
1268 cstring = "1-...";
1269 }
1270 if(locale_text == null) {
1271 if (text != null) {
1272 if(text_context != null) {
1273 locale_text = trc(text_context, fixPresetString(text));
1274 } else {
1275 locale_text = tr(fixPresetString(text));
1276 }
1277 }
1278 }
1279 p.add(new JLabel(locale_text+":"), GBC.std().insets(0,0,10,0));
1280 p.add(new JLabel(key), GBC.std().insets(0,0,10,0));
1281 p.add(new JLabel(cstring), types == null ? GBC.eol() : GBC.std().insets(0,0,10,0));
1282 if(types != null){
1283 JPanel pp = new JPanel();
1284 for(PresetType t : types) {
1285 pp.add(new JLabel(ImageProvider.get(t.getIconName())));
1286 }
1287 p.add(pp, GBC.eol());
1288 }
1289 return true;
1290 }
1291 }
1292
1293 public static class Roles extends Item {
1294
1295 public final List<Role> roles = new LinkedList<Role>();
1296
1297 @Override
1298 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel) {
1299 p.add(new JLabel(" "), GBC.eol()); // space
1300 if (roles.size() > 0) {
1301 JPanel proles = new JPanel(new GridBagLayout());
1302 proles.add(new JLabel(tr("Available roles")), GBC.std().insets(0, 0, 10, 0));
1303 proles.add(new JLabel(tr("role")), GBC.std().insets(0, 0, 10, 0));
1304 proles.add(new JLabel(tr("count")), GBC.std().insets(0, 0, 10, 0));
1305 proles.add(new JLabel(tr("elements")), GBC.eol());
1306 for (Role i : roles) {
1307 i.addToPanel(proles, sel);
1308 }
1309 p.add(proles, GBC.eol());
1310 }
1311 return false;
1312 }
1313
1314 @Override
1315 public void addCommands(List<Tag> changedTags) {
1316 }
1317 }
1318
1319 public static class Optional extends Item {
1320
1321 // TODO: Draw a box around optional stuff
1322 @Override
1323 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel) {
1324 p.add(new JLabel(" "), GBC.eol()); // space
1325 p.add(new JLabel(tr("Optional Attributes:")), GBC.eol());
1326 p.add(new JLabel(" "), GBC.eol()); // space
1327 return false;
1328 }
1329
1330 @Override
1331 public void addCommands(List<Tag> changedTags) {
1332 }
1333 }
1334
1335 public static class Space extends Item {
1336
1337 @Override
1338 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel) {
1339 p.add(new JLabel(" "), GBC.eol()); // space
1340 return false;
1341 }
1342
1343 @Override
1344 public void addCommands(List<Tag> changedTags) {
1345 }
1346 }
1347
1348 public static class Key extends KeyedItem {
1349
1350 public String value;
1351
1352 @Override
1353 public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel) {
1354 return false;
1355 }
1356
1357 @Override
1358 public void addCommands(List<Tag> changedTags) {
1359 changedTags.add(new Tag(key, value));
1360 }
1361
1362 @Override
1363 public MatchType getDefaultMatch() {
1364 return MatchType.KEY_VALUE;
1365 }
1366
1367 @Override
1368 public Collection<String> getValues() {
1369 return Collections.singleton(value);
1370 }
1371
1372 @Override
1373 public String toString() {
1374 return "Key [key=" + key + ", value=" + value + ", text=" + text
1375 + ", text_context=" + text_context + ", match=" + match
1376 + "]";
1377 }
1378 }
1379
1380 /**
1381 * The types as preparsed collection.
1382 */
1383 public EnumSet<PresetType> types;
1384 public List<Item> data = new LinkedList<Item>();
1385 public Roles roles;
1386 public TemplateEntry nameTemplate;
1387 public Match nameTemplateFilter;
1388 private static final HashMap<String,String> lastValue = new HashMap<String,String>();
1389 private static int auto_increment_selected = 0;
1390
1391 /**
1392 * Create an empty tagging preset. This will not have any items and
1393 * will be an empty string as text. createPanel will return null.
1394 * Use this as default item for "do not select anything".
1395 */
1396 public TaggingPreset() {
1397 MapView.addLayerChangeListener(this);
1398 updateEnabledState();
1399 }
1400
1401 /**
1402 * Change the display name without changing the toolbar value.
1403 */
1404 public void setDisplayName() {
1405 putValue(Action.NAME, getName());
1406 putValue("toolbar", "tagging_" + getRawName());
1407 putValue(OPTIONAL_TOOLTIP_TEXT, (group != null ?
1408 tr("Use preset ''{0}'' of group ''{1}''", getLocaleName(), group.getName()) :
1409 tr("Use preset ''{0}''", getLocaleName())));
1410 }
1411
1412 public String getLocaleName() {
1413 if(locale_name == null) {
1414 if(name_context != null) {
1415 locale_name = trc(name_context, fixPresetString(name));
1416 } else {
1417 locale_name = tr(fixPresetString(name));
1418 }
1419 }
1420 return locale_name;
1421 }
1422
1423 public String getName() {
1424 return group != null ? group.getName() + "/" + getLocaleName() : getLocaleName();
1425 }
1426 public String getRawName() {
1427 return group != null ? group.getRawName() + "/" + name : name;
1428 }
1429
1430 protected static ImageIcon loadImageIcon(String iconName, File zipIcons, Integer maxSize) {
1431 final Collection<String> s = Main.pref.getCollection("taggingpreset.icon.sources", null);
1432 ImageProvider imgProv = new ImageProvider(iconName).setDirs(s).setId("presets").setArchive(zipIcons).setOptional(true);
1433 if (maxSize != null) {
1434 imgProv.setMaxSize(maxSize);
1435 }
1436 return imgProv.get();
1437 }
1438
1439 /*
1440 * Called from the XML parser to set the icon.
1441 * This task is performed in the background in order to speedup startup.
1442 *
1443 * FIXME for Java 1.6 - use 24x24 icons for LARGE_ICON_KEY (button bar)
1444 * and the 16x16 icons for SMALL_ICON.
1445 */
1446 public void setIcon(final String iconName) {
1447 ImageProvider imgProv = new ImageProvider(iconName);
1448 final Collection<String> s = Main.pref.getCollection("taggingpreset.icon.sources", null);
1449 imgProv.setDirs(s);
1450 imgProv.setId("presets");
1451 imgProv.setArchive(TaggingPreset.zipIcons);
1452 imgProv.setOptional(true);
1453 imgProv.setMaxWidth(16).setMaxHeight(16);
1454 imgProv.getInBackground(new ImageProvider.ImageCallback() {
1455 @Override
1456 public void finished(final ImageIcon result) {
1457 if (result != null) {
1458 GuiHelper.runInEDT(new Runnable() {
1459 @Override
1460 public void run() {
1461 putValue(Action.SMALL_ICON, result);
1462 }
1463 });
1464 } else {
1465 System.out.println("Could not get presets icon " + iconName);
1466 }
1467 }
1468 });
1469 }
1470
1471 // 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)
1472 private static final Map<String,EnumSet<PresetType>> typeCache =
1473 new LinkedHashMap<String, EnumSet<PresetType>>(16, 1.1f, true);
1474
1475 static public EnumSet<PresetType> getType(String types) throws SAXException {
1476 if (typeCache.containsKey(types))
1477 return typeCache.get(types);
1478 EnumSet<PresetType> result = EnumSet.noneOf(PresetType.class);
1479 for (String type : Arrays.asList(types.split(","))) {
1480 try {
1481 PresetType presetType = PresetType.fromString(type);
1482 result.add(presetType);
1483 } catch (IllegalArgumentException e) {
1484 throw new SAXException(tr("Unknown type: {0}", type));
1485 }
1486 }
1487 typeCache.put(types, result);
1488 return result;
1489 }
1490
1491 /*
1492 * Called from the XML parser to set the types this preset affects.
1493 */
1494 public void setType(String types) throws SAXException {
1495 this.types = getType(types);
1496 }
1497
1498 public void setName_template(String pattern) throws SAXException {
1499 try {
1500 this.nameTemplate = new TemplateParser(pattern).parse();
1501 } catch (ParseError e) {
1502 System.err.println("Error while parsing " + pattern + ": " + e.getMessage());
1503 throw new SAXException(e);
1504 }
1505 }
1506
1507 public void setName_template_filter(String filter) throws SAXException {
1508 try {
1509 this.nameTemplateFilter = SearchCompiler.compile(filter, false, false);
1510 } catch (org.openstreetmap.josm.actions.search.SearchCompiler.ParseError e) {
1511 System.err.println("Error while parsing" + filter + ": " + e.getMessage());
1512 throw new SAXException(e);
1513 }
1514 }
1515
1516
1517 public static List<TaggingPreset> readAll(Reader in, boolean validate) throws SAXException {
1518 XmlObjectParser parser = new XmlObjectParser();
1519 parser.mapOnStart("item", TaggingPreset.class);
1520 parser.mapOnStart("separator", TaggingPresetSeparator.class);
1521 parser.mapBoth("group", TaggingPresetMenu.class);
1522 parser.map("text", Text.class);
1523 parser.map("link", Link.class);
1524 parser.mapOnStart("optional", Optional.class);
1525 parser.mapOnStart("roles", Roles.class);
1526 parser.map("role", Role.class);
1527 parser.map("check", Check.class);
1528 parser.map("combo", Combo.class);
1529 parser.map("multiselect", MultiSelect.class);
1530 parser.map("label", Label.class);
1531 parser.map("space", Space.class);
1532 parser.map("key", Key.class);
1533 parser.map("list_entry", PresetListEntry.class);
1534 LinkedList<TaggingPreset> all = new LinkedList<TaggingPreset>();
1535 TaggingPresetMenu lastmenu = null;
1536 Roles lastrole = null;
1537 List<PresetListEntry> listEntries = new LinkedList<PresetListEntry>();
1538
1539 if (validate) {
1540 parser.startWithValidation(in, "http://josm.openstreetmap.de/tagging-preset-1.0", "resource://data/tagging-preset.xsd");
1541 } else {
1542 parser.start(in);
1543 }
1544 while(parser.hasNext()) {
1545 Object o = parser.next();
1546 if (o instanceof TaggingPresetMenu) {
1547 TaggingPresetMenu tp = (TaggingPresetMenu) o;
1548 if(tp == lastmenu) {
1549 lastmenu = tp.group;
1550 } else
1551 {
1552 tp.group = lastmenu;
1553 tp.setDisplayName();
1554 lastmenu = tp;
1555 all.add(tp);
1556
1557 }
1558 lastrole = null;
1559 } else if (o instanceof TaggingPresetSeparator) {
1560 TaggingPresetSeparator tp = (TaggingPresetSeparator) o;
1561 tp.group = lastmenu;
1562 all.add(tp);
1563 lastrole = null;
1564 } else if (o instanceof TaggingPreset) {
1565 TaggingPreset tp = (TaggingPreset) o;
1566 tp.group = lastmenu;
1567 tp.setDisplayName();
1568 all.add(tp);
1569 lastrole = null;
1570 } else {
1571 if (all.size() != 0) {
1572 if (o instanceof Roles) {
1573 all.getLast().data.add((Item) o);
1574 if (all.getLast().roles != null) {
1575 throw new SAXException(tr("Roles cannot appear more than once"));
1576 }
1577 all.getLast().roles = (Roles) o;
1578 lastrole = (Roles) o;
1579 } else if (o instanceof Role) {
1580 if (lastrole == null)
1581 throw new SAXException(tr("Preset role element without parent"));
1582 lastrole.roles.add((Role) o);
1583 } else if (o instanceof PresetListEntry) {
1584 listEntries.add((PresetListEntry) o);
1585 } else {
1586 all.getLast().data.add((Item) o);
1587 if (o instanceof ComboMultiSelect) {
1588 ((ComboMultiSelect) o).addListEntries(listEntries);
1589 } else if (o instanceof Key) {
1590 if (((Key) o).value == null) {
1591 ((Key) o).value = ""; // Fix #8530
1592 }
1593 }
1594 listEntries = new LinkedList<PresetListEntry>();
1595 lastrole = null;
1596 }
1597 } else
1598 throw new SAXException(tr("Preset sub element without parent"));
1599 }
1600 }
1601 return all;
1602 }
1603
1604 public static Collection<TaggingPreset> readAll(String source, boolean validate) throws SAXException, IOException {
1605 Collection<TaggingPreset> tp;
1606 MirroredInputStream s = new MirroredInputStream(source);
1607 try {
1608 InputStream zip = s.getZipEntry("xml","preset");
1609 if(zip != null) {
1610 zipIcons = s.getFile();
1611 }
1612 InputStreamReader r;
1613 try {
1614 r = new InputStreamReader(zip == null ? s : zip, "UTF-8");
1615 } catch (UnsupportedEncodingException e) {
1616 r = new InputStreamReader(zip == null ? s: zip);
1617 }
1618 try {
1619 tp = TaggingPreset.readAll(new BufferedReader(r), validate);
1620 } finally {
1621 Utils.close(r);
1622 }
1623 } finally {
1624 Utils.close(s);
1625 }
1626 return tp;
1627 }
1628
1629 public static Collection<TaggingPreset> readAll(Collection<String> sources, boolean validate) {
1630 LinkedList<TaggingPreset> allPresets = new LinkedList<TaggingPreset>();
1631 for(String source : sources) {
1632 try {
1633 allPresets.addAll(TaggingPreset.readAll(source, validate));
1634 } catch (IOException e) {
1635 System.err.println(e.getClass().getName()+": "+e.getMessage());
1636 System.err.println(source);
1637 JOptionPane.showMessageDialog(
1638 Main.parent,
1639 tr("Could not read tagging preset source: {0}",source),
1640 tr("Error"),
1641 JOptionPane.ERROR_MESSAGE
1642 );
1643 } catch (SAXException e) {
1644 System.err.println(e.getClass().getName()+": "+e.getMessage());
1645 System.err.println(source);
1646 JOptionPane.showMessageDialog(
1647 Main.parent,
1648 tr("Error parsing {0}: ", source)+e.getMessage(),
1649 tr("Error"),
1650 JOptionPane.ERROR_MESSAGE
1651 );
1652 }
1653 }
1654 return allPresets;
1655 }
1656
1657 public static LinkedList<String> getPresetSources() {
1658 LinkedList<String> sources = new LinkedList<String>();
1659
1660 for (SourceEntry e : (new PresetPrefHelper()).get()) {
1661 sources.add(e.url);
1662 }
1663
1664 return sources;
1665 }
1666
1667 public static Collection<TaggingPreset> readFromPreferences(boolean validate) {
1668 return readAll(getPresetSources(), validate);
1669 }
1670
1671 private static class PresetPanel extends JPanel {
1672 boolean hasElements = false;
1673 PresetPanel()
1674 {
1675 super(new GridBagLayout());
1676 }
1677 }
1678
1679 public PresetPanel createPanel(Collection<OsmPrimitive> selected) {
1680 if (data == null)
1681 return null;
1682 PresetPanel p = new PresetPanel();
1683 LinkedList<Item> l = new LinkedList<Item>();
1684 if(types != null){
1685 JPanel pp = new JPanel();
1686 for(PresetType t : types){
1687 JLabel la = new JLabel(ImageProvider.get(t.getIconName()));
1688 la.setToolTipText(tr("Elements of type {0} are supported.", tr(t.getName())));
1689 pp.add(la);
1690 }
1691 p.add(pp, GBC.eol());
1692 }
1693
1694 JPanel items = new JPanel(new GridBagLayout());
1695 for (Item i : data){
1696 if(i instanceof Link) {
1697 l.add(i);
1698 } else {
1699 if(i.addToPanel(items, selected)) {
1700 p.hasElements = true;
1701 }
1702 }
1703 }
1704 p.add(items, GBC.eol().fill());
1705 if (selected.size() == 0 && !supportsRelation()) {
1706 GuiHelper.setEnabledRec(items, false);
1707 }
1708
1709 for(Item link : l) {
1710 link.addToPanel(p, selected);
1711 }
1712
1713 return p;
1714 }
1715
1716 public boolean isShowable()
1717 {
1718 for(Item i : data)
1719 {
1720 if(!(i instanceof Optional || i instanceof Space || i instanceof Key))
1721 return true;
1722 }
1723 return false;
1724 }
1725
1726 public String suggestRoleForOsmPrimitive(OsmPrimitive osm) {
1727 if (roles != null && osm != null) {
1728 for (Role i : roles.roles) {
1729 if (i.memberExpression != null && i.memberExpression.match(osm)
1730 && (i.types == null || i.types.isEmpty() || i.types.contains(PresetType.forPrimitive(osm)) )) {
1731 return i.key;
1732 }
1733 }
1734 }
1735 return null;
1736 }
1737
1738 public void actionPerformed(ActionEvent e) {
1739 if (Main.main == null) return;
1740 if (Main.main.getCurrentDataSet() == null) return;
1741
1742 Collection<OsmPrimitive> sel = createSelection(Main.main.getCurrentDataSet().getSelected());
1743 int answer = showDialog(sel, supportsRelation());
1744
1745 if (sel.size() != 0 && answer == DIALOG_ANSWER_APPLY) {
1746 Command cmd = createCommand(sel, getChangedTags());
1747 if (cmd != null) {
1748 Main.main.undoRedo.add(cmd);
1749 }
1750 } else if (answer == DIALOG_ANSWER_NEW_RELATION) {
1751 final Relation r = new Relation();
1752 final Collection<RelationMember> members = new HashSet<RelationMember>();
1753 for(Tag t : getChangedTags()) {
1754 r.put(t.getKey(), t.getValue());
1755 }
1756 for (OsmPrimitive osm : Main.main.getCurrentDataSet().getSelected()) {
1757 String role = suggestRoleForOsmPrimitive(osm);
1758 RelationMember rm = new RelationMember(role == null ? "" : role, osm);
1759 r.addMember(rm);
1760 members.add(rm);
1761 }
1762 SwingUtilities.invokeLater(new Runnable() {
1763 @Override
1764 public void run() {
1765 RelationEditor.getEditor(Main.main.getEditLayer(), r, members).setVisible(true);
1766 }
1767 });
1768 }
1769 Main.main.getCurrentDataSet().setSelected(Main.main.getCurrentDataSet().getSelected()); // force update
1770
1771 }
1772
1773 public int showDialog(Collection<OsmPrimitive> sel, final boolean showNewRelation) {
1774 PresetPanel p = createPanel(sel);
1775 if (p == null)
1776 return DIALOG_ANSWER_CANCEL;
1777
1778 int answer = 1;
1779 if (p.getComponentCount() != 0 && (sel.size() == 0 || p.hasElements)) {
1780 String title = trn("Change {0} object", "Change {0} objects", sel.size(), sel.size());
1781 if(sel.size() == 0) {
1782 if(originalSelectionEmpty) {
1783 title = tr("Nothing selected!");
1784 } else {
1785 title = tr("Selection unsuitable!");
1786 }
1787 }
1788
1789 class PresetDialog extends ExtendedDialog {
1790 public PresetDialog(Component content, String title, ImageIcon icon, boolean disableApply) {
1791 super(Main.parent,
1792 title,
1793 showNewRelation?
1794 new String[] { tr("Apply Preset"), tr("New relation"), tr("Cancel") }:
1795 new String[] { tr("Apply Preset"), tr("Cancel") },
1796 true);
1797 if (icon != null)
1798 setIconImage(icon.getImage());
1799 contentInsets = new Insets(10,5,0,5);
1800 if (showNewRelation) {
1801 setButtonIcons(new String[] {"ok.png", "dialogs/addrelation.png", "cancel.png" });
1802 } else {
1803 setButtonIcons(new String[] {"ok.png", "cancel.png" });
1804 }
1805 setContent(content);
1806 setDefaultButton(1);
1807 setupDialog();
1808 buttons.get(0).setEnabled(!disableApply);
1809 buttons.get(0).setToolTipText(title);
1810 // Prevent dialogs of being too narrow (fix #6261)
1811 Dimension d = getSize();
1812 if (d.width < 350) {
1813 d.width = 350;
1814 setSize(d);
1815 }
1816 showDialog();
1817 }
1818 }
1819
1820 answer = new PresetDialog(p, title, (ImageIcon) getValue(Action.SMALL_ICON), (sel.size() == 0)).getValue();
1821 }
1822 if (!showNewRelation && answer == 2)
1823 return DIALOG_ANSWER_CANCEL;
1824 else
1825 return answer;
1826 }
1827
1828 /**
1829 * True whenever the original selection given into createSelection was empty
1830 */
1831 private boolean originalSelectionEmpty = false;
1832
1833 /**
1834 * Removes all unsuitable OsmPrimitives from the given list
1835 * @param participants List of possible OsmPrimitives to tag
1836 * @return Cleaned list with suitable OsmPrimitives only
1837 */
1838 public Collection<OsmPrimitive> createSelection(Collection<OsmPrimitive> participants) {
1839 originalSelectionEmpty = participants.size() == 0;
1840 Collection<OsmPrimitive> sel = new LinkedList<OsmPrimitive>();
1841 for (OsmPrimitive osm : participants)
1842 {
1843 if (types != null)
1844 {
1845 if(osm instanceof Relation)
1846 {
1847 if(!types.contains(PresetType.RELATION) &&
1848 !(types.contains(PresetType.CLOSEDWAY) && ((Relation)osm).isMultipolygon())) {
1849 continue;
1850 }
1851 }
1852 else if(osm instanceof Node)
1853 {
1854 if(!types.contains(PresetType.NODE)) {
1855 continue;
1856 }
1857 }
1858 else if(osm instanceof Way)
1859 {
1860 if(!types.contains(PresetType.WAY) &&
1861 !(types.contains(PresetType.CLOSEDWAY) && ((Way)osm).isClosed())) {
1862 continue;
1863 }
1864 }
1865 }
1866 sel.add(osm);
1867 }
1868 return sel;
1869 }
1870
1871 public List<Tag> getChangedTags() {
1872 List<Tag> result = new ArrayList<Tag>();
1873 for (Item i: data) {
1874 i.addCommands(result);
1875 }
1876 return result;
1877 }
1878
1879 private static String fixPresetString(String s) {
1880 return s == null ? s : s.replaceAll("'","''");
1881 }
1882
1883 public static Command createCommand(Collection<OsmPrimitive> sel, List<Tag> changedTags) {
1884 List<Command> cmds = new ArrayList<Command>();
1885 for (Tag tag: changedTags) {
1886 cmds.add(new ChangePropertyCommand(sel, tag.getKey(), tag.getValue()));
1887 }
1888
1889 if (cmds.size() == 0)
1890 return null;
1891 else if (cmds.size() == 1)
1892 return cmds.get(0);
1893 else
1894 return new SequenceCommand(tr("Change Properties"), cmds);
1895 }
1896
1897 private boolean supportsRelation() {
1898 return types == null || types.contains(PresetType.RELATION);
1899 }
1900
1901 protected void updateEnabledState() {
1902 setEnabled(Main.main != null && Main.main.getCurrentDataSet() != null);
1903 }
1904
1905 public void activeLayerChange(Layer oldLayer, Layer newLayer) {
1906 updateEnabledState();
1907 }
1908
1909 public void layerAdded(Layer newLayer) {
1910 updateEnabledState();
1911 }
1912
1913 public void layerRemoved(Layer oldLayer) {
1914 updateEnabledState();
1915 }
1916
1917 @Override
1918 public String toString() {
1919 return (types == null?"":types) + " " + name;
1920 }
1921
1922 public boolean typeMatches(Collection<PresetType> t) {
1923 return t == null || types == null || types.containsAll(t);
1924 }
1925
1926 public boolean matches(Collection<PresetType> t, Map<String, String> tags, boolean onlyShowable) {
1927 if (onlyShowable && !isShowable())
1928 return false;
1929 else if (!typeMatches(t))
1930 return false;
1931 boolean atLeastOnePositiveMatch = false;
1932 for (Item item : data) {
1933 Boolean m = item.matches(tags);
1934 if (m != null && !m)
1935 return false;
1936 else if (m != null) {
1937 atLeastOnePositiveMatch = true;
1938 }
1939 }
1940 return atLeastOnePositiveMatch;
1941 }
1942
1943 public static Collection<TaggingPreset> getMatchingPresets(final Collection<PresetType> t, final Map<String, String> tags, final boolean onlyShowable) {
1944 return Utils.filter(TaggingPresetPreference.taggingPresets, new Predicate<TaggingPreset>() {
1945 @Override
1946 public boolean evaluate(TaggingPreset object) {
1947 return object.matches(t, tags, onlyShowable);
1948 }
1949 });
1950 }
1951}
Note: See TracBrowser for help on using the repository browser.