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