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

Last change on this file since 10637 was 10634, checked in by Don-vip, 8 years ago

sonar - pmd:UselessQualifiedThis - Useless qualified this usage in the same class

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