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

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

fix #12008 - do not create empty commands from tagging preset dialog + add robustness

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