001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.gpx;
003
004import java.io.File;
005import java.text.MessageFormat;
006import java.time.Instant;
007import java.util.ArrayList;
008import java.util.Arrays;
009import java.util.Collection;
010import java.util.Collections;
011import java.util.Comparator;
012import java.util.HashMap;
013import java.util.HashSet;
014import java.util.Iterator;
015import java.util.List;
016import java.util.LongSummaryStatistics;
017import java.util.Map;
018import java.util.NoSuchElementException;
019import java.util.Objects;
020import java.util.Optional;
021import java.util.OptionalLong;
022import java.util.Set;
023import java.util.stream.Collectors;
024import java.util.stream.Stream;
025
026import org.openstreetmap.josm.data.Bounds;
027import org.openstreetmap.josm.data.Data;
028import org.openstreetmap.josm.data.DataSource;
029import org.openstreetmap.josm.data.coor.EastNorth;
030import org.openstreetmap.josm.data.gpx.IGpxTrack.GpxTrackChangeListener;
031import org.openstreetmap.josm.data.projection.ProjectionRegistry;
032import org.openstreetmap.josm.gui.MainApplication;
033import org.openstreetmap.josm.gui.layer.GpxLayer;
034import org.openstreetmap.josm.tools.ListenerList;
035import org.openstreetmap.josm.tools.ListeningCollection;
036import org.openstreetmap.josm.tools.Utils;
037import org.openstreetmap.josm.tools.date.Interval;
038
039/**
040 * Objects of this class represent a gpx file with tracks, waypoints and routes.
041 * It uses GPX v1.1, see <a href="http://www.topografix.com/GPX/1/1/">the spec</a>
042 * for details.
043 *
044 * @author Raphael Mack &lt;ramack@raphael-mack.de&gt;
045 */
046public class GpxData extends WithAttributes implements Data, IGpxLayerPrefs {
047
048    /**
049     * Constructs a new GpxData.
050     */
051    public GpxData() {}
052
053    /**
054     * Constructs a new GpxData that is currently being initialized, so no listeners will be fired until {@link #endUpdate()} is called.
055     * @param initializing true
056     * @since 15496
057     */
058    public GpxData(boolean initializing) {
059        this.initializing = initializing;
060    }
061
062    /**
063     * The disk file this layer is stored in, if it is a local layer. May be <code>null</code>.
064     */
065    public File storageFile;
066    /**
067     * A boolean flag indicating if the data was read from the OSM server.
068     */
069    public boolean fromServer;
070    /**
071     * A boolean flag indicating if the data was read from a session file.
072     * @since 18287
073     */
074    public boolean fromSession;
075
076    /**
077     * Creator metadata for this file (usually software)
078     */
079    public String creator;
080
081    /**
082     * A list of tracks this file consists of
083     */
084    private final ArrayList<IGpxTrack> privateTracks = new ArrayList<>();
085    /**
086     * GPX routes in this file
087     */
088    private final ArrayList<GpxRoute> privateRoutes = new ArrayList<>();
089    /**
090     * Additional waypoints for this file.
091     */
092    private final ArrayList<WayPoint> privateWaypoints = new ArrayList<>();
093    /**
094     * All namespaces read from the original file
095     */
096    private final List<XMLNamespace> namespaces = new ArrayList<>();
097    /**
098     * The layer specific prefs formerly saved in the preferences, e.g. drawing options.
099     * NOT the track specific settings (e.g. color, width)
100     */
101    private final Map<String, String> layerPrefs = new HashMap<>();
102
103    private final GpxTrackChangeListener proxy = e -> invalidate();
104    private boolean modified;
105    private boolean updating;
106    private boolean initializing;
107    private boolean suppressedInvalidate;
108
109    /**
110     * Tracks. Access is discouraged, use {@link #getTracks()} to read.
111     * @see #getTracks()
112     */
113    public final Collection<IGpxTrack> tracks = new ListeningCollection<>(privateTracks, this::invalidate) {
114
115        @Override
116        protected void removed(IGpxTrack cursor) {
117            cursor.removeListener(proxy);
118            super.removed(cursor);
119        }
120
121        @Override
122        protected void added(IGpxTrack cursor) {
123            super.added(cursor);
124            cursor.addListener(proxy);
125        }
126    };
127
128    /**
129     * Routes. Access is discouraged, use {@link #getTracks()} to read.
130     * @see #getRoutes()
131     */
132    public final Collection<GpxRoute> routes = new ListeningCollection<>(privateRoutes, this::invalidate);
133
134    /**
135     * Waypoints. Access is discouraged, use {@link #getTracks()} to read.
136     * @see #getWaypoints()
137     */
138    public final Collection<WayPoint> waypoints = new ListeningCollection<>(privateWaypoints, this::invalidate);
139
140    /**
141     * All data sources (bounds of downloaded bounds) of this GpxData.<br>
142     * Not part of GPX standard but rather a JOSM extension, needed by the fact that
143     * OSM API does not provide {@code <bounds>} element in its GPX reply.
144     * @since 7575
145     */
146    public final Set<DataSource> dataSources = new HashSet<>();
147
148    private final ListenerList<GpxDataChangeListener> listeners = ListenerList.create();
149
150    private List<GpxTrackSegmentSpan> segSpans;
151
152    /**
153     * Merges data from another object.
154     * @param other existing GPX data
155     */
156    public synchronized void mergeFrom(GpxData other) {
157        mergeFrom(other, false, false);
158    }
159
160    /**
161     * Merges data from another object.
162     * @param other existing GPX data
163     * @param cutOverlapping whether overlapping parts of the given track should be removed
164     * @param connect whether the tracks should be connected on cuts
165     * @since 14338
166     */
167    public synchronized void mergeFrom(GpxData other, boolean cutOverlapping, boolean connect) {
168        if (storageFile == null && other.storageFile != null) {
169            storageFile = other.storageFile;
170        }
171        fromServer = fromServer && other.fromServer;
172
173        for (Map.Entry<String, Object> ent : other.attr.entrySet()) {
174            // TODO: Detect conflicts.
175            String k = ent.getKey();
176            if (META_LINKS.equals(k) && attr.containsKey(META_LINKS)) {
177                Collection<GpxLink> my = super.<GpxLink>getCollection(META_LINKS);
178                @SuppressWarnings("unchecked")
179                Collection<GpxLink> their = (Collection<GpxLink>) ent.getValue();
180                my.addAll(their);
181            } else {
182                put(k, ent.getValue());
183            }
184        }
185
186        if (cutOverlapping) {
187            for (IGpxTrack trk : other.privateTracks) {
188                cutOverlapping(trk, connect);
189            }
190        } else {
191            other.privateTracks.forEach(this::addTrack);
192        }
193        other.privateRoutes.forEach(this::addRoute);
194        other.privateWaypoints.forEach(this::addWaypoint);
195        dataSources.addAll(other.dataSources);
196        invalidate();
197    }
198
199    private void cutOverlapping(IGpxTrack trk, boolean connect) {
200        List<IGpxTrackSegment> segsOld = new ArrayList<>(trk.getSegments());
201        List<IGpxTrackSegment> segsNew = new ArrayList<>();
202        for (IGpxTrackSegment seg : segsOld) {
203            GpxTrackSegmentSpan s = GpxTrackSegmentSpan.tryGetFromSegment(seg);
204            if (s != null && anySegmentOverlapsWith(s)) {
205                List<WayPoint> wpsNew = new ArrayList<>();
206                List<WayPoint> wpsOld = new ArrayList<>(seg.getWayPoints());
207                if (s.isInverted()) {
208                    Collections.reverse(wpsOld);
209                }
210                boolean split = false;
211                WayPoint prevLastOwnWp = null;
212                Instant prevWpTime = null;
213                for (WayPoint wp : wpsOld) {
214                    Instant wpTime = wp.getInstant();
215                    boolean overlap = false;
216                    if (wpTime != null) {
217                        for (GpxTrackSegmentSpan ownspan : getSegmentSpans()) {
218                            if (wpTime.isAfter(ownspan.firstTime) && wpTime.isBefore(ownspan.lastTime)) {
219                                overlap = true;
220                                if (connect) {
221                                    if (!split) {
222                                        wpsNew.add(ownspan.getFirstWp());
223                                    } else {
224                                        connectTracks(prevLastOwnWp, ownspan, trk.getAttributes());
225                                    }
226                                    prevLastOwnWp = ownspan.getLastWp();
227                                }
228                                split = true;
229                                break;
230                            } else if (connect && prevWpTime != null
231                                    && prevWpTime.isBefore(ownspan.firstTime)
232                                    && wpTime.isAfter(ownspan.lastTime)) {
233                                // the overlapping high priority track is shorter than the distance
234                                // between two waypoints of the low priority track
235                                if (split) {
236                                    connectTracks(prevLastOwnWp, ownspan, trk.getAttributes());
237                                    prevLastOwnWp = ownspan.getLastWp();
238                                } else {
239                                    wpsNew.add(ownspan.getFirstWp());
240                                    // splitting needs to be handled here,
241                                    // because other high priority tracks between the same waypoints could follow
242                                    if (!wpsNew.isEmpty()) {
243                                        segsNew.add(new GpxTrackSegment(wpsNew));
244                                    }
245                                    if (!segsNew.isEmpty()) {
246                                        privateTracks.add(new GpxTrack(segsNew, trk.getAttributes()));
247                                    }
248                                    segsNew = new ArrayList<>();
249                                    wpsNew = new ArrayList<>();
250                                    wpsNew.add(ownspan.getLastWp());
251                                    // therefore no break, because another segment could overlap, see above
252                                }
253                            }
254                        }
255                        prevWpTime = wpTime;
256                    }
257                    if (!overlap) {
258                        if (split) {
259                            //track has to be split, because we have an overlapping short track in the middle
260                            if (!wpsNew.isEmpty()) {
261                                segsNew.add(new GpxTrackSegment(wpsNew));
262                            }
263                            if (!segsNew.isEmpty()) {
264                                privateTracks.add(new GpxTrack(segsNew, trk.getAttributes()));
265                            }
266                            segsNew = new ArrayList<>();
267                            wpsNew = new ArrayList<>();
268                            if (connect && prevLastOwnWp != null) {
269                                wpsNew.add(new WayPoint(prevLastOwnWp));
270                            }
271                            prevLastOwnWp = null;
272                            split = false;
273                        }
274                        wpsNew.add(new WayPoint(wp));
275                    }
276                }
277                if (!wpsNew.isEmpty()) {
278                    segsNew.add(new GpxTrackSegment(wpsNew));
279                }
280            } else {
281                segsNew.add(seg);
282            }
283        }
284        if (segsNew.equals(segsOld)) {
285            privateTracks.add(trk);
286        } else if (!segsNew.isEmpty()) {
287            privateTracks.add(new GpxTrack(segsNew, trk.getAttributes()));
288        }
289    }
290
291    private void connectTracks(WayPoint prevWp, GpxTrackSegmentSpan span, Map<String, Object> attr) {
292        if (prevWp != null && !span.lastEquals(prevWp)) {
293            privateTracks.add(new GpxTrack(Arrays.asList(Arrays.asList(new WayPoint(prevWp), span.getFirstWp())), attr));
294        }
295    }
296
297    static class GpxTrackSegmentSpan {
298
299        final Instant firstTime;
300        final Instant lastTime;
301        private final boolean inv;
302        private final WayPoint firstWp;
303        private final WayPoint lastWp;
304
305        GpxTrackSegmentSpan(WayPoint a, WayPoint b) {
306            Instant at = a.getInstant();
307            Instant bt = b.getInstant();
308            inv = at != null && bt != null && bt.isBefore(at);
309            if (inv) {
310                firstWp = b;
311                firstTime = bt;
312                lastWp = a;
313                lastTime = at;
314            } else {
315                firstWp = a;
316                firstTime = at;
317                lastWp = b;
318                lastTime = bt;
319            }
320        }
321
322        WayPoint getFirstWp() {
323            return new WayPoint(firstWp);
324        }
325
326        WayPoint getLastWp() {
327            return new WayPoint(lastWp);
328        }
329
330        // no new instances needed, therefore own methods for that
331
332        boolean firstEquals(Object other) {
333            return firstWp.equals(other);
334        }
335
336        boolean lastEquals(Object other) {
337            return lastWp.equals(other);
338        }
339
340        public boolean isInverted() {
341            return inv;
342        }
343
344        boolean overlapsWith(GpxTrackSegmentSpan other) {
345            return (firstTime.isBefore(other.lastTime) && other.firstTime.isBefore(lastTime))
346                || (other.firstTime.isBefore(lastTime) && firstTime.isBefore(other.lastTime));
347        }
348
349        static GpxTrackSegmentSpan tryGetFromSegment(IGpxTrackSegment seg) {
350            WayPoint b = getNextWpWithTime(seg, true);
351            if (b != null) {
352                WayPoint e = getNextWpWithTime(seg, false);
353                if (e != null) {
354                    return new GpxTrackSegmentSpan(b, e);
355                }
356            }
357            return null;
358        }
359
360        private static WayPoint getNextWpWithTime(IGpxTrackSegment seg, boolean forward) {
361            List<WayPoint> wps = new ArrayList<>(seg.getWayPoints());
362            for (int i = forward ? 0 : wps.size() - 1; i >= 0 && i < wps.size(); i += forward ? 1 : -1) {
363                if (wps.get(i).hasDate()) {
364                    return wps.get(i);
365                }
366            }
367            return null;
368        }
369    }
370
371    /**
372     * Get a list of SegmentSpans containing the beginning and end of each segment
373     * @return the list of SegmentSpans
374     * @since 14338
375     */
376    public synchronized List<GpxTrackSegmentSpan> getSegmentSpans() {
377        if (segSpans == null) {
378            segSpans = new ArrayList<>();
379            for (IGpxTrack trk : privateTracks) {
380                for (IGpxTrackSegment seg : trk.getSegments()) {
381                    GpxTrackSegmentSpan s = GpxTrackSegmentSpan.tryGetFromSegment(seg);
382                    if (s != null) {
383                        segSpans.add(s);
384                    }
385                }
386            }
387            segSpans.sort(Comparator.comparing(o -> o.firstTime));
388        }
389        return segSpans;
390    }
391
392    private boolean anySegmentOverlapsWith(GpxTrackSegmentSpan other) {
393        return getSegmentSpans().stream().anyMatch(s -> s.overlapsWith(other));
394    }
395
396    /**
397     * Get all tracks contained in this data set, without any guaranteed order.
398     * @return The tracks.
399     */
400    public synchronized Collection<IGpxTrack> getTracks() {
401        return Collections.unmodifiableCollection(privateTracks);
402    }
403
404    /**
405     * Get all tracks contained in this data set, ordered chronologically.
406     * @return The tracks in chronological order.
407     * @since 18207
408     */
409    public synchronized List<IGpxTrack> getOrderedTracks() {
410        return privateTracks.stream().sorted((t1, t2) -> {
411            boolean t1empty = Utils.isEmpty(t1.getSegments());
412            boolean t2empty = Utils.isEmpty(t2.getSegments());
413            if (t1empty && t2empty) {
414                return 0;
415            } else if (t1empty && !t2empty) {
416                return -1;
417            } else if (!t1empty && t2empty) {
418                return 1;
419            } else {
420                OptionalLong i1 = getTrackFirstWaypointMin(t1);
421                OptionalLong i2 = getTrackFirstWaypointMin(t2);
422                boolean i1absent = i1.isEmpty();
423                boolean i2absent = i2.isEmpty();
424                if (i1absent && i2absent) {
425                    return 0;
426                } else if (i1absent && !i2absent) {
427                    return 1;
428                } else if (!i1absent && i2absent) {
429                    return -1;
430                } else {
431                    return Long.compare(i1.getAsLong(), i2.getAsLong());
432                }
433            }
434        }).collect(Collectors.toList());
435    }
436
437    private static OptionalLong getTrackFirstWaypointMin(IGpxTrack track) {
438        return track.getSegments().stream().map(IGpxTrackSegment::getWayPoints)
439                .filter(Objects::nonNull).flatMap(Collection::stream)
440                .mapToLong(WayPoint::getTimeInMillis).min();
441    }
442
443    /**
444     * Get stream of track segments.
445     * @return {@code Stream<GPXTrack>}
446     */
447    public synchronized Stream<IGpxTrackSegment> getTrackSegmentsStream() {
448        return getTracks().stream().flatMap(trk -> trk.getSegments().stream());
449    }
450
451    /**
452     * Clear all tracks, empties the current privateTracks container,
453     * helper method for some gpx manipulations.
454     */
455    private synchronized void clearTracks() {
456        privateTracks.forEach(t -> t.removeListener(proxy));
457        privateTracks.clear();
458    }
459
460    /**
461     * Add a new track
462     * @param track The new track
463     * @since 12156
464     */
465    public synchronized void addTrack(IGpxTrack track) {
466        if (privateTracks.stream().anyMatch(t -> t == track)) {
467            throw new IllegalArgumentException(MessageFormat.format("The track was already added to this data: {0}", track));
468        }
469        privateTracks.add(track);
470        track.addListener(proxy);
471        invalidate();
472    }
473
474    /**
475     * Remove a track
476     * @param track The old track
477     * @since 12156
478     */
479    public synchronized void removeTrack(IGpxTrack track) {
480        if (!privateTracks.removeIf(t -> t == track)) {
481            throw new IllegalArgumentException(MessageFormat.format("The track was not in this data: {0}", track));
482        }
483        track.removeListener(proxy);
484        invalidate();
485    }
486
487    /**
488     * Combine tracks into a single, segmented track.
489     * The attributes of the first track are used, the rest discarded.
490     *
491     * @since 13210
492     */
493    public synchronized void combineTracksToSegmentedTrack() {
494        List<IGpxTrackSegment> segs = getTrackSegmentsStream()
495                .collect(Collectors.toCollection(ArrayList<IGpxTrackSegment>::new));
496        Map<String, Object> attrs = new HashMap<>(privateTracks.get(0).getAttributes());
497
498        // do not let the name grow if split / combine operations are called iteratively
499        Object name = attrs.get("name");
500        if (name != null) {
501            attrs.put("name", name.toString().replaceFirst(" #\\d+$", ""));
502        }
503
504        clearTracks();
505        addTrack(new GpxTrack(segs, attrs));
506    }
507
508    /**
509     * Ensures a unique name among gpx layers
510     * @param attrs attributes of/for an gpx track, written to if the name appeared previously in {@code counts}.
511     * @param counts a {@code HashMap} of previously seen names, associated with their count.
512     * @param srcLayerName Source layer name
513     * @return the unique name for the gpx track.
514     *
515     * @since 15397
516     */
517    public static String ensureUniqueName(Map<String, Object> attrs, Map<String, Integer> counts, String srcLayerName) {
518        String name = attrs.getOrDefault("name", srcLayerName).toString().replaceFirst(" #\\d+$", "");
519        Integer count = counts.getOrDefault(name, 0) + 1;
520        counts.put(name, count);
521
522        attrs.put("name", MessageFormat.format("{0}{1}", name, " #" + count));
523        return attrs.get("name").toString();
524    }
525
526    /**
527     * Split tracks so that only single-segment tracks remain.
528     * Each segment will make up one individual track after this operation.
529     *
530     * @param srcLayerName Source layer name
531     *
532     * @since 15397
533     */
534    public synchronized void splitTrackSegmentsToTracks(String srcLayerName) {
535        final HashMap<String, Integer> counts = new HashMap<>();
536
537        List<GpxTrack> trks = getTracks().stream()
538            .flatMap(trk -> trk.getSegments().stream().map(seg -> {
539                    HashMap<String, Object> attrs = new HashMap<>(trk.getAttributes());
540                    ensureUniqueName(attrs, counts, srcLayerName);
541                    return new GpxTrack(Collections.singletonList(seg), attrs);
542                }))
543            .collect(Collectors.toCollection(ArrayList<GpxTrack>::new));
544
545        clearTracks();
546        trks.stream().forEachOrdered(this::addTrack);
547    }
548
549    /**
550     * Split tracks into layers, the result is one layer for each track.
551     * If this layer currently has only one GpxTrack this is a no-operation.
552     * <p>
553     * The new GpxLayers are added to the LayerManager, the original GpxLayer
554     * is untouched as to preserve potential route or wpt parts.
555     *
556     * @param srcLayerName Source layer name
557     *
558     * @since 15397
559     */
560    public synchronized void splitTracksToLayers(String srcLayerName) {
561        final HashMap<String, Integer> counts = new HashMap<>();
562
563        getTracks().stream()
564            .filter(trk -> privateTracks.size() > 1)
565            .map(trk -> {
566                HashMap<String, Object> attrs = new HashMap<>(trk.getAttributes());
567                GpxData d = new GpxData();
568                d.addTrack(trk);
569                return new GpxLayer(d, ensureUniqueName(attrs, counts, srcLayerName));
570            })
571            .forEachOrdered(layer -> MainApplication.getLayerManager().addLayer(layer));
572    }
573
574    /**
575     * Replies the current number of tracks in this GpxData
576     * @return track count
577     * @since 13210
578     */
579    public synchronized int getTrackCount() {
580        return privateTracks.size();
581    }
582
583    /**
584     * Replies the accumulated total of all track segments,
585     * the sum of segment counts for each track present.
586     * @return track segments count
587     * @since 13210
588     */
589    public synchronized int getTrackSegsCount() {
590        return privateTracks.stream().mapToInt(t -> t.getSegments().size()).sum();
591    }
592
593    /**
594     * Gets the list of all routes defined in this data set.
595     * @return The routes
596     * @since 12156
597     */
598    public synchronized Collection<GpxRoute> getRoutes() {
599        return Collections.unmodifiableCollection(privateRoutes);
600    }
601
602    /**
603     * Add a new route
604     * @param route The new route
605     * @since 12156
606     */
607    public synchronized void addRoute(GpxRoute route) {
608        if (privateRoutes.stream().anyMatch(r -> r == route)) {
609            throw new IllegalArgumentException(MessageFormat.format("The route was already added to this data: {0}", route));
610        }
611        privateRoutes.add(route);
612        invalidate();
613    }
614
615    /**
616     * Remove a route
617     * @param route The old route
618     * @since 12156
619     */
620    public synchronized void removeRoute(GpxRoute route) {
621        if (!privateRoutes.removeIf(r -> r == route)) {
622            throw new IllegalArgumentException(MessageFormat.format("The route was not in this data: {0}", route));
623        }
624        invalidate();
625    }
626
627    /**
628     * Gets a list of all way points in this data set.
629     * @return The way points.
630     * @since 12156
631     */
632    public synchronized Collection<WayPoint> getWaypoints() {
633        return Collections.unmodifiableCollection(privateWaypoints);
634    }
635
636    /**
637     * Add a new waypoint
638     * @param waypoint The new waypoint
639     * @since 12156
640     */
641    public synchronized void addWaypoint(WayPoint waypoint) {
642        if (privateWaypoints.stream().anyMatch(w -> w == waypoint)) {
643            throw new IllegalArgumentException(MessageFormat.format("The waypoint was already added to this data: {0}", waypoint));
644        }
645        privateWaypoints.add(waypoint);
646        invalidate();
647    }
648
649    /**
650     * Remove a waypoint
651     * @param waypoint The old waypoint
652     * @since 12156
653     */
654    public synchronized void removeWaypoint(WayPoint waypoint) {
655        if (!privateWaypoints.removeIf(w -> w == waypoint)) {
656            throw new IllegalArgumentException(MessageFormat.format("The waypoint was not in this data: {0}", waypoint));
657        }
658        invalidate();
659    }
660
661    /**
662     * Determines if this GPX data has one or more track points
663     * @return {@code true} if this GPX data has track points, {@code false} otherwise
664     */
665    public synchronized boolean hasTrackPoints() {
666        return getTrackPoints().findAny().isPresent();
667    }
668
669    /**
670     * Gets a stream of all track points in the segments of the tracks of this data.
671     * @return The stream
672     * @see #getTracks()
673     * @see IGpxTrack#getSegments()
674     * @see IGpxTrackSegment#getWayPoints()
675     * @since 12156
676     */
677    public synchronized Stream<WayPoint> getTrackPoints() {
678        return getTracks().stream().flatMap(trk -> trk.getSegments().stream()).flatMap(trkseg -> trkseg.getWayPoints().stream());
679    }
680
681    /**
682     * Determines if this GPX data has one or more route points
683     * @return {@code true} if this GPX data has route points, {@code false} otherwise
684     */
685    public synchronized boolean hasRoutePoints() {
686        return privateRoutes.stream().anyMatch(rte -> !rte.routePoints.isEmpty());
687    }
688
689    /**
690     * Determines if this GPX data is empty (i.e. does not contain any point)
691     * @return {@code true} if this GPX data is empty, {@code false} otherwise
692     */
693    public synchronized boolean isEmpty() {
694        return !hasRoutePoints() && !hasTrackPoints() && waypoints.isEmpty();
695    }
696
697    /**
698     * Returns the bounds defining the extend of this data, as read in metadata, if any.
699     * If no bounds is defined in metadata, {@code null} is returned. There is no guarantee
700     * that data entirely fit in this bounds, as it is not recalculated. To get recalculated bounds,
701     * see {@link #recalculateBounds()}. To get downloaded areas, see {@link #dataSources}.
702     * @return the bounds defining the extend of this data, or {@code null}.
703     * @see #recalculateBounds()
704     * @see #dataSources
705     * @since 7575
706     */
707    public Bounds getMetaBounds() {
708        Object value = get(META_BOUNDS);
709        if (value instanceof Bounds) {
710            return (Bounds) value;
711        }
712        return null;
713    }
714
715    /**
716     * Calculates the bounding box of available data and returns it.
717     * The bounds are not stored internally, but recalculated every time
718     * this function is called.<br>
719     * To get bounds as read from metadata, see {@link #getMetaBounds()}.<br>
720     * To get downloaded areas, see {@link #dataSources}.<br>
721     *
722     * FIXME might perhaps use visitor pattern?
723     * @return the bounds
724     * @see #getMetaBounds()
725     * @see #dataSources
726     */
727    public synchronized Bounds recalculateBounds() {
728        Bounds bounds = null;
729        for (WayPoint wpt : privateWaypoints) {
730            if (bounds == null) {
731                bounds = new Bounds(wpt.getCoor());
732            } else {
733                bounds.extend(wpt.getCoor());
734            }
735        }
736        for (GpxRoute rte : privateRoutes) {
737            for (WayPoint wpt : rte.routePoints) {
738                if (bounds == null) {
739                    bounds = new Bounds(wpt.getCoor());
740                } else {
741                    bounds.extend(wpt.getCoor());
742                }
743            }
744        }
745        for (IGpxTrack trk : privateTracks) {
746            Bounds trkBounds = trk.getBounds();
747            if (trkBounds != null) {
748                if (bounds == null) {
749                    bounds = new Bounds(trkBounds);
750                } else {
751                    bounds.extend(trkBounds);
752                }
753            }
754        }
755        return bounds;
756    }
757
758    /**
759     * calculates the sum of the lengths of all track segments
760     * @return the length in meters
761     */
762    public synchronized double length() {
763        return privateTracks.stream().mapToDouble(IGpxTrack::length).sum();
764    }
765
766    /**
767     * returns minimum and maximum timestamps in the track
768     * @param trk track to analyze
769     * @return minimum and maximum as interval
770     */
771    public static Optional<Interval> getMinMaxTimeForTrack(IGpxTrack trk) {
772        final LongSummaryStatistics statistics = trk.getSegments().stream()
773                .flatMap(seg -> seg.getWayPoints().stream())
774                .mapToLong(WayPoint::getTimeInMillis)
775                .summaryStatistics();
776        return statistics.getCount() == 0 || (statistics.getMin() == 0 && statistics.getMax() == 0)
777                ? Optional.empty()
778                : Optional.of(new Interval(Instant.ofEpochMilli(statistics.getMin()), Instant.ofEpochMilli(statistics.getMax())));
779    }
780
781    /**
782    * Returns minimum and maximum timestamps for all tracks
783    * Warning: there are lot of track with broken timestamps,
784    * so we just ignore points from future and from year before 1970 in this method
785    * @return minimum and maximum as interval
786    * @since 7319
787    */
788    public synchronized Optional<Interval> getMinMaxTimeForAllTracks() {
789        long now = System.currentTimeMillis();
790        final LongSummaryStatistics statistics = tracks.stream()
791                .flatMap(trk -> trk.getSegments().stream())
792                .flatMap(seg -> seg.getWayPoints().stream())
793                .mapToLong(WayPoint::getTimeInMillis)
794                .filter(t -> t > 0 && t <= now)
795                .summaryStatistics();
796        return statistics.getCount() == 0
797                ? Optional.empty()
798                : Optional.of(new Interval(Instant.ofEpochMilli(statistics.getMin()), Instant.ofEpochMilli(statistics.getMax())));
799    }
800
801    /**
802     * Makes a WayPoint at the projection of point p onto the track providing p is less than
803     * tolerance away from the track
804     *
805     * @param p : the point to determine the projection for
806     * @param tolerance : must be no further than this from the track
807     * @return the closest point on the track to p, which may be the first or last point if off the
808     * end of a segment, or may be null if nothing close enough
809     */
810    public synchronized WayPoint nearestPointOnTrack(EastNorth p, double tolerance) {
811        /*
812         * assume the coordinates of P are xp,yp, and those of a section of track between two
813         * trackpoints are R=xr,yr and S=xs,ys. Let N be the projected point.
814         *
815         * The equation of RS is Ax + By + C = 0 where A = ys - yr B = xr - xs C = - Axr - Byr
816         *
817         * Also, note that the distance RS^2 is A^2 + B^2
818         *
819         * If RS^2 == 0.0 ignore the degenerate section of track
820         *
821         * PN^2 = (Axp + Byp + C)^2 / RS^2 that is the distance from P to the line
822         *
823         * so if PN^2 is less than PNmin^2 (initialized to tolerance) we can reject the line
824         * otherwise... determine if the projected poijnt lies within the bounds of the line: PR^2 -
825         * PN^2 <= RS^2 and PS^2 - PN^2 <= RS^2
826         *
827         * where PR^2 = (xp - xr)^2 + (yp-yr)^2 and PS^2 = (xp - xs)^2 + (yp-ys)^2
828         *
829         * If so, calculate N as xn = xr + (RN/RS) B yn = y1 + (RN/RS) A
830         *
831         * where RN = sqrt(PR^2 - PN^2)
832         */
833
834        double pnminsq = tolerance * tolerance;
835        EastNorth bestEN = null;
836        double bestTime = Double.NaN;
837        double px = p.east();
838        double py = p.north();
839        double rx = 0.0, ry = 0.0, sx, sy, x, y;
840        for (IGpxTrack track : privateTracks) {
841            for (IGpxTrackSegment seg : track.getSegments()) {
842                WayPoint r = null;
843                for (WayPoint wpSeg : seg.getWayPoints()) {
844                    EastNorth en = wpSeg.getEastNorth(ProjectionRegistry.getProjection());
845                    if (r == null) {
846                        r = wpSeg;
847                        rx = en.east();
848                        ry = en.north();
849                        x = px - rx;
850                        y = py - ry;
851                        double pRsq = x * x + y * y;
852                        if (pRsq < pnminsq) {
853                            pnminsq = pRsq;
854                            bestEN = en;
855                            if (r.hasDate()) {
856                                bestTime = r.getTime();
857                            }
858                        }
859                    } else {
860                        sx = en.east();
861                        sy = en.north();
862                        double a = sy - ry;
863                        double b = rx - sx;
864                        double c = -a * rx - b * ry;
865                        double rssq = a * a + b * b;
866                        if (rssq == 0) {
867                            continue;
868                        }
869                        double pnsq = a * px + b * py + c;
870                        pnsq = pnsq * pnsq / rssq;
871                        if (pnsq < pnminsq) {
872                            x = px - rx;
873                            y = py - ry;
874                            double prsq = x * x + y * y;
875                            x = px - sx;
876                            y = py - sy;
877                            double pssq = x * x + y * y;
878                            if (prsq - pnsq <= rssq && pssq - pnsq <= rssq) {
879                                double rnoverRS = Math.sqrt((prsq - pnsq) / rssq);
880                                double nx = rx - rnoverRS * b;
881                                double ny = ry + rnoverRS * a;
882                                bestEN = new EastNorth(nx, ny);
883                                if (r.hasDate() && wpSeg.hasDate()) {
884                                    bestTime = r.getTime() + rnoverRS * (wpSeg.getTime() - r.getTime());
885                                }
886                                pnminsq = pnsq;
887                            }
888                        }
889                        r = wpSeg;
890                        rx = sx;
891                        ry = sy;
892                    }
893                }
894                if (r != null) {
895                    EastNorth c = r.getEastNorth(ProjectionRegistry.getProjection());
896                    /* if there is only one point in the seg, it will do this twice, but no matter */
897                    rx = c.east();
898                    ry = c.north();
899                    x = px - rx;
900                    y = py - ry;
901                    double prsq = x * x + y * y;
902                    if (prsq < pnminsq) {
903                        pnminsq = prsq;
904                        bestEN = c;
905                        if (r.hasDate()) {
906                            bestTime = r.getTime();
907                        }
908                    }
909                }
910            }
911        }
912        if (bestEN == null)
913            return null;
914        WayPoint best = new WayPoint(ProjectionRegistry.getProjection().eastNorth2latlon(bestEN));
915        if (!Double.isNaN(bestTime)) {
916            best.setTimeInMillis((long) (bestTime * 1000));
917        }
918        return best;
919    }
920
921    /**
922     * Iterate over all track segments and over all routes.
923     *
924     * @param trackVisibility An array indicating which tracks should be
925     * included in the iteration. Can be null, then all tracks are included.
926     * @return an Iterable object, which iterates over all track segments and
927     * over all routes
928     */
929    public Iterable<Line> getLinesIterable(final boolean... trackVisibility) {
930        return () -> new LinesIterator(this, trackVisibility);
931    }
932
933    /**
934     * Resets the internal caches of east/north coordinates.
935     */
936    public synchronized void resetEastNorthCache() {
937        privateWaypoints.forEach(WayPoint::invalidateEastNorthCache);
938        getTrackPoints().forEach(WayPoint::invalidateEastNorthCache);
939        for (GpxRoute route: getRoutes()) {
940            if (route.routePoints == null) {
941                continue;
942            }
943            for (WayPoint wp: route.routePoints) {
944                wp.invalidateEastNorthCache();
945            }
946        }
947    }
948
949    /**
950     * Iterates over all track segments and then over all routes.
951     */
952    public static class LinesIterator implements Iterator<Line> {
953
954        private Iterator<IGpxTrack> itTracks;
955        private int idxTracks;
956        private Iterator<IGpxTrackSegment> itTrackSegments;
957
958        private Line next;
959        private final boolean[] trackVisibility;
960        private Map<String, Object> trackAttributes;
961        private IGpxTrack curTrack;
962
963        /**
964         * Constructs a new {@code LinesIterator}.
965         * @param data GPX data
966         * @param trackVisibility An array indicating which tracks should be
967         * included in the iteration. Can be null, then all tracks are included.
968         */
969        public LinesIterator(GpxData data, boolean... trackVisibility) {
970            itTracks = data.tracks.iterator();
971            idxTracks = -1;
972            this.trackVisibility = trackVisibility;
973            next = getNext();
974        }
975
976        @Override
977        public boolean hasNext() {
978            return next != null;
979        }
980
981        @Override
982        public Line next() {
983            if (!hasNext()) {
984                throw new NoSuchElementException();
985            }
986            Line current = next;
987            next = getNext();
988            return current;
989        }
990
991        private Line getNext() {
992            if (itTracks != null) {
993                if (itTrackSegments != null && itTrackSegments.hasNext()) {
994                    return new Line(itTrackSegments.next(), trackAttributes, curTrack.getColor());
995                } else {
996                    while (itTracks.hasNext()) {
997                        curTrack = itTracks.next();
998                        trackAttributes = curTrack.getAttributes();
999                        idxTracks++;
1000                        if (trackVisibility != null && !trackVisibility[idxTracks])
1001                            continue;
1002                        itTrackSegments = curTrack.getSegments().iterator();
1003                        if (itTrackSegments.hasNext()) {
1004                            return new Line(itTrackSegments.next(), trackAttributes, curTrack.getColor());
1005                        }
1006                    }
1007                    // if we get here, all the Tracks are finished; Continue with Routes
1008                    trackAttributes = null;
1009                    itTracks = null;
1010                }
1011            }
1012            return null;
1013        }
1014
1015        @Override
1016        public void remove() {
1017            throw new UnsupportedOperationException();
1018        }
1019    }
1020
1021    @Override
1022    public Collection<DataSource> getDataSources() {
1023        return Collections.unmodifiableCollection(dataSources);
1024    }
1025
1026    @Override
1027    public Map<String, String> getLayerPrefs() {
1028        return layerPrefs;
1029    }
1030
1031    /**
1032     * All XML namespaces read from the original file
1033     * @return Modifiable list
1034     * @since 15496
1035     */
1036    public List<XMLNamespace> getNamespaces() {
1037        return namespaces;
1038    }
1039
1040    @Override
1041    public synchronized int hashCode() {
1042        return Objects.hash(
1043                super.hashCode(),
1044                namespaces,
1045                layerPrefs,
1046                dataSources,
1047                privateRoutes,
1048                privateTracks,
1049                privateWaypoints
1050        );
1051    }
1052
1053    @Override
1054    public synchronized boolean equals(Object obj) {
1055        if (this == obj)
1056            return true;
1057        if (obj == null)
1058            return false;
1059        if (!super.equals(obj))
1060            return false;
1061        if (getClass() != obj.getClass())
1062            return false;
1063        GpxData other = (GpxData) obj;
1064        if (dataSources == null) {
1065            if (other.dataSources != null)
1066                return false;
1067        } else if (!dataSources.equals(other.dataSources))
1068            return false;
1069        if (layerPrefs == null) {
1070            if (other.layerPrefs != null)
1071                return false;
1072        } else if (!layerPrefs.equals(other.layerPrefs))
1073            return false;
1074        if (privateRoutes == null) {
1075            if (other.privateRoutes != null)
1076                return false;
1077        } else if (!privateRoutes.equals(other.privateRoutes))
1078            return false;
1079        if (privateTracks == null) {
1080            if (other.privateTracks != null)
1081                return false;
1082        } else if (!privateTracks.equals(other.privateTracks))
1083            return false;
1084        if (privateWaypoints == null) {
1085            if (other.privateWaypoints != null)
1086                return false;
1087        } else if (!privateWaypoints.equals(other.privateWaypoints))
1088            return false;
1089        if (namespaces == null) {
1090            if (other.namespaces != null)
1091                return false;
1092        } else if (!namespaces.equals(other.namespaces))
1093            return false;
1094        return true;
1095    }
1096
1097    /**
1098     * Put a key / value pair as a new attribute. Overrides key / value pair with the same key (if present).
1099     *
1100     * @param key the key
1101     * @param value the value
1102     */
1103    @Override
1104    public void put(String key, Object value) {
1105        put(key, value, true);
1106    }
1107
1108    /**
1109     * Put a key / value pair as a new attribute. Overrides key / value pair with the same key (if present).
1110     * Only sets the modified state when setModified is true.
1111     *
1112     * @param key the key
1113     * @param value the value
1114     * @param setModified whether to change the modified state
1115     * @since 18399
1116     */
1117    public void put(String key, Object value, boolean setModified) {
1118        super.put(key, value);
1119        fireInvalidate(setModified);
1120    }
1121
1122    /**
1123     * Adds a listener that gets called whenever the data changed.
1124     * @param listener The listener
1125     * @since 12156
1126     */
1127    public void addChangeListener(GpxDataChangeListener listener) {
1128        listeners.addListener(listener);
1129    }
1130
1131    /**
1132     * Adds a listener that gets called whenever the data changed. It is added with a weak link
1133     * @param listener The listener
1134     */
1135    public void addWeakChangeListener(GpxDataChangeListener listener) {
1136        listeners.addWeakListener(listener);
1137    }
1138
1139    /**
1140     * Removes a listener that gets called whenever the data changed.
1141     * @param listener The listener
1142     * @since 12156
1143     */
1144    public void removeChangeListener(GpxDataChangeListener listener) {
1145        listeners.removeListener(listener);
1146    }
1147
1148    /**
1149     * Fires event listeners and sets the modified flag to true.
1150     */
1151    public void invalidate() {
1152        fireInvalidate(true);
1153    }
1154
1155    private void fireInvalidate(boolean setModified) {
1156        if (setModified) {
1157            setModified(true);
1158        }
1159        if (updating || initializing) {
1160            suppressedInvalidate = true;
1161        } else {
1162            if (listeners.hasListeners()) {
1163                GpxDataChangeEvent e = new GpxDataChangeEvent(this);
1164                listeners.fireEvent(l -> l.gpxDataChanged(e));
1165            }
1166        }
1167    }
1168
1169    /**
1170     * Begins updating this GpxData and prevents listeners from being fired.
1171     * @since 15496
1172     */
1173    public void beginUpdate() {
1174        updating = true;
1175    }
1176
1177    /**
1178     * Finishes updating this GpxData and fires listeners if required.
1179     * @since 15496
1180     */
1181    public void endUpdate() {
1182        updating = initializing = false;
1183        if (suppressedInvalidate) {
1184            fireInvalidate(false);
1185            suppressedInvalidate = false;
1186        }
1187    }
1188
1189    /**
1190     * A listener that listens to GPX data changes.
1191     * @author Michael Zangl
1192     * @since 12156
1193     */
1194    @FunctionalInterface
1195    public interface GpxDataChangeListener {
1196        /**
1197         * Called when the gpx data changed.
1198         * @param e The event
1199         */
1200        void gpxDataChanged(GpxDataChangeEvent e);
1201
1202        /**
1203         * Called when the modified state of the data changed
1204         * @param modified the new modified state
1205         */
1206        default void modifiedStateChanged(boolean modified) {
1207            // Override if needed
1208        }
1209    }
1210
1211    /**
1212     * A data change event in any of the gpx data.
1213     * @author Michael Zangl
1214     * @since 12156
1215     */
1216    public static class GpxDataChangeEvent {
1217        private final GpxData source;
1218
1219        GpxDataChangeEvent(GpxData source) {
1220            super();
1221            this.source = source;
1222        }
1223
1224        /**
1225         * Get the data that was changed.
1226         * @return The data.
1227         */
1228        public GpxData getSource() {
1229            return source;
1230        }
1231    }
1232
1233    /**
1234     * Determines whether anything has been modified.
1235     * @return whether anything has been modified (e.g. colors)
1236     * @since 15496
1237     */
1238    public boolean isModified() {
1239        return modified;
1240    }
1241
1242    /**
1243     * Sets the modified flag to the value.
1244     * @param value modified flag
1245     * @since 15496
1246     */
1247    @Override
1248    public void setModified(boolean value) {
1249        if (!initializing && modified != value) {
1250            modified = value;
1251            if (listeners.hasListeners()) {
1252                listeners.fireEvent(l -> l.modifiedStateChanged(modified));
1253            }
1254        }
1255    }
1256
1257    /**
1258     * A class containing prefix, URI and location of a namespace
1259     * @since 15496
1260     */
1261    public static class XMLNamespace {
1262        private final String uri;
1263        private final String prefix;
1264        private String location;
1265
1266        /**
1267         * Creates a schema with prefix and URI, tries to determine prefix from URI
1268         * @param fallbackPrefix the namespace prefix, if not determined from URI
1269         * @param uri the namespace URI
1270         */
1271        public XMLNamespace(String fallbackPrefix, String uri) {
1272            this.prefix = Optional.ofNullable(GpxExtension.findPrefix(uri)).orElse(fallbackPrefix);
1273            this.uri = uri;
1274        }
1275
1276        /**
1277         * Creates a schema with prefix, URI and location.
1278         * Does NOT try to determine prefix from URI!
1279         * @param prefix XML namespace prefix
1280         * @param uri XML namespace URI
1281         * @param location XML namespace location
1282         */
1283        public XMLNamespace(String prefix, String uri, String location) {
1284            this.prefix = prefix;
1285            this.uri = uri;
1286            this.location = location;
1287        }
1288
1289        /**
1290         * Returns the URI of the namespace.
1291         * @return the URI of the namespace
1292         */
1293        public String getURI() {
1294            return uri;
1295        }
1296
1297        /**
1298         * Returns the prefix of the namespace.
1299         * @return the prefix of the namespace, determined from URI if possible
1300         */
1301        public String getPrefix() {
1302            return prefix;
1303        }
1304
1305        /**
1306         * Returns the location of the schema.
1307         * @return the location of the schema
1308         */
1309        public String getLocation() {
1310            return location;
1311        }
1312
1313        /**
1314         * Sets the location of the schema
1315         * @param location the location of the schema
1316         */
1317        public void setLocation(String location) {
1318            this.location = location;
1319        }
1320
1321        @Override
1322        public int hashCode() {
1323            return Objects.hash(prefix, uri, location);
1324        }
1325
1326        @Override
1327        public boolean equals(Object obj) {
1328            if (this == obj)
1329                return true;
1330            if (obj == null)
1331                return false;
1332            if (getClass() != obj.getClass())
1333                return false;
1334            XMLNamespace other = (XMLNamespace) obj;
1335            if (prefix == null) {
1336                if (other.prefix != null)
1337                    return false;
1338            } else if (!prefix.equals(other.prefix))
1339                return false;
1340            if (uri == null) {
1341                if (other.uri != null)
1342                    return false;
1343            } else if (!uri.equals(other.uri))
1344                return false;
1345            if (location == null) {
1346                if (other.location != null)
1347                    return false;
1348            } else if (!location.equals(other.location))
1349                return false;
1350            return true;
1351        }
1352    }
1353
1354    /**
1355     * Removes all gpx elements
1356     * @since 17439
1357     */
1358    public void clear() {
1359        dataSources.clear();
1360        layerPrefs.clear();
1361        privateRoutes.clear();
1362        privateTracks.clear();
1363        privateWaypoints.clear();
1364        attr.clear();
1365    }
1366}