| 1 | // License: GPL. Copyright 2007 by Immanuel Scholz and others |
|---|
| 2 | package org.openstreetmap.josm.data.osm; |
|---|
| 3 | |
|---|
| 4 | import java.util.Comparator; |
|---|
| 5 | import java.util.HashMap; |
|---|
| 6 | |
|---|
| 7 | import org.openstreetmap.josm.gui.DefaultNameFormatter; |
|---|
| 8 | |
|---|
| 9 | /** Comparator, comparing by type and objects display names */ |
|---|
| 10 | public class OsmPrimitiveComparator implements Comparator<OsmPrimitive> { |
|---|
| 11 | final private HashMap<OsmPrimitive, String> cache= new HashMap<OsmPrimitive, String>(); |
|---|
| 12 | final private DefaultNameFormatter df = DefaultNameFormatter.getInstance(); |
|---|
| 13 | public boolean relationsFirst = false; |
|---|
| 14 | |
|---|
| 15 | private String cachedName(OsmPrimitive p) { |
|---|
| 16 | String name = cache.get(p); |
|---|
| 17 | if (name == null) { |
|---|
| 18 | name = p.getDisplayName(df); |
|---|
| 19 | cache.put(p, name); |
|---|
| 20 | } |
|---|
| 21 | return name; |
|---|
| 22 | } |
|---|
| 23 | |
|---|
| 24 | private int compareName(OsmPrimitive a, OsmPrimitive b) { |
|---|
| 25 | String an = cachedName(a); |
|---|
| 26 | String bn = cachedName(b); |
|---|
| 27 | // make sure display names starting with digits are the end of the |
|---|
| 28 | // list |
|---|
| 29 | if (Character.isDigit(an.charAt(0)) && Character.isDigit(bn.charAt(0))) |
|---|
| 30 | return an.compareTo(bn); |
|---|
| 31 | else if (Character.isDigit(an.charAt(0)) && !Character.isDigit(bn.charAt(0))) |
|---|
| 32 | return 1; |
|---|
| 33 | else if (!Character.isDigit(an.charAt(0)) && Character.isDigit(bn.charAt(0))) |
|---|
| 34 | return -1; |
|---|
| 35 | return an.compareTo(bn); |
|---|
| 36 | } |
|---|
| 37 | |
|---|
| 38 | private int compareType(OsmPrimitive a, OsmPrimitive b) { |
|---|
| 39 | if(relationsFirst) { |
|---|
| 40 | // show relations before ways, then nodes |
|---|
| 41 | if (a.getType().equals(OsmPrimitiveType.RELATION)) return -1; |
|---|
| 42 | if (a.getType().equals(OsmPrimitiveType.NODE)) return 1; |
|---|
| 43 | // a is a way |
|---|
| 44 | if (b.getType().equals(OsmPrimitiveType.RELATION)) return 1; |
|---|
| 45 | // b is a node |
|---|
| 46 | } else { |
|---|
| 47 | // show ways before relations, then nodes |
|---|
| 48 | if (a.getType().equals(OsmPrimitiveType.WAY)) return -1; |
|---|
| 49 | if (a.getType().equals(OsmPrimitiveType.NODE)) return 1; |
|---|
| 50 | // a is a relation |
|---|
| 51 | if (b.getType().equals(OsmPrimitiveType.WAY)) return 1; |
|---|
| 52 | // b is a node |
|---|
| 53 | } |
|---|
| 54 | return -1; |
|---|
| 55 | } |
|---|
| 56 | |
|---|
| 57 | public int compare(OsmPrimitive a, OsmPrimitive b) { |
|---|
| 58 | if (a.getType().equals(b.getType())) |
|---|
| 59 | return compareName(a, b); |
|---|
| 60 | return compareType(a, b); |
|---|
| 61 | } |
|---|
| 62 | } |
|---|