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

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

see #13191 - fix typos - gsoc-core

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