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

Last change on this file since 10714 was 10714, checked in by simon04, 8 years ago

see #11390 - Use CompletableFuture for async image loading

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