001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.gui; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005import static org.openstreetmap.josm.tools.I18n.trc; 006import static org.openstreetmap.josm.tools.I18n.trc_lazy; 007import static org.openstreetmap.josm.tools.I18n.trn; 008 009import java.awt.ComponentOrientation; 010import java.util.ArrayList; 011import java.util.Arrays; 012import java.util.Collection; 013import java.util.Collections; 014import java.util.Comparator; 015import java.util.HashSet; 016import java.util.LinkedList; 017import java.util.List; 018import java.util.Locale; 019import java.util.Map; 020import java.util.Set; 021 022import org.openstreetmap.josm.Main; 023import org.openstreetmap.josm.data.coor.CoordinateFormat; 024import org.openstreetmap.josm.data.coor.LatLon; 025import org.openstreetmap.josm.data.osm.Changeset; 026import org.openstreetmap.josm.data.osm.IPrimitive; 027import org.openstreetmap.josm.data.osm.IRelation; 028import org.openstreetmap.josm.data.osm.NameFormatter; 029import org.openstreetmap.josm.data.osm.Node; 030import org.openstreetmap.josm.data.osm.OsmPrimitive; 031import org.openstreetmap.josm.data.osm.OsmUtils; 032import org.openstreetmap.josm.data.osm.Relation; 033import org.openstreetmap.josm.data.osm.Way; 034import org.openstreetmap.josm.data.osm.history.HistoryNameFormatter; 035import org.openstreetmap.josm.data.osm.history.HistoryNode; 036import org.openstreetmap.josm.data.osm.history.HistoryOsmPrimitive; 037import org.openstreetmap.josm.data.osm.history.HistoryRelation; 038import org.openstreetmap.josm.data.osm.history.HistoryWay; 039import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset; 040import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetNameTemplateList; 041import org.openstreetmap.josm.tools.AlphanumComparator; 042import org.openstreetmap.josm.tools.I18n; 043import org.openstreetmap.josm.tools.Utils; 044import org.openstreetmap.josm.tools.Utils.Function; 045 046/** 047 * This is the default implementation of a {@link NameFormatter} for names of {@link OsmPrimitive}s 048 * and {@link HistoryOsmPrimitive}s. 049 * @since 1990 050 */ 051public class DefaultNameFormatter implements NameFormatter, HistoryNameFormatter { 052 053 private static DefaultNameFormatter instance; 054 055 private static final List<NameFormatterHook> formatHooks = new LinkedList<>(); 056 057 /** 058 * Replies the unique instance of this formatter 059 * 060 * @return the unique instance of this formatter 061 */ 062 public static synchronized DefaultNameFormatter getInstance() { 063 if (instance == null) { 064 instance = new DefaultNameFormatter(); 065 } 066 return instance; 067 } 068 069 /** 070 * Registers a format hook. Adds the hook at the first position of the format hooks. 071 * (for plugins) 072 * 073 * @param hook the format hook. Ignored if null. 074 */ 075 public static void registerFormatHook(NameFormatterHook hook) { 076 if (hook == null) return; 077 if (!formatHooks.contains(hook)) { 078 formatHooks.add(0, hook); 079 } 080 } 081 082 /** 083 * Unregisters a format hook. Removes the hook from the list of format hooks. 084 * 085 * @param hook the format hook. Ignored if null. 086 */ 087 public static void unregisterFormatHook(NameFormatterHook hook) { 088 if (hook == null) return; 089 if (formatHooks.contains(hook)) { 090 formatHooks.remove(hook); 091 } 092 } 093 094 /** The default list of tags which are used as naming tags in relations. 095 * A ? prefix indicates a boolean value, for which the key (instead of the value) is used. 096 */ 097 protected static final String[] DEFAULT_NAMING_TAGS_FOR_RELATIONS = {"name", "ref", "restriction", "landuse", "natural", 098 "public_transport", ":LocationCode", "note", "?building"}; 099 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 * @return HTML unordered list 647 */ 648 public String formatAsHtmlUnorderedList(Collection<? extends OsmPrimitive> primitives) { 649 return Utils.joinAsHtmlUnorderedList(Utils.transform(primitives, new Function<OsmPrimitive, String>() { 650 651 @Override 652 public String apply(OsmPrimitive x) { 653 return x.getDisplayName(DefaultNameFormatter.this); 654 } 655 })); 656 } 657 658 /** 659 * Formats the given primitive(s) as an HTML unordered list. 660 * @param primitives primitive(s) to format 661 * @return HTML unordered list 662 */ 663 public String formatAsHtmlUnorderedList(OsmPrimitive... primitives) { 664 return formatAsHtmlUnorderedList(Arrays.asList(primitives)); 665 } 666}