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

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

fix #9668 - Sort entries in validation results naturally

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