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