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

Last change on this file since 16585 was 16585, checked in by GerdP, 4 years ago

fix #14228: Order the members when creating boundaries and multipolygons

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