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

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

see #15182 - introduce Main.getEditDataSet to avoid unneeded GUI dependence in validator tests and tagging presets

  • Property svn:eol-style set to native
File size: 23.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.tagging.presets;
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.GridBagLayout;
11import java.awt.Insets;
12import java.awt.event.ActionEvent;
13import java.io.File;
14import java.util.ArrayList;
15import java.util.Collection;
16import java.util.Collections;
17import java.util.EnumSet;
18import java.util.HashSet;
19import java.util.LinkedList;
20import java.util.List;
21import java.util.Map;
22import java.util.Set;
23import java.util.function.Predicate;
24
25import javax.swing.AbstractAction;
26import javax.swing.Action;
27import javax.swing.ImageIcon;
28import javax.swing.JLabel;
29import javax.swing.JOptionPane;
30import javax.swing.JPanel;
31import javax.swing.JToggleButton;
32import javax.swing.SwingUtilities;
33
34import org.openstreetmap.josm.Main;
35import org.openstreetmap.josm.actions.AdaptableAction;
36import org.openstreetmap.josm.command.ChangePropertyCommand;
37import org.openstreetmap.josm.command.Command;
38import org.openstreetmap.josm.command.SequenceCommand;
39import org.openstreetmap.josm.data.osm.DataSet;
40import org.openstreetmap.josm.data.osm.OsmPrimitive;
41import org.openstreetmap.josm.data.osm.Relation;
42import org.openstreetmap.josm.data.osm.RelationMember;
43import org.openstreetmap.josm.data.osm.Tag;
44import org.openstreetmap.josm.data.osm.search.SearchCompiler;
45import org.openstreetmap.josm.data.osm.search.SearchCompiler.Match;
46import org.openstreetmap.josm.data.osm.search.SearchParseError;
47import org.openstreetmap.josm.gui.ExtendedDialog;
48import org.openstreetmap.josm.gui.MainApplication;
49import org.openstreetmap.josm.gui.Notification;
50import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor;
51import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeEvent;
52import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeListener;
53import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
54import org.openstreetmap.josm.gui.tagging.presets.items.Key;
55import org.openstreetmap.josm.gui.tagging.presets.items.Link;
56import org.openstreetmap.josm.gui.tagging.presets.items.Optional;
57import org.openstreetmap.josm.gui.tagging.presets.items.PresetLink;
58import org.openstreetmap.josm.gui.tagging.presets.items.Roles;
59import org.openstreetmap.josm.gui.tagging.presets.items.Roles.Role;
60import org.openstreetmap.josm.gui.tagging.presets.items.Space;
61import org.openstreetmap.josm.gui.util.GuiHelper;
62import org.openstreetmap.josm.tools.GBC;
63import org.openstreetmap.josm.tools.ImageProvider;
64import org.openstreetmap.josm.tools.Logging;
65import org.openstreetmap.josm.tools.Utils;
66import org.openstreetmap.josm.tools.template_engine.ParseError;
67import org.openstreetmap.josm.tools.template_engine.TemplateEntry;
68import org.openstreetmap.josm.tools.template_engine.TemplateParser;
69import org.xml.sax.SAXException;
70
71/**
72 * This class read encapsulate one tagging preset. A class method can
73 * read in all predefined presets, either shipped with JOSM or that are
74 * in the config directory.
75 *
76 * It is also able to construct dialogs out of preset definitions.
77 * @since 294
78 */
79public class TaggingPreset extends AbstractAction implements ActiveLayerChangeListener, AdaptableAction, Predicate<OsmPrimitive> {
80
81 public static final int DIALOG_ANSWER_APPLY = 1;
82 public static final int DIALOG_ANSWER_NEW_RELATION = 2;
83 public static final int DIALOG_ANSWER_CANCEL = 3;
84
85 public static final String OPTIONAL_TOOLTIP_TEXT = "Optional tooltip text";
86
87 /** Prefix of preset icon loading failure error message */
88 public static final String PRESET_ICON_ERROR_MSG_PREFIX = "Could not get presets icon ";
89
90 /**
91 * The preset group this preset belongs to.
92 */
93 public TaggingPresetMenu group;
94
95 /**
96 * The name of the tagging preset.
97 * @see #getRawName()
98 */
99 public String name;
100 /**
101 * The icon name assigned to this preset.
102 */
103 public String iconName;
104 public String name_context;
105 /**
106 * A cache for the local name. Should never be accessed directly.
107 * @see #getLocaleName()
108 */
109 public String locale_name;
110 public boolean preset_name_label;
111
112 /**
113 * The types as preparsed collection.
114 */
115 public transient Set<TaggingPresetType> types;
116 public final transient List<TaggingPresetItem> data = new LinkedList<>();
117 public transient Roles roles;
118 public transient TemplateEntry nameTemplate;
119 public transient Match nameTemplateFilter;
120
121 /**
122 * True whenever the original selection given into createSelection was empty
123 */
124 private boolean originalSelectionEmpty;
125
126 /**
127 * Create an empty tagging preset. This will not have any items and
128 * will be an empty string as text. createPanel will return null.
129 * Use this as default item for "do not select anything".
130 */
131 public TaggingPreset() {
132 MainApplication.getLayerManager().addActiveLayerChangeListener(this);
133 updateEnabledState();
134 }
135
136 /**
137 * Change the display name without changing the toolbar value.
138 */
139 public void setDisplayName() {
140 putValue(Action.NAME, getName());
141 putValue("toolbar", "tagging_" + getRawName());
142 putValue(OPTIONAL_TOOLTIP_TEXT, group != null ?
143 tr("Use preset ''{0}'' of group ''{1}''", getLocaleName(), group.getName()) :
144 tr("Use preset ''{0}''", getLocaleName()));
145 }
146
147 /**
148 * Gets the localized version of the name
149 * @return The name that should be displayed to the user.
150 */
151 public String getLocaleName() {
152 if (locale_name == null) {
153 if (name_context != null) {
154 locale_name = trc(name_context, TaggingPresetItem.fixPresetString(name));
155 } else {
156 locale_name = tr(TaggingPresetItem.fixPresetString(name));
157 }
158 }
159 return locale_name;
160 }
161
162 /**
163 * Returns the translated name of this preset, prefixed with the group names it belongs to.
164 * @return the translated name of this preset, prefixed with the group names it belongs to
165 */
166 public String getName() {
167 return group != null ? group.getName() + '/' + getLocaleName() : getLocaleName();
168 }
169
170 /**
171 * Returns the non translated name of this preset, prefixed with the (non translated) group names it belongs to.
172 * @return the non translated name of this preset, prefixed with the (non translated) group names it belongs to
173 */
174 public String getRawName() {
175 return group != null ? group.getRawName() + '/' + name : name;
176 }
177
178 /**
179 * Returns the preset icon (16px).
180 * @return The preset icon, or {@code null} if none defined
181 * @since 6403
182 */
183 public final ImageIcon getIcon() {
184 return getIcon(Action.SMALL_ICON);
185 }
186
187 /**
188 * Returns the preset icon (16 or 24px).
189 * @param key Key determining icon size: {@code Action.SMALL_ICON} for 16x, {@code Action.LARGE_ICON_KEY} for 24px
190 * @return The preset icon, or {@code null} if none defined
191 * @since 10849
192 */
193 public final ImageIcon getIcon(String key) {
194 Object icon = getValue(key);
195 if (icon instanceof ImageIcon) {
196 return (ImageIcon) icon;
197 }
198 return null;
199 }
200
201 /**
202 * Called from the XML parser to set the icon.
203 * The loading task is performed in the background in order to speedup startup.
204 * @param iconName icon name
205 */
206 public void setIcon(final String iconName) {
207 this.iconName = iconName;
208 if (!TaggingPresetReader.isLoadIcons()) {
209 return;
210 }
211 File arch = TaggingPresetReader.getZipIcons();
212 final Collection<String> s = Main.pref.getCollection("taggingpreset.icon.sources", null);
213 ImageProvider imgProv = new ImageProvider(iconName);
214 imgProv.setDirs(s);
215 imgProv.setId("presets");
216 imgProv.setArchive(arch);
217 imgProv.setOptional(true);
218 imgProv.getResourceAsync().thenAccept(result -> {
219 if (result != null) {
220 GuiHelper.runInEDT(() -> result.attachImageIcon(this));
221 } else {
222 Logging.warn(toString() + ": " + PRESET_ICON_ERROR_MSG_PREFIX + iconName);
223 }
224 });
225 }
226
227 /**
228 * Called from the XML parser to set the types this preset affects.
229 * @param types comma-separated primitive types ("node", "way", "relation" or "closedway")
230 * @throws SAXException if any SAX error occurs
231 * @see TaggingPresetType#fromString
232 */
233 public void setType(String types) throws SAXException {
234 this.types = TaggingPresetItem.getType(types);
235 }
236
237 public void setName_template(String pattern) throws SAXException {
238 try {
239 this.nameTemplate = new TemplateParser(pattern).parse();
240 } catch (ParseError e) {
241 Logging.error("Error while parsing " + pattern + ": " + e.getMessage());
242 throw new SAXException(e);
243 }
244 }
245
246 public void setName_template_filter(String filter) throws SAXException {
247 try {
248 this.nameTemplateFilter = SearchCompiler.compile(filter);
249 } catch (SearchParseError e) {
250 Logging.error("Error while parsing" + filter + ": " + e.getMessage());
251 throw new SAXException(e);
252 }
253 }
254
255 private static class PresetPanel extends JPanel {
256 private boolean hasElements;
257
258 PresetPanel() {
259 super(new GridBagLayout());
260 }
261 }
262
263 /**
264 * Returns the tags being directly applied (without UI element) by {@link Key} items
265 *
266 * @return a list of tags
267 */
268 private List<Tag> getDirectlyAppliedTags() {
269 List<Tag> tags = new ArrayList<>();
270 for (TaggingPresetItem item : data) {
271 if (item instanceof Key) {
272 tags.add(((Key) item).asTag());
273 }
274 }
275 return tags;
276 }
277
278 /**
279 * Creates a panel for this preset. This includes general information such as name and supported {@link TaggingPresetType types}.
280 * This includes the elements from the individual {@link TaggingPresetItem items}.
281 *
282 * @param selected the selected primitives
283 * @return the newly created panel
284 */
285 public PresetPanel createPanel(Collection<OsmPrimitive> selected) {
286 PresetPanel p = new PresetPanel();
287 List<Link> l = new LinkedList<>();
288 List<PresetLink> presetLink = new LinkedList<>();
289
290 final JPanel pp = new JPanel();
291 if (types != null) {
292 for (TaggingPresetType t : types) {
293 JLabel la = new JLabel(ImageProvider.get(t.getIconName()));
294 la.setToolTipText(tr("Elements of type {0} are supported.", tr(t.getName())));
295 pp.add(la);
296 }
297 }
298 final List<Tag> directlyAppliedTags = getDirectlyAppliedTags();
299 if (!directlyAppliedTags.isEmpty()) {
300 final JLabel label = new JLabel(ImageProvider.get("pastetags"));
301 label.setToolTipText("<html>" + tr("This preset also sets: {0}", Utils.joinAsHtmlUnorderedList(directlyAppliedTags)));
302 pp.add(label);
303 }
304 final int count = pp.getComponentCount();
305 if (preset_name_label) {
306 p.add(new JLabel(getIcon(Action.LARGE_ICON_KEY)), GBC.std(0, 0).span(1, count > 0 ? 2 : 1).insets(0, 0, 5, 0));
307 }
308 if (count > 0) {
309 p.add(pp, GBC.std(1, 0).span(GBC.REMAINDER));
310 }
311 if (preset_name_label) {
312 p.add(new JLabel(getName()), GBC.std(1, count > 0 ? 1 : 0).insets(5, 0, 0, 0).span(GBC.REMAINDER).fill(GBC.HORIZONTAL));
313 }
314
315 boolean presetInitiallyMatches = !selected.isEmpty() && selected.stream().allMatch(this);
316 JPanel items = new JPanel(new GridBagLayout());
317 for (TaggingPresetItem i : data) {
318 if (i instanceof Link) {
319 l.add((Link) i);
320 p.hasElements = true;
321 } else if (i instanceof PresetLink) {
322 presetLink.add((PresetLink) i);
323 } else {
324 if (i.addToPanel(items, selected, presetInitiallyMatches)) {
325 p.hasElements = true;
326 }
327 }
328 }
329 p.add(items, GBC.eol().fill());
330 if (selected.isEmpty() && !supportsRelation()) {
331 GuiHelper.setEnabledRec(items, false);
332 }
333
334 // add PresetLink
335 if (!presetLink.isEmpty()) {
336 p.add(new JLabel(tr("Edit also …")), GBC.eol().insets(0, 8, 0, 0));
337 for (PresetLink link : presetLink) {
338 link.addToPanel(p, selected, presetInitiallyMatches);
339 }
340 }
341
342 // add Link
343 for (Link link : l) {
344 link.addToPanel(p, selected, presetInitiallyMatches);
345 }
346
347 // "Add toolbar button"
348 JToggleButton tb = new JToggleButton(new ToolbarButtonAction());
349 tb.setFocusable(false);
350 p.add(tb, GBC.std(1, 0).anchor(GBC.LINE_END));
351 return p;
352 }
353
354 /**
355 * Determines whether a dialog can be shown for this preset, i.e., at least one tag can/must be set by the user.
356 *
357 * @return {@code true} if a dialog can be shown for this preset
358 */
359 public boolean isShowable() {
360 for (TaggingPresetItem i : data) {
361 if (!(i instanceof Optional || i instanceof Space || i instanceof Key))
362 return true;
363 }
364 return false;
365 }
366
367 public String suggestRoleForOsmPrimitive(OsmPrimitive osm) {
368 if (roles != null && osm != null) {
369 for (Role i : roles.roles) {
370 if (i.memberExpression != null && i.memberExpression.match(osm)
371 && (i.types == null || i.types.isEmpty() || i.types.contains(TaggingPresetType.forPrimitive(osm)))) {
372 return i.key;
373 }
374 }
375 }
376 return null;
377 }
378
379 @Override
380 public void actionPerformed(ActionEvent e) {
381 if (Main.main == null) {
382 return;
383 }
384 DataSet ds = Main.main.getEditDataSet();
385 Collection<OsmPrimitive> participants = Collections.emptyList();
386 if (ds != null) {
387 participants = ds.getSelected();
388 }
389
390 // Display dialog even if no data layer (used by preset-tagging-tester plugin)
391 Collection<OsmPrimitive> sel = createSelection(participants);
392 int answer = showDialog(sel, supportsRelation());
393
394 if (ds == null) {
395 return;
396 }
397
398 if (!sel.isEmpty() && answer == DIALOG_ANSWER_APPLY) {
399 Command cmd = createCommand(sel, getChangedTags());
400 if (cmd != null) {
401 MainApplication.undoRedo.add(cmd);
402 }
403 } else if (answer == DIALOG_ANSWER_NEW_RELATION) {
404 final Relation r = new Relation();
405 final Collection<RelationMember> members = new HashSet<>();
406 for (Tag t : getChangedTags()) {
407 r.put(t.getKey(), t.getValue());
408 }
409 for (OsmPrimitive osm : ds.getSelected()) {
410 String role = suggestRoleForOsmPrimitive(osm);
411 RelationMember rm = new RelationMember(role == null ? "" : role, osm);
412 r.addMember(rm);
413 members.add(rm);
414 }
415 SwingUtilities.invokeLater(() -> RelationEditor.getEditor(
416 MainApplication.getLayerManager().getEditLayer(), r, members).setVisible(true));
417 }
418 ds.setSelected(ds.getSelected()); // force update
419 }
420
421 private static class PresetDialog extends ExtendedDialog {
422
423 /**
424 * Constructs a new {@code PresetDialog}.
425 * @param content the content that will be displayed in this dialog
426 * @param title the text that will be shown in the window titlebar
427 * @param icon the image to be displayed as the icon for this window
428 * @param disableApply whether to disable "Apply" button
429 * @param showNewRelation whether to display "New relation" button
430 */
431 PresetDialog(Component content, String title, ImageIcon icon, boolean disableApply, boolean showNewRelation) {
432 super(Main.parent, title,
433 showNewRelation ?
434 (new String[] {tr("Apply Preset"), tr("New relation"), tr("Cancel")}) :
435 (new String[] {tr("Apply Preset"), tr("Cancel")}),
436 true);
437 if (icon != null)
438 setIconImage(icon.getImage());
439 contentInsets = new Insets(10, 5, 0, 5);
440 if (showNewRelation) {
441 setButtonIcons("ok", "dialogs/addrelation", "cancel");
442 } else {
443 setButtonIcons("ok", "cancel");
444 }
445 setContent(content);
446 setDefaultButton(1);
447 setupDialog();
448 buttons.get(0).setEnabled(!disableApply);
449 buttons.get(0).setToolTipText(title);
450 // Prevent dialogs of being too narrow (fix #6261)
451 Dimension d = getSize();
452 if (d.width < 350) {
453 d.width = 350;
454 setSize(d);
455 }
456 super.showDialog();
457 }
458 }
459
460 /**
461 * Shows the preset dialog.
462 * @param sel selection
463 * @param showNewRelation whether to display "New relation" button
464 * @return the user choice after the dialog has been closed
465 */
466 public int showDialog(Collection<OsmPrimitive> sel, boolean showNewRelation) {
467 PresetPanel p = createPanel(sel);
468
469 int answer = 1;
470 boolean canCreateRelation = types == null || types.contains(TaggingPresetType.RELATION);
471 if (originalSelectionEmpty && !canCreateRelation) {
472 new Notification(
473 tr("The preset <i>{0}</i> cannot be applied since nothing has been selected!", getLocaleName()))
474 .setIcon(JOptionPane.WARNING_MESSAGE)
475 .show();
476 return DIALOG_ANSWER_CANCEL;
477 } else if (sel.isEmpty() && !canCreateRelation) {
478 new Notification(
479 tr("The preset <i>{0}</i> cannot be applied since the selection is unsuitable!", getLocaleName()))
480 .setIcon(JOptionPane.WARNING_MESSAGE)
481 .show();
482 return DIALOG_ANSWER_CANCEL;
483 } else if (p.getComponentCount() != 0 && (sel.isEmpty() || p.hasElements)) {
484 String title = trn("Change {0} object", "Change {0} objects", sel.size(), sel.size());
485 if (sel.isEmpty()) {
486 if (originalSelectionEmpty) {
487 title = tr("Nothing selected!");
488 } else {
489 title = tr("Selection unsuitable!");
490 }
491 }
492
493 answer = new PresetDialog(p, title, preset_name_label ? null : (ImageIcon) getValue(Action.SMALL_ICON),
494 sel.isEmpty(), showNewRelation).getValue();
495 }
496 if (!showNewRelation && answer == 2)
497 return DIALOG_ANSWER_CANCEL;
498 else
499 return answer;
500 }
501
502 /**
503 * Removes all unsuitable OsmPrimitives from the given list
504 * @param participants List of possible OsmPrimitives to tag
505 * @return Cleaned list with suitable OsmPrimitives only
506 */
507 public Collection<OsmPrimitive> createSelection(Collection<OsmPrimitive> participants) {
508 originalSelectionEmpty = participants.isEmpty();
509 Collection<OsmPrimitive> sel = new LinkedList<>();
510 for (OsmPrimitive osm : participants) {
511 if (typeMatches(EnumSet.of(TaggingPresetType.forPrimitive(osm)))) {
512 sel.add(osm);
513 }
514 }
515 return sel;
516 }
517
518 /**
519 * Gets a list of tags that are set by this preset.
520 * @return The list of tags.
521 */
522 public List<Tag> getChangedTags() {
523 List<Tag> result = new ArrayList<>();
524 for (TaggingPresetItem i: data) {
525 i.addCommands(result);
526 }
527 return result;
528 }
529
530 /**
531 * Create a command to change the given list of tags.
532 * @param sel The primitives to change the tags for
533 * @param changedTags The tags to change
534 * @return A command that changes the tags.
535 */
536 public static Command createCommand(Collection<OsmPrimitive> sel, List<Tag> changedTags) {
537 List<Command> cmds = new ArrayList<>();
538 for (Tag tag: changedTags) {
539 ChangePropertyCommand cmd = new ChangePropertyCommand(sel, tag.getKey(), tag.getValue());
540 if (cmd.getObjectsNumber() > 0) {
541 cmds.add(cmd);
542 }
543 }
544
545 if (cmds.isEmpty())
546 return null;
547 else if (cmds.size() == 1)
548 return cmds.get(0);
549 else
550 return new SequenceCommand(tr("Change Tags"), cmds);
551 }
552
553 private boolean supportsRelation() {
554 return types == null || types.contains(TaggingPresetType.RELATION);
555 }
556
557 protected final void updateEnabledState() {
558 setEnabled(Main.main != null && Main.main.getEditDataSet() != null);
559 }
560
561 @Override
562 public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) {
563 updateEnabledState();
564 }
565
566 @Override
567 public String toString() {
568 return (types == null ? "" : types.toString()) + ' ' + name;
569 }
570
571 /**
572 * Determines whether this preset matches the types.
573 * @param t The types that must match
574 * @return <code>true</code> if all types match.
575 */
576 public boolean typeMatches(Collection<TaggingPresetType> t) {
577 return t == null || types == null || types.containsAll(t);
578 }
579
580 /**
581 * Determines whether this preset matches the given primitive, i.e.,
582 * whether the {@link #typeMatches(Collection) type matches} and the {@link TaggingPresetItem#matches(Map) tags match}.
583 *
584 * @param p the primitive
585 * @return {@code true} if this preset matches the primitive
586 */
587 @Override
588 public boolean test(OsmPrimitive p) {
589 return matches(EnumSet.of(TaggingPresetType.forPrimitive(p)), p.getKeys(), false);
590 }
591
592 /**
593 * Determines whether this preset matches the parameters.
594 *
595 * @param t the preset types to include, see {@link #typeMatches(Collection)}
596 * @param tags the tags to perform matching on, see {@link TaggingPresetItem#matches(Map)}
597 * @param onlyShowable whether the preset must be {@link #isShowable() showable}
598 * @return {@code true} if this preset matches the parameters.
599 */
600 public boolean matches(Collection<TaggingPresetType> t, Map<String, String> tags, boolean onlyShowable) {
601 if ((onlyShowable && !isShowable()) || !typeMatches(t)) {
602 return false;
603 } else {
604 return TaggingPresetItem.matches(data, tags);
605 }
606 }
607
608 /**
609 * Action that adds or removes the button on main toolbar
610 */
611 public class ToolbarButtonAction extends AbstractAction {
612 private final int toolbarIndex;
613
614 /**
615 * Constructs a new {@code ToolbarButtonAction}.
616 */
617 public ToolbarButtonAction() {
618 super("", ImageProvider.get("dialogs", "pin"));
619 putValue(SHORT_DESCRIPTION, tr("Add or remove toolbar button"));
620 List<String> t = new LinkedList<>(ToolbarPreferences.getToolString());
621 toolbarIndex = t.indexOf(getToolbarString());
622 putValue(SELECTED_KEY, toolbarIndex >= 0);
623 }
624
625 @Override
626 public void actionPerformed(ActionEvent ae) {
627 String res = getToolbarString();
628 MainApplication.getToolbar().addCustomButton(res, toolbarIndex, true);
629 }
630 }
631
632 /**
633 * Gets a string describing this preset that can be used for the toolbar
634 * @return A String that can be passed on to the toolbar
635 * @see ToolbarPreferences#addCustomButton(String, int, boolean)
636 */
637 public String getToolbarString() {
638 ToolbarPreferences.ActionParser actionParser = new ToolbarPreferences.ActionParser(null);
639 return actionParser.saveAction(new ToolbarPreferences.ActionDefinition(this));
640 }
641}
Note: See TracBrowser for help on using the repository browser.