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