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

Last change on this file since 6068 was 6068, checked in by akks, 11 years ago

see #8853: Massive (and dumb) refactoring of TaggingPreset class (splitting into smaller files)
Separate preset-choosing panel (TaggingPresetSelector class) for reuse not only in F3.

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