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

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

see #10512 - taginfoextract: add initial presets extration, switch all links to HTTPS

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