001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.validation.tests;
003
004import static org.openstreetmap.josm.data.validation.tests.CrossingWays.HIGHWAY;
005import static org.openstreetmap.josm.tools.I18n.tr;
006
007import java.util.ArrayList;
008import java.util.Arrays;
009import java.util.HashMap;
010import java.util.HashSet;
011import java.util.List;
012import java.util.Locale;
013import java.util.Map;
014import java.util.Map.Entry;
015import java.util.Set;
016import java.util.stream.Collectors;
017
018import org.openstreetmap.josm.command.ChangePropertyCommand;
019import org.openstreetmap.josm.data.osm.Node;
020import org.openstreetmap.josm.data.osm.OsmPrimitive;
021import org.openstreetmap.josm.data.osm.OsmUtils;
022import org.openstreetmap.josm.data.osm.Way;
023import org.openstreetmap.josm.data.validation.Severity;
024import org.openstreetmap.josm.data.validation.Test;
025import org.openstreetmap.josm.data.validation.TestError;
026import org.openstreetmap.josm.tools.Logging;
027import org.openstreetmap.josm.tools.Utils;
028
029/**
030 * Test that performs semantic checks on highways.
031 * @since 5902
032 */
033public class Highways extends Test {
034
035    protected static final int WRONG_ROUNDABOUT_HIGHWAY = 2701;
036    protected static final int MISSING_PEDESTRIAN_CROSSING = 2702;
037    protected static final int SOURCE_MAXSPEED_UNKNOWN_COUNTRY_CODE = 2703;
038    protected static final int SOURCE_MAXSPEED_UNKNOWN_CONTEXT = 2704;
039    protected static final int SOURCE_MAXSPEED_CONTEXT_MISMATCH_VS_MAXSPEED = 2705;
040    protected static final int SOURCE_MAXSPEED_CONTEXT_MISMATCH_VS_HIGHWAY = 2706;
041    protected static final int SOURCE_WRONG_LINK = 2707;
042    protected static final int DIFFERENT_LAYERS = 2708;
043
044    protected static final String SOURCE_MAXSPEED = "source:maxspeed";
045
046    /**
047     * Classified highways in order of importance
048     */
049    // CHECKSTYLE.OFF: SingleSpaceSeparator
050    static final List<String> CLASSIFIED_HIGHWAYS = Arrays.asList(
051            "motorway",  "motorway_link",
052            "trunk",     "trunk_link",
053            "primary",   "primary_link",
054            "secondary", "secondary_link",
055            "tertiary",  "tertiary_link",
056            "unclassified",
057            "residential",
058            "living_street");
059    // CHECKSTYLE.ON: SingleSpaceSeparator
060
061    private static final Set<String> KNOWN_SOURCE_MAXSPEED_CONTEXTS = new HashSet<>(Arrays.asList(
062            "urban", "rural", "zone", "zone10", "zone:10", "zone20", "zone:20", "zone30", "zone:30", "zone40", "zone:40", "zone60", "zone:60",
063            "nsl_single", "nsl_dual", "motorway", "trunk", "living_street", "bicycle_road", "expressway"));
064
065    private static final Set<String> ISO_COUNTRIES = new HashSet<>(Arrays.asList(Locale.getISOCountries()));
066
067    private boolean leftByPedestrians;
068    private boolean leftByCyclists;
069    private boolean leftByCars;
070    private int pedestrianWays;
071    private int cyclistWays;
072    private int carsWays;
073
074    /**
075     * Constructs a new {@code Highways} test.
076     */
077    public Highways() {
078        super(tr("Highways"), tr("Performs semantic checks on highways."));
079    }
080
081    @Override
082    public void visit(Node n) {
083        if (n.isUsable()) {
084            if (!n.hasTag("crossing", "no")
085             && !(n.hasKey("crossing") && (n.hasTag(HIGHWAY, "crossing")
086                                        || n.hasTag(HIGHWAY, "traffic_signals")))
087             && n.isReferredByWays(2)) {
088                testMissingPedestrianCrossing(n);
089            }
090            if (n.hasKey(SOURCE_MAXSPEED)) {
091                // Check maxspeed but not context against highway for nodes
092                // as maxspeed is not set on highways here but on signs, speed cameras, etc.
093                testSourceMaxspeed(n, false);
094            }
095            if (n.isReferredByWays(2)) {
096                testDifferentLayers(n);
097            }
098        }
099    }
100
101    @Override
102    public void visit(Way w) {
103        if (w.isUsable()) {
104            if (w.isClosed() && w.hasTag(HIGHWAY, CLASSIFIED_HIGHWAYS) && w.hasTag("junction", "circular", "roundabout")
105                    && IN_DOWNLOADED_AREA_STRICT.test(w)) {
106                // TODO: find out how to handle split roundabouts (see #12841)
107                testWrongRoundabout(w);
108            }
109            if (w.hasKey(SOURCE_MAXSPEED)) {
110                // Check maxspeed, including context against highway
111                testSourceMaxspeed(w, true);
112            }
113            testHighwayLink(w);
114        }
115    }
116
117    private void testWrongRoundabout(Way w) {
118        Map<String, List<Way>> map = new HashMap<>();
119        // Count all highways (per type) connected to this roundabout, except correct links
120        // As roundabouts are closed ways, take care of not processing the first/last node twice
121        for (Node n : new HashSet<>(w.getNodes())) {
122            for (Way h : (Iterable<Way>) n.referrers(Way.class)::iterator) {
123                String value = h.get(HIGHWAY);
124                if (h != w && value != null) {
125                    boolean link = value.endsWith("_link");
126                    boolean linkOk = isHighwayLinkOkay(h);
127                    if (link && !linkOk) {
128                        // "Autofix" bad link value to avoid false positive in roundabout check
129                        value = value.replaceAll("_link$", "");
130                    }
131                    if (!link || !linkOk) {
132                        List<Way> list = map.computeIfAbsent(value, k -> new ArrayList<>());
133                        list.add(h);
134                    }
135                }
136            }
137        }
138        // The roundabout should carry the highway tag of its two biggest highways
139        for (String s : CLASSIFIED_HIGHWAYS) {
140            List<Way> list = map.get(s);
141            if (list != null && list.size() >= 2) {
142                // Except when a single road is connected, but with two oneway segments
143                Boolean oneway1 = OsmUtils.getOsmBoolean(list.get(0).get("oneway"));
144                Boolean oneway2 = OsmUtils.getOsmBoolean(list.get(1).get("oneway"));
145                if (list.size() > 2 || oneway1 == null || oneway2 == null || !oneway1 || !oneway2) {
146                    // Error when the highway tags do not match
147                    String value = w.get(HIGHWAY);
148                    if (!value.equals(s)) {
149                        errors.add(TestError.builder(this, Severity.WARNING, WRONG_ROUNDABOUT_HIGHWAY)
150                                .message(tr("Incorrect roundabout (highway: {0} instead of {1})", value, s))
151                                .primitives(w)
152                                .fix(() -> new ChangePropertyCommand(w, HIGHWAY, s))
153                                .build());
154                    }
155                    break;
156                }
157            }
158        }
159    }
160
161    /**
162     * Determines if the given link road is correct, see https://wiki.openstreetmap.org/wiki/Highway_link.
163     * @param way link road
164     * @return {@code true} if the link road is correct or if the check cannot be performed due to missing data
165     */
166    public static boolean isHighwayLinkOkay(final Way way) {
167        final String highway = way.get(HIGHWAY);
168        if (highway == null || !highway.endsWith("_link")
169                || !IN_DOWNLOADED_AREA.test(way.getNode(0)) || !IN_DOWNLOADED_AREA.test(way.getNode(way.getNodesCount()-1))) {
170            return true;
171        }
172
173        final Set<OsmPrimitive> referrers = new HashSet<>();
174
175        if (way.isClosed()) {
176            // for closed way we need to check all adjacent ways
177            for (Node n: way.getNodes()) {
178                referrers.addAll(n.getReferrers());
179            }
180        } else {
181            referrers.addAll(way.firstNode().getReferrers());
182            referrers.addAll(way.lastNode().getReferrers());
183        }
184
185        // Find ways of same class (exact class of class_link)
186        List<Way> sameClass = Utils.filteredCollection(referrers, Way.class).stream().filter(
187                otherWay -> !way.equals(otherWay) && otherWay.hasTag(HIGHWAY, highway, highway.replaceAll("_link$", "")))
188                .collect(Collectors.toList());
189        if (sameClass.size() > 1) {
190            // It is possible to have a class_link between 2 segments of same class
191            // in roundabout designs that physically separate a specific turn from the main roundabout
192            // But if we have more than a single adjacent class, and one of them is a roundabout, that's an error
193            for (Way w : sameClass) {
194                if (w.hasTag("junction", "circular", "roundabout")) {
195                    return false;
196                }
197            }
198        }
199        // Link roads should always at least one adjacent segment of same class
200        return !sameClass.isEmpty();
201    }
202
203    private void testHighwayLink(final Way way) {
204        if (!isHighwayLinkOkay(way)) {
205            errors.add(TestError.builder(this, Severity.WARNING, SOURCE_WRONG_LINK)
206                    .message(tr("Highway link is not linked to adequate highway/link"))
207                    .primitives(way)
208                    .build());
209        }
210    }
211
212    private void testMissingPedestrianCrossing(Node n) {
213        leftByPedestrians = false;
214        leftByCyclists = false;
215        leftByCars = false;
216        pedestrianWays = 0;
217        cyclistWays = 0;
218        carsWays = 0;
219
220        if (n.hasTag("highway", "crossing") && !n.hasKey("crossing"))
221            return; // see #20905 handled by mapcss test
222
223        for (Way w : n.getParentWays()) {
224            String highway = w.get(HIGHWAY);
225            if (highway != null) {
226                if ("footway".equals(highway) || "path".equals(highway)) {
227                    handlePedestrianWay(n, w);
228                    if (w.hasTag("bicycle", "yes", "designated")) {
229                        handleCyclistWay(n, w);
230                    }
231                } else if ("cycleway".equals(highway)) {
232                    handleCyclistWay(n, w);
233                    if (w.hasTag("foot", "yes", "designated")) {
234                        handlePedestrianWay(n, w);
235                    }
236                } else if (CLASSIFIED_HIGHWAYS.contains(highway)) {
237                    // Only look at classified highways for now:
238                    // - service highways support is TBD (see #9141 comments)
239                    // - roads should be determined first. Another warning is raised anyway
240                    handleCarWay(n, w);
241                }
242                if ((leftByPedestrians || leftByCyclists) && leftByCars) {
243                    errors.add(TestError.builder(this, Severity.OTHER, MISSING_PEDESTRIAN_CROSSING)
244                            .message(tr("Incomplete pedestrian crossing tagging. Required tags are {0} and {1}.",
245                            "highway=crossing|traffic_signals", "crossing=*"))
246                            .primitives(n)
247                            .build());
248                    return;
249                }
250            }
251        }
252    }
253
254    private void handleCarWay(Node n, Way w) {
255        carsWays++;
256        if (!w.isFirstLastNode(n) || carsWays > 1) {
257            leftByCars = true;
258        }
259    }
260
261    private void handleCyclistWay(Node n, Way w) {
262        cyclistWays++;
263        if (!w.isFirstLastNode(n) || cyclistWays > 1) {
264            leftByCyclists = true;
265        }
266    }
267
268    private void handlePedestrianWay(Node n, Way w) {
269        pedestrianWays++;
270        if (!w.isFirstLastNode(n) || pedestrianWays > 1) {
271            leftByPedestrians = true;
272        }
273    }
274
275    private void testSourceMaxspeed(OsmPrimitive p, boolean testContextHighway) {
276        String value = p.get(SOURCE_MAXSPEED);
277        if (value.matches("[A-Z]{2}:.+")) {
278            int index = value.indexOf(':');
279            // Check country
280            String country = value.substring(0, index);
281            if (!ISO_COUNTRIES.contains(country)) {
282                final TestError.Builder error = TestError.builder(this, Severity.WARNING, SOURCE_MAXSPEED_UNKNOWN_COUNTRY_CODE)
283                        .message(tr("Unknown country code: {0}", country))
284                        .primitives(p);
285                if ("UK".equals(country)) {
286                    errors.add(error.fix(() -> new ChangePropertyCommand(p, SOURCE_MAXSPEED, value.replace("UK:", "GB:"))).build());
287                } else {
288                    errors.add(error.build());
289                }
290            }
291            // Check context
292            String context = value.substring(index+1);
293            if (!KNOWN_SOURCE_MAXSPEED_CONTEXTS.contains(context)) {
294                errors.add(TestError.builder(this, Severity.WARNING, SOURCE_MAXSPEED_UNKNOWN_CONTEXT)
295                        .message(tr("Unknown source:maxspeed context: {0}", context))
296                        .primitives(p)
297                        .build());
298            }
299            if (testContextHighway) {
300                // TODO: Check coherence of context against maxspeed
301                // TODO: Check coherence of context against highway
302                Logging.trace("TODO: test context highway - https://josm.openstreetmap.de/ticket/9400");
303            }
304        }
305    }
306
307    /**
308     * See #9304: Find Highways connected to bridges or tunnels at the wrong place.
309     * @param connection the connection node of two or more different ways
310     */
311    private void testDifferentLayers(Node connection) {
312        if (connection.hasTag("highway", "elevator"))
313            return;
314        List<Way> ways = connection.getParentWays();
315        ways.removeIf(w -> !w.hasTag("highway") || w.hasTag("highway", "steps") || isSpecialArea(w));
316        if (ways.size() < 2 || ways.stream().noneMatch(w -> w.hasKey("layer")))
317            return;
318        // check if connection has ways with different layers
319        Map<String, List<Way>> layerCount = new HashMap<>();
320        for (Way w : ways) {
321            String layer = w.get("layer");
322            if (layer == null)
323                layer = "0";
324            layerCount.computeIfAbsent(layer, k-> new ArrayList<>()).add(w);
325        }
326        if (layerCount.size() == 1)
327            return; // all on the same layer
328
329        for (Entry<String, List<Way>> entry : layerCount.entrySet()) {
330            if ("0".equals(entry.getKey()))
331                continue;
332            if (checkLayer(connection, entry.getValue())) {
333                errors.add(TestError.builder(this, Severity.WARNING, DIFFERENT_LAYERS)
334                        .message(tr("Node connects highways on different layers"))
335                        .primitives(connection)
336                        .build());
337                return;
338            }
339        }
340    }
341
342    /**
343     * Check if way is an area on a layer above or below 0.
344     * @param w the way
345     * @return true if way is an area on a layer above or below 0
346     */
347    private static boolean isSpecialArea(Way w) {
348        return w.hasAreaTags() && OsmUtils.getLayer(w) != null;
349    }
350
351    /**
352     * Check if there are at least two neighbouring nodes on the given ways.
353     * If so, the connection node can be considered to be at a specific layer, else it marks the end of such a layer
354     * @param connection the connection node
355     * @param ways the ways with the same layer attribute connected to that node
356     * @return true if the node can be considered to be at a specific layer
357     */
358    private static boolean checkLayer(Node connection, List<Way> ways) {
359        int count = 0;
360        for (Way w : ways) {
361            if (!w.isFirstLastNode(connection))
362                return true; // connection node has two neighbouring nodes
363            count++;
364        }
365        return count > 1;
366    }
367}