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