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