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

Last change on this file since 4431 was 4431, checked in by jttt, 14 years ago

Custom primitive name formatters via tagging presets

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