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

Last change on this file since 17829 was 17662, checked in by simon04, 4 years ago

fix #19012 - Tagging presets: additional matching criteria via <item match_expression="...">

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