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

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

major code cleanup/refactoring of tagging presets: slay the monster TaggingPresetItems (60 Kb, 1600 lines) and extract all its internal classes to a new package gui.tagging.presets.items

  • Property svn:eol-style set to native
File size: 19.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.Collections;
17import java.util.EnumSet;
18import java.util.HashSet;
19import java.util.LinkedList;
20import java.util.List;
21import java.util.Map;
22import java.util.Set;
23
24import javax.swing.AbstractAction;
25import javax.swing.Action;
26import javax.swing.ImageIcon;
27import javax.swing.JLabel;
28import javax.swing.JOptionPane;
29import javax.swing.JPanel;
30import javax.swing.JToggleButton;
31import javax.swing.SwingUtilities;
32
33import org.openstreetmap.josm.Main;
34import org.openstreetmap.josm.actions.search.SearchCompiler;
35import org.openstreetmap.josm.actions.search.SearchCompiler.Match;
36import org.openstreetmap.josm.command.ChangePropertyCommand;
37import org.openstreetmap.josm.command.Command;
38import org.openstreetmap.josm.command.SequenceCommand;
39import org.openstreetmap.josm.data.osm.DataSet;
40import org.openstreetmap.josm.data.osm.OsmPrimitive;
41import org.openstreetmap.josm.data.osm.Relation;
42import org.openstreetmap.josm.data.osm.RelationMember;
43import org.openstreetmap.josm.data.osm.Tag;
44import org.openstreetmap.josm.gui.ExtendedDialog;
45import org.openstreetmap.josm.gui.MapView;
46import org.openstreetmap.josm.gui.Notification;
47import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor;
48import org.openstreetmap.josm.gui.layer.Layer;
49import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
50import org.openstreetmap.josm.gui.tagging.presets.items.Key;
51import org.openstreetmap.josm.gui.tagging.presets.items.Label;
52import org.openstreetmap.josm.gui.tagging.presets.items.Link;
53import org.openstreetmap.josm.gui.tagging.presets.items.Optional;
54import org.openstreetmap.josm.gui.tagging.presets.items.PresetLink;
55import org.openstreetmap.josm.gui.tagging.presets.items.Roles;
56import org.openstreetmap.josm.gui.tagging.presets.items.Roles.Role;
57import org.openstreetmap.josm.gui.tagging.presets.items.Space;
58import org.openstreetmap.josm.gui.util.GuiHelper;
59import org.openstreetmap.josm.tools.GBC;
60import org.openstreetmap.josm.tools.ImageProvider;
61import org.openstreetmap.josm.tools.ImageResource;
62import org.openstreetmap.josm.tools.Predicate;
63import org.openstreetmap.josm.tools.Utils;
64import org.openstreetmap.josm.tools.template_engine.ParseError;
65import org.openstreetmap.josm.tools.template_engine.TemplateEntry;
66import org.openstreetmap.josm.tools.template_engine.TemplateParser;
67import org.xml.sax.SAXException;
68
69/**
70 * This class read encapsulate one tagging preset. A class method can
71 * read in all predefined presets, either shipped with JOSM or that are
72 * in the config directory.
73 *
74 * It is also able to construct dialogs out of preset definitions.
75 * @since 294
76 */
77public class TaggingPreset extends AbstractAction implements MapView.LayerChangeListener, Predicate<OsmPrimitive> {
78
79 public static final int DIALOG_ANSWER_APPLY = 1;
80 public static final int DIALOG_ANSWER_NEW_RELATION = 2;
81 public static final int DIALOG_ANSWER_CANCEL = 3;
82
83 public static final String OPTIONAL_TOOLTIP_TEXT = "Optional tooltip text";
84
85 public TaggingPresetMenu group;
86 public String name;
87 public String iconName;
88 public String name_context;
89 public String locale_name;
90 public boolean preset_name_label;
91
92 /**
93 * The types as preparsed collection.
94 */
95 public Set<TaggingPresetType> types;
96 public transient List<TaggingPresetItem> data = new LinkedList<>();
97 public transient Roles roles;
98 public transient TemplateEntry nameTemplate;
99 public transient Match nameTemplateFilter;
100
101 /**
102 * True whenever the original selection given into createSelection was empty
103 */
104 private boolean originalSelectionEmpty;
105
106 /**
107 * Create an empty tagging preset. This will not have any items and
108 * will be an empty string as text. createPanel will return null.
109 * Use this as default item for "do not select anything".
110 */
111 public TaggingPreset() {
112 MapView.addLayerChangeListener(this);
113 updateEnabledState();
114 }
115
116 /**
117 * Change the display name without changing the toolbar value.
118 */
119 public void setDisplayName() {
120 putValue(Action.NAME, getName());
121 putValue("toolbar", "tagging_" + getRawName());
122 putValue(OPTIONAL_TOOLTIP_TEXT, group != null ?
123 tr("Use preset ''{0}'' of group ''{1}''", getLocaleName(), group.getName()) :
124 tr("Use preset ''{0}''", getLocaleName()));
125 }
126
127 public String getLocaleName() {
128 if (locale_name == null) {
129 if (name_context != null) {
130 locale_name = trc(name_context, TaggingPresetItem.fixPresetString(name));
131 } else {
132 locale_name = tr(TaggingPresetItem.fixPresetString(name));
133 }
134 }
135 return locale_name;
136 }
137
138 /**
139 * Returns the translated name of this preset, prefixed with the group names it belongs to.
140 */
141 public String getName() {
142 return group != null ? group.getName() + '/' + getLocaleName() : getLocaleName();
143 }
144
145 /**
146 * Returns the non translated name of this preset, prefixed with the (non translated) group names it belongs to.
147 */
148 public String getRawName() {
149 return group != null ? group.getRawName() + '/' + name : name;
150 }
151
152 /**
153 * Returns the preset icon.
154 * @return The preset icon, or {@code null} if none defined
155 * @since 6403
156 */
157 public final ImageIcon getIcon() {
158 Object icon = getValue(Action.SMALL_ICON);
159 if (icon instanceof ImageIcon) {
160 return (ImageIcon) icon;
161 }
162 return null;
163 }
164
165 /**
166 * Called from the XML parser to set the icon.
167 * The loading task is performed in the background in order to speedup startup.
168 */
169 public void setIcon(final String iconName) {
170 this.iconName = iconName;
171 if (!TaggingPresetReader.isLoadIcons()) {
172 return;
173 }
174 File arch = TaggingPresetReader.getZipIcons();
175 final Collection<String> s = Main.pref.getCollection("taggingpreset.icon.sources", null);
176 ImageProvider imgProv = new ImageProvider(iconName);
177 imgProv.setDirs(s);
178 imgProv.setId("presets");
179 imgProv.setArchive(arch);
180 imgProv.setOptional(true);
181 imgProv.getInBackground(new ImageProvider.ImageResourceCallback() {
182 @Override
183 public void finished(final ImageResource result) {
184 if (result != null) {
185 GuiHelper.runInEDT(new Runnable() {
186 @Override
187 public void run() {
188 result.getImageIcon(TaggingPreset.this);
189 }
190 });
191 } else {
192 Main.warn("Could not get presets icon " + iconName);
193 }
194 }
195 });
196 }
197
198 /**
199 * Called from the XML parser to set the types this preset affects.
200 */
201 public void setType(String types) throws SAXException {
202 this.types = TaggingPresetItem.getType(types);
203 }
204
205 public void setName_template(String pattern) throws SAXException {
206 try {
207 this.nameTemplate = new TemplateParser(pattern).parse();
208 } catch (ParseError e) {
209 Main.error("Error while parsing " + pattern + ": " + e.getMessage());
210 throw new SAXException(e);
211 }
212 }
213
214 public void setName_template_filter(String filter) throws SAXException {
215 try {
216 this.nameTemplateFilter = SearchCompiler.compile(filter);
217 } catch (org.openstreetmap.josm.actions.search.SearchCompiler.ParseError e) {
218 Main.error("Error while parsing" + filter + ": " + e.getMessage());
219 throw new SAXException(e);
220 }
221 }
222
223 private static class PresetPanel extends JPanel {
224 private boolean hasElements;
225
226 PresetPanel() {
227 super(new GridBagLayout());
228 }
229 }
230
231 public PresetPanel createPanel(Collection<OsmPrimitive> selected) {
232 if (data == null)
233 return null;
234 PresetPanel p = new PresetPanel();
235 List<Link> l = new LinkedList<>();
236 List<PresetLink> presetLink = new LinkedList<>();
237 if (types != null) {
238 JPanel pp = new JPanel();
239 for (TaggingPresetType t : types) {
240 JLabel la = new JLabel(ImageProvider.get(t.getIconName()));
241 la.setToolTipText(tr("Elements of type {0} are supported.", tr(t.getName())));
242 pp.add(la);
243 }
244 p.add(pp, GBC.eol());
245 }
246 if (preset_name_label) {
247 Label.addLabel(p, getIcon(), getName());
248 }
249
250 boolean presetInitiallyMatches = !selected.isEmpty() && Utils.forAll(selected, this);
251 JPanel items = new JPanel(new GridBagLayout());
252 for (TaggingPresetItem i : data) {
253 if (i instanceof Link) {
254 l.add((Link) i);
255 p.hasElements = true;
256 } else if (i instanceof PresetLink) {
257 presetLink.add((PresetLink) i);
258 } else {
259 if (i.addToPanel(items, selected, presetInitiallyMatches)) {
260 p.hasElements = true;
261 }
262 }
263 }
264 p.add(items, GBC.eol().fill());
265 if (selected.isEmpty() && !supportsRelation()) {
266 GuiHelper.setEnabledRec(items, false);
267 }
268
269 // add PresetLink
270 if (!presetLink.isEmpty()) {
271 p.add(new JLabel(tr("Edit also …")), GBC.eol().insets(0, 8, 0, 0));
272 for (PresetLink link : presetLink) {
273 link.addToPanel(p, selected, presetInitiallyMatches);
274 }
275 }
276
277 // add Link
278 for (Link link : l) {
279 link.addToPanel(p, selected, presetInitiallyMatches);
280 }
281
282 // "Add toolbar button"
283 JToggleButton tb = new JToggleButton(new ToolbarButtonAction());
284 tb.setFocusable(false);
285 p.add(tb, GBC.std(0, 0).anchor(GBC.LINE_END));
286 return p;
287 }
288
289 public boolean isShowable() {
290 for (TaggingPresetItem i : data) {
291 if (!(i instanceof Optional || i instanceof Space || i instanceof Key))
292 return true;
293 }
294 return false;
295 }
296
297 public String suggestRoleForOsmPrimitive(OsmPrimitive osm) {
298 if (roles != null && osm != null) {
299 for (Role i : roles.roles) {
300 if (i.memberExpression != null && i.memberExpression.match(osm)
301 && (i.types == null || i.types.isEmpty() || i.types.contains(TaggingPresetType.forPrimitive(osm)))) {
302 return i.key;
303 }
304 }
305 }
306 return null;
307 }
308
309 @Override
310 public void actionPerformed(ActionEvent e) {
311 if (Main.main == null) {
312 return;
313 }
314 DataSet ds = Main.main.getCurrentDataSet();
315 Collection<OsmPrimitive> participants = Collections.emptyList();
316 if (Main.main != null && ds != null) {
317 participants = ds.getSelected();
318 }
319
320 // Display dialog even if no data layer (used by preset-tagging-tester plugin)
321 Collection<OsmPrimitive> sel = createSelection(participants);
322 int answer = showDialog(sel, supportsRelation());
323
324 if (ds == null) {
325 return;
326 }
327
328 if (!sel.isEmpty() && answer == DIALOG_ANSWER_APPLY) {
329 Command cmd = createCommand(sel, getChangedTags());
330 if (cmd != null) {
331 Main.main.undoRedo.add(cmd);
332 }
333 } else if (answer == DIALOG_ANSWER_NEW_RELATION) {
334 final Relation r = new Relation();
335 final Collection<RelationMember> members = new HashSet<>();
336 for (Tag t : getChangedTags()) {
337 r.put(t.getKey(), t.getValue());
338 }
339 for (OsmPrimitive osm : ds.getSelected()) {
340 String role = suggestRoleForOsmPrimitive(osm);
341 RelationMember rm = new RelationMember(role == null ? "" : role, osm);
342 r.addMember(rm);
343 members.add(rm);
344 }
345 SwingUtilities.invokeLater(new Runnable() {
346 @Override
347 public void run() {
348 RelationEditor.getEditor(Main.main.getEditLayer(), r, members).setVisible(true);
349 }
350 });
351 }
352 ds.setSelected(ds.getSelected()); // force update
353 }
354
355 private static class PresetDialog extends ExtendedDialog {
356 PresetDialog(Component content, String title, ImageIcon icon, boolean disableApply, boolean showNewRelation) {
357 super(Main.parent, title,
358 showNewRelation ?
359 new String[] {tr("Apply Preset"), tr("New relation"), tr("Cancel")} :
360 new String[] {tr("Apply Preset"), tr("Cancel")},
361 true);
362 if (icon != null)
363 setIconImage(icon.getImage());
364 contentInsets = new Insets(10, 5, 0, 5);
365 if (showNewRelation) {
366 setButtonIcons(new String[] {"ok", "dialogs/addrelation", "cancel" });
367 } else {
368 setButtonIcons(new String[] {"ok", "cancel" });
369 }
370 setContent(content);
371 setDefaultButton(1);
372 setupDialog();
373 buttons.get(0).setEnabled(!disableApply);
374 buttons.get(0).setToolTipText(title);
375 // Prevent dialogs of being too narrow (fix #6261)
376 Dimension d = getSize();
377 if (d.width < 350) {
378 d.width = 350;
379 setSize(d);
380 }
381 showDialog();
382 }
383 }
384
385 public int showDialog(Collection<OsmPrimitive> sel, boolean showNewRelation) {
386 PresetPanel p = createPanel(sel);
387 if (p == null)
388 return DIALOG_ANSWER_CANCEL;
389
390 int answer = 1;
391 boolean canCreateRelation = types == null || types.contains(TaggingPresetType.RELATION);
392 if (originalSelectionEmpty && !canCreateRelation) {
393 new Notification(
394 tr("The preset <i>{0}</i> cannot be applied since nothing has been selected!", getLocaleName()))
395 .setIcon(JOptionPane.WARNING_MESSAGE)
396 .show();
397 return DIALOG_ANSWER_CANCEL;
398 } else if (sel.isEmpty() && !canCreateRelation) {
399 new Notification(
400 tr("The preset <i>{0}</i> cannot be applied since the selection is unsuitable!", getLocaleName()))
401 .setIcon(JOptionPane.WARNING_MESSAGE)
402 .show();
403 return DIALOG_ANSWER_CANCEL;
404 } else if (p.getComponentCount() != 0 && (sel.isEmpty() || p.hasElements)) {
405 String title = trn("Change {0} object", "Change {0} objects", sel.size(), sel.size());
406 if (sel.isEmpty()) {
407 if (originalSelectionEmpty) {
408 title = tr("Nothing selected!");
409 } else {
410 title = tr("Selection unsuitable!");
411 }
412 }
413
414 answer = new PresetDialog(p, title, preset_name_label ? null : (ImageIcon) getValue(Action.SMALL_ICON),
415 sel.isEmpty(), showNewRelation).getValue();
416 }
417 if (!showNewRelation && answer == 2)
418 return DIALOG_ANSWER_CANCEL;
419 else
420 return answer;
421 }
422
423 /**
424 * Removes all unsuitable OsmPrimitives from the given list
425 * @param participants List of possible OsmPrimitives to tag
426 * @return Cleaned list with suitable OsmPrimitives only
427 */
428 public Collection<OsmPrimitive> createSelection(Collection<OsmPrimitive> participants) {
429 originalSelectionEmpty = participants.isEmpty();
430 Collection<OsmPrimitive> sel = new LinkedList<>();
431 for (OsmPrimitive osm : participants) {
432 if (typeMatches(EnumSet.of(TaggingPresetType.forPrimitive(osm)))) {
433 sel.add(osm);
434 }
435 }
436 return sel;
437 }
438
439 public List<Tag> getChangedTags() {
440 List<Tag> result = new ArrayList<>();
441 for (TaggingPresetItem i: data) {
442 i.addCommands(result);
443 }
444 return result;
445 }
446
447 public static Command createCommand(Collection<OsmPrimitive> sel, List<Tag> changedTags) {
448 List<Command> cmds = new ArrayList<>();
449 for (Tag tag: changedTags) {
450 cmds.add(new ChangePropertyCommand(sel, tag.getKey(), tag.getValue()));
451 }
452
453 if (cmds.isEmpty())
454 return null;
455 else if (cmds.size() == 1)
456 return cmds.get(0);
457 else
458 return new SequenceCommand(tr("Change Tags"), cmds);
459 }
460
461 private boolean supportsRelation() {
462 return types == null || types.contains(TaggingPresetType.RELATION);
463 }
464
465 protected final void updateEnabledState() {
466 setEnabled(Main.main != null && Main.main.getCurrentDataSet() != null);
467 }
468
469 @Override
470 public void activeLayerChange(Layer oldLayer, Layer newLayer) {
471 updateEnabledState();
472 }
473
474 @Override
475 public void layerAdded(Layer newLayer) {
476 updateEnabledState();
477 }
478
479 @Override
480 public void layerRemoved(Layer oldLayer) {
481 updateEnabledState();
482 }
483
484 @Override
485 public String toString() {
486 return (types == null ? "" : types) + " " + name;
487 }
488
489 public boolean typeMatches(Collection<TaggingPresetType> t) {
490 return t == null || types == null || types.containsAll(t);
491 }
492
493 @Override
494 public boolean evaluate(OsmPrimitive p) {
495 return matches(EnumSet.of(TaggingPresetType.forPrimitive(p)), p.getKeys(), false);
496 }
497
498 public boolean matches(Collection<TaggingPresetType> t, Map<String, String> tags, boolean onlyShowable) {
499 if (onlyShowable && !isShowable())
500 return false;
501 else if (!typeMatches(t))
502 return false;
503 boolean atLeastOnePositiveMatch = false;
504 for (TaggingPresetItem item : data) {
505 Boolean m = item.matches(tags);
506 if (m != null && !m)
507 return false;
508 else if (m != null) {
509 atLeastOnePositiveMatch = true;
510 }
511 }
512 return atLeastOnePositiveMatch;
513 }
514
515 public static Collection<TaggingPreset> getMatchingPresets(final Collection<TaggingPresetType> t,
516 final Map<String, String> tags, final boolean onlyShowable) {
517 return Utils.filter(TaggingPresets.getTaggingPresets(), new Predicate<TaggingPreset>() {
518 @Override
519 public boolean evaluate(TaggingPreset object) {
520 return object.matches(t, tags, onlyShowable);
521 }
522 });
523 }
524
525 /**
526 * Action that adds or removes the button on main toolbar
527 */
528 public class ToolbarButtonAction extends AbstractAction {
529 private final int toolbarIndex;
530
531 /**
532 * Constructs a new {@code ToolbarButtonAction}.
533 */
534 public ToolbarButtonAction() {
535 super("", ImageProvider.get("dialogs", "pin"));
536 putValue(SHORT_DESCRIPTION, tr("Add or remove toolbar button"));
537 List<String> t = new LinkedList<>(ToolbarPreferences.getToolString());
538 toolbarIndex = t.indexOf(getToolbarString());
539 putValue(SELECTED_KEY, toolbarIndex >= 0);
540 }
541
542 @Override
543 public void actionPerformed(ActionEvent ae) {
544 String res = getToolbarString();
545 Main.toolbar.addCustomButton(res, toolbarIndex, true);
546 }
547 }
548
549 public String getToolbarString() {
550 ToolbarPreferences.ActionParser actionParser = new ToolbarPreferences.ActionParser(null);
551 return actionParser.saveAction(new ToolbarPreferences.ActionDefinition(this));
552 }
553}
Note: See TracBrowser for help on using the repository browser.