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

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

Sonar/FindBugs - Loose coupling

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