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

Last change on this file since 7082 was 7018, checked in by Don-vip, 10 years ago

refactor duplicated code

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