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

Last change on this file since 5328 was 5328, checked in by bastiK, 13 years ago

fix NPE as deleted nodes can have null coordinates now (see #7847)

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