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

Last change on this file since 4552 was 4477, checked in by bastiK, 13 years ago

fixed #6813 - Quote characters not displayed in relations "note" attribute (preliminary)

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