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

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

code style - Close curly brace and the next "else", "catch" and "finally" keywords should be located on the same line

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