source: josm/trunk/src/org/openstreetmap/josm/gui/DefaultNameFormatter.java@ 7112

Last change on this file since 7112 was 7112, checked in by simon04, 10 years ago

fix #9880 - Recognise building=(!yes) relations as buildings (name formatter)

  • Property svn:eol-style set to native
File size: 24.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trc;
6import static org.openstreetmap.josm.tools.I18n.trc_lazy;
7import static org.openstreetmap.josm.tools.I18n.trn;
8
9import java.util.ArrayList;
10import java.util.Arrays;
11import java.util.Collection;
12import java.util.Collections;
13import java.util.Comparator;
14import java.util.HashSet;
15import java.util.LinkedList;
16import java.util.List;
17import java.util.Map;
18import java.util.Set;
19
20import org.openstreetmap.josm.Main;
21import org.openstreetmap.josm.data.coor.CoordinateFormat;
22import org.openstreetmap.josm.data.coor.LatLon;
23import org.openstreetmap.josm.data.osm.Changeset;
24import org.openstreetmap.josm.data.osm.IPrimitive;
25import org.openstreetmap.josm.data.osm.IRelation;
26import org.openstreetmap.josm.data.osm.NameFormatter;
27import org.openstreetmap.josm.data.osm.Node;
28import org.openstreetmap.josm.data.osm.OsmPrimitive;
29import org.openstreetmap.josm.data.osm.OsmUtils;
30import org.openstreetmap.josm.data.osm.Relation;
31import org.openstreetmap.josm.data.osm.Way;
32import org.openstreetmap.josm.data.osm.history.HistoryNameFormatter;
33import org.openstreetmap.josm.data.osm.history.HistoryNode;
34import org.openstreetmap.josm.data.osm.history.HistoryOsmPrimitive;
35import org.openstreetmap.josm.data.osm.history.HistoryRelation;
36import org.openstreetmap.josm.data.osm.history.HistoryWay;
37import org.openstreetmap.josm.gui.tagging.TaggingPreset;
38import org.openstreetmap.josm.tools.AlphanumComparator;
39import org.openstreetmap.josm.tools.I18n;
40import org.openstreetmap.josm.tools.TaggingPresetNameTemplateList;
41import org.openstreetmap.josm.tools.Utils;
42import org.openstreetmap.josm.tools.Utils.Function;
43
44/**
45 * This is the default implementation of a {@link NameFormatter} for names of {@link OsmPrimitive}s.
46 *
47 */
48public class DefaultNameFormatter implements NameFormatter, HistoryNameFormatter {
49
50 private static DefaultNameFormatter instance;
51
52 private static final List<NameFormatterHook> formatHooks = new LinkedList<>();
53
54 /**
55 * Replies the unique instance of this formatter
56 *
57 * @return the unique instance of this formatter
58 */
59 public static DefaultNameFormatter getInstance() {
60 if (instance == null) {
61 instance = new DefaultNameFormatter();
62 }
63 return instance;
64 }
65
66 /**
67 * Registers a format hook. Adds the hook at the first position of the format hooks.
68 * (for plugins)
69 *
70 * @param hook the format hook. Ignored if null.
71 */
72 public static void registerFormatHook(NameFormatterHook hook) {
73 if (hook == null) return;
74 if (!formatHooks.contains(hook)) {
75 formatHooks.add(0,hook);
76 }
77 }
78
79 /**
80 * Unregisters a format hook. Removes the hook from the list of format hooks.
81 *
82 * @param hook the format hook. Ignored if null.
83 */
84 public static void unregisterFormatHook(NameFormatterHook hook) {
85 if (hook == null) return;
86 if (formatHooks.contains(hook)) {
87 formatHooks.remove(hook);
88 }
89 }
90
91 /** The default list of tags which are used as naming tags in relations.
92 * A ? prefix indicates a boolean value, for which the key (instead of the value) is used.
93 */
94 public static final String[] DEFAULT_NAMING_TAGS_FOR_RELATIONS = {"name", "ref", "restriction", "landuse", "natural",
95 "public_transport", ":LocationCode", "note", "?building"};
96
97 /** the current list of tags used as naming tags in relations */
98 private static List<String> namingTagsForRelations = null;
99
100 /**
101 * Replies the list of naming tags used in relations. The list is given (in this order) by:
102 * <ul>
103 * <li>by the tag names in the preference <tt>relation.nameOrder</tt></li>
104 * <li>by the default tags in {@link #DEFAULT_NAMING_TAGS_FOR_RELATIONS}
105 * </ul>
106 *
107 * @return the list of naming tags used in relations
108 */
109 public static List<String> getNamingtagsForRelations() {
110 if (namingTagsForRelations == null) {
111 namingTagsForRelations = new ArrayList<>(
112 Main.pref.getCollection("relation.nameOrder", Arrays.asList(DEFAULT_NAMING_TAGS_FOR_RELATIONS))
113 );
114 }
115 return namingTagsForRelations;
116 }
117
118 /**
119 * Decorates the name of primitive with its id, if the preference
120 * <tt>osm-primitives.showid</tt> is set. Shows unique id if osm-primitives.showid.new-primitives is set
121 *
122 * @param name the name without the id
123 * @param primitive the primitive
124 */
125 protected void decorateNameWithId(StringBuilder name, IPrimitive primitive) {
126 if (Main.pref.getBoolean("osm-primitives.showid")) {
127 if (Main.pref.getBoolean("osm-primitives.showid.new-primitives")) {
128 name.append(tr(" [id: {0}]", primitive.getUniqueId()));
129 } else {
130 name.append(tr(" [id: {0}]", primitive.getId()));
131 }
132 }
133 }
134
135 /**
136 * Formats a name for a node
137 *
138 * @param node the node
139 * @return the name
140 */
141 @Override
142 public String format(Node node) {
143 StringBuilder name = new StringBuilder();
144 if (node.isIncomplete()) {
145 name.append(tr("incomplete"));
146 } else {
147 TaggingPreset preset = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(node);
148 if (preset == null) {
149 String n;
150 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
151 n = node.getLocalName();
152 } else {
153 n = node.getName();
154 }
155 if(n == null)
156 {
157 String s;
158 if((s = node.get("addr:housename")) != null) {
159 /* I18n: name of house as parameter */
160 n = tr("House {0}", s);
161 }
162 if(n == null && (s = node.get("addr:housenumber")) != null) {
163 String t = node.get("addr:street");
164 if(t != null) {
165 /* I18n: house number, street as parameter, number should remain
166 before street for better visibility */
167 n = tr("House number {0} at {1}", s, t);
168 }
169 else {
170 /* I18n: house number as parameter */
171 n = tr("House number {0}", s);
172 }
173 }
174 }
175
176 if (n == null) {
177 n = node.isNew() ? tr("node") : Long.toString(node.getId());
178 }
179 name.append(n);
180 } else {
181 preset.nameTemplate.appendText(name, node);
182 }
183 if (node.getCoor() != null) {
184 name.append(" \u200E(").append(node.getCoor().latToString(CoordinateFormat.getDefaultFormat())).append(", ").append(node.getCoor().lonToString(CoordinateFormat.getDefaultFormat())).append(")");
185 }
186 }
187 decorateNameWithId(name, node);
188
189
190 String result = name.toString();
191 for (NameFormatterHook hook: formatHooks) {
192 String hookResult = hook.checkFormat(node, result);
193 if (hookResult != null)
194 return hookResult;
195 }
196
197 return result;
198 }
199
200 private final Comparator<Node> nodeComparator = new Comparator<Node>() {
201 @Override
202 public int compare(Node n1, Node n2) {
203 return format(n1).compareTo(format(n2));
204 }
205 };
206
207 @Override
208 public Comparator<Node> getNodeComparator() {
209 return nodeComparator;
210 }
211
212
213 /**
214 * Formats a name for a way
215 *
216 * @param way the way
217 * @return the name
218 */
219 @Override
220 public String format(Way way) {
221 StringBuilder name = new StringBuilder();
222 if (way.isIncomplete()) {
223 name.append(tr("incomplete"));
224 } else {
225 TaggingPreset preset = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(way);
226 if (preset == null) {
227 String n;
228 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
229 n = way.getLocalName();
230 } else {
231 n = way.getName();
232 }
233 if (n == null) {
234 n = way.get("ref");
235 }
236 if (n == null) {
237 n =
238 (way.get("highway") != null) ? tr("highway") :
239 (way.get("railway") != null) ? tr("railway") :
240 (way.get("waterway") != null) ? tr("waterway") :
241 (way.get("landuse") != null) ? tr("landuse") : null;
242 }
243 if(n == null)
244 {
245 String s;
246 if((s = way.get("addr:housename")) != null) {
247 /* I18n: name of house as parameter */
248 n = tr("House {0}", s);
249 }
250 if(n == null && (s = way.get("addr:housenumber")) != null) {
251 String t = way.get("addr:street");
252 if(t != null) {
253 /* I18n: house number, street as parameter, number should remain
254 before street for better visibility */
255 n = tr("House number {0} at {1}", s, t);
256 }
257 else {
258 /* I18n: house number as parameter */
259 n = tr("House number {0}", s);
260 }
261 }
262 }
263 if(n == null && way.get("building") != null) n = tr("building");
264 if(n == null || n.length() == 0) {
265 n = String.valueOf(way.getId());
266 }
267
268 name.append(n);
269 } else {
270 preset.nameTemplate.appendText(name, way);
271 }
272
273 int nodesNo = way.getRealNodesCount();
274 /* note: length == 0 should no longer happen, but leave the bracket code
275 nevertheless, who knows what future brings */
276 /* I18n: count of nodes as parameter */
277 String nodes = trn("{0} node", "{0} nodes", nodesNo, nodesNo);
278 name.append(" (").append(nodes).append(")");
279 }
280 decorateNameWithId(name, way);
281
282 String result = name.toString();
283 for (NameFormatterHook hook: formatHooks) {
284 String hookResult = hook.checkFormat(way, result);
285 if (hookResult != null)
286 return hookResult;
287 }
288
289 return result;
290 }
291
292 private final Comparator<Way> wayComparator = new Comparator<Way>() {
293 @Override
294 public int compare(Way w1, Way w2) {
295 return format(w1).compareTo(format(w2));
296 }
297 };
298
299 @Override
300 public Comparator<Way> getWayComparator() {
301 return wayComparator;
302 }
303
304
305 /**
306 * Formats a name for a relation
307 *
308 * @param relation the relation
309 * @return the name
310 */
311 @Override
312 public String format(Relation relation) {
313 StringBuilder name = new StringBuilder();
314 if (relation.isIncomplete()) {
315 name.append(tr("incomplete"));
316 } else {
317 TaggingPreset preset = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(relation);
318
319 formatRelationNameAndType(relation, name, preset);
320
321 int mbno = relation.getMembersCount();
322 name.append(trn("{0} member", "{0} members", mbno, mbno));
323
324 if (relation.hasIncompleteMembers()) {
325 name.append(", ").append(tr("incomplete"));
326 }
327
328 name.append(")");
329 }
330 decorateNameWithId(name, relation);
331
332 String result = name.toString();
333 for (NameFormatterHook hook: formatHooks) {
334 String hookResult = hook.checkFormat(relation, result);
335 if (hookResult != null)
336 return hookResult;
337 }
338
339 return result;
340 }
341
342 private void formatRelationNameAndType(Relation relation, StringBuilder result, TaggingPreset preset) {
343 if (preset == null) {
344 result.append(getRelationTypeName(relation));
345 String relationName = getRelationName(relation);
346 if (relationName == null) {
347 relationName = Long.toString(relation.getId());
348 } else {
349 relationName = "\"" + relationName + "\"";
350 }
351 result.append(" (").append(relationName).append(", ");
352 } else {
353 preset.nameTemplate.appendText(result, relation);
354 result.append("(");
355 }
356 }
357
358 private final Comparator<Relation> relationComparator = new Comparator<Relation>() {
359 @Override
360 public int compare(Relation r1, Relation r2) {
361 //TODO This doesn't work correctly with formatHooks
362
363 TaggingPreset preset1 = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(r1);
364 TaggingPreset preset2 = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(r2);
365
366 if (preset1 != null || preset2 != null) {
367 StringBuilder name1 = new StringBuilder();
368 formatRelationNameAndType(r1, name1, preset1);
369 StringBuilder name2 = new StringBuilder();
370 formatRelationNameAndType(r2, name2, preset2);
371
372 int comp = AlphanumComparator.getInstance().compare(name1.toString(), name2.toString());
373 if (comp != 0)
374 return comp;
375 } else {
376
377 String type1 = getRelationTypeName(r1);
378 String type2 = getRelationTypeName(r2);
379
380 int comp = AlphanumComparator.getInstance().compare(type1, type2);
381 if (comp != 0)
382 return comp;
383
384 String name1 = getRelationName(r1);
385 String name2 = getRelationName(r2);
386
387 comp = AlphanumComparator.getInstance().compare(name1, name2);
388 if (comp != 0)
389 return comp;
390 }
391
392 if (r1.getMembersCount() != r2.getMembersCount())
393 return (r1.getMembersCount() > r2.getMembersCount())?1:-1;
394
395 int comp = Boolean.valueOf(r1.hasIncompleteMembers()).compareTo(Boolean.valueOf(r2.hasIncompleteMembers()));
396 if (comp != 0)
397 return comp;
398
399 if (r1.getUniqueId() > r2.getUniqueId())
400 return 1;
401 else if (r1.getUniqueId() < r2.getUniqueId())
402 return -1;
403 else
404 return 0;
405 }
406 };
407
408 @Override
409 public Comparator<Relation> getRelationComparator() {
410 return relationComparator;
411 }
412
413 private String getRelationTypeName(IRelation relation) {
414 String name = trc("Relation type", relation.get("type"));
415 if (name == null) {
416 name = (relation.get("public_transport") != null) ? tr("public transport") : null;
417 }
418 if (name == null) {
419 String building = relation.get("building");
420 if (OsmUtils.isTrue(building)) {
421 name = tr("building");
422 } else if(building != null)
423 {
424 name = tr(building); // translate tag!
425 }
426 }
427 if (name == null) {
428 name = trc("Place type", relation.get("place"));
429 }
430 if (name == null) {
431 name = tr("relation");
432 }
433 String admin_level = relation.get("admin_level");
434 if (admin_level != null) {
435 name += "["+admin_level+"]";
436 }
437
438 for (NameFormatterHook hook: formatHooks) {
439 String hookResult = hook.checkRelationTypeName(relation, name);
440 if (hookResult != null)
441 return hookResult;
442 }
443
444 return name;
445 }
446
447 private String getNameTagValue(IRelation relation, String nameTag) {
448 if ("name".equals(nameTag)) {
449 if (Main.pref.getBoolean("osm-primitives.localize-name", true))
450 return relation.getLocalName();
451 else
452 return relation.getName();
453 } else if (":LocationCode".equals(nameTag)) {
454 for (String m : relation.keySet()) {
455 if (m.endsWith(nameTag))
456 return relation.get(m);
457 }
458 return null;
459 } else if (nameTag.startsWith("?") && OsmUtils.isTrue(relation.get(nameTag.substring(1)))) {
460 return tr(nameTag.substring(1));
461 } else if (nameTag.startsWith("?") && OsmUtils.isFalse(relation.get(nameTag.substring(1)))) {
462 return null;
463 } else if (nameTag.startsWith("?")) {
464 return trc_lazy(nameTag, I18n.escape(relation.get(nameTag.substring(1))));
465 } else {
466 return trc_lazy(nameTag, I18n.escape(relation.get(nameTag)));
467 }
468 }
469
470 private String getRelationName(IRelation relation) {
471 String nameTag = null;
472 for (String n : getNamingtagsForRelations()) {
473 nameTag = getNameTagValue(relation, n);
474 if (nameTag != null)
475 return nameTag;
476 }
477 return null;
478 }
479
480 /**
481 * Formats a name for a changeset
482 *
483 * @param changeset the changeset
484 * @return the name
485 */
486 @Override
487 public String format(Changeset changeset) {
488 return tr("Changeset {0}",changeset.getId());
489 }
490
491 /**
492 * Builds a default tooltip text for the primitive <code>primitive</code>.
493 *
494 * @param primitive the primitmive
495 * @return the tooltip text
496 */
497 public String buildDefaultToolTip(IPrimitive primitive) {
498 return buildDefaultToolTip(primitive.getId(), primitive.getKeys());
499 }
500
501 private String buildDefaultToolTip(long id, Map<String, String> tags) {
502 StringBuilder sb = new StringBuilder();
503 sb.append("<html>");
504 sb.append("<strong>id</strong>=")
505 .append(id)
506 .append("<br>");
507 List<String> keyList = new ArrayList<>(tags.keySet());
508 Collections.sort(keyList);
509 for (int i = 0; i < keyList.size(); i++) {
510 if (i > 0) {
511 sb.append("<br>");
512 }
513 String key = keyList.get(i);
514 sb.append("<strong>")
515 .append(key)
516 .append("</strong>")
517 .append("=");
518 String value = tags.get(key);
519 while(value.length() != 0) {
520 sb.append(value.substring(0,Math.min(50, value.length())));
521 if (value.length() > 50) {
522 sb.append("<br>");
523 value = value.substring(50);
524 } else {
525 value = "";
526 }
527 }
528 }
529 sb.append("</html>");
530 return sb.toString();
531 }
532
533 /**
534 * Decorates the name of primitive with its id, if the preference
535 * <tt>osm-primitives.showid</tt> is set.
536 *
537 * The id is append to the {@link StringBuilder} passed in in <code>name</code>.
538 *
539 * @param name the name without the id
540 * @param primitive the primitive
541 */
542 protected void decorateNameWithId(StringBuilder name, HistoryOsmPrimitive primitive) {
543 if (Main.pref.getBoolean("osm-primitives.showid")) {
544 name.append(tr(" [id: {0}]", primitive.getId()));
545 }
546 }
547
548 /**
549 * Formats a name for a history node
550 *
551 * @param node the node
552 * @return the name
553 */
554 @Override
555 public String format(HistoryNode node) {
556 StringBuilder sb = new StringBuilder();
557 String name;
558 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
559 name = node.getLocalName();
560 } else {
561 name = node.getName();
562 }
563 if (name == null) {
564 sb.append(node.getId());
565 } else {
566 sb.append(name);
567 }
568 LatLon coord = node.getCoords();
569 if (coord != null) {
570 sb.append(" (")
571 .append(coord.latToString(CoordinateFormat.getDefaultFormat()))
572 .append(", ")
573 .append(coord.lonToString(CoordinateFormat.getDefaultFormat()))
574 .append(")");
575 }
576 decorateNameWithId(sb, node);
577 return sb.toString();
578 }
579
580 /**
581 * Formats a name for a way
582 *
583 * @param way the way
584 * @return the name
585 */
586 @Override
587 public String format(HistoryWay way) {
588 StringBuilder sb = new StringBuilder();
589 String name;
590 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
591 name = way.getLocalName();
592 } else {
593 name = way.getName();
594 }
595 if (name != null) {
596 sb.append(name);
597 }
598 if (sb.length() == 0 && way.get("ref") != null) {
599 sb.append(way.get("ref"));
600 }
601 if (sb.length() == 0) {
602 sb.append(
603 (way.get("highway") != null) ? tr("highway") :
604 (way.get("railway") != null) ? tr("railway") :
605 (way.get("waterway") != null) ? tr("waterway") :
606 (way.get("landuse") != null) ? tr("landuse") : ""
607 );
608 }
609
610 int nodesNo = way.isClosed() ? way.getNumNodes() -1 : way.getNumNodes();
611 String nodes = trn("{0} node", "{0} nodes", nodesNo, nodesNo);
612 if(sb.length() == 0 ) {
613 sb.append(way.getId());
614 }
615 /* note: length == 0 should no longer happen, but leave the bracket code
616 nevertheless, who knows what future brings */
617 sb.append((sb.length() > 0) ? " ("+nodes+")" : nodes);
618 decorateNameWithId(sb, way);
619 return sb.toString();
620 }
621
622 /**
623 * Formats a name for a {@link HistoryRelation})
624 *
625 * @param relation the relation
626 * @return the name
627 */
628 @Override
629 public String format(HistoryRelation relation) {
630 StringBuilder sb = new StringBuilder();
631 if (relation.get("type") != null) {
632 sb.append(relation.get("type"));
633 } else {
634 sb.append(tr("relation"));
635 }
636 sb.append(" (");
637 String nameTag = null;
638 Set<String> namingTags = new HashSet<>(getNamingtagsForRelations());
639 for (String n : relation.getTags().keySet()) {
640 // #3328: "note " and " note" are name tags too
641 if (namingTags.contains(n.trim())) {
642 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
643 nameTag = relation.getLocalName();
644 } else {
645 nameTag = relation.getName();
646 }
647 if (nameTag == null) {
648 nameTag = relation.get(n);
649 }
650 }
651 if (nameTag != null) {
652 break;
653 }
654 }
655 if (nameTag == null) {
656 sb.append(Long.toString(relation.getId())).append(", ");
657 } else {
658 sb.append("\"").append(nameTag).append("\", ");
659 }
660
661 int mbno = relation.getNumMembers();
662 sb.append(trn("{0} member", "{0} members", mbno, mbno)).append(")");
663
664 decorateNameWithId(sb, relation);
665 return sb.toString();
666 }
667
668 /**
669 * Builds a default tooltip text for an HistoryOsmPrimitive <code>primitive</code>.
670 *
671 * @param primitive the primitmive
672 * @return the tooltip text
673 */
674 public String buildDefaultToolTip(HistoryOsmPrimitive primitive) {
675 return buildDefaultToolTip(primitive.getId(), primitive.getTags());
676 }
677
678 public String formatAsHtmlUnorderedList(Collection<? extends OsmPrimitive> primitives) {
679 return Utils.joinAsHtmlUnorderedList(Utils.transform(primitives, new Function<OsmPrimitive, String>() {
680
681 @Override
682 public String apply(OsmPrimitive x) {
683 return x.getDisplayName(DefaultNameFormatter.this);
684 }
685 }));
686 }
687
688 public String formatAsHtmlUnorderedList(OsmPrimitive... primitives) {
689 return formatAsHtmlUnorderedList(Arrays.asList(primitives));
690 }
691}
Note: See TracBrowser for help on using the repository browser.