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

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

fix #8481 - RelationComparator does not detect equal relations

  • Property svn:eol-style set to native
File size: 24.9 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 LinkedList<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 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 comp = ALPHANUM_COMPARATOR.compare(name1, name2);
386 if (comp != 0)
387 return comp;
388 }
389
390 if (r1.getMembersCount() != r2.getMembersCount())
391 return (r1.getMembersCount() > r2.getMembersCount())?1:-1;
392
393 int comp = Boolean.valueOf(r1.hasIncompleteMembers()).compareTo(Boolean.valueOf(r2.hasIncompleteMembers()));
394 if (comp != 0)
395 return comp;
396
397 if (r1.getUniqueId() > r2.getUniqueId())
398 return 1;
399 else if (r1.getUniqueId() < r2.getUniqueId())
400 return -1;
401 else
402 return 0;
403 }
404 };
405
406 public Comparator<Relation> getRelationComparator() {
407 return relationComparator;
408 }
409
410 private String getLeadingNumber(String s) {
411 int i = 0;
412 while (i < s.length() && Character.isDigit(s.charAt(i))) {
413 i++;
414 }
415 return s.substring(0, i);
416 }
417
418 private String getRelationTypeName(IRelation relation) {
419 String name = trc("Relation type", relation.get("type"));
420 if (name == null) {
421 name = (relation.get("public_transport") != null) ? tr("public transport") : null;
422 }
423 if (name == null) {
424 String building = relation.get("building");
425 if (OsmUtils.isTrue(building)) {
426 name = tr("building");
427 } else if(building != null)
428 {
429 name = tr(building); // translate tag!
430 }
431 }
432 if (name == null) {
433 name = trc("Place type", relation.get("place"));
434 }
435 if (name == null) {
436 name = tr("relation");
437 }
438 String admin_level = relation.get("admin_level");
439 if (admin_level != null) {
440 name += "["+admin_level+"]";
441 }
442
443 for (NameFormatterHook hook: formatHooks) {
444 String hookResult = hook.checkRelationTypeName(relation, name);
445 if (hookResult != null)
446 return hookResult;
447 }
448
449 return name;
450 }
451
452 private String getNameTagValue(IRelation relation, String nameTag) {
453 if (nameTag.equals("name")) {
454 if (Main.pref.getBoolean("osm-primitives.localize-name", true))
455 return relation.getLocalName();
456 else
457 return relation.getName();
458 } else if (nameTag.equals(":LocationCode")) {
459 for (String m : relation.keySet()) {
460 if (m.endsWith(nameTag))
461 return relation.get(m);
462 }
463 return null;
464 } else if (nameTag.startsWith("?") && OsmUtils.isTrue(relation.get(nameTag.substring(1)))) {
465 return tr(nameTag.substring(1));
466 } else if (nameTag.startsWith("?") && OsmUtils.isFalse(relation.get(nameTag.substring(1)))) {
467 return null;
468 } else {
469 return trc_lazy(nameTag, I18n.escape(relation.get(nameTag)));
470 }
471 }
472
473 private String getRelationName(IRelation relation) {
474 String nameTag = null;
475 for (String n : getNamingtagsForRelations()) {
476 nameTag = getNameTagValue(relation, n);
477 if (nameTag != null)
478 return nameTag;
479 }
480 return null;
481 }
482
483 /**
484 * Formats a name for a changeset
485 *
486 * @param changeset the changeset
487 * @return the name
488 */
489 public String format(Changeset changeset) {
490 return tr("Changeset {0}",changeset.getId());
491 }
492
493 /**
494 * Builds a default tooltip text for the primitive <code>primitive</code>.
495 *
496 * @param primitive the primitmive
497 * @return the tooltip text
498 */
499 public String buildDefaultToolTip(IPrimitive primitive) {
500 StringBuilder sb = new StringBuilder();
501 sb.append("<html>");
502 sb.append("<strong>id</strong>=")
503 .append(primitive.getId())
504 .append("<br>");
505 ArrayList<String> keyList = new ArrayList<String>(primitive.keySet());
506 Collections.sort(keyList);
507 for (int i = 0; i < keyList.size(); i++) {
508 if (i > 0) {
509 sb.append("<br>");
510 }
511 String key = keyList.get(i);
512 sb.append("<strong>")
513 .append(key)
514 .append("</strong>")
515 .append("=");
516 String value = primitive.get(key);
517 while(value.length() != 0) {
518 sb.append(value.substring(0,Math.min(50, value.length())));
519 if (value.length() > 50) {
520 sb.append("<br>");
521 value = value.substring(50);
522 } else {
523 value = "";
524 }
525 }
526 }
527 sb.append("</html>");
528 return sb.toString();
529 }
530
531 /**
532 * Decorates the name of primitive with its id, if the preference
533 * <tt>osm-primitives.showid</tt> is set.
534 *
535 * The id is append to the {@link StringBuilder} passed in in <code>name</code>.
536 *
537 * @param name the name without the id
538 * @param primitive the primitive
539 */
540 protected void decorateNameWithId(StringBuilder name, HistoryOsmPrimitive primitive) {
541 if (Main.pref.getBoolean("osm-primitives.showid")) {
542 name.append(tr(" [id: {0}]", primitive.getId()));
543 }
544 }
545
546 /**
547 * Formats a name for a history node
548 *
549 * @param node the node
550 * @return the name
551 */
552 public String format(HistoryNode node) {
553 StringBuilder sb = new StringBuilder();
554 String name;
555 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
556 name = node.getLocalName();
557 } else {
558 name = node.getName();
559 }
560 if (name == null) {
561 sb.append(node.getId());
562 } else {
563 sb.append(name);
564 }
565 LatLon coord = node.getCoords();
566 if (coord != null) {
567 sb.append(" (")
568 .append(coord.latToString(CoordinateFormat.getDefaultFormat()))
569 .append(", ")
570 .append(coord.lonToString(CoordinateFormat.getDefaultFormat()))
571 .append(")");
572 }
573 decorateNameWithId(sb, node);
574 return sb.toString();
575 }
576
577 /**
578 * Formats a name for a way
579 *
580 * @param way the way
581 * @return the name
582 */
583 public String format(HistoryWay way) {
584 StringBuilder sb = new StringBuilder();
585 String name;
586 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
587 name = way.getLocalName();
588 } else {
589 name = way.getName();
590 }
591 if (name != null) {
592 sb.append(name);
593 }
594 if (sb.length() == 0 && way.get("ref") != null) {
595 sb.append(way.get("ref"));
596 }
597 if (sb.length() == 0) {
598 sb.append(
599 (way.get("highway") != null) ? tr("highway") :
600 (way.get("railway") != null) ? tr("railway") :
601 (way.get("waterway") != null) ? tr("waterway") :
602 (way.get("landuse") != null) ? tr("landuse") : ""
603 );
604 }
605
606 int nodesNo = way.isClosed() ? way.getNumNodes() -1 : way.getNumNodes();
607 String nodes = trn("{0} node", "{0} nodes", nodesNo, nodesNo);
608 if(sb.length() == 0 ) {
609 sb.append(way.getId());
610 }
611 /* note: length == 0 should no longer happen, but leave the bracket code
612 nevertheless, who knows what future brings */
613 sb.append((sb.length() > 0) ? " ("+nodes+")" : nodes);
614 decorateNameWithId(sb, way);
615 return sb.toString();
616 }
617
618 /**
619 * Formats a name for a {@link HistoryRelation})
620 *
621 * @param relation the relation
622 * @return the name
623 */
624 public String format(HistoryRelation relation) {
625 StringBuilder sb = new StringBuilder();
626 if (relation.get("type") != null) {
627 sb.append(relation.get("type"));
628 } else {
629 sb.append(tr("relation"));
630 }
631 sb.append(" (");
632 String nameTag = null;
633 Set<String> namingTags = new HashSet<String>(getNamingtagsForRelations());
634 for (String n : relation.getTags().keySet()) {
635 // #3328: "note " and " note" are name tags too
636 if (namingTags.contains(n.trim())) {
637 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
638 nameTag = relation.getLocalName();
639 } else {
640 nameTag = relation.getName();
641 }
642 if (nameTag == null) {
643 nameTag = relation.get(n);
644 }
645 }
646 if (nameTag != null) {
647 break;
648 }
649 }
650 if (nameTag == null) {
651 sb.append(Long.toString(relation.getId())).append(", ");
652 } else {
653 sb.append("\"").append(nameTag).append("\", ");
654 }
655
656 int mbno = relation.getNumMembers();
657 sb.append(trn("{0} member", "{0} members", mbno, mbno)).append(")");
658
659 decorateNameWithId(sb, relation);
660 return sb.toString();
661 }
662
663 /**
664 * Builds a default tooltip text for an HistoryOsmPrimitive <code>primitive</code>.
665 *
666 * @param primitive the primitmive
667 * @return the tooltip text
668 */
669 public String buildDefaultToolTip(HistoryOsmPrimitive primitive) {
670 StringBuilder sb = new StringBuilder();
671 sb.append("<html>");
672 sb.append("<strong>id</strong>=")
673 .append(primitive.getId())
674 .append("<br>");
675 ArrayList<String> keyList = new ArrayList<String>(primitive.getTags().keySet());
676 Collections.sort(keyList);
677 for (int i = 0; i < keyList.size(); i++) {
678 if (i > 0) {
679 sb.append("<br>");
680 }
681 String key = keyList.get(i);
682 sb.append("<strong>")
683 .append(key)
684 .append("</strong>")
685 .append("=");
686 String value = primitive.get(key);
687 while(value.length() != 0) {
688 sb.append(value.substring(0,Math.min(50, value.length())));
689 if (value.length() > 50) {
690 sb.append("<br>");
691 value = value.substring(50);
692 } else {
693 value = "";
694 }
695 }
696 }
697 sb.append("</html>");
698 return sb.toString();
699 }
700
701 public String formatAsHtmlUnorderedList(Collection<? extends OsmPrimitive> primitives) {
702 return Utils.joinAsHtmlUnorderedList(Utils.transform(primitives, new Function<OsmPrimitive, String>() {
703
704 @Override
705 public String apply(OsmPrimitive x) {
706 return x.getDisplayName(DefaultNameFormatter.this);
707 }
708 }));
709 }
710
711 public String formatAsHtmlUnorderedList(OsmPrimitive... primitives) {
712 return formatAsHtmlUnorderedList(Arrays.asList(primitives));
713 }
714}
Note: See TracBrowser for help on using the repository browser.