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

Last change on this file since 4751 was 4744, checked in by Don-vip, 12 years ago

Building presets

  • 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.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", "building"};
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("building") != null) ? tr("building") :
229 (way.get("landuse") != null) ? tr("landuse") : null;
230 }
231 if(n == null)
232 {
233 String s;
234 if((s = way.get("addr:housename")) != null) {
235 /* I18n: name of house as parameter */
236 n = tr("House {0}", s);
237 }
238 if(n == null && (s = way.get("addr:housenumber")) != null) {
239 String t = way.get("addr:street");
240 if(t != null) {
241 /* I18n: house number, street as parameter, number should remain
242 before street for better visibility */
243 n = tr("House number {0} at {1}", s, t);
244 }
245 else {
246 /* I18n: house number as parameter */
247 n = tr("House number {0}", s);
248 }
249 }
250 }
251 if(n == null || n.length() == 0) {
252 n = String.valueOf(way.getId());
253 }
254
255 name.append(n);
256 } else {
257 preset.nameTemplate.appendText(name, way);
258 }
259
260 int nodesNo = way.getNodesCount();
261 if (nodesNo > 1 && way.isClosed()) {
262 nodesNo--;
263 }
264 /* note: length == 0 should no longer happen, but leave the bracket code
265 nevertheless, who knows what future brings */
266 /* I18n: count of nodes as parameter */
267 String nodes = trn("{0} node", "{0} nodes", nodesNo, nodesNo);
268 name.append(" (").append(nodes).append(")");
269 }
270 decorateNameWithId(name, way);
271
272 String result = name.toString();
273 for (NameFormatterHook hook: formatHooks) {
274 String hookResult = hook.checkFormat(way, result);
275 if (hookResult != null)
276 return hookResult;
277 }
278
279 return result;
280 }
281
282 private final Comparator<Way> wayComparator = new Comparator<Way>() {
283 @Override
284 public int compare(Way w1, Way w2) {
285 return format(w1).compareTo(format(w2));
286 }
287 };
288
289 public Comparator<Way> getWayComparator() {
290 return wayComparator;
291 }
292
293
294 /**
295 * Formats a name for a relation
296 *
297 * @param relation the relation
298 * @return the name
299 */
300 public String format(Relation relation) {
301 StringBuilder name = new StringBuilder();
302 if (relation.isIncomplete()) {
303 name.append(tr("incomplete"));
304 } else {
305 TaggingPreset preset = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(relation);
306
307 formatRelationNameAndType(relation, name, preset);
308
309 int mbno = relation.getMembersCount();
310 name.append(trn("{0} member", "{0} members", mbno, mbno));
311
312 if (relation.hasIncompleteMembers()) {
313 name.append(", ").append(tr("incomplete"));
314 }
315
316 name.append(")");
317 }
318 decorateNameWithId(name, relation);
319
320 String result = name.toString();
321 for (NameFormatterHook hook: formatHooks) {
322 String hookResult = hook.checkFormat(relation, result);
323 if (hookResult != null)
324 return hookResult;
325 }
326
327 return result;
328 }
329
330 private void formatRelationNameAndType(Relation relation, StringBuilder result, TaggingPreset preset) {
331 if (preset == null) {
332 result.append(getRelationTypeName(relation));
333 String relationName = getRelationName(relation);
334 if (relationName == null) {
335 relationName = Long.toString(relation.getId());
336 } else {
337 relationName = "\"" + relationName + "\"";
338 }
339 result.append(" (").append(relationName).append(", ");
340 } else {
341 preset.nameTemplate.appendText(result, relation);
342 result.append("(");
343 }
344 }
345
346 private final Comparator<Relation> relationComparator = new Comparator<Relation>() {
347 @Override
348 public int compare(Relation r1, Relation r2) {
349 //TODO This doesn't work correctly with formatHooks
350
351 TaggingPreset preset1 = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(r1);
352 TaggingPreset preset2 = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(r2);
353
354 if (preset1 != null || preset2 != null) {
355 StringBuilder name1 = new StringBuilder();
356 formatRelationNameAndType(r1, name1, preset1);
357 StringBuilder name2 = new StringBuilder();
358 formatRelationNameAndType(r2, name2, preset2);
359
360 int comp = name1.toString().compareTo(name2.toString());
361 if (comp != 0)
362 return comp;
363 } else {
364
365 String type1 = getRelationTypeName(r1);
366 String type2 = getRelationTypeName(r2);
367
368 int comp = type1.compareTo(type2);
369 if (comp != 0)
370 return comp;
371
372 String name1 = getRelationName(r1);
373 String name2 = getRelationName(r2);
374
375 if (name1 == null && name2 == null)
376 return (r1.getUniqueId() > r2.getUniqueId())?1:-1;
377 else if (name1 == null)
378 return -1;
379 else if (name2 == null)
380 return 1;
381 else if (!name1.isEmpty() && !name2.isEmpty() && Character.isDigit(name1.charAt(0)) && Character.isDigit(name2.charAt(0))) {
382 //Compare numerically
383 String ln1 = getLeadingNumber(name1);
384 String ln2 = getLeadingNumber(name2);
385
386 comp = Long.valueOf(ln1).compareTo(Long.valueOf(ln2));
387 if (comp != 0)
388 return comp;
389
390 // put 1 before 0001
391 comp = ln1.compareTo(ln2);
392 if (comp != 0)
393 return comp;
394
395 comp = name1.substring(ln1.length()).compareTo(name2.substring(ln2.length()));
396 if (comp != 0)
397 return comp;
398 } else {
399 comp = name1.compareToIgnoreCase(name2);
400 if (comp != 0)
401 return comp;
402 }
403 }
404
405
406 if (r1.getMembersCount() != r2.getMembersCount())
407 return (r1.getMembersCount() > r2.getMembersCount())?1:-1;
408
409 int comp = Boolean.valueOf(r1.hasIncompleteMembers()).compareTo(Boolean.valueOf(r2.hasIncompleteMembers()));
410 if (comp != 0)
411 return comp;
412
413 return r1.getUniqueId() > r2.getUniqueId()?1:-1;
414 }
415 };
416
417 public Comparator<Relation> getRelationComparator() {
418 return relationComparator;
419 }
420
421 private String getLeadingNumber(String s) {
422 int i = 0;
423 while (i < s.length() && Character.isDigit(s.charAt(i))) {
424 i++;
425 }
426 return s.substring(0, i);
427 }
428
429 private String getRelationTypeName(IRelation relation) {
430 String name = trc("Relation type", relation.get("type"));
431 if (name == null) {
432 name = (relation.get("public_transport") != null) ? tr("public transport") : null;
433 }
434 if (name == null) {
435 String building = relation.get("building");
436 if (OsmUtils.isTrue(building)) {
437 name = tr("building");
438 } else if(building != null)
439 {
440 name = tr(building); // translate tag!
441 }
442 }
443 if (name == null) {
444 name = trc("Place type", relation.get("place"));
445 }
446 if (name == null) {
447 name = tr("relation");
448 }
449 String admin_level = relation.get("admin_level");
450 if (admin_level != null) {
451 name += "["+admin_level+"]";
452 }
453
454 for (NameFormatterHook hook: formatHooks) {
455 String hookResult = hook.checkRelationTypeName(relation, name);
456 if (hookResult != null)
457 return hookResult;
458 }
459
460 return name;
461 }
462
463 private String getNameTagValue(IRelation relation, String nameTag) {
464 if (nameTag.equals("name")) {
465 if (Main.pref.getBoolean("osm-primitives.localize-name", true))
466 return relation.getLocalName();
467 else
468 return relation.getName();
469 } else if (nameTag.equals(":LocationCode")) {
470 for (String m : relation.keySet()) {
471 if (m.endsWith(nameTag))
472 return relation.get(m);
473 }
474 return null;
475 } else if (OsmUtils.isTrue(relation.get(nameTag))) {
476 return tr(nameTag);
477 } else if (OsmUtils.isFalse(relation.get(nameTag))) {
478 return null;
479 } else {
480 return trc_lazy(nameTag, I18n.escape(relation.get(nameTag)));
481 }
482 }
483
484 private String getRelationName(IRelation relation) {
485 String nameTag = null;
486 for (String n : getNamingtagsForRelations()) {
487 nameTag = getNameTagValue(relation, n);
488 if (nameTag != null)
489 return nameTag;
490 }
491 return null;
492 }
493
494 /**
495 * Formats a name for a changeset
496 *
497 * @param changeset the changeset
498 * @return the name
499 */
500 public String format(Changeset changeset) {
501 return tr("Changeset {0}",changeset.getId());
502 }
503
504 /**
505 * Builds a default tooltip text for the primitive <code>primitive</code>.
506 *
507 * @param primitive the primitmive
508 * @return the tooltip text
509 */
510 public String buildDefaultToolTip(IPrimitive primitive) {
511 StringBuilder sb = new StringBuilder();
512 sb.append("<html>");
513 sb.append("<strong>id</strong>=")
514 .append(primitive.getId())
515 .append("<br>");
516 ArrayList<String> keyList = new ArrayList<String>(primitive.keySet());
517 Collections.sort(keyList);
518 for (int i = 0; i < keyList.size(); i++) {
519 if (i > 0) {
520 sb.append("<br>");
521 }
522 String key = keyList.get(i);
523 sb.append("<strong>")
524 .append(key)
525 .append("</strong>")
526 .append("=");
527 String value = primitive.get(key);
528 while(value.length() != 0) {
529 sb.append(value.substring(0,Math.min(50, value.length())));
530 if (value.length() > 50) {
531 sb.append("<br>");
532 value = value.substring(50);
533 } else {
534 value = "";
535 }
536 }
537 }
538 sb.append("</html>");
539 return sb.toString();
540 }
541
542 /**
543 * Decorates the name of primitive with its id, if the preference
544 * <tt>osm-primitives.showid</tt> is set.
545 *
546 * The id is append to the {@see StringBuilder} passed in in <code>name</code>.
547 *
548 * @param name the name without the id
549 * @param primitive the primitive
550 */
551 protected void decorateNameWithId(StringBuilder name, HistoryOsmPrimitive primitive) {
552 if (Main.pref.getBoolean("osm-primitives.showid")) {
553 name.append(tr(" [id: {0}]", primitive.getId()));
554 }
555 }
556
557 /**
558 * Formats a name for a history node
559 *
560 * @param node the node
561 * @return the name
562 */
563 public String format(HistoryNode node) {
564 StringBuilder sb = new StringBuilder();
565 String name;
566 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
567 name = node.getLocalName();
568 } else {
569 name = node.getName();
570 }
571 if (name == null) {
572 sb.append(node.getId());
573 } else {
574 sb.append(name);
575 }
576 sb.append(" (")
577 .append(node.getCoords().latToString(CoordinateFormat.getDefaultFormat()))
578 .append(", ")
579 .append(node.getCoords().lonToString(CoordinateFormat.getDefaultFormat()))
580 .append(")");
581 decorateNameWithId(sb, node);
582 return sb.toString();
583 }
584
585 /**
586 * Formats a name for a way
587 *
588 * @param way the way
589 * @return the name
590 */
591 public String format(HistoryWay way) {
592 StringBuilder sb = new StringBuilder();
593 String name;
594 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
595 name = way.getLocalName();
596 } else {
597 name = way.getName();
598 }
599 if (name != null) {
600 sb.append(name);
601 }
602 if (sb.length() == 0 && way.get("ref") != null) {
603 sb.append(way.get("ref"));
604 }
605 if (sb.length() == 0) {
606 sb.append(
607 (way.get("highway") != null) ? tr("highway") :
608 (way.get("railway") != null) ? tr("railway") :
609 (way.get("waterway") != null) ? tr("waterway") :
610 (way.get("landuse") != null) ? tr("landuse") : ""
611 );
612 }
613
614 int nodesNo = way.isClosed() ? way.getNumNodes() -1 : way.getNumNodes();
615 String nodes = trn("{0} node", "{0} nodes", nodesNo, nodesNo);
616 if(sb.length() == 0 ) {
617 sb.append(way.getId());
618 }
619 /* note: length == 0 should no longer happen, but leave the bracket code
620 nevertheless, who knows what future brings */
621 sb.append((sb.length() > 0) ? " ("+nodes+")" : nodes);
622 decorateNameWithId(sb, way);
623 return sb.toString();
624 }
625
626 /**
627 * Formats a name for a {@see HistoryRelation})
628 *
629 * @param relation the relation
630 * @return the name
631 */
632 public String format(HistoryRelation relation) {
633 StringBuilder sb = new StringBuilder();
634 if (relation.get("type") != null) {
635 sb.append(relation.get("type"));
636 } else {
637 sb.append(tr("relation"));
638 }
639 sb.append(" (");
640 String nameTag = null;
641 Set<String> namingTags = new HashSet<String>(getNamingtagsForRelations());
642 for (String n : relation.getTags().keySet()) {
643 // #3328: "note " and " note" are name tags too
644 if (namingTags.contains(n.trim())) {
645 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) {
646 nameTag = relation.getLocalName();
647 } else {
648 nameTag = relation.getName();
649 }
650 if (nameTag == null) {
651 nameTag = relation.get(n);
652 }
653 }
654 if (nameTag != null) {
655 break;
656 }
657 }
658 if (nameTag == null) {
659 sb.append(Long.toString(relation.getId())).append(", ");
660 } else {
661 sb.append("\"").append(nameTag).append("\", ");
662 }
663
664 int mbno = relation.getNumMembers();
665 sb.append(trn("{0} member", "{0} members", mbno, mbno)).append(")");
666
667 decorateNameWithId(sb, relation);
668 return sb.toString();
669 }
670
671 /**
672 * Builds a default tooltip text for an HistoryOsmPrimitive <code>primitive</code>.
673 *
674 * @param primitive the primitmive
675 * @return the tooltip text
676 */
677 public String buildDefaultToolTip(HistoryOsmPrimitive primitive) {
678 StringBuilder sb = new StringBuilder();
679 sb.append("<html>");
680 sb.append("<strong>id</strong>=")
681 .append(primitive.getId())
682 .append("<br>");
683 ArrayList<String> keyList = new ArrayList<String>(primitive.getTags().keySet());
684 Collections.sort(keyList);
685 for (int i = 0; i < keyList.size(); i++) {
686 if (i > 0) {
687 sb.append("<br>");
688 }
689 String key = keyList.get(i);
690 sb.append("<strong>")
691 .append(key)
692 .append("</strong>")
693 .append("=");
694 String value = primitive.get(key);
695 while(value.length() != 0) {
696 sb.append(value.substring(0,Math.min(50, value.length())));
697 if (value.length() > 50) {
698 sb.append("<br>");
699 value = value.substring(50);
700 } else {
701 value = "";
702 }
703 }
704 }
705 sb.append("</html>");
706 return sb.toString();
707 }
708}
Note: See TracBrowser for help on using the repository browser.