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

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

Search: fix invalid results for nodes: operator with closed ways

  • Property svn:eol-style set to native
File size: 24.8 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.getRealNodesCount();
270 /* note: length == 0 should no longer happen, but leave the bracket code
271 nevertheless, who knows what future brings */
272 /* I18n: count of nodes as parameter */
273 String nodes = trn("{0} node", "{0} nodes", nodesNo, nodesNo);
274 name.append(" (").append(nodes).append(")");
275 }
276 decorateNameWithId(name, way);
277
278 String result = name.toString();
279 for (NameFormatterHook hook: formatHooks) {
280 String hookResult = hook.checkFormat(way, result);
281 if (hookResult != null)
282 return hookResult;
283 }
284
285 return result;
286 }
287
288 private final Comparator<Way> wayComparator = new Comparator<Way>() {
289 @Override
290 public int compare(Way w1, Way w2) {
291 return format(w1).compareTo(format(w2));
292 }
293 };
294
295 public Comparator<Way> getWayComparator() {
296 return wayComparator;
297 }
298
299
300 /**
301 * Formats a name for a relation
302 *
303 * @param relation the relation
304 * @return the name
305 */
306 public String format(Relation relation) {
307 StringBuilder name = new StringBuilder();
308 if (relation.isIncomplete()) {
309 name.append(tr("incomplete"));
310 } else {
311 TaggingPreset preset = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(relation);
312
313 formatRelationNameAndType(relation, name, preset);
314
315 int mbno = relation.getMembersCount();
316 name.append(trn("{0} member", "{0} members", mbno, mbno));
317
318 if (relation.hasIncompleteMembers()) {
319 name.append(", ").append(tr("incomplete"));
320 }
321
322 name.append(")");
323 }
324 decorateNameWithId(name, relation);
325
326 String result = name.toString();
327 for (NameFormatterHook hook: formatHooks) {
328 String hookResult = hook.checkFormat(relation, result);
329 if (hookResult != null)
330 return hookResult;
331 }
332
333 return result;
334 }
335
336 private void formatRelationNameAndType(Relation relation, StringBuilder result, TaggingPreset preset) {
337 if (preset == null) {
338 result.append(getRelationTypeName(relation));
339 String relationName = getRelationName(relation);
340 if (relationName == null) {
341 relationName = Long.toString(relation.getId());
342 } else {
343 relationName = "\"" + relationName + "\"";
344 }
345 result.append(" (").append(relationName).append(", ");
346 } else {
347 preset.nameTemplate.appendText(result, relation);
348 result.append("(");
349 }
350 }
351
352 private final Comparator<Relation> relationComparator = new Comparator<Relation>() {
353 private final AlphanumComparator ALPHANUM_COMPARATOR = new AlphanumComparator();
354 @Override
355 public int compare(Relation r1, Relation r2) {
356 //TODO This doesn't work correctly with formatHooks
357
358 TaggingPreset preset1 = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(r1);
359 TaggingPreset preset2 = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(r2);
360
361 if (preset1 != null || preset2 != null) {
362 StringBuilder name1 = new StringBuilder();
363 formatRelationNameAndType(r1, name1, preset1);
364 StringBuilder name2 = new StringBuilder();
365 formatRelationNameAndType(r2, name2, preset2);
366
367 int comp = name1.toString().compareTo(name2.toString());
368 if (comp != 0)
369 return comp;
370 } else {
371
372 String type1 = getRelationTypeName(r1);
373 String type2 = getRelationTypeName(r2);
374
375 int comp = ALPHANUM_COMPARATOR.compare(type1, type2);
376 if (comp != 0)
377 return comp;
378
379 String name1 = getRelationName(r1);
380 String name2 = getRelationName(r2);
381
382 comp = ALPHANUM_COMPARATOR.compare(name1, name2);
383 if (comp != 0)
384 return comp;
385 }
386
387 if (r1.getMembersCount() != r2.getMembersCount())
388 return (r1.getMembersCount() > r2.getMembersCount())?1:-1;
389
390 int comp = Boolean.valueOf(r1.hasIncompleteMembers()).compareTo(Boolean.valueOf(r2.hasIncompleteMembers()));
391 if (comp != 0)
392 return comp;
393
394 if (r1.getUniqueId() > r2.getUniqueId())
395 return 1;
396 else if (r1.getUniqueId() < r2.getUniqueId())
397 return -1;
398 else
399 return 0;
400 }
401 };
402
403 public Comparator<Relation> getRelationComparator() {
404 return relationComparator;
405 }
406
407 private String getLeadingNumber(String s) {
408 int i = 0;
409 while (i < s.length() && Character.isDigit(s.charAt(i))) {
410 i++;
411 }
412 return s.substring(0, i);
413 }
414
415 private String getRelationTypeName(IRelation relation) {
416 String name = trc("Relation type", relation.get("type"));
417 if (name == null) {
418 name = (relation.get("public_transport") != null) ? tr("public transport") : null;
419 }
420 if (name == null) {
421 String building = relation.get("building");
422 if (OsmUtils.isTrue(building)) {
423 name = tr("building");
424 } else if(building != null)
425 {
426 name = tr(building); // translate tag!
427 }
428 }
429 if (name == null) {
430 name = trc("Place type", relation.get("place"));
431 }
432 if (name == null) {
433 name = tr("relation");
434 }
435 String admin_level = relation.get("admin_level");
436 if (admin_level != null) {
437 name += "["+admin_level+"]";
438 }
439
440 for (NameFormatterHook hook: formatHooks) {
441 String hookResult = hook.checkRelationTypeName(relation, name);
442 if (hookResult != null)
443 return hookResult;
444 }
445
446 return name;
447 }
448
449 private String getNameTagValue(IRelation relation, String nameTag) {
450 if (nameTag.equals("name")) {
451 if (Main.pref.getBoolean("osm-primitives.localize-name", true))
452 return relation.getLocalName();
453 else
454 return relation.getName();
455 } else if (nameTag.equals(":LocationCode")) {
456 for (String m : relation.keySet()) {
457 if (m.endsWith(nameTag))
458 return relation.get(m);
459 }
460 return null;
461 } else if (nameTag.startsWith("?") && OsmUtils.isTrue(relation.get(nameTag.substring(1)))) {
462 return tr(nameTag.substring(1));
463 } else if (nameTag.startsWith("?") && OsmUtils.isFalse(relation.get(nameTag.substring(1)))) {
464 return null;
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 public String format(Changeset changeset) {
487 return tr("Changeset {0}",changeset.getId());
488 }
489
490 /**
491 * Builds a default tooltip text for the primitive <code>primitive</code>.
492 *
493 * @param primitive the primitmive
494 * @return the tooltip text
495 */
496 public String buildDefaultToolTip(IPrimitive primitive) {
497 StringBuilder sb = new StringBuilder();
498 sb.append("<html>");
499 sb.append("<strong>id</strong>=")
500 .append(primitive.getId())
501 .append("<br>");
502 ArrayList<String> keyList = new ArrayList<String>(primitive.keySet());
503 Collections.sort(keyList);
504 for (int i = 0; i < keyList.size(); i++) {
505 if (i > 0) {
506 sb.append("<br>");
507 }
508 String key = keyList.get(i);
509 sb.append("<strong>")
510 .append(key)
511 .append("</strong>")
512 .append("=");
513 String value = primitive.get(key);
514 while(value.length() != 0) {
515 sb.append(value.substring(0,Math.min(50, value.length())));
516 if (value.length() > 50) {
517 sb.append("<br>");
518 value = value.substring(50);
519 } else {
520 value = "";
521 }
522 }
523 }
524 sb.append("</html>");
525 return sb.toString();
526 }
527
528 /**
529 * Decorates the name of primitive with its id, if the preference
530 * <tt>osm-primitives.showid</tt> is set.
531 *
532 * The id is append to the {@link StringBuilder} passed in in <code>name</code>.
533 *
534 * @param name the name without the id
535 * @param primitive the primitive
536 */
537 protected void decorateNameWithId(StringBuilder name, HistoryOsmPrimitive primitive) {
538 if (Main.pref.getBoolean("osm-primitives.showid")) {
539 name.append(tr(" [id: {0}]", primitive.getId()));
540 }
541 }
542
543 /**
544 * Formats a name for a history node
545 *
546 * @param node the node
547 * @return the name
548 */
549 public String format(HistoryNode node) {
550 StringBuilder sb = new StringBuilder();
551 String name;
552 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
553 name = node.getLocalName();
554 } else {
555 name = node.getName();
556 }
557 if (name == null) {
558 sb.append(node.getId());
559 } else {
560 sb.append(name);
561 }
562 LatLon coord = node.getCoords();
563 if (coord != null) {
564 sb.append(" (")
565 .append(coord.latToString(CoordinateFormat.getDefaultFormat()))
566 .append(", ")
567 .append(coord.lonToString(CoordinateFormat.getDefaultFormat()))
568 .append(")");
569 }
570 decorateNameWithId(sb, node);
571 return sb.toString();
572 }
573
574 /**
575 * Formats a name for a way
576 *
577 * @param way the way
578 * @return the name
579 */
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 public String format(HistoryRelation relation) {
622 StringBuilder sb = new StringBuilder();
623 if (relation.get("type") != null) {
624 sb.append(relation.get("type"));
625 } else {
626 sb.append(tr("relation"));
627 }
628 sb.append(" (");
629 String nameTag = null;
630 Set<String> namingTags = new HashSet<String>(getNamingtagsForRelations());
631 for (String n : relation.getTags().keySet()) {
632 // #3328: "note " and " note" are name tags too
633 if (namingTags.contains(n.trim())) {
634 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
635 nameTag = relation.getLocalName();
636 } else {
637 nameTag = relation.getName();
638 }
639 if (nameTag == null) {
640 nameTag = relation.get(n);
641 }
642 }
643 if (nameTag != null) {
644 break;
645 }
646 }
647 if (nameTag == null) {
648 sb.append(Long.toString(relation.getId())).append(", ");
649 } else {
650 sb.append("\"").append(nameTag).append("\", ");
651 }
652
653 int mbno = relation.getNumMembers();
654 sb.append(trn("{0} member", "{0} members", mbno, mbno)).append(")");
655
656 decorateNameWithId(sb, relation);
657 return sb.toString();
658 }
659
660 /**
661 * Builds a default tooltip text for an HistoryOsmPrimitive <code>primitive</code>.
662 *
663 * @param primitive the primitmive
664 * @return the tooltip text
665 */
666 public String buildDefaultToolTip(HistoryOsmPrimitive primitive) {
667 StringBuilder sb = new StringBuilder();
668 sb.append("<html>");
669 sb.append("<strong>id</strong>=")
670 .append(primitive.getId())
671 .append("<br>");
672 ArrayList<String> keyList = new ArrayList<String>(primitive.getTags().keySet());
673 Collections.sort(keyList);
674 for (int i = 0; i < keyList.size(); i++) {
675 if (i > 0) {
676 sb.append("<br>");
677 }
678 String key = keyList.get(i);
679 sb.append("<strong>")
680 .append(key)
681 .append("</strong>")
682 .append("=");
683 String value = primitive.get(key);
684 while(value.length() != 0) {
685 sb.append(value.substring(0,Math.min(50, value.length())));
686 if (value.length() > 50) {
687 sb.append("<br>");
688 value = value.substring(50);
689 } else {
690 value = "";
691 }
692 }
693 }
694 sb.append("</html>");
695 return sb.toString();
696 }
697
698 public String formatAsHtmlUnorderedList(Collection<? extends OsmPrimitive> primitives) {
699 return Utils.joinAsHtmlUnorderedList(Utils.transform(primitives, new Function<OsmPrimitive, String>() {
700
701 @Override
702 public String apply(OsmPrimitive x) {
703 return x.getDisplayName(DefaultNameFormatter.this);
704 }
705 }));
706 }
707
708 public String formatAsHtmlUnorderedList(OsmPrimitive... primitives) {
709 return formatAsHtmlUnorderedList(Arrays.asList(primitives));
710 }
711}
Note: See TracBrowser for help on using the repository browser.