]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/data/Track.java
Version 16, February 2014
[GpsPrune.git] / tim / prune / data / Track.java
1 package tim.prune.data;
2
3 import java.util.List;
4
5 import tim.prune.UpdateMessageBroker;
6 import tim.prune.function.edit.FieldEdit;
7 import tim.prune.function.edit.FieldEditList;
8 import tim.prune.gui.map.MapUtils;
9
10
11 /**
12  * Class to hold all track information,
13  * including track points and waypoints
14  */
15 public class Track
16 {
17         // Data points
18         private DataPoint[] _dataPoints = null;
19         // Scaled x, y values
20         private double[] _xValues = null;
21         private double[] _yValues = null;
22         private boolean _scaled = false;
23         private int _numPoints = 0;
24         private boolean _hasTrackpoint = false;
25         private boolean _hasWaypoint = false;
26         // Master field list
27         private FieldList _masterFieldList = null;
28         // variable ranges
29         private DoubleRange _latRange = null, _longRange = null;
30         private DoubleRange _xRange = null, _yRange = null;
31
32
33         /**
34          * Constructor for empty track
35          */
36         public Track()
37         {
38                 // create field list
39                 _masterFieldList = new FieldList(null);
40                 // make empty DataPoint array
41                 _dataPoints = new DataPoint[0];
42                 _numPoints = 0;
43                 // needs to be scaled
44                 _scaled = false;
45         }
46
47         /**
48          * Constructor using fields and points from another Track
49          * @param inFieldList Field list from another Track object
50          * @param inPoints (edited) point array
51          */
52         public Track(FieldList inFieldList, DataPoint[] inPoints)
53         {
54                 _masterFieldList = inFieldList;
55                 _dataPoints = inPoints;
56                 if (_dataPoints == null) _dataPoints = new DataPoint[0];
57                 _numPoints = _dataPoints.length;
58                 _scaled = false;
59         }
60
61         /**
62          * Load method, for initialising and reinitialising data
63          * @param inFieldArray array of Field objects describing fields
64          * @param inPointArray 2d object array containing data
65          * @param inOptions load options such as units
66          */
67         public void load(Field[] inFieldArray, Object[][] inPointArray, PointCreateOptions inOptions)
68         {
69                 if (inFieldArray == null || inPointArray == null)
70                 {
71                         _numPoints = 0;
72                         return;
73                 }
74                 // copy field list
75                 _masterFieldList = new FieldList(inFieldArray);
76                 // make DataPoint object from each point in inPointList
77                 _dataPoints = new DataPoint[inPointArray.length];
78                 String[] dataArray = null;
79                 int pointIndex = 0;
80                 for (int p=0; p < inPointArray.length; p++)
81                 {
82                         dataArray = (String[]) inPointArray[p];
83                         // Convert to DataPoint objects
84                         DataPoint point = new DataPoint(dataArray, _masterFieldList, inOptions);
85                         if (point.isValid())
86                         {
87                                 _dataPoints[pointIndex] = point;
88                                 pointIndex++;
89                         }
90                 }
91                 _numPoints = pointIndex;
92                 // Set first track point to be start of segment
93                 DataPoint firstTrackPoint = getNextTrackPoint(0);
94                 if (firstTrackPoint != null) {
95                         firstTrackPoint.setSegmentStart(true);
96                 }
97                 // needs to be scaled
98                 _scaled = false;
99         }
100
101
102         /**
103          * Load the track by transferring the contents from a loaded Track object
104          * @param inOther Track object containing loaded data
105          */
106         public void load(Track inOther)
107         {
108                 _numPoints = inOther._numPoints;
109                 _masterFieldList = inOther._masterFieldList;
110                 _dataPoints = inOther._dataPoints;
111                 // needs to be scaled
112                 _scaled = false;
113         }
114
115         /**
116          * Request that a rescale be done to recalculate derived values
117          */
118         public void requestRescale()
119         {
120                 _scaled = false;
121         }
122
123         /**
124          * Extend the track's field list with the given additional fields
125          * @param inFieldList list of fields to be added
126          */
127         public void extendFieldList(FieldList inFieldList)
128         {
129                 _masterFieldList = _masterFieldList.merge(inFieldList);
130         }
131
132         ////////////////// Modification methods //////////////////////
133
134
135         /**
136          * Combine this Track with new data
137          * @param inOtherTrack other track to combine
138          */
139         public void combine(Track inOtherTrack)
140         {
141                 // merge field list
142                 _masterFieldList = _masterFieldList.merge(inOtherTrack._masterFieldList);
143                 // expand data array and add other track's data points
144                 int totalPoints = getNumPoints() + inOtherTrack.getNumPoints();
145                 DataPoint[] mergedPoints = new DataPoint[totalPoints];
146                 System.arraycopy(_dataPoints, 0, mergedPoints, 0, getNumPoints());
147                 System.arraycopy(inOtherTrack._dataPoints, 0, mergedPoints, getNumPoints(), inOtherTrack.getNumPoints());
148                 _dataPoints = mergedPoints;
149                 // combine point count
150                 _numPoints = totalPoints;
151                 // needs to be scaled again
152                 _scaled = false;
153                 // inform listeners
154                 UpdateMessageBroker.informSubscribers();
155         }
156
157
158         /**
159          * Crop the track to the given size - subsequent points are not (yet) deleted
160          * @param inNewSize new number of points in track
161          */
162         public void cropTo(int inNewSize)
163         {
164                 if (inNewSize >= 0 && inNewSize < getNumPoints())
165                 {
166                         _numPoints = inNewSize;
167                         // needs to be scaled again
168                         _scaled = false;
169                         UpdateMessageBroker.informSubscribers();
170                 }
171         }
172
173
174         /**
175          * Delete the points marked for deletion
176          * @return number of points deleted
177          */
178         public int deleteMarkedPoints()
179         {
180                 int numCopied = 0;
181                 // Copy selected points
182                 DataPoint[] newPointArray = new DataPoint[_numPoints];
183                 for (int i=0; i<_numPoints; i++)
184                 {
185                         DataPoint point = _dataPoints[i];
186                         // Don't delete photo points
187                         if (point.hasMedia() || !point.getDeleteFlag())
188                         {
189                                 newPointArray[numCopied] = point;
190                                 numCopied++;
191                         }
192                 }
193
194                 // Copy array references
195                 int numDeleted = _numPoints - numCopied;
196                 if (numDeleted > 0)
197                 {
198                         _dataPoints = new DataPoint[numCopied];
199                         System.arraycopy(newPointArray, 0, _dataPoints, 0, numCopied);
200                         _numPoints = _dataPoints.length;
201                         _scaled = false;
202                 }
203                 return numDeleted;
204         }
205
206
207         /**
208          * Delete the specified point
209          * @param inIndex point index
210          * @return true if successful
211          */
212         public boolean deletePoint(int inIndex)
213         {
214                 boolean answer = deleteRange(inIndex, inIndex);
215                 return answer;
216         }
217
218
219         /**
220          * Delete the specified range of points from the Track
221          * @param inStart start of range (inclusive)
222          * @param inEnd end of range (inclusive)
223          * @return true if successful
224          */
225         public boolean deleteRange(int inStart, int inEnd)
226         {
227                 if (inStart < 0 || inEnd < 0 || inEnd < inStart)
228                 {
229                         // no valid range selected so can't delete
230                         return false;
231                 }
232                 // check through range to be deleted, and see if any new segment flags present
233                 boolean hasSegmentStart = false;
234                 DataPoint nextTrackPoint = getNextTrackPoint(inEnd+1);
235                 if (nextTrackPoint != null) {
236                         for (int i=inStart; i<=inEnd && !hasSegmentStart; i++) {
237                                 hasSegmentStart |= _dataPoints[i].getSegmentStart();
238                         }
239                         // If segment break found, make sure next trackpoint also has break
240                         if (hasSegmentStart) {nextTrackPoint.setSegmentStart(true);}
241                 }
242                 // valid range, let's delete it
243                 int numToDelete = inEnd - inStart + 1;
244                 DataPoint[] newPointArray = new DataPoint[_numPoints - numToDelete];
245                 // Copy points before the selected range
246                 if (inStart > 0)
247                 {
248                         System.arraycopy(_dataPoints, 0, newPointArray, 0, inStart);
249                 }
250                 // Copy points after the deleted one(s)
251                 if (inEnd < (_numPoints - 1))
252                 {
253                         System.arraycopy(_dataPoints, inEnd + 1, newPointArray, inStart,
254                                 _numPoints - inEnd - 1);
255                 }
256                 // Copy points over original array
257                 _dataPoints = newPointArray;
258                 _numPoints -= numToDelete;
259                 // needs to be scaled again
260                 _scaled = false;
261                 return true;
262         }
263
264
265         /**
266          * Reverse the specified range of points
267          * @param inStart start index
268          * @param inEnd end index
269          * @return true if successful, false otherwise
270          */
271         public boolean reverseRange(int inStart, int inEnd)
272         {
273                 if (inStart < 0 || inEnd < 0 || inStart >= inEnd || inEnd >= _numPoints)
274                 {
275                         return false;
276                 }
277                 // calculate how many point swaps are required
278                 int numPointsToReverse = (inEnd - inStart + 1) / 2;
279                 DataPoint p = null;
280                 for (int i=0; i<numPointsToReverse; i++)
281                 {
282                         // swap pairs of points
283                         p = _dataPoints[inStart + i];
284                         _dataPoints[inStart + i] = _dataPoints[inEnd - i];
285                         _dataPoints[inEnd - i] = p;
286                 }
287                 // adjust segment starts
288                 shiftSegmentStarts(inStart, inEnd);
289                 // Find first track point and following track point, and set segment starts to true
290                 DataPoint firstTrackPoint = getNextTrackPoint(inStart);
291                 if (firstTrackPoint != null) {firstTrackPoint.setSegmentStart(true);}
292                 DataPoint nextTrackPoint = getNextTrackPoint(inEnd+1);
293                 if (nextTrackPoint != null) {nextTrackPoint.setSegmentStart(true);}
294                 // needs to be scaled again
295                 _scaled = false;
296                 UpdateMessageBroker.informSubscribers();
297                 return true;
298         }
299
300
301         /**
302          * Add the given time offset to the specified range
303          * @param inStart start of range
304          * @param inEnd end of range
305          * @param inOffset offset to add (-ve to subtract)
306          * @param inUndo true for undo operation
307          * @return true on success
308          */
309         public boolean addTimeOffset(int inStart, int inEnd, long inOffset, boolean inUndo)
310         {
311                 // sanity check
312                 if (inStart < 0 || inEnd < 0 || inStart >= inEnd || inEnd >= _numPoints) {
313                         return false;
314                 }
315                 boolean foundTimestamp = false;
316                 // Loop over all points within range
317                 for (int i=inStart; i<=inEnd; i++)
318                 {
319                         DataPoint p = _dataPoints[i];
320                         if (p != null && p.hasTimestamp())
321                         {
322                                 // This point has a timestamp so add the offset to it
323                                 foundTimestamp = true;
324                                 p.addTimeOffset(inOffset);
325                                 p.setModified(inUndo);
326                         }
327                 }
328                 return foundTimestamp;
329         }
330
331         /**
332          * Add the given altitude offset to the specified range
333          * @param inStart start of range
334          * @param inEnd end of range
335          * @param inOffset offset to add (-ve to subtract)
336          * @param inUnit altitude unit of offset
337          * @param inDecimals number of decimal places in offset
338          * @return true on success
339          */
340         public boolean addAltitudeOffset(int inStart, int inEnd, double inOffset,
341          Unit inUnit, int inDecimals)
342         {
343                 // sanity check
344                 if (inStart < 0 || inEnd < 0 || inStart >= inEnd || inEnd >= _numPoints) {
345                         return false;
346                 }
347                 boolean foundAlt = false;
348                 // Loop over all points within range
349                 for (int i=inStart; i<=inEnd; i++)
350                 {
351                         DataPoint p = _dataPoints[i];
352                         if (p != null && p.hasAltitude())
353                         {
354                                 // This point has an altitude so add the offset to it
355                                 foundAlt = true;
356                                 p.addAltitudeOffset(inOffset, inUnit, inDecimals);
357                                 p.setModified(false);
358                         }
359                 }
360                 // needs to be scaled again
361                 _scaled = false;
362                 return foundAlt;
363         }
364
365
366         /**
367          * Collect all waypoints to the start or end of the track
368          * @param inAtStart true to collect at start, false for end
369          * @return true if successful, false if no change
370          */
371         public boolean collectWaypoints(boolean inAtStart)
372         {
373                 // Check for mixed data, numbers of waypoints & nons
374                 int numWaypoints = 0, numNonWaypoints = 0;
375                 boolean wayAfterNon = false, nonAfterWay = false;
376                 DataPoint[] waypoints = new DataPoint[_numPoints];
377                 DataPoint[] nonWaypoints = new DataPoint[_numPoints];
378                 DataPoint point = null;
379                 for (int i=0; i<_numPoints; i++)
380                 {
381                         point = _dataPoints[i];
382                         if (point.isWaypoint())
383                         {
384                                 waypoints[numWaypoints] = point;
385                                 numWaypoints++;
386                                 wayAfterNon |= (numNonWaypoints > 0);
387                         }
388                         else
389                         {
390                                 nonWaypoints[numNonWaypoints] = point;
391                                 numNonWaypoints++;
392                                 nonAfterWay |= (numWaypoints > 0);
393                         }
394                 }
395                 // Exit if the data is already in the specified order
396                 if (numWaypoints == 0 || numNonWaypoints == 0
397                         || (inAtStart && !wayAfterNon && nonAfterWay)
398                         || (!inAtStart && wayAfterNon && !nonAfterWay))
399                 {
400                         return false;
401                 }
402
403                 // Copy the arrays back into _dataPoints in the specified order
404                 if (inAtStart)
405                 {
406                         System.arraycopy(waypoints, 0, _dataPoints, 0, numWaypoints);
407                         System.arraycopy(nonWaypoints, 0, _dataPoints, numWaypoints, numNonWaypoints);
408                 }
409                 else
410                 {
411                         System.arraycopy(nonWaypoints, 0, _dataPoints, 0, numNonWaypoints);
412                         System.arraycopy(waypoints, 0, _dataPoints, numNonWaypoints, numWaypoints);
413                 }
414                 // needs to be scaled again
415                 _scaled = false;
416                 UpdateMessageBroker.informSubscribers();
417                 return true;
418         }
419
420
421         /**
422          * Interleave all waypoints by each nearest track point
423          * @return true if successful, false if no change
424          */
425         public boolean interleaveWaypoints()
426         {
427                 // Separate waypoints and find nearest track point
428                 int numWaypoints = 0;
429                 DataPoint[] waypoints = new DataPoint[_numPoints];
430                 int[] pointIndices = new int[_numPoints];
431                 DataPoint point = null;
432                 int i = 0;
433                 for (i=0; i<_numPoints; i++)
434                 {
435                         point = _dataPoints[i];
436                         if (point.isWaypoint())
437                         {
438                                 waypoints[numWaypoints] = point;
439                                 pointIndices[numWaypoints] = getNearestPointIndex(
440                                         _xValues[i], _yValues[i], -1.0, true);
441                                 numWaypoints++;
442                         }
443                 }
444                 // Exit if data not mixed
445                 if (numWaypoints == 0 || numWaypoints == _numPoints)
446                         return false;
447
448                 // Loop round points copying to correct order
449                 DataPoint[] dataCopy = new DataPoint[_numPoints];
450                 int copyIndex = 0;
451                 for (i=0; i<_numPoints; i++)
452                 {
453                         point = _dataPoints[i];
454                         // if it's a track point, copy it
455                         if (!point.isWaypoint())
456                         {
457                                 dataCopy[copyIndex] = point;
458                                 copyIndex++;
459                         }
460                         // check for waypoints with this index
461                         for (int j=0; j<numWaypoints; j++)
462                         {
463                                 if (pointIndices[j] == i)
464                                 {
465                                         dataCopy[copyIndex] = waypoints[j];
466                                         copyIndex++;
467                                 }
468                         }
469                 }
470                 // Copy data back to track
471                 _dataPoints = dataCopy;
472                 // needs to be scaled again to recalc x, y
473                 _scaled = false;
474                 UpdateMessageBroker.informSubscribers();
475                 return true;
476         }
477
478
479         /**
480          * Cut and move the specified section
481          * @param inSectionStart start index of section
482          * @param inSectionEnd end index of section
483          * @param inMoveTo index of move to point
484          * @return true if move successful
485          */
486         public boolean cutAndMoveSection(int inSectionStart, int inSectionEnd, int inMoveTo)
487         {
488                 // TODO: Move cut/move into separate function?
489                 // Check that indices make sense
490                 if (inSectionStart >= 0 && inSectionEnd > inSectionStart && inMoveTo >= 0
491                         && (inMoveTo < inSectionStart || inMoveTo > (inSectionEnd+1)))
492                 {
493                         // do the cut and move
494                         DataPoint[] newPointArray = new DataPoint[_numPoints];
495                         // System.out.println("Cut/move section (" + inSectionStart + " - " + inSectionEnd + ") to before point " + inMoveTo);
496                         // Is it a forward copy or a backward copy?
497                         if (inSectionStart > inMoveTo)
498                         {
499                                 int sectionLength = inSectionEnd - inSectionStart + 1;
500                                 // move section to earlier point
501                                 if (inMoveTo > 0) {
502                                         System.arraycopy(_dataPoints, 0, newPointArray, 0, inMoveTo); // unchanged points before
503                                 }
504                                 System.arraycopy(_dataPoints, inSectionStart, newPointArray, inMoveTo, sectionLength); // moved bit
505                                 // after insertion point, before moved bit
506                                 System.arraycopy(_dataPoints, inMoveTo, newPointArray, inMoveTo + sectionLength, inSectionStart - inMoveTo);
507                                 // after moved bit
508                                 if (inSectionEnd < (_numPoints - 1)) {
509                                         System.arraycopy(_dataPoints, inSectionEnd+1, newPointArray, inSectionEnd+1, _numPoints - inSectionEnd - 1);
510                                 }
511                         }
512                         else
513                         {
514                                 // Move section to later point
515                                 if (inSectionStart > 0) {
516                                         System.arraycopy(_dataPoints, 0, newPointArray, 0, inSectionStart); // unchanged points before
517                                 }
518                                 // from end of section to move to point
519                                 if (inMoveTo > (inSectionEnd + 1)) {
520                                         System.arraycopy(_dataPoints, inSectionEnd+1, newPointArray, inSectionStart, inMoveTo - inSectionEnd - 1);
521                                 }
522                                 // moved bit
523                                 System.arraycopy(_dataPoints, inSectionStart, newPointArray, inSectionStart + inMoveTo - inSectionEnd - 1,
524                                         inSectionEnd - inSectionStart + 1);
525                                 // unchanged bit after
526                                 if (inSectionEnd < (_numPoints - 1)) {
527                                         System.arraycopy(_dataPoints, inMoveTo, newPointArray, inMoveTo, _numPoints - inMoveTo);
528                                 }
529                         }
530                         // Copy array references
531                         _dataPoints = newPointArray;
532                         _scaled = false;
533                         return true;
534                 }
535                 return false;
536         }
537
538
539         /**
540          * Interpolate extra points between two selected ones
541          * @param inStartIndex start index of interpolation
542          * @param inNumPoints num points to insert
543          * @return true if successful
544          */
545         public boolean interpolate(int inStartIndex, int inNumPoints)
546         {
547                 // check parameters
548                 if (inStartIndex < 0 || inStartIndex >= _numPoints || inNumPoints <= 0)
549                         return false;
550
551                 // get start and end points
552                 DataPoint startPoint = getPoint(inStartIndex);
553                 DataPoint endPoint = getPoint(inStartIndex + 1);
554
555                 // Make array of points to insert
556                 DataPoint[] insertedPoints = startPoint.interpolate(endPoint, inNumPoints);
557
558                 // Insert points into track
559                 return insertRange(insertedPoints, inStartIndex + 1);
560         }
561
562
563         /**
564          * Average selected points
565          * @param inStartIndex start index of selection
566          * @param inEndIndex end index of selection
567          * @return true if successful
568          */
569         public boolean average(int inStartIndex, int inEndIndex)
570         {
571                 // check parameters
572                 if (inStartIndex < 0 || inStartIndex >= _numPoints || inEndIndex <= inStartIndex)
573                         return false;
574
575                 DataPoint startPoint = getPoint(inStartIndex);
576                 double firstLatitude = startPoint.getLatitude().getDouble();
577                 double firstLongitude = startPoint.getLongitude().getDouble();
578                 double latitudeDiff = 0.0, longitudeDiff = 0.0;
579                 double totalAltitude = 0;
580                 int numAltitudes = 0;
581                 Unit altUnit = null;
582                 // loop between start and end points
583                 for (int i=inStartIndex; i<= inEndIndex; i++)
584                 {
585                         DataPoint currPoint = getPoint(i);
586                         latitudeDiff += (currPoint.getLatitude().getDouble() - firstLatitude);
587                         longitudeDiff += (currPoint.getLongitude().getDouble() - firstLongitude);
588                         if (currPoint.hasAltitude())
589                         {
590                                 totalAltitude += currPoint.getAltitude().getValue(altUnit);
591                                 // Use altitude format of first valid altitude
592                                 if (altUnit == null)
593                                         altUnit = currPoint.getAltitude().getUnit();
594                                 numAltitudes++;
595                         }
596                 }
597                 int numPoints = inEndIndex - inStartIndex + 1;
598                 double meanLatitude = firstLatitude + (latitudeDiff / numPoints);
599                 double meanLongitude = firstLongitude + (longitudeDiff / numPoints);
600                 Altitude meanAltitude = null;
601                 if (numAltitudes > 0) {
602                         meanAltitude = new Altitude((int) (totalAltitude / numAltitudes), altUnit);
603                 }
604
605                 DataPoint insertedPoint = new DataPoint(new Latitude(meanLatitude, Coordinate.FORMAT_NONE),
606                         new Longitude(meanLongitude, Coordinate.FORMAT_NONE), meanAltitude);
607                 // Make into singleton
608                 insertedPoint.setSegmentStart(true);
609                 DataPoint nextPoint = getNextTrackPoint(inEndIndex+1);
610                 if (nextPoint != null) {nextPoint.setSegmentStart(true);}
611                 // Insert points into track
612                 return insertRange(new DataPoint[] {insertedPoint}, inEndIndex + 1);
613         }
614
615
616         /**
617          * Append the specified points to the end of the track
618          * @param inPoints DataPoint objects to add
619          */
620         public void appendPoints(DataPoint[] inPoints)
621         {
622                 // Insert points into track
623                 if (inPoints != null && inPoints.length > 0)
624                 {
625                         insertRange(inPoints, _numPoints);
626                 }
627                 // needs to be scaled again to recalc x, y
628                 _scaled = false;
629                 UpdateMessageBroker.informSubscribers();
630         }
631
632
633         //////// information methods /////////////
634
635
636         /**
637          * Get the point at the given index
638          * @param inPointNum index number, starting at 0
639          * @return DataPoint object, or null if out of range
640          */
641         public DataPoint getPoint(int inPointNum)
642         {
643                 if (inPointNum > -1 && inPointNum < getNumPoints())
644                 {
645                         return _dataPoints[inPointNum];
646                 }
647                 return null;
648         }
649
650         /**
651          * @return the number of (valid) points in the track
652          */
653         public int getNumPoints()
654         {
655                 return _numPoints;
656         }
657
658         /**
659          * @return The range of x values as a DoubleRange object
660          */
661         public DoubleRange getXRange()
662         {
663                 if (!_scaled) {scalePoints();}
664                 return _xRange;
665         }
666
667         /**
668          * @return The range of y values as a DoubleRange object
669          */
670         public DoubleRange getYRange()
671         {
672                 if (!_scaled) {scalePoints();}
673                 return _yRange;
674         }
675
676         /**
677          * @return The range of lat values as a DoubleRange object
678          */
679         public DoubleRange getLatRange()
680         {
681                 if (!_scaled) {scalePoints();}
682                 return _latRange;
683         }
684         /**
685          * @return The range of lon values as a DoubleRange object
686          */
687         public DoubleRange getLonRange()
688         {
689                 if (!_scaled) {scalePoints();}
690                 return _longRange;
691         }
692
693         /**
694          * @param inPointNum point index, starting at 0
695          * @return scaled x value of specified point
696          */
697         public double getX(int inPointNum)
698         {
699                 if (!_scaled) {scalePoints();}
700                 return _xValues[inPointNum];
701         }
702
703         /**
704          * @param inPointNum point index, starting at 0
705          * @return scaled y value of specified point
706          */
707         public double getY(int inPointNum)
708         {
709                 if (!_scaled) {scalePoints();}
710                 return _yValues[inPointNum];
711         }
712
713         /**
714          * @return the master field list
715          */
716         public FieldList getFieldList()
717         {
718                 return _masterFieldList;
719         }
720
721
722         /**
723          * Checks if any data exists for the specified field
724          * @param inField Field to examine
725          * @return true if data exists for this field
726          */
727         public boolean hasData(Field inField)
728         {
729                 // Don't use this method for altitudes
730                 if (inField.equals(Field.ALTITUDE)) {return hasAltitudeData();}
731                 return hasData(inField, 0, _numPoints-1);
732         }
733
734
735         /**
736          * Checks if any data exists for the specified field in the specified range
737          * @param inField Field to examine
738          * @param inStart start of range to check
739          * @param inEnd end of range to check (inclusive)
740          * @return true if data exists for this field
741          */
742         public boolean hasData(Field inField, int inStart, int inEnd)
743         {
744                 // Loop over selected point range
745                 for (int i=inStart; i<=inEnd; i++)
746                 {
747                         if (_dataPoints[i].getFieldValue(inField) != null)
748                         {
749                                 // Check altitudes and timestamps
750                                 if ((inField != Field.ALTITUDE || _dataPoints[i].getAltitude().isValid())
751                                         && (inField != Field.TIMESTAMP || _dataPoints[i].getTimestamp().isValid()))
752                                 {
753                                         return true;
754                                 }
755                         }
756                 }
757                 return false;
758         }
759
760         /**
761          * @return true if track has altitude data
762          */
763         public boolean hasAltitudeData()
764         {
765                 for (int i=0; i<_numPoints; i++) {
766                         if (_dataPoints[i].hasAltitude()) {return true;}
767                 }
768                 return false;
769         }
770
771         /**
772          * @return true if track contains at least one trackpoint
773          */
774         public boolean hasTrackPoints()
775         {
776                 if (!_scaled) {scalePoints();}
777                 return _hasTrackpoint;
778         }
779
780         /**
781          * @return true if track contains waypoints
782          */
783         public boolean hasWaypoints()
784         {
785                 if (!_scaled) {scalePoints();}
786                 return _hasWaypoint;
787         }
788
789         /**
790          * @return true if track contains any points marked for deletion
791          */
792         public boolean hasMarkedPoints()
793         {
794                 if (_numPoints < 1) {
795                         return false;
796                 }
797                 // Loop over points looking for any marked for deletion
798                 for (int i=0; i<=_numPoints-1; i++)
799                 {
800                         if (_dataPoints[i] != null && _dataPoints[i].getDeleteFlag()) {
801                                 return true;
802                         }
803                 }
804                 // None found
805                 return false;
806         }
807
808         /**
809          * Clear all the deletion markers
810          */
811         public void clearDeletionMarkers()
812         {
813                 for (int i=0; i<_numPoints; i++)
814                 {
815                         _dataPoints[i].setMarkedForDeletion(false);
816                 }
817         }
818
819         /**
820          * Collect all the waypoints into the given List
821          * @param inList List to fill with waypoints
822          */
823         public void getWaypoints(List<DataPoint> inList)
824         {
825                 // clear list
826                 inList.clear();
827                 // loop over points and copy all waypoints into list
828                 for (int i=0; i<=_numPoints-1; i++)
829                 {
830                         if (_dataPoints[i] != null && _dataPoints[i].isWaypoint())
831                         {
832                                 inList.add(_dataPoints[i]);
833                         }
834                 }
835         }
836
837
838         /**
839          * Search for the given Point in the track and return the index
840          * @param inPoint Point to look for
841          * @return index of Point, if any or -1 if not found
842          */
843         public int getPointIndex(DataPoint inPoint)
844         {
845                 if (inPoint != null)
846                 {
847                         // Loop over points in track
848                         for (int i=0; i<=_numPoints-1; i++)
849                         {
850                                 if (_dataPoints[i] == inPoint)
851                                 {
852                                         return i;
853                                 }
854                         }
855                 }
856                 // not found
857                 return -1;
858         }
859
860
861         ///////// Internal processing methods ////////////////
862
863
864         /**
865          * Scale all the points in the track to gain x and y values
866          * ready for plotting
867          */
868         private synchronized void scalePoints()
869         {
870                 // Loop through all points in track, to see limits of lat, long
871                 _longRange = new DoubleRange();
872                 _latRange = new DoubleRange();
873                 int p;
874                 _hasWaypoint = false; _hasTrackpoint = false;
875                 for (p=0; p < getNumPoints(); p++)
876                 {
877                         DataPoint point = getPoint(p);
878                         if (point != null && point.isValid())
879                         {
880                                 _longRange.addValue(point.getLongitude().getDouble());
881                                 _latRange.addValue(point.getLatitude().getDouble());
882                                 if (point.isWaypoint())
883                                         _hasWaypoint = true;
884                                 else
885                                         _hasTrackpoint = true;
886                         }
887                 }
888
889                 // Loop over points and calculate scales
890                 _xValues = new double[getNumPoints()];
891                 _yValues = new double[getNumPoints()];
892                 _xRange = new DoubleRange();
893                 _yRange = new DoubleRange();
894                 for (p=0; p < getNumPoints(); p++)
895                 {
896                         DataPoint point = getPoint(p);
897                         if (point != null)
898                         {
899                                 _xValues[p] = MapUtils.getXFromLongitude(point.getLongitude().getDouble());
900                                 _xRange.addValue(_xValues[p]);
901                                 _yValues[p] = MapUtils.getYFromLatitude(point.getLatitude().getDouble());
902                                 _yRange.addValue(_yValues[p]);
903                         }
904                 }
905                 _scaled = true;
906         }
907
908
909         /**
910          * Find the nearest point to the specified x and y coordinates
911          * or -1 if no point is within the specified max distance
912          * @param inX x coordinate
913          * @param inY y coordinate
914          * @param inMaxDist maximum distance from selected coordinates
915          * @param inJustTrackPoints true if waypoints should be ignored
916          * @return index of nearest point or -1 if not found
917          */
918         public int getNearestPointIndex(double inX, double inY, double inMaxDist, boolean inJustTrackPoints)
919         {
920                 int nearestPoint = 0;
921                 double nearestDist = -1.0;
922                 double mDist, yDist;
923                 for (int i=0; i < getNumPoints(); i++)
924                 {
925                         if (!inJustTrackPoints || !_dataPoints[i].isWaypoint())
926                         {
927                                 yDist = Math.abs(_yValues[i] - inY);
928                                 if (yDist < nearestDist || nearestDist < 0.0)
929                                 {
930                                         // y dist is within range, so check x too
931                                         mDist = yDist + getMinXDist(_xValues[i] - inX);
932                                         if (mDist < nearestDist || nearestDist < 0.0)
933                                         {
934                                                 nearestPoint = i;
935                                                 nearestDist = mDist;
936                                         }
937                                 }
938                         }
939                 }
940                 // Check whether it's within required distance
941                 if (nearestDist > inMaxDist && inMaxDist > 0.0)
942                 {
943                         return -1;
944                 }
945                 return nearestPoint;
946         }
947
948         /**
949          * @param inX x value of point
950          * @return minimum wrapped value
951          */
952         private static final double getMinXDist(double inX)
953         {
954                 // TODO: Can use some kind of floor here?
955                 return Math.min(Math.min(Math.abs(inX), Math.abs(inX-1.0)), Math.abs(inX+1.0));
956         }
957
958         /**
959          * Get the next track point starting from the given index
960          * @param inStartIndex index to start looking from
961          * @return next track point, or null if end of data reached
962          */
963         public DataPoint getNextTrackPoint(int inStartIndex)
964         {
965                 return getNextTrackPoint(inStartIndex, _numPoints, true);
966         }
967
968         /**
969          * Get the next track point in the given range
970          * @param inStartIndex index to start looking from
971          * @param inEndIndex index to stop looking
972          * @return next track point, or null if end of data reached
973          */
974         public DataPoint getNextTrackPoint(int inStartIndex, int inEndIndex)
975         {
976                 return getNextTrackPoint(inStartIndex, inEndIndex, true);
977         }
978
979         /**
980          * Get the previous track point starting from the given index
981          * @param inStartIndex index to start looking from
982          * @return next track point, or null if end of data reached
983          */
984         public DataPoint getPreviousTrackPoint(int inStartIndex)
985         {
986                 // end index is given as _numPoints but actually it just counts down to -1
987                 return getNextTrackPoint(inStartIndex, _numPoints, false);
988         }
989
990         /**
991          * Get the next track point starting from the given index
992          * @param inStartIndex index to start looking from
993          * @param inEndIndex index to stop looking (inclusive)
994          * @param inCountUp true for next, false for previous
995          * @return next track point, or null if end of data reached
996          */
997         private DataPoint getNextTrackPoint(int inStartIndex, int inEndIndex, boolean inCountUp)
998         {
999                 // Loop forever over points
1000                 int increment = inCountUp?1:-1;
1001                 for (int i=inStartIndex; i<=inEndIndex; i+=increment)
1002                 {
1003                         DataPoint point = getPoint(i);
1004                         // Exit if end of data reached - there wasn't a track point
1005                         if (point == null) {return null;}
1006                         if (point.isValid() && !point.isWaypoint()) {
1007                                 // next track point found
1008                                 return point;
1009                         }
1010                 }
1011                 return null;
1012         }
1013
1014         /**
1015          * Shift all the segment start flags in the given range by 1
1016          * Method used by reverse range and its undo
1017          * @param inStartIndex start of range, inclusive
1018          * @param inEndIndex end of range, inclusive
1019          */
1020         public void shiftSegmentStarts(int inStartIndex, int inEndIndex)
1021         {
1022                 boolean prevFlag = true;
1023                 boolean currFlag = true;
1024                 for (int i=inStartIndex; i<= inEndIndex; i++)
1025                 {
1026                         DataPoint point = getPoint(i);
1027                         if (point != null && !point.isWaypoint())
1028                         {
1029                                 // remember flag
1030                                 currFlag = point.getSegmentStart();
1031                                 // shift flag by 1
1032                                 point.setSegmentStart(prevFlag);
1033                                 prevFlag = currFlag;
1034                         }
1035                 }
1036         }
1037
1038         ////////////////// Cloning and replacing ///////////////////
1039
1040         /**
1041          * Clone the array of DataPoints
1042          * @return shallow copy of DataPoint objects
1043          */
1044         public DataPoint[] cloneContents()
1045         {
1046                 DataPoint[] clone = new DataPoint[getNumPoints()];
1047                 System.arraycopy(_dataPoints, 0, clone, 0, getNumPoints());
1048                 return clone;
1049         }
1050
1051
1052         /**
1053          * Clone the specified range of data points
1054          * @param inStart start index (inclusive)
1055          * @param inEnd end index (inclusive)
1056          * @return shallow copy of DataPoint objects
1057          */
1058         public DataPoint[] cloneRange(int inStart, int inEnd)
1059         {
1060                 int numSelected = 0;
1061                 if (inEnd >= 0 && inEnd >= inStart)
1062                 {
1063                         numSelected = inEnd - inStart + 1;
1064                 }
1065                 DataPoint[] result = new DataPoint[numSelected>0?numSelected:0];
1066                 if (numSelected > 0)
1067                 {
1068                         System.arraycopy(_dataPoints, inStart, result, 0, numSelected);
1069                 }
1070                 return result;
1071         }
1072
1073
1074         /**
1075          * Re-insert the specified point at the given index
1076          * @param inPoint point to insert
1077          * @param inIndex index at which to insert the point
1078          * @return true if it worked, false otherwise
1079          */
1080         public boolean insertPoint(DataPoint inPoint, int inIndex)
1081         {
1082                 if (inIndex > _numPoints || inPoint == null)
1083                 {
1084                         return false;
1085                 }
1086                 // Make new array to copy points over to
1087                 DataPoint[] newPointArray = new DataPoint[_numPoints + 1];
1088                 if (inIndex > 0)
1089                 {
1090                         System.arraycopy(_dataPoints, 0, newPointArray, 0, inIndex);
1091                 }
1092                 newPointArray[inIndex] = inPoint;
1093                 if (inIndex < _numPoints)
1094                 {
1095                         System.arraycopy(_dataPoints, inIndex, newPointArray, inIndex+1, _numPoints - inIndex);
1096                 }
1097                 // Change over to new array
1098                 _dataPoints = newPointArray;
1099                 _numPoints++;
1100                 // needs to be scaled again
1101                 _scaled = false;
1102                 UpdateMessageBroker.informSubscribers();
1103                 return true;
1104         }
1105
1106
1107         /**
1108          * Re-insert the specified point range at the given index
1109          * @param inPoints point array to insert
1110          * @param inIndex index at which to insert the points
1111          * @return true if it worked, false otherwise
1112          */
1113         public boolean insertRange(DataPoint[] inPoints, int inIndex)
1114         {
1115                 if (inIndex > _numPoints || inPoints == null)
1116                 {
1117                         return false;
1118                 }
1119                 // Make new array to copy points over to
1120                 DataPoint[] newPointArray = new DataPoint[_numPoints + inPoints.length];
1121                 if (inIndex > 0)
1122                 {
1123                         System.arraycopy(_dataPoints, 0, newPointArray, 0, inIndex);
1124                 }
1125                 System.arraycopy(inPoints, 0, newPointArray, inIndex, inPoints.length);
1126                 if (inIndex < _numPoints)
1127                 {
1128                         System.arraycopy(_dataPoints, inIndex, newPointArray, inIndex+inPoints.length, _numPoints - inIndex);
1129                 }
1130                 // Change over to new array
1131                 _dataPoints = newPointArray;
1132                 _numPoints += inPoints.length;
1133                 // needs to be scaled again
1134                 _scaled = false;
1135                 UpdateMessageBroker.informSubscribers();
1136                 return true;
1137         }
1138
1139
1140         /**
1141          * Replace the track contents with the given point array
1142          * @param inContents array of DataPoint objects
1143          * @return true on success
1144          */
1145         public boolean replaceContents(DataPoint[] inContents)
1146         {
1147                 // master field array stays the same
1148                 // (would need to store field array too if we wanted to redo a load)
1149                 // replace data array
1150                 _dataPoints = inContents;
1151                 _numPoints = _dataPoints.length;
1152                 _scaled = false;
1153                 UpdateMessageBroker.informSubscribers();
1154                 return true;
1155         }
1156
1157
1158         /**
1159          * Edit the specified point
1160          * @param inPoint point to edit
1161          * @param inEditList list of edits to make
1162          * @param inUndo true if undo operation, false otherwise
1163          * @return true if successful
1164          */
1165         public boolean editPoint(DataPoint inPoint, FieldEditList inEditList, boolean inUndo)
1166         {
1167                 if (inPoint != null && inEditList != null && inEditList.getNumEdits() > 0)
1168                 {
1169                         // remember if coordinates have changed
1170                         boolean coordsChanged = false;
1171                         // go through edits one by one
1172                         int numEdits = inEditList.getNumEdits();
1173                         for (int i=0; i<numEdits; i++)
1174                         {
1175                                 FieldEdit edit = inEditList.getEdit(i);
1176                                 Field editField = edit.getField();
1177                                 inPoint.setFieldValue(editField, edit.getValue(), inUndo);
1178                                 // Check that master field list has this field already (maybe point name has been added)
1179                                 if (!_masterFieldList.contains(editField)) {
1180                                         _masterFieldList.extendList(editField);
1181                                 }
1182                                 // check coordinates
1183                                 coordsChanged |= (editField.equals(Field.LATITUDE)
1184                                         || editField.equals(Field.LONGITUDE) || editField.equals(Field.ALTITUDE));
1185                         }
1186                         // set photo status if coordinates have changed
1187                         if (inPoint.getPhoto() != null && coordsChanged)
1188                         {
1189                                 inPoint.getPhoto().setCurrentStatus(Photo.Status.CONNECTED);
1190                         }
1191                         // point possibly needs to be scaled again
1192                         _scaled = false;
1193                         // trigger listeners
1194                         UpdateMessageBroker.informSubscribers();
1195                         return true;
1196                 }
1197                 return false;
1198         }
1199
1200         /**
1201          * @param inPoint point to check
1202          * @return true if this track contains the given point
1203          */
1204         public boolean containsPoint(DataPoint inPoint)
1205         {
1206                 if (inPoint == null) return false;
1207                 for (int i=0; i < getNumPoints(); i++)
1208                 {
1209                         if (getPoint(i) == inPoint) return true;
1210                 }
1211                 return false; // not found
1212         }
1213 }