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

Last change on this file since 9616 was 9473, checked in by simon04, 8 years ago

fix #12343 - Display at most 20 primitives for some confirmation dialogs (e.g., deletion of relations)

  • Property svn:eol-style set to native
File size: 24.4 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 protected 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 = new Comparator<Node>() {
197 @Override
198 public int compare(Node n1, Node n2) {
199 return format(n1).compareTo(format(n2));
200 }
201 };
202
203 @Override
204 public Comparator<Node> getNodeComparator() {
205 return nodeComparator;
206 }
207
208 @Override
209 public String format(Way way) {
210 StringBuilder name = new StringBuilder();
211
212 char mark = 0;
213 // If current language is left-to-right (almost all languages)
214 if (ComponentOrientation.getOrientation(Locale.getDefault()).isLeftToRight()) {
215 // will insert Left-To-Right Mark to ensure proper display of text in the case when object name is right-to-left
216 mark = '\u200E';
217 } else {
218 // otherwise will insert Right-To-Left Mark to ensure proper display in the opposite case
219 mark = '\u200F';
220 }
221 // Initialize base direction of the string
222 name.append(mark);
223
224 if (way.isIncomplete()) {
225 name.append(tr("incomplete"));
226 } else {
227 TaggingPreset preset = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(way);
228 if (preset == null) {
229 String n;
230 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
231 n = way.getLocalName();
232 } else {
233 n = way.getName();
234 }
235 if (n == null) {
236 n = way.get("ref");
237 }
238 if (n == null) {
239 n = (way.get("highway") != null) ? tr("highway") :
240 (way.get("railway") != null) ? tr("railway") :
241 (way.get("waterway") != null) ? tr("waterway") :
242 (way.get("landuse") != null) ? tr("landuse") : null;
243 }
244 if (n == null) {
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 } else {
257 /* I18n: house number as parameter */
258 n = tr("House number {0}", s);
259 }
260 }
261 }
262 if (n == null && way.get("building") != null) n = tr("building");
263 if (n == null || n.isEmpty()) {
264 n = String.valueOf(way.getId());
265 }
266
267 name.append(n);
268 } else {
269 preset.nameTemplate.appendText(name, way);
270 }
271
272 int nodesNo = way.getRealNodesCount();
273 /* note: length == 0 should no longer happen, but leave the bracket code
274 nevertheless, who knows what future brings */
275 /* I18n: count of nodes as parameter */
276 String nodes = trn("{0} node", "{0} nodes", nodesNo, nodesNo);
277 name.append(mark).append(" (").append(nodes).append(')');
278 }
279 decorateNameWithId(name, way);
280
281 String result = name.toString();
282 for (NameFormatterHook hook: formatHooks) {
283 String hookResult = hook.checkFormat(way, result);
284 if (hookResult != null)
285 return hookResult;
286 }
287
288 return result;
289 }
290
291 private final Comparator<Way> wayComparator = new Comparator<Way>() {
292 @Override
293 public int compare(Way w1, Way w2) {
294 return format(w1).compareTo(format(w2));
295 }
296 };
297
298 @Override
299 public Comparator<Way> getWayComparator() {
300 return wayComparator;
301 }
302
303 @Override
304 public String format(Relation relation) {
305 StringBuilder name = new StringBuilder();
306 if (relation.isIncomplete()) {
307 name.append(tr("incomplete"));
308 } else {
309 TaggingPreset preset = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(relation);
310
311 formatRelationNameAndType(relation, name, preset);
312
313 int mbno = relation.getMembersCount();
314 name.append(trn("{0} member", "{0} members", mbno, mbno));
315
316 if (relation.hasIncompleteMembers()) {
317 name.append(", ").append(tr("incomplete"));
318 }
319
320 name.append(')');
321 }
322 decorateNameWithId(name, relation);
323
324 String result = name.toString();
325 for (NameFormatterHook hook: formatHooks) {
326 String hookResult = hook.checkFormat(relation, result);
327 if (hookResult != null)
328 return hookResult;
329 }
330
331 return result;
332 }
333
334 private void formatRelationNameAndType(Relation relation, StringBuilder result, TaggingPreset preset) {
335 if (preset == null) {
336 result.append(getRelationTypeName(relation));
337 String relationName = getRelationName(relation);
338 if (relationName == null) {
339 relationName = Long.toString(relation.getId());
340 } else {
341 relationName = '\"' + relationName + '\"';
342 }
343 result.append(" (").append(relationName).append(", ");
344 } else {
345 preset.nameTemplate.appendText(result, relation);
346 result.append('(');
347 }
348 }
349
350 private final Comparator<Relation> relationComparator = new Comparator<Relation>() {
351 @Override
352 public int compare(Relation r1, Relation r2) {
353 //TODO This doesn't work correctly with formatHooks
354
355 TaggingPreset preset1 = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(r1);
356 TaggingPreset preset2 = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(r2);
357
358 if (preset1 != null || preset2 != null) {
359 StringBuilder name1 = new StringBuilder();
360 formatRelationNameAndType(r1, name1, preset1);
361 StringBuilder name2 = new StringBuilder();
362 formatRelationNameAndType(r2, name2, preset2);
363
364 int comp = AlphanumComparator.getInstance().compare(name1.toString(), name2.toString());
365 if (comp != 0)
366 return comp;
367 } else {
368
369 String type1 = getRelationTypeName(r1);
370 String type2 = getRelationTypeName(r2);
371
372 int comp = AlphanumComparator.getInstance().compare(type1, type2);
373 if (comp != 0)
374 return comp;
375
376 String name1 = getRelationName(r1);
377 String name2 = getRelationName(r2);
378
379 comp = AlphanumComparator.getInstance().compare(name1, name2);
380 if (comp != 0)
381 return comp;
382 }
383
384 if (r1.getMembersCount() != r2.getMembersCount())
385 return (r1.getMembersCount() > r2.getMembersCount()) ? 1 : -1;
386
387 int comp = Boolean.valueOf(r1.hasIncompleteMembers()).compareTo(Boolean.valueOf(r2.hasIncompleteMembers()));
388 if (comp != 0)
389 return comp;
390
391 if (r1.getUniqueId() > r2.getUniqueId())
392 return 1;
393 else if (r1.getUniqueId() < r2.getUniqueId())
394 return -1;
395 else
396 return 0;
397 }
398 };
399
400 @Override
401 public Comparator<Relation> getRelationComparator() {
402 return relationComparator;
403 }
404
405 private static String getRelationTypeName(IRelation relation) {
406 String name = trc("Relation type", relation.get("type"));
407 if (name == null) {
408 name = (relation.get("public_transport") != null) ? tr("public transport") : null;
409 }
410 if (name == null) {
411 String building = relation.get("building");
412 if (OsmUtils.isTrue(building)) {
413 name = tr("building");
414 } else if (building != null) {
415 name = tr(building); // translate tag!
416 }
417 }
418 if (name == null) {
419 name = trc("Place type", relation.get("place"));
420 }
421 if (name == null) {
422 name = tr("relation");
423 }
424 String admin_level = relation.get("admin_level");
425 if (admin_level != null) {
426 name += '['+admin_level+']';
427 }
428
429 for (NameFormatterHook hook: formatHooks) {
430 String hookResult = hook.checkRelationTypeName(relation, name);
431 if (hookResult != null)
432 return hookResult;
433 }
434
435 return name;
436 }
437
438 private static String getNameTagValue(IRelation relation, String nameTag) {
439 if ("name".equals(nameTag)) {
440 if (Main.pref.getBoolean("osm-primitives.localize-name", true))
441 return relation.getLocalName();
442 else
443 return relation.getName();
444 } else if (":LocationCode".equals(nameTag)) {
445 for (String m : relation.keySet()) {
446 if (m.endsWith(nameTag))
447 return relation.get(m);
448 }
449 return null;
450 } else if (nameTag.startsWith("?") && OsmUtils.isTrue(relation.get(nameTag.substring(1)))) {
451 return tr(nameTag.substring(1));
452 } else if (nameTag.startsWith("?") && OsmUtils.isFalse(relation.get(nameTag.substring(1)))) {
453 return null;
454 } else if (nameTag.startsWith("?")) {
455 return trc_lazy(nameTag, I18n.escape(relation.get(nameTag.substring(1))));
456 } else {
457 return trc_lazy(nameTag, I18n.escape(relation.get(nameTag)));
458 }
459 }
460
461 private String getRelationName(IRelation relation) {
462 String nameTag = null;
463 for (String n : getNamingtagsForRelations()) {
464 nameTag = getNameTagValue(relation, n);
465 if (nameTag != null)
466 return nameTag;
467 }
468 return null;
469 }
470
471 @Override
472 public String format(Changeset changeset) {
473 return tr("Changeset {0}", changeset.getId());
474 }
475
476 /**
477 * Builds a default tooltip text for the primitive <code>primitive</code>.
478 *
479 * @param primitive the primitmive
480 * @return the tooltip text
481 */
482 public String buildDefaultToolTip(IPrimitive primitive) {
483 return buildDefaultToolTip(primitive.getId(), primitive.getKeys());
484 }
485
486 private static String buildDefaultToolTip(long id, Map<String, String> tags) {
487 StringBuilder sb = new StringBuilder();
488 sb.append("<html><strong>id</strong>=")
489 .append(id)
490 .append("<br>");
491 List<String> keyList = new ArrayList<>(tags.keySet());
492 Collections.sort(keyList);
493 for (int i = 0; i < keyList.size(); i++) {
494 if (i > 0) {
495 sb.append("<br>");
496 }
497 String key = keyList.get(i);
498 sb.append("<strong>")
499 .append(key)
500 .append("</strong>=");
501 String value = tags.get(key);
502 while (!value.isEmpty()) {
503 sb.append(value.substring(0, Math.min(50, value.length())));
504 if (value.length() > 50) {
505 sb.append("<br>");
506 value = value.substring(50);
507 } else {
508 value = "";
509 }
510 }
511 }
512 sb.append("</html>");
513 return sb.toString();
514 }
515
516 /**
517 * Decorates the name of primitive with its id, if the preference
518 * <tt>osm-primitives.showid</tt> is set.
519 *
520 * The id is append to the {@link StringBuilder} passed in <code>name</code>.
521 *
522 * @param name the name without the id
523 * @param primitive the primitive
524 */
525 protected void decorateNameWithId(StringBuilder name, HistoryOsmPrimitive primitive) {
526 if (Main.pref.getBoolean("osm-primitives.showid")) {
527 name.append(tr(" [id: {0}]", primitive.getId()));
528 }
529 }
530
531 @Override
532 public String format(HistoryNode node) {
533 StringBuilder sb = new StringBuilder();
534 String name;
535 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
536 name = node.getLocalName();
537 } else {
538 name = node.getName();
539 }
540 if (name == null) {
541 sb.append(node.getId());
542 } else {
543 sb.append(name);
544 }
545 LatLon coord = node.getCoords();
546 if (coord != null) {
547 sb.append(" (")
548 .append(coord.latToString(CoordinateFormat.getDefaultFormat()))
549 .append(", ")
550 .append(coord.lonToString(CoordinateFormat.getDefaultFormat()))
551 .append(')');
552 }
553 decorateNameWithId(sb, node);
554 return sb.toString();
555 }
556
557 @Override
558 public String format(HistoryWay way) {
559 StringBuilder sb = new StringBuilder();
560 String name;
561 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
562 name = way.getLocalName();
563 } else {
564 name = way.getName();
565 }
566 if (name != null) {
567 sb.append(name);
568 }
569 if (sb.length() == 0 && way.get("ref") != null) {
570 sb.append(way.get("ref"));
571 }
572 if (sb.length() == 0) {
573 sb.append(
574 (way.get("highway") != null) ? tr("highway") :
575 (way.get("railway") != null) ? tr("railway") :
576 (way.get("waterway") != null) ? tr("waterway") :
577 (way.get("landuse") != null) ? tr("landuse") : ""
578 );
579 }
580
581 int nodesNo = way.isClosed() ? way.getNumNodes() -1 : way.getNumNodes();
582 String nodes = trn("{0} node", "{0} nodes", nodesNo, nodesNo);
583 if (sb.length() == 0) {
584 sb.append(way.getId());
585 }
586 /* note: length == 0 should no longer happen, but leave the bracket code
587 nevertheless, who knows what future brings */
588 sb.append((sb.length() > 0) ? " ("+nodes+')' : nodes);
589 decorateNameWithId(sb, way);
590 return sb.toString();
591 }
592
593 @Override
594 public String format(HistoryRelation relation) {
595 StringBuilder sb = new StringBuilder();
596 if (relation.get("type") != null) {
597 sb.append(relation.get("type"));
598 } else {
599 sb.append(tr("relation"));
600 }
601 sb.append(" (");
602 String nameTag = null;
603 Set<String> namingTags = new HashSet<>(getNamingtagsForRelations());
604 for (String n : relation.getTags().keySet()) {
605 // #3328: "note " and " note" are name tags too
606 if (namingTags.contains(n.trim())) {
607 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
608 nameTag = relation.getLocalName();
609 } else {
610 nameTag = relation.getName();
611 }
612 if (nameTag == null) {
613 nameTag = relation.get(n);
614 }
615 }
616 if (nameTag != null) {
617 break;
618 }
619 }
620 if (nameTag == null) {
621 sb.append(Long.toString(relation.getId())).append(", ");
622 } else {
623 sb.append('\"').append(nameTag).append("\", ");
624 }
625
626 int mbno = relation.getNumMembers();
627 sb.append(trn("{0} member", "{0} members", mbno, mbno)).append(')');
628
629 decorateNameWithId(sb, relation);
630 return sb.toString();
631 }
632
633 /**
634 * Builds a default tooltip text for an HistoryOsmPrimitive <code>primitive</code>.
635 *
636 * @param primitive the primitmive
637 * @return the tooltip text
638 */
639 public String buildDefaultToolTip(HistoryOsmPrimitive primitive) {
640 return buildDefaultToolTip(primitive.getId(), primitive.getTags());
641 }
642
643 /**
644 * Formats the given collection of primitives as an HTML unordered list.
645 * @param primitives collection of primitives to format
646 * @param maxElements the maximum number of elements to display
647 * @return HTML unordered list
648 */
649 public String formatAsHtmlUnorderedList(Collection<? extends OsmPrimitive> primitives, int maxElements) {
650 final Collection<String> displayNames = Utils.transform(primitives, new Function<OsmPrimitive, String>() {
651
652 @Override
653 public String apply(OsmPrimitive x) {
654 return x.getDisplayName(DefaultNameFormatter.this);
655 }
656 });
657 return Utils.joinAsHtmlUnorderedList(Utils.limit(displayNames, maxElements, "..."));
658 }
659
660 /**
661 * Formats the given primitive as an HTML unordered list.
662 * @param primitive primitive to format
663 * @return HTML unordered list
664 */
665 public String formatAsHtmlUnorderedList(OsmPrimitive primitive) {
666 return formatAsHtmlUnorderedList(Collections.singletonList(primitive), 1);
667 }
668}
Note: See TracBrowser for help on using the repository browser.