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

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

remove extra whitespaces

  • Property svn:eol-style set to native
File size: 18.6 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 public String getName() {
127 return group != null ? group.getName() + "/" + getLocaleName() : getLocaleName();
128 }
129 public String getRawName() {
130 return group != null ? group.getRawName() + "/" + name : name;
131 }
132
133 /**
134 * Returns the preset icon.
135 * @return The preset icon, or {@code null} if none defined
136 * @since 6403
137 */
138 public final ImageIcon getIcon() {
139 Object icon = getValue(Action.SMALL_ICON);
140 if (icon instanceof ImageIcon) {
141 return (ImageIcon) icon;
142 }
143 return null;
144 }
145
146 /**
147 * Called from the XML parser to set the icon.
148 * This task is performed in the background in order to speedup startup.
149 */
150 public void setIcon(final String iconName) {
151 this.iconName = iconName;
152 File arch = TaggingPresetReader.getZipIcons();
153 final Collection<String> s = Main.pref.getCollection("taggingpreset.icon.sources", null);
154 ImageProvider imgProv = new ImageProvider(iconName);
155 imgProv.setDirs(s);
156 imgProv.setId("presets");
157 imgProv.setArchive(arch);
158 imgProv.setOptional(true);
159 imgProv.getInBackground(new ImageProvider.ImageResourceCallback() {
160 @Override
161 public void finished(final ImageResource result) {
162 if (result != null) {
163 GuiHelper.runInEDT(new Runnable() {
164 @Override
165 public void run() {
166 result.getImageIcon(TaggingPreset.this);
167 }
168 });
169 } else {
170 Main.warn("Could not get presets icon " + iconName);
171 }
172 }
173 });
174 }
175
176 /**
177 * Called from the XML parser to set the types this preset affects.
178 */
179 public void setType(String types) throws SAXException {
180 this.types = TaggingPresetItems.getType(types);
181 }
182
183 public void setName_template(String pattern) throws SAXException {
184 try {
185 this.nameTemplate = new TemplateParser(pattern).parse();
186 } catch (ParseError e) {
187 Main.error("Error while parsing " + pattern + ": " + e.getMessage());
188 throw new SAXException(e);
189 }
190 }
191
192 public void setName_template_filter(String filter) throws SAXException {
193 try {
194 this.nameTemplateFilter = SearchCompiler.compile(filter, false, false);
195 } catch (org.openstreetmap.josm.actions.search.SearchCompiler.ParseError e) {
196 Main.error("Error while parsing" + filter + ": " + e.getMessage());
197 throw new SAXException(e);
198 }
199 }
200
201 private static class PresetPanel extends JPanel {
202 private boolean hasElements = false;
203 PresetPanel() {
204 super(new GridBagLayout());
205 }
206 }
207
208 public PresetPanel createPanel(Collection<OsmPrimitive> selected) {
209 if (data == null)
210 return null;
211 PresetPanel p = new PresetPanel();
212 List<Link> l = new LinkedList<>();
213 List<PresetLink> presetLink = new LinkedList<>();
214 if (types != null){
215 JPanel pp = new JPanel();
216 for (TaggingPresetType t : types) {
217 JLabel la = new JLabel(ImageProvider.get(t.getIconName()));
218 la.setToolTipText(tr("Elements of type {0} are supported.", tr(t.getName())));
219 pp.add(la);
220 }
221 p.add(pp, GBC.eol());
222 }
223 if (preset_name_label) {
224 TaggingPresetItems.Label.addLabel(p, getIcon(), getName());
225 }
226
227 boolean presetInitiallyMatches = !selected.isEmpty() && Utils.forAll(selected, this);
228 JPanel items = new JPanel(new GridBagLayout());
229 for (TaggingPresetItem i : data) {
230 if (i instanceof Link) {
231 l.add((Link) i);
232 p.hasElements = true;
233 } else if (i instanceof PresetLink) {
234 presetLink.add((PresetLink) i);
235 } else {
236 if (i.addToPanel(items, selected, presetInitiallyMatches)) {
237 p.hasElements = true;
238 }
239 }
240 }
241 p.add(items, GBC.eol().fill());
242 if (selected.isEmpty() && !supportsRelation()) {
243 GuiHelper.setEnabledRec(items, false);
244 }
245
246 // add PresetLink
247 if (!presetLink.isEmpty()) {
248 p.add(new JLabel(tr("Edit also …")), GBC.eol().insets(0, 8, 0, 0));
249 for (PresetLink link : presetLink) {
250 link.addToPanel(p, selected, presetInitiallyMatches);
251 }
252 }
253
254 // add Link
255 for (Link link : l) {
256 link.addToPanel(p, selected, presetInitiallyMatches);
257 }
258
259 // "Add toolbar button"
260 JToggleButton tb = new JToggleButton(new ToolbarButtonAction());
261 tb.setFocusable(false);
262 p.add(tb, GBC.std(0,0).anchor(GBC.LINE_END));
263 return p;
264 }
265
266 public boolean isShowable() {
267 for (TaggingPresetItem i : data) {
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) {
289 return;
290 }
291 DataSet ds = Main.main.getCurrentDataSet();
292 Collection<OsmPrimitive> participants = Collections.emptyList();
293 if (Main.main != null && ds != null) {
294 participants = ds.getSelected();
295 }
296
297 // Display dialog even if no data layer (used by preset-tagging-tester plugin)
298 Collection<OsmPrimitive> sel = createSelection(participants);
299 int answer = showDialog(sel, supportsRelation());
300
301 if (ds == null) {
302 return;
303 }
304
305 if (!sel.isEmpty() && answer == DIALOG_ANSWER_APPLY) {
306 Command cmd = createCommand(sel, getChangedTags());
307 if (cmd != null) {
308 Main.main.undoRedo.add(cmd);
309 }
310 } else if (answer == DIALOG_ANSWER_NEW_RELATION) {
311 final Relation r = new Relation();
312 final Collection<RelationMember> members = new HashSet<>();
313 for(Tag t : getChangedTags()) {
314 r.put(t.getKey(), t.getValue());
315 }
316 for (OsmPrimitive osm : ds.getSelected()) {
317 String role = suggestRoleForOsmPrimitive(osm);
318 RelationMember rm = new RelationMember(role == null ? "" : role, osm);
319 r.addMember(rm);
320 members.add(rm);
321 }
322 SwingUtilities.invokeLater(new Runnable() {
323 @Override
324 public void run() {
325 RelationEditor.getEditor(Main.main.getEditLayer(), r, members).setVisible(true);
326 }
327 });
328 }
329 ds.setSelected(ds.getSelected()); // force update
330 }
331
332 private static class PresetDialog extends ExtendedDialog {
333 public PresetDialog(Component content, String title, ImageIcon icon, boolean disableApply, boolean showNewRelation) {
334 super(Main.parent, title,
335 showNewRelation?
336 new String[] {tr("Apply Preset"), tr("New relation"), tr("Cancel")} :
337 new String[] {tr("Apply Preset"), tr("Cancel")},
338 true);
339 if (icon != null)
340 setIconImage(icon.getImage());
341 contentInsets = new Insets(10,5,0,5);
342 if (showNewRelation) {
343 setButtonIcons(new String[] {"ok", "dialogs/addrelation", "cancel" });
344 } else {
345 setButtonIcons(new String[] {"ok", "cancel" });
346 }
347 setContent(content);
348 setDefaultButton(1);
349 setupDialog();
350 buttons.get(0).setEnabled(!disableApply);
351 buttons.get(0).setToolTipText(title);
352 // Prevent dialogs of being too narrow (fix #6261)
353 Dimension d = getSize();
354 if (d.width < 350) {
355 d.width = 350;
356 setSize(d);
357 }
358 showDialog();
359 }
360 }
361
362 public int showDialog(Collection<OsmPrimitive> sel, boolean showNewRelation) {
363 PresetPanel p = createPanel(sel);
364 if (p == null)
365 return DIALOG_ANSWER_CANCEL;
366
367 int answer = 1;
368 if (p.getComponentCount() != 0 && (sel.isEmpty() || p.hasElements)) {
369 String title = trn("Change {0} object", "Change {0} objects", sel.size(), sel.size());
370 if(sel.isEmpty()) {
371 if(originalSelectionEmpty) {
372 title = tr("Nothing selected!");
373 } else {
374 title = tr("Selection unsuitable!");
375 }
376 }
377
378 answer = new PresetDialog(p, title, preset_name_label ? null : (ImageIcon) getValue(Action.SMALL_ICON),
379 sel.isEmpty(), showNewRelation).getValue();
380 }
381 if (!showNewRelation && answer == 2)
382 return DIALOG_ANSWER_CANCEL;
383 else
384 return answer;
385 }
386
387 /**
388 * True whenever the original selection given into createSelection was empty
389 */
390 private boolean originalSelectionEmpty = false;
391
392 /**
393 * Removes all unsuitable OsmPrimitives from the given list
394 * @param participants List of possible OsmPrimitives to tag
395 * @return Cleaned list with suitable OsmPrimitives only
396 */
397 public Collection<OsmPrimitive> createSelection(Collection<OsmPrimitive> participants) {
398 originalSelectionEmpty = participants.isEmpty();
399 Collection<OsmPrimitive> sel = new LinkedList<>();
400 for (OsmPrimitive osm : participants) {
401 if (typeMatches(EnumSet.of(TaggingPresetType.forPrimitive(osm)))) {
402 sel.add(osm);
403 }
404 }
405 return sel;
406 }
407
408 public List<Tag> getChangedTags() {
409 List<Tag> result = new ArrayList<>();
410 for (TaggingPresetItem i: data) {
411 i.addCommands(result);
412 }
413 return result;
414 }
415
416 public static Command createCommand(Collection<OsmPrimitive> sel, List<Tag> changedTags) {
417 List<Command> cmds = new ArrayList<>();
418 for (Tag tag: changedTags) {
419 cmds.add(new ChangePropertyCommand(sel, tag.getKey(), tag.getValue()));
420 }
421
422 if (cmds.isEmpty())
423 return null;
424 else if (cmds.size() == 1)
425 return cmds.get(0);
426 else
427 return new SequenceCommand(tr("Change Tags"), cmds);
428 }
429
430 private boolean supportsRelation() {
431 return types == null || types.contains(TaggingPresetType.RELATION);
432 }
433
434 protected final void updateEnabledState() {
435 setEnabled(Main.main != null && Main.main.getCurrentDataSet() != null);
436 }
437
438 @Override
439 public void activeLayerChange(Layer oldLayer, Layer newLayer) {
440 updateEnabledState();
441 }
442
443 @Override
444 public void layerAdded(Layer newLayer) {
445 updateEnabledState();
446 }
447
448 @Override
449 public void layerRemoved(Layer oldLayer) {
450 updateEnabledState();
451 }
452
453 @Override
454 public String toString() {
455 return (types == null?"":types) + " " + name;
456 }
457
458 public boolean typeMatches(Collection<TaggingPresetType> t) {
459 return t == null || types == null || types.containsAll(t);
460 }
461
462 @Override
463 public boolean evaluate(OsmPrimitive p) {
464 return matches(EnumSet.of(TaggingPresetType.forPrimitive(p)), p.getKeys(), false);
465 }
466
467 public boolean matches(Collection<TaggingPresetType> t, Map<String, String> tags, boolean onlyShowable) {
468 if (onlyShowable && !isShowable())
469 return false;
470 else if (!typeMatches(t))
471 return false;
472 boolean atLeastOnePositiveMatch = false;
473 for (TaggingPresetItem item : data) {
474 Boolean m = item.matches(tags);
475 if (m != null && !m)
476 return false;
477 else if (m != null) {
478 atLeastOnePositiveMatch = true;
479 }
480 }
481 return atLeastOnePositiveMatch;
482 }
483
484 public static Collection<TaggingPreset> getMatchingPresets(final Collection<TaggingPresetType> t, final Map<String, String> tags, final boolean onlyShowable) {
485 return Utils.filter(TaggingPresets.getTaggingPresets(), new Predicate<TaggingPreset>() {
486 @Override
487 public boolean evaluate(TaggingPreset object) {
488 return object.matches(t, tags, onlyShowable);
489 }
490 });
491 }
492
493 /**
494 * Action that adds or removes the button on main toolbar
495 */
496 public class ToolbarButtonAction extends AbstractAction {
497 private final int toolbarIndex;
498
499 /**
500 * Constructs a new {@code ToolbarButtonAction}.
501 */
502 public ToolbarButtonAction() {
503 super("", ImageProvider.get("dialogs", "pin"));
504 putValue(SHORT_DESCRIPTION, tr("Add or remove toolbar button"));
505 List<String> t = new LinkedList<>(ToolbarPreferences.getToolString());
506 toolbarIndex = t.indexOf(getToolbarString());
507 putValue(SELECTED_KEY, toolbarIndex >= 0);
508 }
509
510 @Override
511 public void actionPerformed(ActionEvent ae) {
512 String res = getToolbarString();
513 Main.toolbar.addCustomButton(res, toolbarIndex, true);
514 }
515 }
516
517 public String getToolbarString() {
518 ToolbarPreferences.ActionParser actionParser = new ToolbarPreferences.ActionParser(null);
519 return actionParser.saveAction(new ToolbarPreferences.ActionDefinition(this));
520 }
521}
Note: See TracBrowser for help on using the repository browser.