source: josm/trunk/src/org/openstreetmap/josm/data/gpx/GpxData.java@ 15427

Last change on this file since 15427 was 15427, checked in by Don-vip, 5 years ago

fix recent SonarQube issues

  • Property svn:eol-style set to native
File size: 38.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.gpx;
3
4import java.io.File;
5import java.text.MessageFormat;
6import java.util.ArrayList;
7import java.util.Arrays;
8import java.util.Collection;
9import java.util.Collections;
10import java.util.Date;
11import java.util.HashMap;
12import java.util.HashSet;
13import java.util.Iterator;
14import java.util.List;
15import java.util.LongSummaryStatistics;
16import java.util.Map;
17import java.util.NoSuchElementException;
18import java.util.Set;
19import java.util.stream.Collectors;
20import java.util.stream.Stream;
21
22import org.openstreetmap.josm.data.Bounds;
23import org.openstreetmap.josm.data.Data;
24import org.openstreetmap.josm.data.DataSource;
25import org.openstreetmap.josm.data.coor.EastNorth;
26import org.openstreetmap.josm.data.gpx.GpxTrack.GpxTrackChangeListener;
27import org.openstreetmap.josm.data.projection.ProjectionRegistry;
28import org.openstreetmap.josm.gui.MainApplication;
29import org.openstreetmap.josm.gui.layer.GpxLayer;
30import org.openstreetmap.josm.tools.ListenerList;
31import org.openstreetmap.josm.tools.ListeningCollection;
32
33/**
34 * Objects of this class represent a gpx file with tracks, waypoints and routes.
35 * It uses GPX v1.1, see <a href="http://www.topografix.com/GPX/1/1/">the spec</a>
36 * for details.
37 *
38 * @author Raphael Mack &lt;ramack@raphael-mack.de&gt;
39 */
40public class GpxData extends WithAttributes implements Data {
41
42 /**
43 * The disk file this layer is stored in, if it is a local layer. May be <code>null</code>.
44 */
45 public File storageFile;
46 /**
47 * A boolean flag indicating if the data was read from the OSM server.
48 */
49 public boolean fromServer;
50
51 /**
52 * Creator metadata for this file (usually software)
53 */
54 public String creator;
55
56 /**
57 * A list of tracks this file consists of
58 */
59 private final ArrayList<GpxTrack> privateTracks = new ArrayList<>();
60 /**
61 * GPX routes in this file
62 */
63 private final ArrayList<GpxRoute> privateRoutes = new ArrayList<>();
64 /**
65 * Addidionaly waypoints for this file.
66 */
67 private final ArrayList<WayPoint> privateWaypoints = new ArrayList<>();
68 private final GpxTrackChangeListener proxy = e -> fireInvalidate();
69
70 /**
71 * Tracks. Access is discouraged, use {@link #getTracks()} to read.
72 * @see #getTracks()
73 */
74 public final Collection<GpxTrack> tracks = new ListeningCollection<GpxTrack>(privateTracks, this::fireInvalidate) {
75
76 @Override
77 protected void removed(GpxTrack cursor) {
78 cursor.removeListener(proxy);
79 super.removed(cursor);
80 }
81
82 @Override
83 protected void added(GpxTrack cursor) {
84 super.added(cursor);
85 cursor.addListener(proxy);
86 }
87 };
88
89 /**
90 * Routes. Access is discouraged, use {@link #getTracks()} to read.
91 * @see #getRoutes()
92 */
93 public final Collection<GpxRoute> routes = new ListeningCollection<>(privateRoutes, this::fireInvalidate);
94
95 /**
96 * Waypoints. Access is discouraged, use {@link #getTracks()} to read.
97 * @see #getWaypoints()
98 */
99 public final Collection<WayPoint> waypoints = new ListeningCollection<>(privateWaypoints, this::fireInvalidate);
100
101 /**
102 * All data sources (bounds of downloaded bounds) of this GpxData.<br>
103 * Not part of GPX standard but rather a JOSM extension, needed by the fact that
104 * OSM API does not provide {@code <bounds>} element in its GPX reply.
105 * @since 7575
106 */
107 public final Set<DataSource> dataSources = new HashSet<>();
108
109 private final ListenerList<GpxDataChangeListener> listeners = ListenerList.create();
110
111 static class TimestampConfictException extends Exception {}
112
113 private List<GpxTrackSegmentSpan> segSpans;
114
115 /**
116 * Merges data from another object.
117 * @param other existing GPX data
118 */
119 public synchronized void mergeFrom(GpxData other) {
120 mergeFrom(other, false, false);
121 }
122
123 /**
124 * Merges data from another object.
125 * @param other existing GPX data
126 * @param cutOverlapping whether overlapping parts of the given track should be removed
127 * @param connect whether the tracks should be connected on cuts
128 * @since 14338
129 */
130 public synchronized void mergeFrom(GpxData other, boolean cutOverlapping, boolean connect) {
131 if (storageFile == null && other.storageFile != null) {
132 storageFile = other.storageFile;
133 }
134 fromServer = fromServer && other.fromServer;
135
136 for (Map.Entry<String, Object> ent : other.attr.entrySet()) {
137 // TODO: Detect conflicts.
138 String k = ent.getKey();
139 if (META_LINKS.equals(k) && attr.containsKey(META_LINKS)) {
140 Collection<GpxLink> my = super.<GpxLink>getCollection(META_LINKS);
141 @SuppressWarnings("unchecked")
142 Collection<GpxLink> their = (Collection<GpxLink>) ent.getValue();
143 my.addAll(their);
144 } else {
145 put(k, ent.getValue());
146 }
147 }
148
149 if (cutOverlapping) {
150 for (GpxTrack trk : other.privateTracks) {
151 cutOverlapping(trk, connect);
152 }
153 } else {
154 other.privateTracks.forEach(this::addTrack);
155 }
156 other.privateRoutes.forEach(this::addRoute);
157 other.privateWaypoints.forEach(this::addWaypoint);
158 dataSources.addAll(other.dataSources);
159 fireInvalidate();
160 }
161
162 private void cutOverlapping(GpxTrack trk, boolean connect) {
163 List<GpxTrackSegment> segsOld = new ArrayList<>(trk.getSegments());
164 List<GpxTrackSegment> segsNew = new ArrayList<>();
165 for (GpxTrackSegment seg : segsOld) {
166 GpxTrackSegmentSpan s = GpxTrackSegmentSpan.tryGetFromSegment(seg);
167 if (s != null && anySegmentOverlapsWith(s)) {
168 List<WayPoint> wpsNew = new ArrayList<>();
169 List<WayPoint> wpsOld = new ArrayList<>(seg.getWayPoints());
170 if (s.isInverted()) {
171 Collections.reverse(wpsOld);
172 }
173 boolean split = false;
174 WayPoint prevLastOwnWp = null;
175 Date prevWpTime = null;
176 for (WayPoint wp : wpsOld) {
177 Date wpTime = wp.getDate();
178 boolean overlap = false;
179 if (wpTime != null) {
180 for (GpxTrackSegmentSpan ownspan : getSegmentSpans()) {
181 if (wpTime.after(ownspan.firstTime) && wpTime.before(ownspan.lastTime)) {
182 overlap = true;
183 if (connect) {
184 if (!split) {
185 wpsNew.add(ownspan.getFirstWp());
186 } else {
187 connectTracks(prevLastOwnWp, ownspan, trk.getAttributes());
188 }
189 prevLastOwnWp = ownspan.getLastWp();
190 }
191 split = true;
192 break;
193 } else if (connect && prevWpTime != null
194 && prevWpTime.before(ownspan.firstTime)
195 && wpTime.after(ownspan.lastTime)) {
196 // the overlapping high priority track is shorter than the distance
197 // between two waypoints of the low priority track
198 if (split) {
199 connectTracks(prevLastOwnWp, ownspan, trk.getAttributes());
200 prevLastOwnWp = ownspan.getLastWp();
201 } else {
202 wpsNew.add(ownspan.getFirstWp());
203 // splitting needs to be handled here,
204 // because other high priority tracks between the same waypoints could follow
205 if (!wpsNew.isEmpty()) {
206 segsNew.add(new ImmutableGpxTrackSegment(wpsNew));
207 }
208 if (!segsNew.isEmpty()) {
209 privateTracks.add(new ImmutableGpxTrack(segsNew, trk.getAttributes()));
210 }
211 segsNew = new ArrayList<>();
212 wpsNew = new ArrayList<>();
213 wpsNew.add(ownspan.getLastWp());
214 // therefore no break, because another segment could overlap, see above
215 }
216 }
217 }
218 prevWpTime = wpTime;
219 }
220 if (!overlap) {
221 if (split) {
222 //track has to be split, because we have an overlapping short track in the middle
223 if (!wpsNew.isEmpty()) {
224 segsNew.add(new ImmutableGpxTrackSegment(wpsNew));
225 }
226 if (!segsNew.isEmpty()) {
227 privateTracks.add(new ImmutableGpxTrack(segsNew, trk.getAttributes()));
228 }
229 segsNew = new ArrayList<>();
230 wpsNew = new ArrayList<>();
231 if (connect && prevLastOwnWp != null) {
232 wpsNew.add(new WayPoint(prevLastOwnWp));
233 }
234 prevLastOwnWp = null;
235 split = false;
236 }
237 wpsNew.add(new WayPoint(wp));
238 }
239 }
240 if (!wpsNew.isEmpty()) {
241 segsNew.add(new ImmutableGpxTrackSegment(wpsNew));
242 }
243 } else {
244 segsNew.add(seg);
245 }
246 }
247 if (segsNew.equals(segsOld)) {
248 privateTracks.add(trk);
249 } else if (!segsNew.isEmpty()) {
250 privateTracks.add(new ImmutableGpxTrack(segsNew, trk.getAttributes()));
251 }
252 }
253
254 private void connectTracks(WayPoint prevWp, GpxTrackSegmentSpan span, Map<String, Object> attr) {
255 if (prevWp != null && !span.lastEquals(prevWp)) {
256 privateTracks.add(new ImmutableGpxTrack(Arrays.asList(Arrays.asList(new WayPoint(prevWp), span.getFirstWp())), attr));
257 }
258 }
259
260 static class GpxTrackSegmentSpan {
261
262 final Date firstTime;
263 final Date lastTime;
264 private final boolean inv;
265 private final WayPoint firstWp;
266 private final WayPoint lastWp;
267
268 GpxTrackSegmentSpan(WayPoint a, WayPoint b) {
269 Date at = a.getDate();
270 Date bt = b.getDate();
271 inv = bt.before(at);
272 if (inv) {
273 firstWp = b;
274 firstTime = bt;
275 lastWp = a;
276 lastTime = at;
277 } else {
278 firstWp = a;
279 firstTime = at;
280 lastWp = b;
281 lastTime = bt;
282 }
283 }
284
285 WayPoint getFirstWp() {
286 return new WayPoint(firstWp);
287 }
288
289 WayPoint getLastWp() {
290 return new WayPoint(lastWp);
291 }
292
293 // no new instances needed, therefore own methods for that
294
295 boolean firstEquals(Object other) {
296 return firstWp.equals(other);
297 }
298
299 boolean lastEquals(Object other) {
300 return lastWp.equals(other);
301 }
302
303 public boolean isInverted() {
304 return inv;
305 }
306
307 boolean overlapsWith(GpxTrackSegmentSpan other) {
308 return (firstTime.before(other.lastTime) && other.firstTime.before(lastTime))
309 || (other.firstTime.before(lastTime) && firstTime.before(other.lastTime));
310 }
311
312 static GpxTrackSegmentSpan tryGetFromSegment(GpxTrackSegment seg) {
313 WayPoint b = getNextWpWithTime(seg, true);
314 if (b != null) {
315 WayPoint e = getNextWpWithTime(seg, false);
316 if (e != null) {
317 return new GpxTrackSegmentSpan(b, e);
318 }
319 }
320 return null;
321 }
322
323 private static WayPoint getNextWpWithTime(GpxTrackSegment seg, boolean forward) {
324 List<WayPoint> wps = new ArrayList<>(seg.getWayPoints());
325 for (int i = forward ? 0 : wps.size() - 1; i >= 0 && i < wps.size(); i += forward ? 1 : -1) {
326 if (wps.get(i).hasDate()) {
327 return wps.get(i);
328 }
329 }
330 return null;
331 }
332 }
333
334 /**
335 * Get a list of SegmentSpans containing the beginning and end of each segment
336 * @return the list of SegmentSpans
337 * @since 14338
338 */
339 public synchronized List<GpxTrackSegmentSpan> getSegmentSpans() {
340 if (segSpans == null) {
341 segSpans = new ArrayList<>();
342 for (GpxTrack trk : privateTracks) {
343 for (GpxTrackSegment seg : trk.getSegments()) {
344 GpxTrackSegmentSpan s = GpxTrackSegmentSpan.tryGetFromSegment(seg);
345 if (s != null) {
346 segSpans.add(s);
347 }
348 }
349 }
350 segSpans.sort((o1, o2) -> o1.firstTime.compareTo(o2.firstTime));
351 }
352 return segSpans;
353 }
354
355 private boolean anySegmentOverlapsWith(GpxTrackSegmentSpan other) {
356 for (GpxTrackSegmentSpan s : getSegmentSpans()) {
357 if (s.overlapsWith(other)) {
358 return true;
359 }
360 }
361 return false;
362 }
363
364 /**
365 * Get all tracks contained in this data set.
366 * @return The tracks.
367 */
368 public synchronized Collection<GpxTrack> getTracks() {
369 return Collections.unmodifiableCollection(privateTracks);
370 }
371
372 /**
373 * Get stream of track segments.
374 * @return {@code Stream<GPXTrack>}
375 */
376 private synchronized Stream<GpxTrackSegment> getTrackSegmentsStream() {
377 return getTracks().stream().flatMap(trk -> trk.getSegments().stream());
378 }
379
380 /**
381 * Clear all tracks, empties the current privateTracks container,
382 * helper method for some gpx manipulations.
383 */
384 private synchronized void clearTracks() {
385 privateTracks.forEach(t -> t.removeListener(proxy));
386 privateTracks.clear();
387 }
388
389 /**
390 * Add a new track
391 * @param track The new track
392 * @since 12156
393 */
394 public synchronized void addTrack(GpxTrack track) {
395 if (privateTracks.stream().anyMatch(t -> t == track)) {
396 throw new IllegalArgumentException(MessageFormat.format("The track was already added to this data: {0}", track));
397 }
398 privateTracks.add(track);
399 track.addListener(proxy);
400 fireInvalidate();
401 }
402
403 /**
404 * Remove a track
405 * @param track The old track
406 * @since 12156
407 */
408 public synchronized void removeTrack(GpxTrack track) {
409 if (!privateTracks.removeIf(t -> t == track)) {
410 throw new IllegalArgumentException(MessageFormat.format("The track was not in this data: {0}", track));
411 }
412 track.removeListener(proxy);
413 fireInvalidate();
414 }
415
416 /**
417 * Combine tracks into a single, segmented track.
418 * The attributes of the first track are used, the rest discarded.
419 *
420 * @since 13210
421 */
422 public synchronized void combineTracksToSegmentedTrack() {
423 List<GpxTrackSegment> segs = getTrackSegmentsStream()
424 .collect(Collectors.toCollection(ArrayList<GpxTrackSegment>::new));
425 Map<String, Object> attrs = new HashMap<>(privateTracks.get(0).getAttributes());
426
427 // do not let the name grow if split / combine operations are called iteratively
428 Object name = attrs.get("name");
429 if (name != null) {
430 attrs.put("name", name.toString().replaceFirst(" #\\d+$", ""));
431 }
432
433 clearTracks();
434 addTrack(new ImmutableGpxTrack(segs, attrs));
435 }
436
437 /**
438 * Ensures a unique name among gpx layers
439 * @param attrs attributes of/for an gpx track, written to if the name appeared previously in {@code counts}.
440 * @param counts a {@code HashMap} of previously seen names, associated with their count.
441 * @param srcLayerName Source layer name
442 * @return the unique name for the gpx track.
443 *
444 * @since 15397
445 */
446 public static String ensureUniqueName(Map<String, Object> attrs, Map<String, Integer> counts, String srcLayerName) {
447 String name = attrs.getOrDefault("name", srcLayerName).toString().replaceFirst(" #\\d+$", "");
448 Integer count = counts.getOrDefault(name, 0) + 1;
449 counts.put(name, count);
450
451 attrs.put("name", MessageFormat.format("{0}{1}", name, " #" + count));
452 return attrs.get("name").toString();
453 }
454
455 /**
456 * Split tracks so that only single-segment tracks remain.
457 * Each segment will make up one individual track after this operation.
458 *
459 * @param srcLayerName Source layer name
460 *
461 * @since 15397
462 */
463 public synchronized void splitTrackSegmentsToTracks(String srcLayerName) {
464 final HashMap<String, Integer> counts = new HashMap<>();
465
466 List<GpxTrack> trks = getTracks().stream()
467 .flatMap(trk -> trk.getSegments().stream().map(seg -> {
468 HashMap<String, Object> attrs = new HashMap<>(trk.getAttributes());
469 ensureUniqueName(attrs, counts, srcLayerName);
470 return new ImmutableGpxTrack(Arrays.asList(seg), attrs);
471 }))
472 .collect(Collectors.toCollection(ArrayList<GpxTrack>::new));
473
474 clearTracks();
475 trks.stream().forEachOrdered(this::addTrack);
476 }
477
478 /**
479 * Split tracks into layers, the result is one layer for each track.
480 * If this layer currently has only one GpxTrack this is a no-operation.
481 *
482 * The new GpxLayers are added to the LayerManager, the original GpxLayer
483 * is untouched as to preserve potential route or wpt parts.
484 *
485 * @param srcLayerName Source layer name
486 *
487 * @since 15397
488 */
489 public synchronized void splitTracksToLayers(String srcLayerName) {
490 final HashMap<String, Integer> counts = new HashMap<>();
491
492 getTracks().stream()
493 .filter(trk -> privateTracks.size() > 1)
494 .map(trk -> {
495 HashMap<String, Object> attrs = new HashMap<>(trk.getAttributes());
496 GpxData d = new GpxData();
497 d.addTrack(trk);
498 return new GpxLayer(d, ensureUniqueName(attrs, counts, srcLayerName));
499 })
500 .forEachOrdered(layer -> MainApplication.getLayerManager().addLayer(layer));
501 }
502
503 /**
504 * Replies the current number of tracks in this GpxData
505 * @return track count
506 * @since 13210
507 */
508 public synchronized int getTrackCount() {
509 return privateTracks.size();
510 }
511
512 /**
513 * Replies the accumulated total of all track segments,
514 * the sum of segment counts for each track present.
515 * @return track segments count
516 * @since 13210
517 */
518 public synchronized int getTrackSegsCount() {
519 return privateTracks.stream().mapToInt(t -> t.getSegments().size()).sum();
520 }
521
522 /**
523 * Gets the list of all routes defined in this data set.
524 * @return The routes
525 * @since 12156
526 */
527 public synchronized Collection<GpxRoute> getRoutes() {
528 return Collections.unmodifiableCollection(privateRoutes);
529 }
530
531 /**
532 * Add a new route
533 * @param route The new route
534 * @since 12156
535 */
536 public synchronized void addRoute(GpxRoute route) {
537 if (privateRoutes.stream().anyMatch(r -> r == route)) {
538 throw new IllegalArgumentException(MessageFormat.format("The route was already added to this data: {0}", route));
539 }
540 privateRoutes.add(route);
541 fireInvalidate();
542 }
543
544 /**
545 * Remove a route
546 * @param route The old route
547 * @since 12156
548 */
549 public synchronized void removeRoute(GpxRoute route) {
550 if (!privateRoutes.removeIf(r -> r == route)) {
551 throw new IllegalArgumentException(MessageFormat.format("The route was not in this data: {0}", route));
552 }
553 fireInvalidate();
554 }
555
556 /**
557 * Gets a list of all way points in this data set.
558 * @return The way points.
559 * @since 12156
560 */
561 public synchronized Collection<WayPoint> getWaypoints() {
562 return Collections.unmodifiableCollection(privateWaypoints);
563 }
564
565 /**
566 * Add a new waypoint
567 * @param waypoint The new waypoint
568 * @since 12156
569 */
570 public synchronized void addWaypoint(WayPoint waypoint) {
571 if (privateWaypoints.stream().anyMatch(w -> w == waypoint)) {
572 throw new IllegalArgumentException(MessageFormat.format("The route was already added to this data: {0}", waypoint));
573 }
574 privateWaypoints.add(waypoint);
575 fireInvalidate();
576 }
577
578 /**
579 * Remove a waypoint
580 * @param waypoint The old waypoint
581 * @since 12156
582 */
583 public synchronized void removeWaypoint(WayPoint waypoint) {
584 if (!privateWaypoints.removeIf(w -> w == waypoint)) {
585 throw new IllegalArgumentException(MessageFormat.format("The route was not in this data: {0}", waypoint));
586 }
587 fireInvalidate();
588 }
589
590 /**
591 * Determines if this GPX data has one or more track points
592 * @return {@code true} if this GPX data has track points, {@code false} otherwise
593 */
594 public synchronized boolean hasTrackPoints() {
595 return getTrackPoints().findAny().isPresent();
596 }
597
598 /**
599 * Gets a stream of all track points in the segments of the tracks of this data.
600 * @return The stream
601 * @see #getTracks()
602 * @see GpxTrack#getSegments()
603 * @see GpxTrackSegment#getWayPoints()
604 * @since 12156
605 */
606 public synchronized Stream<WayPoint> getTrackPoints() {
607 return getTracks().stream().flatMap(trk -> trk.getSegments().stream()).flatMap(trkseg -> trkseg.getWayPoints().stream());
608 }
609
610 /**
611 * Determines if this GPX data has one or more route points
612 * @return {@code true} if this GPX data has route points, {@code false} otherwise
613 */
614 public synchronized boolean hasRoutePoints() {
615 return privateRoutes.stream().anyMatch(rte -> !rte.routePoints.isEmpty());
616 }
617
618 /**
619 * Determines if this GPX data is empty (i.e. does not contain any point)
620 * @return {@code true} if this GPX data is empty, {@code false} otherwise
621 */
622 public synchronized boolean isEmpty() {
623 return !hasRoutePoints() && !hasTrackPoints() && waypoints.isEmpty();
624 }
625
626 /**
627 * Returns the bounds defining the extend of this data, as read in metadata, if any.
628 * If no bounds is defined in metadata, {@code null} is returned. There is no guarantee
629 * that data entirely fit in this bounds, as it is not recalculated. To get recalculated bounds,
630 * see {@link #recalculateBounds()}. To get downloaded areas, see {@link #dataSources}.
631 * @return the bounds defining the extend of this data, or {@code null}.
632 * @see #recalculateBounds()
633 * @see #dataSources
634 * @since 7575
635 */
636 public Bounds getMetaBounds() {
637 Object value = get(META_BOUNDS);
638 if (value instanceof Bounds) {
639 return (Bounds) value;
640 }
641 return null;
642 }
643
644 /**
645 * Calculates the bounding box of available data and returns it.
646 * The bounds are not stored internally, but recalculated every time
647 * this function is called.<br>
648 * To get bounds as read from metadata, see {@link #getMetaBounds()}.<br>
649 * To get downloaded areas, see {@link #dataSources}.<br>
650 *
651 * FIXME might perhaps use visitor pattern?
652 * @return the bounds
653 * @see #getMetaBounds()
654 * @see #dataSources
655 */
656 public synchronized Bounds recalculateBounds() {
657 Bounds bounds = null;
658 for (WayPoint wpt : privateWaypoints) {
659 if (bounds == null) {
660 bounds = new Bounds(wpt.getCoor());
661 } else {
662 bounds.extend(wpt.getCoor());
663 }
664 }
665 for (GpxRoute rte : privateRoutes) {
666 for (WayPoint wpt : rte.routePoints) {
667 if (bounds == null) {
668 bounds = new Bounds(wpt.getCoor());
669 } else {
670 bounds.extend(wpt.getCoor());
671 }
672 }
673 }
674 for (GpxTrack trk : privateTracks) {
675 Bounds trkBounds = trk.getBounds();
676 if (trkBounds != null) {
677 if (bounds == null) {
678 bounds = new Bounds(trkBounds);
679 } else {
680 bounds.extend(trkBounds);
681 }
682 }
683 }
684 return bounds;
685 }
686
687 /**
688 * calculates the sum of the lengths of all track segments
689 * @return the length in meters
690 */
691 public synchronized double length() {
692 return privateTracks.stream().mapToDouble(GpxTrack::length).sum();
693 }
694
695 /**
696 * returns minimum and maximum timestamps in the track
697 * @param trk track to analyze
698 * @return minimum and maximum dates in array of 2 elements
699 */
700 public static Date[] getMinMaxTimeForTrack(GpxTrack trk) {
701 final LongSummaryStatistics statistics = trk.getSegments().stream()
702 .flatMap(seg -> seg.getWayPoints().stream())
703 .mapToLong(WayPoint::getTimeInMillis)
704 .summaryStatistics();
705 return statistics.getCount() == 0
706 ? null
707 : new Date[]{new Date(statistics.getMin()), new Date(statistics.getMax())};
708 }
709
710 /**
711 * Returns minimum and maximum timestamps for all tracks
712 * Warning: there are lot of track with broken timestamps,
713 * so we just ignore points from future and from year before 1970 in this method
714 * @return minimum and maximum dates in array of 2 elements
715 * @since 7319
716 */
717 public synchronized Date[] getMinMaxTimeForAllTracks() {
718 long now = System.currentTimeMillis();
719 final LongSummaryStatistics statistics = tracks.stream()
720 .flatMap(trk -> trk.getSegments().stream())
721 .flatMap(seg -> seg.getWayPoints().stream())
722 .mapToLong(WayPoint::getTimeInMillis)
723 .filter(t -> t > 0 && t <= now)
724 .summaryStatistics();
725 return statistics.getCount() == 0
726 ? new Date[0]
727 : new Date[]{new Date(statistics.getMin()), new Date(statistics.getMax())};
728 }
729
730 /**
731 * Makes a WayPoint at the projection of point p onto the track providing p is less than
732 * tolerance away from the track
733 *
734 * @param p : the point to determine the projection for
735 * @param tolerance : must be no further than this from the track
736 * @return the closest point on the track to p, which may be the first or last point if off the
737 * end of a segment, or may be null if nothing close enough
738 */
739 public synchronized WayPoint nearestPointOnTrack(EastNorth p, double tolerance) {
740 /*
741 * assume the coordinates of P are xp,yp, and those of a section of track between two
742 * trackpoints are R=xr,yr and S=xs,ys. Let N be the projected point.
743 *
744 * The equation of RS is Ax + By + C = 0 where A = ys - yr B = xr - xs C = - Axr - Byr
745 *
746 * Also, note that the distance RS^2 is A^2 + B^2
747 *
748 * If RS^2 == 0.0 ignore the degenerate section of track
749 *
750 * PN^2 = (Axp + Byp + C)^2 / RS^2 that is the distance from P to the line
751 *
752 * so if PN^2 is less than PNmin^2 (initialized to tolerance) we can reject the line
753 * otherwise... determine if the projected poijnt lies within the bounds of the line: PR^2 -
754 * PN^2 <= RS^2 and PS^2 - PN^2 <= RS^2
755 *
756 * where PR^2 = (xp - xr)^2 + (yp-yr)^2 and PS^2 = (xp - xs)^2 + (yp-ys)^2
757 *
758 * If so, calculate N as xn = xr + (RN/RS) B yn = y1 + (RN/RS) A
759 *
760 * where RN = sqrt(PR^2 - PN^2)
761 */
762
763 double pnminsq = tolerance * tolerance;
764 EastNorth bestEN = null;
765 double bestTime = Double.NaN;
766 double px = p.east();
767 double py = p.north();
768 double rx = 0.0, ry = 0.0, sx, sy, x, y;
769 for (GpxTrack track : privateTracks) {
770 for (GpxTrackSegment seg : track.getSegments()) {
771 WayPoint r = null;
772 for (WayPoint wpSeg : seg.getWayPoints()) {
773 EastNorth en = wpSeg.getEastNorth(ProjectionRegistry.getProjection());
774 if (r == null) {
775 r = wpSeg;
776 rx = en.east();
777 ry = en.north();
778 x = px - rx;
779 y = py - ry;
780 double pRsq = x * x + y * y;
781 if (pRsq < pnminsq) {
782 pnminsq = pRsq;
783 bestEN = en;
784 if (r.hasDate()) {
785 bestTime = r.getTime();
786 }
787 }
788 } else {
789 sx = en.east();
790 sy = en.north();
791 double a = sy - ry;
792 double b = rx - sx;
793 double c = -a * rx - b * ry;
794 double rssq = a * a + b * b;
795 if (rssq == 0) {
796 continue;
797 }
798 double pnsq = a * px + b * py + c;
799 pnsq = pnsq * pnsq / rssq;
800 if (pnsq < pnminsq) {
801 x = px - rx;
802 y = py - ry;
803 double prsq = x * x + y * y;
804 x = px - sx;
805 y = py - sy;
806 double pssq = x * x + y * y;
807 if (prsq - pnsq <= rssq && pssq - pnsq <= rssq) {
808 double rnoverRS = Math.sqrt((prsq - pnsq) / rssq);
809 double nx = rx - rnoverRS * b;
810 double ny = ry + rnoverRS * a;
811 bestEN = new EastNorth(nx, ny);
812 if (r.hasDate() && wpSeg.hasDate()) {
813 bestTime = r.getTime() + rnoverRS * (wpSeg.getTime() - r.getTime());
814 }
815 pnminsq = pnsq;
816 }
817 }
818 r = wpSeg;
819 rx = sx;
820 ry = sy;
821 }
822 }
823 if (r != null) {
824 EastNorth c = r.getEastNorth(ProjectionRegistry.getProjection());
825 /* if there is only one point in the seg, it will do this twice, but no matter */
826 rx = c.east();
827 ry = c.north();
828 x = px - rx;
829 y = py - ry;
830 double prsq = x * x + y * y;
831 if (prsq < pnminsq) {
832 pnminsq = prsq;
833 bestEN = c;
834 if (r.hasDate()) {
835 bestTime = r.getTime();
836 }
837 }
838 }
839 }
840 }
841 if (bestEN == null)
842 return null;
843 WayPoint best = new WayPoint(ProjectionRegistry.getProjection().eastNorth2latlon(bestEN));
844 if (!Double.isNaN(bestTime)) {
845 best.setTimeInMillis((long) (bestTime * 1000));
846 }
847 return best;
848 }
849
850 /**
851 * Iterate over all track segments and over all routes.
852 *
853 * @param trackVisibility An array indicating which tracks should be
854 * included in the iteration. Can be null, then all tracks are included.
855 * @return an Iterable object, which iterates over all track segments and
856 * over all routes
857 */
858 public Iterable<Line> getLinesIterable(final boolean... trackVisibility) {
859 return () -> new LinesIterator(this, trackVisibility);
860 }
861
862 /**
863 * Resets the internal caches of east/north coordinates.
864 */
865 public synchronized void resetEastNorthCache() {
866 privateWaypoints.forEach(WayPoint::invalidateEastNorthCache);
867 getTrackPoints().forEach(WayPoint::invalidateEastNorthCache);
868 for (GpxRoute route: getRoutes()) {
869 if (route.routePoints == null) {
870 continue;
871 }
872 for (WayPoint wp: route.routePoints) {
873 wp.invalidateEastNorthCache();
874 }
875 }
876 }
877
878 /**
879 * Iterates over all track segments and then over all routes.
880 */
881 public static class LinesIterator implements Iterator<Line> {
882
883 private Iterator<GpxTrack> itTracks;
884 private int idxTracks;
885 private Iterator<GpxTrackSegment> itTrackSegments;
886 private final Iterator<GpxRoute> itRoutes;
887
888 private Line next;
889 private final boolean[] trackVisibility;
890 private Map<String, Object> trackAttributes;
891
892 /**
893 * Constructs a new {@code LinesIterator}.
894 * @param data GPX data
895 * @param trackVisibility An array indicating which tracks should be
896 * included in the iteration. Can be null, then all tracks are included.
897 */
898 public LinesIterator(GpxData data, boolean... trackVisibility) {
899 itTracks = data.tracks.iterator();
900 idxTracks = -1;
901 itRoutes = data.routes.iterator();
902 this.trackVisibility = trackVisibility;
903 next = getNext();
904 }
905
906 @Override
907 public boolean hasNext() {
908 return next != null;
909 }
910
911 @Override
912 public Line next() {
913 if (!hasNext()) {
914 throw new NoSuchElementException();
915 }
916 Line current = next;
917 next = getNext();
918 return current;
919 }
920
921 private Line getNext() {
922 if (itTracks != null) {
923 if (itTrackSegments != null && itTrackSegments.hasNext()) {
924 return new Line(itTrackSegments.next(), trackAttributes);
925 } else {
926 while (itTracks.hasNext()) {
927 GpxTrack nxtTrack = itTracks.next();
928 trackAttributes = nxtTrack.getAttributes();
929 idxTracks++;
930 if (trackVisibility != null && !trackVisibility[idxTracks])
931 continue;
932 itTrackSegments = nxtTrack.getSegments().iterator();
933 if (itTrackSegments.hasNext()) {
934 return new Line(itTrackSegments.next(), trackAttributes);
935 }
936 }
937 // if we get here, all the Tracks are finished; Continue with Routes
938 trackAttributes = null;
939 itTracks = null;
940 }
941 }
942 if (itRoutes.hasNext()) {
943 return new Line(itRoutes.next());
944 }
945 return null;
946 }
947
948 @Override
949 public void remove() {
950 throw new UnsupportedOperationException();
951 }
952 }
953
954 @Override
955 public Collection<DataSource> getDataSources() {
956 return Collections.unmodifiableCollection(dataSources);
957 }
958
959 @Override
960 public synchronized int hashCode() {
961 final int prime = 31;
962 int result = 1;
963 result = prime * result + ((dataSources == null) ? 0 : dataSources.hashCode());
964 result = prime * result + ((privateRoutes == null) ? 0 : privateRoutes.hashCode());
965 result = prime * result + ((privateTracks == null) ? 0 : privateTracks.hashCode());
966 result = prime * result + ((privateWaypoints == null) ? 0 : privateWaypoints.hashCode());
967 return result;
968 }
969
970 @Override
971 public synchronized boolean equals(Object obj) {
972 if (this == obj)
973 return true;
974 if (obj == null)
975 return false;
976 if (getClass() != obj.getClass())
977 return false;
978 GpxData other = (GpxData) obj;
979 if (dataSources == null) {
980 if (other.dataSources != null)
981 return false;
982 } else if (!dataSources.equals(other.dataSources))
983 return false;
984 if (privateRoutes == null) {
985 if (other.privateRoutes != null)
986 return false;
987 } else if (!privateRoutes.equals(other.privateRoutes))
988 return false;
989 if (privateTracks == null) {
990 if (other.privateTracks != null)
991 return false;
992 } else if (!privateTracks.equals(other.privateTracks))
993 return false;
994 if (privateWaypoints == null) {
995 if (other.privateWaypoints != null)
996 return false;
997 } else if (!privateWaypoints.equals(other.privateWaypoints))
998 return false;
999 return true;
1000 }
1001
1002 /**
1003 * Adds a listener that gets called whenever the data changed.
1004 * @param listener The listener
1005 * @since 12156
1006 */
1007 public void addChangeListener(GpxDataChangeListener listener) {
1008 listeners.addListener(listener);
1009 }
1010
1011 /**
1012 * Adds a listener that gets called whenever the data changed. It is added with a weak link
1013 * @param listener The listener
1014 */
1015 public void addWeakChangeListener(GpxDataChangeListener listener) {
1016 listeners.addWeakListener(listener);
1017 }
1018
1019 /**
1020 * Removes a listener that gets called whenever the data changed.
1021 * @param listener The listener
1022 * @since 12156
1023 */
1024 public void removeChangeListener(GpxDataChangeListener listener) {
1025 listeners.removeListener(listener);
1026 }
1027
1028 private void fireInvalidate() {
1029 if (listeners.hasListeners()) {
1030 GpxDataChangeEvent e = new GpxDataChangeEvent(this);
1031 listeners.fireEvent(l -> l.gpxDataChanged(e));
1032 }
1033 }
1034
1035 /**
1036 * A listener that listens to GPX data changes.
1037 * @author Michael Zangl
1038 * @since 12156
1039 */
1040 @FunctionalInterface
1041 public interface GpxDataChangeListener {
1042 /**
1043 * Called when the gpx data changed.
1044 * @param e The event
1045 */
1046 void gpxDataChanged(GpxDataChangeEvent e);
1047 }
1048
1049 /**
1050 * A data change event in any of the gpx data.
1051 * @author Michael Zangl
1052 * @since 12156
1053 */
1054 public static class GpxDataChangeEvent {
1055 private final GpxData source;
1056
1057 GpxDataChangeEvent(GpxData source) {
1058 super();
1059 this.source = source;
1060 }
1061
1062 /**
1063 * Get the data that was changed.
1064 * @return The data.
1065 */
1066 public GpxData getSource() {
1067 return source;
1068 }
1069 }
1070}
Note: See TracBrowser for help on using the repository browser.