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 private 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; 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 static StringBuilder 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 return result; 349 } 350 351 private final Comparator<Relation> relationComparator = new Comparator<Relation>() { 352 @Override 353 public int compare(Relation r1, Relation r2) { 354 //TODO This doesn't work correctly with formatHooks 355 356 TaggingPreset preset1 = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(r1); 357 TaggingPreset preset2 = TaggingPresetNameTemplateList.getInstance().findPresetTemplate(r2); 358 359 if (preset1 != null || preset2 != null) { 360 String name1 = formatRelationNameAndType(r1, new StringBuilder(), preset1).toString(); 361 String name2 = formatRelationNameAndType(r2, new StringBuilder(), preset2).toString(); 362 363 int comp = AlphanumComparator.getInstance().compare(name1, name2); 364 if (comp != 0) 365 return comp; 366 } else { 367 368 String type1 = getRelationTypeName(r1); 369 String type2 = getRelationTypeName(r2); 370 371 int comp = AlphanumComparator.getInstance().compare(type1, type2); 372 if (comp != 0) 373 return comp; 374 375 String name1 = getRelationName(r1); 376 String name2 = getRelationName(r2); 377 378 comp = AlphanumComparator.getInstance().compare(name1, name2); 379 if (comp != 0) 380 return comp; 381 } 382 383 int comp = Integer.compare(r1.getMembersCount(), r2.getMembersCount()); 384 if (comp != 0) 385 return comp; 386 387 388 comp = Boolean.compare(r1.hasIncompleteMembers(), r2.hasIncompleteMembers()); 389 if (comp != 0) 390 return comp; 391 392 return Long.compare(r1.getUniqueId(), r2.getUniqueId()); 393 } 394 }; 395 396 @Override 397 public Comparator<Relation> getRelationComparator() { 398 return relationComparator; 399 } 400 401 private static String getRelationTypeName(IRelation relation) { 402 String name = trc("Relation type", relation.get("type")); 403 if (name == null) { 404 name = (relation.get("public_transport") != null) ? tr("public transport") : null; 405 } 406 if (name == null) { 407 String building = relation.get("building"); 408 if (OsmUtils.isTrue(building)) { 409 name = tr("building"); 410 } else if (building != null) { 411 name = tr(building); // translate tag! 412 } 413 } 414 if (name == null) { 415 name = trc("Place type", relation.get("place")); 416 } 417 if (name == null) { 418 name = tr("relation"); 419 } 420 String adminLevel = relation.get("admin_level"); 421 if (adminLevel != null) { 422 name += '['+adminLevel+']'; 423 } 424 425 for (NameFormatterHook hook: formatHooks) { 426 String hookResult = hook.checkRelationTypeName(relation, name); 427 if (hookResult != null) 428 return hookResult; 429 } 430 431 return name; 432 } 433 434 private static String getNameTagValue(IRelation relation, String nameTag) { 435 if ("name".equals(nameTag)) { 436 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) 437 return relation.getLocalName(); 438 else 439 return relation.getName(); 440 } else if (":LocationCode".equals(nameTag)) { 441 for (String m : relation.keySet()) { 442 if (m.endsWith(nameTag)) 443 return relation.get(m); 444 } 445 return null; 446 } else if (nameTag.startsWith("?") && OsmUtils.isTrue(relation.get(nameTag.substring(1)))) { 447 return tr(nameTag.substring(1)); 448 } else if (nameTag.startsWith("?") && OsmUtils.isFalse(relation.get(nameTag.substring(1)))) { 449 return null; 450 } else if (nameTag.startsWith("?")) { 451 return trc_lazy(nameTag, I18n.escape(relation.get(nameTag.substring(1)))); 452 } else { 453 return trc_lazy(nameTag, I18n.escape(relation.get(nameTag))); 454 } 455 } 456 457 private static String getRelationName(IRelation relation) { 458 String nameTag; 459 for (String n : getNamingtagsForRelations()) { 460 nameTag = getNameTagValue(relation, n); 461 if (nameTag != null) 462 return nameTag; 463 } 464 return null; 465 } 466 467 @Override 468 public String format(Changeset changeset) { 469 return tr("Changeset {0}", changeset.getId()); 470 } 471 472 /** 473 * Builds a default tooltip text for the primitive <code>primitive</code>. 474 * 475 * @param primitive the primitmive 476 * @return the tooltip text 477 */ 478 public String buildDefaultToolTip(IPrimitive primitive) { 479 return buildDefaultToolTip(primitive.getId(), primitive.getKeys()); 480 } 481 482 private static String buildDefaultToolTip(long id, Map<String, String> tags) { 483 StringBuilder sb = new StringBuilder(128); 484 sb.append("<html><strong>id</strong>=") 485 .append(id) 486 .append("<br>"); 487 List<String> keyList = new ArrayList<>(tags.keySet()); 488 Collections.sort(keyList); 489 for (int i = 0; i < keyList.size(); i++) { 490 if (i > 0) { 491 sb.append("<br>"); 492 } 493 String key = keyList.get(i); 494 sb.append("<strong>") 495 .append(key) 496 .append("</strong>="); 497 String value = tags.get(key); 498 while (!value.isEmpty()) { 499 sb.append(value.substring(0, Math.min(50, value.length()))); 500 if (value.length() > 50) { 501 sb.append("<br>"); 502 value = value.substring(50); 503 } else { 504 value = ""; 505 } 506 } 507 } 508 sb.append("</html>"); 509 return sb.toString(); 510 } 511 512 /** 513 * Decorates the name of primitive with its id, if the preference 514 * <tt>osm-primitives.showid</tt> is set. 515 * 516 * The id is append to the {@link StringBuilder} passed in <code>name</code>. 517 * 518 * @param name the name without the id 519 * @param primitive the primitive 520 */ 521 protected void decorateNameWithId(StringBuilder name, HistoryOsmPrimitive primitive) { 522 if (Main.pref.getBoolean("osm-primitives.showid")) { 523 name.append(tr(" [id: {0}]", primitive.getId())); 524 } 525 } 526 527 @Override 528 public String format(HistoryNode node) { 529 StringBuilder sb = new StringBuilder(); 530 String name; 531 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) { 532 name = node.getLocalName(); 533 } else { 534 name = node.getName(); 535 } 536 if (name == null) { 537 sb.append(node.getId()); 538 } else { 539 sb.append(name); 540 } 541 LatLon coord = node.getCoords(); 542 if (coord != null) { 543 sb.append(" (") 544 .append(coord.latToString(CoordinateFormat.getDefaultFormat())) 545 .append(", ") 546 .append(coord.lonToString(CoordinateFormat.getDefaultFormat())) 547 .append(')'); 548 } 549 decorateNameWithId(sb, node); 550 return sb.toString(); 551 } 552 553 @Override 554 public String format(HistoryWay way) { 555 StringBuilder sb = new StringBuilder(); 556 String name; 557 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) { 558 name = way.getLocalName(); 559 } else { 560 name = way.getName(); 561 } 562 if (name != null) { 563 sb.append(name); 564 } 565 if (sb.length() == 0 && way.get("ref") != null) { 566 sb.append(way.get("ref")); 567 } 568 if (sb.length() == 0) { 569 sb.append( 570 (way.get("highway") != null) ? tr("highway") : 571 (way.get("railway") != null) ? tr("railway") : 572 (way.get("waterway") != null) ? tr("waterway") : 573 (way.get("landuse") != null) ? tr("landuse") : "" 574 ); 575 } 576 577 int nodesNo = way.isClosed() ? way.getNumNodes() -1 : way.getNumNodes(); 578 String nodes = trn("{0} node", "{0} nodes", nodesNo, nodesNo); 579 if (sb.length() == 0) { 580 sb.append(way.getId()); 581 } 582 /* note: length == 0 should no longer happen, but leave the bracket code 583 nevertheless, who knows what future brings */ 584 sb.append((sb.length() > 0) ? " ("+nodes+')' : nodes); 585 decorateNameWithId(sb, way); 586 return sb.toString(); 587 } 588 589 @Override 590 public String format(HistoryRelation relation) { 591 StringBuilder sb = new StringBuilder(); 592 if (relation.get("type") != null) { 593 sb.append(relation.get("type")); 594 } else { 595 sb.append(tr("relation")); 596 } 597 sb.append(" ("); 598 String nameTag = null; 599 Set<String> namingTags = new HashSet<>(getNamingtagsForRelations()); 600 for (String n : relation.getTags().keySet()) { 601 // #3328: "note " and " note" are name tags too 602 if (namingTags.contains(n.trim())) { 603 if (Main.pref.getBoolean("osm-primitives.localize-name", true)) { 604 nameTag = relation.getLocalName(); 605 } else { 606 nameTag = relation.getName(); 607 } 608 if (nameTag == null) { 609 nameTag = relation.get(n); 610 } 611 } 612 if (nameTag != null) { 613 break; 614 } 615 } 616 if (nameTag == null) { 617 sb.append(Long.toString(relation.getId())).append(", "); 618 } else { 619 sb.append('\"').append(nameTag).append("\", "); 620 } 621 622 int mbno = relation.getNumMembers(); 623 sb.append(trn("{0} member", "{0} members", mbno, mbno)).append(')'); 624 625 decorateNameWithId(sb, relation); 626 return sb.toString(); 627 } 628 629 /** 630 * Builds a default tooltip text for an HistoryOsmPrimitive <code>primitive</code>. 631 * 632 * @param primitive the primitmive 633 * @return the tooltip text 634 */ 635 public String buildDefaultToolTip(HistoryOsmPrimitive primitive) { 636 return buildDefaultToolTip(primitive.getId(), primitive.getTags()); 637 } 638 639 /** 640 * Formats the given collection of primitives as an HTML unordered list. 641 * @param primitives collection of primitives to format 642 * @param maxElements the maximum number of elements to display 643 * @return HTML unordered list 644 */ 645 public String formatAsHtmlUnorderedList(Collection<? extends OsmPrimitive> primitives, int maxElements) { 646 final Collection<String> displayNames = Utils.transform(primitives, new Function<OsmPrimitive, String>() { 647 648 @Override 649 public String apply(OsmPrimitive x) { 650 return x.getDisplayName(DefaultNameFormatter.this); 651 } 652 }); 653 return Utils.joinAsHtmlUnorderedList(Utils.limit(displayNames, maxElements, "...")); 654 } 655 656 /** 657 * Formats the given primitive as an HTML unordered list. 658 * @param primitive primitive to format 659 * @return HTML unordered list 660 */ 661 public String formatAsHtmlUnorderedList(OsmPrimitive primitive) { 662 return formatAsHtmlUnorderedList(Collections.singletonList(primitive), 1); 663 } 664}