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

Last change on this file since 8792 was 8710, checked in by simon04, 9 years ago

see #11795 - taginfoextract: avoid "Could not get presets icon" by not loading icons

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