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

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

fix some Sonar issues

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