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

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

global use of Utils.isEmpty/isBlank

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