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

Last change on this file since 18824 was 18607, checked in by taylor.smock, 19 months ago

See #21829: DataIntegrityProblemException: Primitive must be part of the dataset

This ensures we fail earlier -- validateAsync is called later from the EDT,
which means we cannot figure out where the data came from.

  • Property svn:eol-style set to native
File size: 30.9 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.ComponentOrientation;
10import java.awt.Dimension;
11import java.awt.GridBagLayout;
12import java.awt.Insets;
13import java.awt.event.ActionEvent;
14import java.io.File;
15import java.util.ArrayList;
16import java.util.Collection;
17import java.util.EnumSet;
18import java.util.LinkedHashSet;
19import java.util.List;
20import java.util.Map;
21import java.util.Objects;
22import java.util.Set;
23import java.util.concurrent.CompletableFuture;
24import java.util.function.Predicate;
25import java.util.stream.Collectors;
26
27import javax.swing.AbstractAction;
28import javax.swing.Action;
29import javax.swing.ImageIcon;
30import javax.swing.JLabel;
31import javax.swing.JOptionPane;
32import javax.swing.JPanel;
33import javax.swing.JToggleButton;
34import javax.swing.SwingUtilities;
35
36import org.openstreetmap.josm.actions.AdaptableAction;
37import org.openstreetmap.josm.actions.CreateMultipolygonAction;
38import org.openstreetmap.josm.command.ChangePropertyCommand;
39import org.openstreetmap.josm.command.Command;
40import org.openstreetmap.josm.command.SequenceCommand;
41import org.openstreetmap.josm.data.UndoRedoHandler;
42import org.openstreetmap.josm.data.osm.DataSet;
43import org.openstreetmap.josm.data.osm.IPrimitive;
44import org.openstreetmap.josm.data.osm.OsmData;
45import org.openstreetmap.josm.data.osm.OsmDataManager;
46import org.openstreetmap.josm.data.osm.OsmPrimitive;
47import org.openstreetmap.josm.data.osm.Relation;
48import org.openstreetmap.josm.data.osm.RelationMember;
49import org.openstreetmap.josm.data.osm.Tag;
50import org.openstreetmap.josm.data.osm.Tagged;
51import org.openstreetmap.josm.data.osm.Way;
52import org.openstreetmap.josm.data.osm.search.SearchCompiler;
53import org.openstreetmap.josm.data.osm.search.SearchCompiler.Match;
54import org.openstreetmap.josm.data.osm.search.SearchParseError;
55import org.openstreetmap.josm.data.preferences.BooleanProperty;
56import org.openstreetmap.josm.gui.ExtendedDialog;
57import org.openstreetmap.josm.gui.MainApplication;
58import org.openstreetmap.josm.gui.Notification;
59import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor;
60import org.openstreetmap.josm.gui.dialogs.relation.sort.RelationSorter;
61import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeEvent;
62import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeListener;
63import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
64import org.openstreetmap.josm.gui.tagging.presets.items.Key;
65import org.openstreetmap.josm.gui.tagging.presets.items.Link;
66import org.openstreetmap.josm.gui.tagging.presets.items.Optional;
67import org.openstreetmap.josm.gui.tagging.presets.items.PresetLink;
68import org.openstreetmap.josm.gui.tagging.presets.items.Roles;
69import org.openstreetmap.josm.gui.tagging.presets.items.Space;
70import org.openstreetmap.josm.gui.util.GuiHelper;
71import org.openstreetmap.josm.tools.GBC;
72import org.openstreetmap.josm.tools.ImageProvider;
73import org.openstreetmap.josm.tools.ImageResource;
74import org.openstreetmap.josm.tools.Logging;
75import org.openstreetmap.josm.tools.Pair;
76import org.openstreetmap.josm.tools.StreamUtils;
77import org.openstreetmap.josm.tools.Utils;
78import org.openstreetmap.josm.tools.template_engine.ParseError;
79import org.openstreetmap.josm.tools.template_engine.TemplateEntry;
80import org.openstreetmap.josm.tools.template_engine.TemplateParser;
81import org.xml.sax.SAXException;
82
83/**
84 * This class read encapsulate one tagging preset. A class method can
85 * read in all predefined presets, either shipped with JOSM or that are
86 * in the config directory.
87 *
88 * It is also able to construct dialogs out of preset definitions.
89 * @since 294
90 */
91public class TaggingPreset extends AbstractAction implements ActiveLayerChangeListener, AdaptableAction, Predicate<IPrimitive> {
92
93 /** The user pressed the "Apply" button */
94 public static final int DIALOG_ANSWER_APPLY = 1;
95 /** The user pressed the "New Relation" button */
96 public static final int DIALOG_ANSWER_NEW_RELATION = 2;
97 /** The user pressed the "Cancel" button */
98 public static final int DIALOG_ANSWER_CANCEL = 3;
99
100 /** The action key for optional tooltips */
101 public static final String OPTIONAL_TOOLTIP_TEXT = "Optional tooltip text";
102
103 /** Prefix of preset icon loading failure error message */
104 public static final String PRESET_ICON_ERROR_MSG_PREFIX = "Could not get presets icon ";
105
106 /**
107 * Defines whether the validator should be active in the preset dialog
108 * @see TaggingPresetValidation
109 */
110 public static final BooleanProperty USE_VALIDATOR = new BooleanProperty("taggingpreset.validator", false);
111
112 /**
113 * The preset group this preset belongs to.
114 */
115 public TaggingPresetMenu group;
116
117 /**
118 * The name of the tagging preset.
119 * @see #getRawName()
120 */
121 public String name;
122 /**
123 * The icon name assigned to this preset.
124 */
125 public String iconName;
126 /**
127 * Translation context for name
128 */
129 public String name_context;
130 /**
131 * A cache for the local name. Should never be accessed directly.
132 * @see #getLocaleName()
133 */
134 public String locale_name;
135 /**
136 * Show the preset name if true
137 */
138 public boolean preset_name_label;
139
140 /**
141 * The types as preparsed collection.
142 */
143 public transient Set<TaggingPresetType> types;
144 /**
145 * The list of preset items
146 */
147 public final transient List<TaggingPresetItem> data = new ArrayList<>(2);
148 /**
149 * The roles for this relation (if we are editing a relation). See:
150 * <a href="https://josm.openstreetmap.de/wiki/TaggingPresets#Tags">JOSM wiki</a>
151 */
152 public transient Roles roles;
153 /**
154 * The name_template custom name formatter. See:
155 * <a href="https://josm.openstreetmap.de/wiki/TaggingPresets#Attributes">JOSM wiki</a>
156 */
157 public transient TemplateEntry nameTemplate;
158 /** The name_template_filter */
159 public transient Match nameTemplateFilter;
160 /** The match_expression */
161 public transient Match matchExpression;
162
163 /**
164 * True whenever the original selection given into createSelection was empty
165 */
166 private boolean originalSelectionEmpty;
167
168 /** The completable future task of asynchronous icon loading */
169 private CompletableFuture<Void> iconFuture;
170
171 /** Support functions */
172 protected TaggingPresetItemGuiSupport itemGuiSupport;
173
174 /**
175 * Create an empty tagging preset. This will not have any items and
176 * will be an empty string as text. createPanel will return null.
177 * Use this as default item for "do not select anything".
178 */
179 public TaggingPreset() {
180 updateEnabledState();
181 }
182
183 /**
184 * Change the display name without changing the toolbar value.
185 */
186 public void setDisplayName() {
187 putValue(Action.NAME, getName());
188 putValue("toolbar", "tagging_" + getRawName());
189 putValue(OPTIONAL_TOOLTIP_TEXT, group != null ?
190 tr("Use preset ''{0}'' of group ''{1}''", getLocaleName(), group.getName()) :
191 tr("Use preset ''{0}''", getLocaleName()));
192 }
193
194 /**
195 * Gets the localized version of the name
196 * @return The name that should be displayed to the user.
197 */
198 public String getLocaleName() {
199 if (locale_name == null) {
200 if (name_context != null) {
201 locale_name = trc(name_context, TaggingPresetItem.fixPresetString(name));
202 } else {
203 locale_name = tr(TaggingPresetItem.fixPresetString(name));
204 }
205 }
206 return locale_name;
207 }
208
209 /**
210 * Returns the translated name of this preset, prefixed with the group names it belongs to.
211 * @return the translated name of this preset, prefixed with the group names it belongs to
212 */
213 public String getName() {
214 return group != null ? group.getName() + '/' + getLocaleName() : getLocaleName();
215 }
216
217 /**
218 * Returns the non translated name of this preset, prefixed with the (non translated) group names it belongs to.
219 * @return the non translated name of this preset, prefixed with the (non translated) group names it belongs to
220 */
221 public String getRawName() {
222 return group != null ? group.getRawName() + '/' + name : name;
223 }
224
225 /**
226 * Returns the preset icon (16px).
227 * @return The preset icon, or {@code null} if none defined
228 * @since 6403
229 */
230 public final ImageIcon getIcon() {
231 return getIcon(Action.SMALL_ICON);
232 }
233
234 /**
235 * Returns the preset icon (16 or 24px).
236 * @param key Key determining icon size: {@code Action.SMALL_ICON} for 16x, {@code Action.LARGE_ICON_KEY} for 24px
237 * @return The preset icon, or {@code null} if none defined
238 * @since 10849
239 */
240 public final ImageIcon getIcon(String key) {
241 Object icon = getValue(key);
242 if (icon instanceof ImageIcon) {
243 return (ImageIcon) icon;
244 }
245 return null;
246 }
247
248 /**
249 * Returns the {@link ImageResource} attached to this preset, if any.
250 * @return the {@code ImageResource} attached to this preset, or {@code null}
251 * @since 16060
252 */
253 public final ImageResource getImageResource() {
254 return ImageResource.getAttachedImageResource(this);
255 }
256
257 /**
258 * Called from the XML parser to set the icon.
259 * The loading task is performed in the background in order to speedup startup.
260 * @param iconName icon name
261 */
262 public void setIcon(final String iconName) {
263 this.iconName = iconName;
264 if (iconName == null || !TaggingPresetReader.isLoadIcons()) {
265 return;
266 }
267 File arch = TaggingPresetReader.getZipIcons();
268 final Collection<String> s = TaggingPresets.ICON_SOURCES.get();
269 this.iconFuture = new CompletableFuture<>();
270 new ImageProvider(iconName)
271 .setDirs(s)
272 .setId("presets")
273 .setArchive(arch)
274 .setOptional(true)
275 .getResourceAsync(result -> {
276 if (result != null) {
277 GuiHelper.runInEDT(() -> {
278 try {
279 result.attachImageIcon(this, true);
280 } catch (IllegalArgumentException e) {
281 Logging.warn(toString() + ": " + PRESET_ICON_ERROR_MSG_PREFIX + iconName);
282 Logging.warn(e);
283 } finally {
284 iconFuture.complete(null);
285 }
286 });
287 } else {
288 Logging.warn(toString() + ": " + PRESET_ICON_ERROR_MSG_PREFIX + iconName);
289 iconFuture.complete(null);
290 }
291 });
292 }
293
294 /**
295 * Called from the XML parser to set the types this preset affects.
296 * @param types comma-separated primitive types ("node", "way", "relation" or "closedway")
297 * @throws SAXException if any SAX error occurs
298 * @see TaggingPresetType#fromString
299 */
300 public void setType(String types) throws SAXException {
301 this.types = TaggingPresetItem.getType(types);
302 }
303
304 /**
305 * Sets the name_template custom name formatter.
306 *
307 * @param template The format template
308 * @throws SAXException on template parse error
309 * @see <a href="https://josm.openstreetmap.de/wiki/TaggingPresets#name_templatedetails">JOSM wiki</a>
310 */
311 public void setName_template(String template) throws SAXException {
312 try {
313 this.nameTemplate = new TemplateParser(template).parse();
314 } catch (ParseError e) {
315 Logging.error("Error while parsing " + template + ": " + e.getMessage());
316 throw new SAXException(e);
317 }
318 }
319
320 /**
321 * Sets the name_template_filter.
322 *
323 * @param filter The search pattern
324 * @throws SAXException on search patern parse error
325 * @see <a href="https://josm.openstreetmap.de/wiki/TaggingPresets#name_templatedetails">JOSM wiki</a>
326 */
327 public void setName_template_filter(String filter) throws SAXException {
328 try {
329 this.nameTemplateFilter = SearchCompiler.compile(filter);
330 } catch (SearchParseError e) {
331 Logging.error("Error while parsing" + filter + ": " + e.getMessage());
332 throw new SAXException(e);
333 }
334 }
335
336 /**
337 * Sets the match_expression additional criteria for matching primitives.
338 *
339 * @param filter The search pattern
340 * @throws SAXException on search patern parse error
341 * @see <a href="https://josm.openstreetmap.de/wiki/TaggingPresets#Attributes">JOSM wiki</a>
342 */
343 public void setMatch_expression(String filter) throws SAXException {
344 try {
345 this.matchExpression = SearchCompiler.compile(filter);
346 } catch (SearchParseError e) {
347 Logging.error("Error while parsing" + filter + ": " + e.getMessage());
348 throw new SAXException(e);
349 }
350 }
351
352 private static class PresetPanel extends JPanel {
353 private boolean hasElements;
354
355 PresetPanel() {
356 super(new GridBagLayout());
357 }
358 }
359
360 /**
361 * Creates a panel for this preset. This includes general information such as name and supported {@link TaggingPresetType types}.
362 * This includes the elements from the individual {@link TaggingPresetItem items}.
363 *
364 * @param selected the selected primitives
365 * @return the newly created panel
366 */
367 public PresetPanel createPanel(Collection<OsmPrimitive> selected) {
368 PresetPanel p = new PresetPanel();
369
370 final JPanel pp = new JPanel();
371 if (types != null) {
372 for (TaggingPresetType t : types) {
373 JLabel la = new JLabel(ImageProvider.get(t.getIconName()));
374 la.setToolTipText(tr("Elements of type {0} are supported.", tr(t.getName())));
375 pp.add(la);
376 }
377 }
378 final List<Tag> directlyAppliedTags = Utils.filteredCollection(data, Key.class).stream()
379 .map(Key::asTag)
380 .collect(Collectors.toList());
381 if (!directlyAppliedTags.isEmpty()) {
382 final JLabel label = new JLabel(ImageProvider.get("pastetags"));
383 label.setToolTipText("<html>" + tr("This preset also sets: {0}", Utils.joinAsHtmlUnorderedList(directlyAppliedTags)));
384 pp.add(label);
385 }
386 JLabel validationLabel = new JLabel(ImageProvider.get("warning-small", ImageProvider.ImageSizes.LARGEICON));
387 validationLabel.setVisible(false);
388 pp.add(validationLabel);
389
390 final int count = pp.getComponentCount();
391 if (preset_name_label) {
392 p.add(new JLabel(getIcon(Action.LARGE_ICON_KEY)), GBC.std(0, 0).span(1, count > 0 ? 2 : 1).insets(0, 0, 5, 0));
393 }
394 if (count > 0) {
395 p.add(pp, GBC.std(1, 0).span(GBC.REMAINDER));
396 }
397 if (preset_name_label) {
398 p.add(new JLabel(getName()), GBC.std(1, count > 0 ? 1 : 0).insets(5, 0, 0, 0).span(GBC.REMAINDER).fill(GBC.HORIZONTAL));
399 }
400
401 boolean presetInitiallyMatches = !selected.isEmpty() && selected.stream().allMatch(this);
402 itemGuiSupport = TaggingPresetItemGuiSupport.create(presetInitiallyMatches, selected, this::getChangedTags);
403
404 JPanel itemPanel = new JPanel(new GridBagLayout()) {
405 /**
406 * This hack allows the items to have their own orientation.
407 *
408 * The problem is that
409 * {@link org.openstreetmap.josm.gui.ExtendedDialog#showDialog ExtendedDialog} calls
410 * {@code applyComponentOrientation} very late in the dialog construction process thus
411 * overwriting the orientation the components have chosen for themselves.
412 *
413 * This stops the propagation of {@code applyComponentOrientation}, thus all
414 * {@code TaggingPresetItem}s may (and have to) set their own orientation.
415 */
416 @Override
417 public void applyComponentOrientation(ComponentOrientation o) {
418 setComponentOrientation(o);
419 }
420 };
421 JPanel linkPanel = new JPanel(new GridBagLayout());
422 TaggingPresetItem previous = null;
423 for (TaggingPresetItem i : data) {
424 if (i instanceof Link) {
425 i.addToPanel(linkPanel, itemGuiSupport);
426 p.hasElements = true;
427 } else {
428 if (i instanceof PresetLink) {
429 PresetLink link = (PresetLink) i;
430 if (!(previous instanceof PresetLink && Objects.equals(((PresetLink) previous).text, link.text))) {
431 itemPanel.add(link.createLabel(), GBC.eol().insets(0, 8, 0, 0));
432 }
433 }
434 if (i.addToPanel(itemPanel, itemGuiSupport)) {
435 p.hasElements = true;
436 }
437 }
438 previous = i;
439 }
440 p.add(itemPanel, GBC.eol().fill());
441 p.add(linkPanel, GBC.eol().fill());
442
443 if (selected.isEmpty() && !supportsRelation()) {
444 GuiHelper.setEnabledRec(itemPanel, false);
445 }
446
447 if (selected.size() == 1 && Boolean.TRUE.equals(USE_VALIDATOR.get())) {
448 // Fail early -- validateAsync requires the primitive(s) to be part of a dataset. Failing later in validateAsync ''does not'' give us
449 // a usable stack trace. See #21829 for details.
450 selected.forEach(OsmPrimitive::checkDataset);
451 itemGuiSupport.addListener((source, key, newValue) ->
452 TaggingPresetValidation.validateAsync(selected.iterator().next(), validationLabel, getChangedTags()));
453 }
454
455 // "Add toolbar button"
456 JToggleButton tb = new JToggleButton(new ToolbarButtonAction());
457 tb.setFocusable(false);
458 p.add(tb, GBC.std(1, 0).anchor(GBC.LINE_END));
459
460 // Trigger initial updates once and only once
461 itemGuiSupport.setEnabled(true);
462 itemGuiSupport.fireItemValueModified(null, null, null);
463
464 return p;
465 }
466
467 /**
468 * Determines whether a dialog can be shown for this preset, i.e., at least one tag can/must be set by the user.
469 *
470 * @return {@code true} if a dialog can be shown for this preset
471 */
472 public boolean isShowable() {
473 // Not using streams makes this method effectively allocation free and uses ~40% fewer CPU cycles.
474 for (TaggingPresetItem i : data) {
475 if (!(i instanceof Optional || i instanceof Space || i instanceof Key)) {
476 return true;
477 }
478 }
479 return false;
480 }
481
482 /**
483 * Suggests a relation role for this primitive
484 *
485 * @param osm The primitive
486 * @return the suggested role or null
487 */
488 public String suggestRoleForOsmPrimitive(OsmPrimitive osm) {
489 if (roles != null && osm != null) {
490 return roles.roles.stream()
491 .filter(i -> i.memberExpression != null && i.memberExpression.match(osm))
492 .filter(i -> Utils.isEmpty(i.types) || i.types.contains(TaggingPresetType.forPrimitive(osm)))
493 .findFirst()
494 .map(i -> i.key)
495 .orElse(null);
496 }
497 return null;
498 }
499
500 @Override
501 public void actionPerformed(ActionEvent e) {
502 DataSet ds = OsmDataManager.getInstance().getEditDataSet();
503 if (ds == null) {
504 return;
505 }
506 showAndApply(ds.getSelected());
507 }
508
509 /**
510 * {@linkplain #showDialog Show preset dialog}, apply changes
511 * @param primitives the primitives
512 */
513 public void showAndApply(Collection<OsmPrimitive> primitives) {
514 // Display dialog even if no data layer (used by preset-tagging-tester plugin)
515 Collection<OsmPrimitive> sel = createSelection(primitives);
516 int answer = showDialog(sel, supportsRelation());
517
518 if (!sel.isEmpty() && answer == DIALOG_ANSWER_APPLY) {
519 Command cmd = createCommand(sel, getChangedTags());
520 if (cmd != null) {
521 UndoRedoHandler.getInstance().add(cmd);
522 }
523 } else if (answer == DIALOG_ANSWER_NEW_RELATION) {
524 Relation calculated = null;
525 if (getChangedTags().stream().anyMatch(t -> "boundary".equals(t.get("type")) || "multipolygon".equals(t.get("type")))) {
526 Collection<Way> ways = Utils.filteredCollection(primitives, Way.class);
527 Pair<Relation, Relation> res = CreateMultipolygonAction.createMultipolygonRelation(ways, true);
528 if (res != null) {
529 calculated = res.b;
530 }
531 }
532 final Relation r = calculated != null ? calculated : new Relation();
533 final Collection<RelationMember> members = new LinkedHashSet<>(r.getMembers());
534 for (Tag t : getChangedTags()) {
535 r.put(t.getKey(), t.getValue());
536 }
537 for (OsmPrimitive osm : primitives) {
538 if (r == calculated && osm instanceof Way)
539 continue;
540 String role = suggestRoleForOsmPrimitive(osm);
541 RelationMember rm = new RelationMember(role == null ? "" : role, osm);
542 r.addMember(rm);
543 members.add(rm);
544 }
545 if (r.isMultipolygon() && r != calculated) {
546 r.setMembers(RelationSorter.sortMembersByConnectivity(r.getMembers()));
547 }
548 SwingUtilities.invokeLater(() -> RelationEditor.getEditor(
549 MainApplication.getLayerManager().getEditLayer(), r, members).setVisible(true));
550 }
551 if (!primitives.isEmpty()) {
552 DataSet ds = primitives.iterator().next().getDataSet();
553 ds.setSelected(primitives); // force update
554 }
555 }
556
557 private static class PresetDialog extends ExtendedDialog {
558
559 /**
560 * Constructs a new {@code PresetDialog}.
561 * @param content the content that will be displayed in this dialog
562 * @param title the text that will be shown in the window titlebar
563 * @param icon the image to be displayed as the icon for this window
564 * @param disableApply whether to disable "Apply" button
565 * @param showNewRelation whether to display "New relation" button
566 */
567 PresetDialog(Component content, String title, ImageIcon icon, boolean disableApply, boolean showNewRelation) {
568 super(MainApplication.getMainFrame(), title,
569 showNewRelation ?
570 (new String[] {tr("Apply Preset"), tr("New relation"), tr("Cancel")}) :
571 (new String[] {tr("Apply Preset"), tr("Cancel")}),
572 true);
573 if (icon != null)
574 setIconImage(icon.getImage());
575 contentInsets = new Insets(10, 5, 0, 5);
576 if (showNewRelation) {
577 setButtonIcons("ok", "data/relation", "cancel");
578 } else {
579 setButtonIcons("ok", "cancel");
580 }
581 configureContextsensitiveHelp("/Menu/Presets", true);
582 setContent(content);
583 setDefaultButton(1);
584 setupDialog();
585 buttons.get(0).setEnabled(!disableApply);
586 buttons.get(0).setToolTipText(title);
587 // Prevent dialogs of being too narrow (fix #6261)
588 Dimension d = getSize();
589 if (d.width < 350) {
590 d.width = 350;
591 setSize(d);
592 }
593 super.showDialog();
594 }
595 }
596
597 /**
598 * Shows the preset dialog.
599 * @param sel selection
600 * @param showNewRelation whether to display "New relation" button
601 * @return the user choice after the dialog has been closed
602 */
603 public int showDialog(Collection<OsmPrimitive> sel, boolean showNewRelation) {
604 PresetPanel p = createPanel(sel);
605
606 int answer = 1;
607 boolean canCreateRelation = types == null || types.contains(TaggingPresetType.RELATION);
608 if (originalSelectionEmpty && !canCreateRelation) {
609 new Notification(
610 tr("The preset <i>{0}</i> cannot be applied since nothing has been selected!", getLocaleName()))
611 .setIcon(JOptionPane.WARNING_MESSAGE)
612 .show();
613 return DIALOG_ANSWER_CANCEL;
614 } else if (sel.isEmpty() && !canCreateRelation) {
615 new Notification(
616 tr("The preset <i>{0}</i> cannot be applied since the selection is unsuitable!", getLocaleName()))
617 .setIcon(JOptionPane.WARNING_MESSAGE)
618 .show();
619 return DIALOG_ANSWER_CANCEL;
620 } else if (p.getComponentCount() != 0 && (sel.isEmpty() || p.hasElements)) {
621 int size = sel.size();
622 String title = trn("Change {0} object", "Change {0} objects", size, size);
623 if (!showNewRelation && size == 0) {
624 if (originalSelectionEmpty) {
625 title = tr("Nothing selected!");
626 } else {
627 title = tr("Selection unsuitable!");
628 }
629 }
630
631 boolean disableApply = size == 0;
632 if (!disableApply) {
633 OsmData<?, ?, ?, ?> ds = sel.iterator().next().getDataSet();
634 disableApply = ds != null && ds.isLocked();
635 }
636 answer = new PresetDialog(p, title, preset_name_label ? null : (ImageIcon) getValue(Action.SMALL_ICON),
637 disableApply, showNewRelation).getValue();
638 }
639 if (!showNewRelation && answer == 2)
640 return DIALOG_ANSWER_CANCEL;
641 else
642 return answer;
643 }
644
645 /**
646 * Removes all unsuitable OsmPrimitives from the given list
647 * @param participants List of possible OsmPrimitives to tag
648 * @return Cleaned list with suitable OsmPrimitives only
649 */
650 public Collection<OsmPrimitive> createSelection(Collection<OsmPrimitive> participants) {
651 originalSelectionEmpty = participants.isEmpty();
652 return participants.stream().filter(this::typeMatches).collect(Collectors.toList());
653 }
654
655 /**
656 * Gets a list of tags that are set by this preset.
657 * @return The list of tags.
658 */
659 public List<Tag> getChangedTags() {
660 List<Tag> result = new ArrayList<>();
661 data.forEach(i -> i.addCommands(result));
662 return result;
663 }
664
665 /**
666 * Create a command to change the given list of tags.
667 * @param sel The primitives to change the tags for
668 * @param changedTags The tags to change
669 * @return A command that changes the tags.
670 */
671 public static Command createCommand(Collection<OsmPrimitive> sel, List<Tag> changedTags) {
672 List<Command> cmds = changedTags.stream()
673 .map(tag -> new ChangePropertyCommand(sel, tag.getKey(), tag.getValue()))
674 .filter(cmd -> cmd.getObjectsNumber() > 0)
675 .collect(StreamUtils.toUnmodifiableList());
676 return cmds.isEmpty() ? null : SequenceCommand.wrapIfNeeded(tr("Change Tags"), cmds);
677 }
678
679 private boolean supportsRelation() {
680 return types == null || types.contains(TaggingPresetType.RELATION);
681 }
682
683 protected final void updateEnabledState() {
684 setEnabled(OsmDataManager.getInstance().getEditDataSet() != null);
685 }
686
687 @Override
688 public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) {
689 updateEnabledState();
690 }
691
692 @Override
693 public String toString() {
694 return (types == null ? "" : types.toString()) + ' ' + name;
695 }
696
697 /**
698 * Determines whether this preset matches the OSM primitive type.
699 * @param primitive The OSM primitive for which type must match
700 * @return <code>true</code> if type matches.
701 * @since 15640
702 */
703 public final boolean typeMatches(IPrimitive primitive) {
704 return typeMatches(EnumSet.of(TaggingPresetType.forPrimitive(primitive)));
705 }
706
707 /**
708 * Determines whether this preset matches the types.
709 * @param t The types that must match
710 * @return <code>true</code> if all types match.
711 */
712 public boolean typeMatches(Collection<TaggingPresetType> t) {
713 return t == null || types == null || types.containsAll(t);
714 }
715
716 /**
717 * Determines whether this preset matches the given primitive, i.e.,
718 * whether the {@link #typeMatches(Collection) type matches} and the {@link TaggingPresetItem#matches(Map) tags match}.
719 *
720 * @param p the primitive
721 * @return {@code true} if this preset matches the primitive
722 * @since 13623 (signature)
723 */
724 @Override
725 public boolean test(IPrimitive p) {
726 return matches(EnumSet.of(TaggingPresetType.forPrimitive(p)), p.getKeys(), false);
727 }
728
729 /**
730 * Determines whether this preset matches the parameters.
731 *
732 * @param t the preset types to include, see {@link #typeMatches(Collection)}
733 * @param tags the tags to perform matching on, see {@link TaggingPresetItem#matches(Map)}
734 * @param onlyShowable whether the preset must be {@link #isShowable() showable}
735 * @return {@code true} if this preset matches the parameters.
736 */
737 public boolean matches(Collection<TaggingPresetType> t, Map<String, String> tags, boolean onlyShowable) {
738 if ((onlyShowable && !isShowable()) || !typeMatches(t)) {
739 return false;
740 } else if (matchExpression != null && !matchExpression.match(Tagged.ofMap(tags))) {
741 return false;
742 } else {
743 return TaggingPresetItem.matches(data, tags);
744 }
745 }
746
747 /**
748 * Action that adds or removes the button on main toolbar
749 */
750 public class ToolbarButtonAction extends AbstractAction {
751 private final int toolbarIndex;
752
753 /**
754 * Constructs a new {@code ToolbarButtonAction}.
755 */
756 public ToolbarButtonAction() {
757 super("");
758 new ImageProvider("dialogs", "pin").getResource().attachImageIcon(this, true);
759 putValue(SHORT_DESCRIPTION, tr("Add or remove toolbar button"));
760 List<String> t = new ArrayList<>(ToolbarPreferences.getToolString());
761 toolbarIndex = t.indexOf(getToolbarString());
762 putValue(SELECTED_KEY, toolbarIndex >= 0);
763 }
764
765 @Override
766 public void actionPerformed(ActionEvent ae) {
767 String res = getToolbarString();
768 MainApplication.getToolbar().addCustomButton(res, toolbarIndex, true);
769 }
770 }
771
772 /**
773 * Gets a string describing this preset that can be used for the toolbar
774 * @return A String that can be passed on to the toolbar
775 * @see ToolbarPreferences#addCustomButton(String, int, boolean)
776 */
777 public String getToolbarString() {
778 ToolbarPreferences.ActionParser actionParser = new ToolbarPreferences.ActionParser(null);
779 return actionParser.saveAction(new ToolbarPreferences.ActionDefinition(this));
780 }
781
782 /**
783 * Returns the completable future task that performs icon loading, if any.
784 * @return the completable future task that performs icon loading, or null
785 * @since 14449
786 */
787 public CompletableFuture<Void> getIconLoadingTask() {
788 return iconFuture;
789 }
790
791}
Note: See TracBrowser for help on using the repository browser.