blib/lib/Geo/TCX.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Build ↑ Summary blib/lib/Geo/TCX/Track.pm »
1 package Geo::TCX;
2 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 our $VERSION = '1.00';
6  
7 =encoding utf-8
8  
9 =head1 NAME
10  
11 Geo::TCX - Parse and edit and TCX activity and course files from GPS training devices
12  
13 =head1 SYNOPSIS
14  
15 use Geo::TCX;
16  
17 =head1 DESCRIPTION
18  
19 C<Geo::TCX> enables the parsing and editing of TCX activity and course files. TCX files follow an XML schema developed by Garmin and common to its GPS sports devices. Among other methods, the module enables laps from an activity to be saved as individual *.tcx files, split into separate laps based on a given point, merged, or converted to courses to plan a future activity.
20  
21 The documentation regarding TCX files in general uses the terms history and activity quite interchangeably, including in the user guides such as the one for the Garmin Edge device the author of this module is using. In C<Geo::TCX>, the terms Activity/Activities are used to refer to tracks recorded by a device (consistently with the XML mark-up) and Course/Courses refer to planned tracks meant to be followed during an activity (i.e. the term history is seldomly used).
22  
23 =cut
24  
25 5 ▶use Geo::TCX::Lap;
Subroutine BEGIN: called CC=1 SCAR=2.6
26 use File::Basename;
27 use Cwd qw(cwd abs_path);
28 use Carp qw(confess croak cluck);
29  
30 =head2 Constructor Methods (class)
31  
32 =over 4
33  
34 =item new( $filename or $str_ref, work_dir => $working_directory )
35  
36 loads and returns a new Geo::TCX instance using the I<$filename> supplied as first argument or a string reference equivalent to the xml tags of a *.tcx file.
37  
38 $o = Geo::TCX->new('2022-08-11-10-27-15.tcx');
39 or
40 $o = Geo::TCX->new( \'...');
41  
42 C<work_dir> or C<wd> for short can be set to specify where to save any working files (such as with the save_laps() method). The module never actually L<chdir>'s, it just keeps track of where the user wants to save files (and not have to type filenames with path each time), hence it is always defined.
43  
44 The working directory can be supplied as a relative (to L<Cwd::cwd>) or absolute path but is internally stored by C<set_wd()> as a full path. If C<work_dir> is ommitted, it is set based on the path of the I<$filename> supplied or the current working directory if the constructor is called with a string reference.
45  
46 =back
47  
48 =cut
49  
50 sub new {
51 my ($proto, $first_arg) = (shift, shift);
52 my %opts = @_;
53 my $o = {};
54 my $class = ref($proto) || $proto;
55 bless($o, $class);
56  
57 my $txt;
58 if (ref( $first_arg ) eq 'SCALAR') {
59 $txt = $$first_arg
60 } else {
61 croak 'first argument must be a filename' unless -f $first_arg;
62 $txt = do { local(@ARGV, $/) = $first_arg; <> };
63 $o->set_filename($first_arg)
64 }
65  
66 $txt =~ s,\r,,g; # if it's a windows file
67 $txt =~ s,>\s+<,><,g;
68 $o->{tag_creator} = $1 if $txt =~ s/(<Creator.*<\/Creator>)//;
69  
70 # Activities/Activity - are as recorded by an EDGE 705 device
71 # Courses/Course - are as converted by an EDGE 705 device from an Activity
72  
73 $o->{tag_xml_version} = $1 if $txt =~ /(<.xml version[^>]*>)/;
74 $o->{tag_trainingcenterdatabase} = $1 if $txt =~ /(<TrainingCenterDatabase.*<\/TrainingCenterDatabase>)/;
75 $o->{tag_activities} = $1 if $txt =~ /(<Activities.*<\/Activities>)/;
76 $o->{tag_activity} = $1 if $txt =~ /(<Activity.*<\/Activity>)/;
77 $o->{tag_courses} = $1 if $txt =~ /(<Courses.*<\/Courses>)/;
78 $o->{tag_course} = $1 if $txt =~ /(<Course(?!s).*<\/Course>)/;
79  
80 # Id seems only for Activities/Activity...
81 if ($o->{tag_activity}) {
82 $o->{tag_id} = $1 if $o->{tag_activity} =~ /<Activity.*<Id>(.*)<\/Id>/;
83 $o->{tag_activity_type} = $1 if $o->{tag_activity} =~ /<Activity Sport="([^"]+)"/;
84 }
85  
86 # ... and Name only for Courses/Course
87 if ($o->{tag_course}) {
88 # will pick up device name under Creator if we are not specific about the Course tag
89 $o->{tag_name} = $1 if $o->{tag_course} =~ /<Course.*<Name>(.*)<\/Name>/
90 }
91  
92 $o->{tag_author} = $1 if $txt =~ /(<Author.*<\/Author>)/;
93 $o->_parse_author_tag if $o->{tag_author};
94  
95 my @Lap;
96 if ( $o->{tag_activity} ) {
97 my $i = 0;
98 my $lap;
99 while ( $o->{tag_activity} =~ /(\<Lap StartTime=.*?\>.*?\<\/Lap\>)/g ) {
100 my ($lapstring, $last_point_previous_lap);
101 $lapstring = $1;
102 $last_point_previous_lap = $lap->trackpoint(-1) if $i > 0;
103 $lap = Geo::TCX::Lap->new($lapstring, ++$i, $last_point_previous_lap);
104 push @{ $o->{Laps} }, $lap
105 }
106 }
107 if ( $o->{tag_course} ) {
108 # in Courses, data is structured as <Lap>...</Lap><Lap>...</Lap><Track>...</Track><Track>...</Track>
109 # actually, not sure just seem like it's one long ... track, not multiple ones, which complicates things
110 my $xml_str = $o->{tag_course};
111  
112 my (@lap_tags, @lap_endpoints, @track_tags);
113  
114 if ( $xml_str =~ m,(<Lap>.*</Lap>),s ) {
115 my $str = $1;
116 @lap_tags = split(/(?s)<\/Lap>\s*<Lap>/, $str );
117 if (@lap_tags == 0) { push @lap_tags, $str }
118 }
119  
120 for my $i (0 .. $#lap_tags) {
121 my ($end_pos, $end_pt);
122 if ( $lap_tags[$i] =~ m,<EndPosition>(.*)</EndPosition>,s ) {
123 $end_pt = Geo::TCX::Trackpoint->new( $1 );
124 push @lap_endpoints, $end_pt
125 }
126 # since split removed tags sometimes at ^ of string for other at $
127 # let's remove them all and add back
128 $lap_tags[$i] =~ s,</?Lap>,,g;
129 $lap_tags[$i] =~ s,^,<Lap>,g;
130 $lap_tags[$i] =~ s,$,</Lap>,g
131 }
132 my $track_str;
133 if ( $xml_str =~ m,(<Track>.*</Track>),s ) {
134 $track_str = $1;
135 }
136  
137 my $t = Geo::TCX::Track->new( $track_str );
138 if (@lap_tags ==1) { $track_tags[0] = $track_str }
139 else {
140 my ($t1, $t2);
141 for my $i (0 .. $#lap_tags ) {
142 if ($i < $#lap_tags) {
143 ($t1, $t2) = $t->split_at_point_closest_to( $lap_endpoints[$i] );
144 push @track_tags, $t1->xml_string;
145 $t = $t2
146 } else { push @track_tags, $t->xml_string } # ie don't split the last track portion
147 }
148 }
149  
150 my $lap;
151 for my $i (0 .. $#lap_tags) {
152 my ($lapstring, $last_point_previous_lap);
153 $lapstring = $lap_tags[$i] . $track_tags[$i];
154 $last_point_previous_lap = $lap->trackpoint(-1) if $i > 0;
155 $lap = Geo::TCX::Lap->new($lapstring, ++$i, $last_point_previous_lap);
156 push @{ $o->{Laps} }, $lap
157 }
158 }
159  
160 my $n = $o->laps;
161 die "cannot find any laps, must not be a *.tcx file or str" unless $n;
162 print "\nFound " . $n, ($n > 1 ? " Laps": " Lap"), "\n\n";
163 $o->{_txt} = $txt; # only for debugging
164 $o->set_wd( $opts{work_dir} || $opts{wd} );
165 return $o
166 }
167  
168 =head2 Constructor Methods (object)
169  
170 =over 4
171  
172 =item activity_to_course( key/values )
173  
174 returns a new <Geo::TCX> instance as a course, based on the current activity.
175  
176 All I<key/values> are optional:
177  
178 Z<> C<< lap => I<#> >>: converts lap number I<#> to a course, dropping all other laps. All laps are converted if C<lap> is omitted.
179 Z<> C<< course_name => I<$string> >>: the name for the course. The name will be the lap's C<StartTime> if a value is not specified.
180 Z<> C<< filename => I<$filename> >>: will call C<set_filename()> with this value.
181 Z<> C<< work_dir => I<$work_dir> >>: if omitted, it will be set to the same as that of the current object.
182  
183 =back
184  
185 =cut
186  
187 sub activity_to_course {
188 my $clone = shift->clone;
189 my %opts = @_;
190 croak 'this instance is already a course' if $clone->is_course;
191 my $wd = $opts{work_dir} || $opts{wd} || $clone->set_wd();
192  
193 my (@laps, $course);
194 @laps = $opts{lap} ? ($opts{lap}) : (1 .. $clone->laps);
195  
196 for my $lap_i (@laps) {
197 my $str = $clone->save_laps( [ $lap_i ], nosave => 1, course => 1, course_name => $opts{course_name} );
198 my $course_i = Geo::TCX->new( \$str, work_dir => $wd );
199 if ( defined $course ) {
200 push @{ $course->{Laps} }, $course_i->lap(1)
201 } else { $course = $course_i }
202 }
203 $course->set_filename( $opts{filename} );
204 return $course
205 }
206  
207 =over 4
208  
209 =item clone()
210  
211 Returns a deep copy of a C<Geo::TCX> instance.
212  
213 $clone = $o->clone;
214  
215 =back
216  
217 =cut
218  
219 sub clone {
220 my $clone;
221 eval(Data::Dumper->Dump([ shift ], ['$clone']));
222 confess $@ if $@;
223 return $clone
224 }
225  
226 =head2 Object Methods
227  
228 =over 4
229  
230 =item lap( # )
231  
232 Returns the lap object corresponding to the lap number I<#> specified. I<#> is one-indexed but negative numbers can be used to count from the end, e.g C<-1> to get the last lap.
233  
234 =back
235  
236 =cut
237  
238 sub lap {
239 my ($o, $lap_i, %exists) = (shift, shift);
240 croak 'requires a single integer as argument' if ! $lap_i or @_;
241 $lap_i = $o->_lap_number($lap_i);
242 return $o->{Laps}[$lap_i-1]
243 }
244  
245 =over 4
246  
247 =item laps( qw/ # # ... / )
248  
249 Returns a list of L<Geo::TCX::Lap> objects corresponding to the lap number(s) specified, or all laps if called without arguments. This method is useful as an access for the number of laps (i.e. without arguments in scalar context).
250  
251 =back
252  
253 =cut
254  
255 sub laps {
256 my $o = shift;
257 return @{$o->{Laps}} unless @_;
258 my @numbers = @_;
259 my @laps;
260 for my $lap_i (@numbers) {
261 $lap_i = $o->_lap_number($lap_i);
262 push @laps, $o->{Laps}[$lap_i-1]
263 }
264 return @laps
265 }
266  
267 =over 4
268  
269 =item merge_laps( #1, #2 )
270  
271 Merges lap I<#1> with lap I<#2> and returns true. Both laps must be consecutive laps and the number of laps in the object decreases by one.
272  
273 The C<TotalTimeSeconds> and C<DistanceMeters> aggregates of the merged lap are adjusted. For Activity laps, performance metrics are also adjusted. For Course laps, C<EndPosition> is also adjusted. See L<Geo::TCX::Lap>.
274  
275 =back
276  
277 =cut
278  
279 sub merge_laps {
280 my ($o, $i1, $i2, %exists) = (shift, shift, shift);
281 croak 'merge_laps() requires two integers as argument' if ! $i2 or @_;
282 croak 'can only merge consecutive laps' unless ($i2 - $i1)==1;
283 my $l1 = $o->lap($i1);
284 my $l2 = $o->lap($i2);
285  
286 my $lap = $l1->merge($l2, as_is => 1);
287  
288 splice @{ $o->{Laps}}, $i1 - 1, 2, $lap;
289 return 1
290 }
291  
292 =over 4
293  
294 =item split_lap( #, $trackpoint_no )
295  
296 Splits lap number I<#> at the specified I<$trackpoint_no> into two laps and returns true. The number of laps in the object increases by one.
297  
298 =back
299  
300 =cut
301  
302 sub split_lap {
303 my ($o, $lap_i, $pt_no, %exists) = (shift, shift, shift);
304 croak 'split_lap() requires two integers as argument' if ! $pt_no or @_;
305 $lap_i = $o->_lap_number($lap_i);
306 my ($lap_a, $lap_b) = $o->lap($lap_i)->split($pt_no);
307 splice @{ $o->{Laps}}, $lap_i -1, 1, ( $lap_a, $lap_b );
308 return 1
309 }
310  
311 =over 4
312  
313 =item split_lap_at_point_closest_to(#, $point or $trackpoint or $coord_str )
314  
315 Equivalent to C<split_lap()> but splits the specified lap I<#> at the trackpoint that lies closest to a given L<Geo::Gpx::Point>, L<Geo::TCX::Trackpoint>, or a string that can be interpreted as coordinates by C<< Geo::Gpx::Point->flex_coordinates >>. Returns true.
316  
317 =back
318  
319 =cut
320  
321 sub split_lap_at_point_closest_to {
322 my ($o, $lap_i, $to_pt) = (shift, shift, shift);
323 croak 'split_lap_at_point_closest_to() expects two arguments' if @_;
324 $lap_i = $o->_lap_number($lap_i);
325 $to_pt = Geo::Gpx::Point->flex_coordinates( \$to_pt ) unless ref $to_pt;
326 my ($closest_pt, $min_dist, $pt_no) = $o->lap($lap_i)->point_closest_to( $to_pt );
327 # here we can print some info about the original track and where it will be split
328 $o->split_lap( $lap_i, $pt_no );
329 return 1
330 }
331  
332 =over 4
333  
334 =item time_add( @duration )
335  
336 =item time_subtract( @duration )
337  
338 Perform L<DateTime> math on the timestamps of each trackpoint in the track by adding the specified time as per the syntax of L<DateTime>'s C<add()> and C<subtract()> methods. Returns true.
339  
340 Perform L<Date::Time> math on the timestamps of each lap's starttime and trackpoint by adding the specified time as per the syntax of L<Date::Time>'s C<add()> method. Returns true.
341  
342 =back
343  
344 =cut
345  
346 sub time_add {
347 my $o = shift;
348 my @duration = @_;
349 my @laps = @{$o->{Laps}};
350 for my $l (@laps) {
351 $l->time_add( @duration )
352 }
353 return 1
354 }
355  
356 sub time_subtract {
357 my $o = shift;
358 my @duration = @_;
359 my @laps = @{$o->{Laps}};
360 for my $l (@laps) {
361 $l->time_subtract( @duration )
362 }
363 return 1
364 }
365  
366 =over 4
367  
368 =item delete_lap( # )
369  
370 =item keep_lap( # )
371  
372 delete or keep the specified lap I<#> form the object. Returns the list of laps removed in both cases.
373  
374 =back
375  
376 =cut
377  
378 sub delete_lap {
379 my ($o, $lap_i) = (shift, shift);
380 croak 'requires a single integer as argument' unless $lap_i;
381 $lap_i = $o->_lap_number( $lap_i );
382 my @removed = splice @{ $o->{Laps}}, $lap_i - 1, 1;
383 return @removed
384 }
385  
386 sub keep_lap {
387 my ($o, $lap_i) = (shift, shift);
388 my @keep = $o->delete_lap($lap_i);
389 my @removed = @{ $o->{Laps}};
390 @{ $o->{Laps}} = @keep;
391 return @removed
392 }
393  
394 =over 4
395  
396 =item save_laps( \@laplist , key/values )
397  
398 saves each lap as a separate *.tcx file in the working directory as per <set_wd()>. The filenames will consist of the original source file's name, suffixed by the respective lap number.
399  
400 An array reference can be provided to save only a a subset of lap numbers.
401  
402 I<key/values> are:
403  
404 Z<> C<course>: converts activity lap(s) as course files if true.
405 Z<> C<< course_name => $string >>: is only relevant with C<course> and will set the name of the course to I<$string>.
406 Z<> C<force>: overwrites existing files if true, otherwise it won't.
407 Z<> C<indent>: adds white space and indents the xml mark-up in the saved file if true.
408 Z<> C<nosave>: no files are actually saved if true. Useful if only interested in the xml string of the last lap processed.
409  
410 C<course_name> will be ignored if there is more than one lap and the lap's C<StartTime> will be used instead. This is to avoid having multiple files with the same name given that devices use this tag when listing available courses. Acttvity files have an C<Id> tag instead of C<Name> and the laps's C<StartTime> is used at all times. It is easy to edit any of these tags manually in a text editor; just look for the C<< <Name>...</Name> >> tag or C<< <Id>...</Id> >> tags near the top of the files.
411  
412 Returns a string containing the xml of the last lap processed which can subsequently be passed directly to C<< Geo::TCX->new() >> to construct a new instsance.
413  
414 =back
415  
416 =cut
417  
418 sub save_laps {
419 my $o = shift;
420 my @laps_to_save;
421 if (ref ($_[0]) eq 'ARRAY') {
422 my $aref = shift;
423 for my $lap_i (@$aref) {
424 push @laps_to_save, $o->lap($lap_i)
425 }
426 } else { @laps_to_save = @{$o->{Laps}} }
427 my %opts = @_;
428  
429 my ($as_course, $fname);
430 $as_course = 1 if $o->is_course or $opts{course};
431 $fname = $o->set_filename;
432 croak 'no filename found, set_filename(<name>) before saving' unless $fname;
433  
434 # as mentioned in the pod, files will be saved in work_dir as they are new files
435 # use has expectation that that's where working files go
436 my ($name, $path, $ext) = fileparse( $fname, '\..*' );
437 my $wd = $o->set_wd();
438  
439 my ($tags_before_lap, $tags_after_lap) = $o->_prep_tags( %opts );
440  
441 # Id (for Activity) or Name (for Course) tag
442 my $tag_id_or_name = '';
443 if ($as_course) {
444 # a bit tricky to determine Name when saving as course, bear with us here
445 if (@laps_to_save == 1 ) {
446 my $name;
447 if ( defined $opts{course_name} ) { $name = $opts{course_name} }
448 else {
449 if ($o->is_course) { $name = $o->{tag_name} }
450 else { $name = 'StartTimePlaceHolder' }
451 }
452 $tag_id_or_name .= '<Name>' . $name . '</Name>'
453 } else {
454 $tag_id_or_name .= '<Name>' . 'StartTimePlaceHolder' . '</Name>';
455 # i.e. it's StartTime regardless if more than one lap
456 }
457 } else { $tag_id_or_name .= '<Id>' . 'StartTimePlaceHolder' . '</Id>' }
458  
459 # Now from what is left below, we can create a save() method to save a file with multilaps. Simply move the $tags_before_lap and $tags_after_lap outside of the loop, continue to add to the $str (i.e. it gets appended to at all times) and we put the saving block outside of the loop at the very end.
460 # Yah ! And don't distance_net
461  
462 my $str;
463 for my $i (0 .. $#laps_to_save) {
464 my $l = $laps_to_save[$i]->clone;
465 $l->distance_net;
466  
467 $str = $tags_before_lap;
468 $str .= $tag_id_or_name;
469 $str =~ s/StartTimePlaceHolder/$l->StartTime/e;
470  
471 my $xml_lap = $l->xml_string( course => $as_course, indent => $opts{indent} );
472 $str .= $xml_lap;
473 $str .= $tags_after_lap;
474  
475 unless ($opts{nosave}) {
476 my $fname_lap = $wd . $name . '-Lap-' . ($i+1) . $ext;
477 croak "$fname_lap already exists" if -f $fname_lap and !$opts{force};
478 open(my $fh, '>', $fname_lap) or die "can't open $fname_lap $!";
479 print $fh $str
480 }
481 }
482 return $str
483 }
484  
485 =over 4
486  
487 =item save( key/values )
488  
489 saves the current instance.
490  
491 I<key/values> are:
492  
493 Z<> C<filename>: the name of the file to be saved. Has the effect calling C<set_filename()> and changes the name of the file in the current instance (e.g. akin to "save as" in many applications).
494 Z<> C<force>: overwrites existing files if true, otherwise it won't.
495 Z<> C<indent>: adds white space and indents the xml mark-up in the saved file if true.
496  
497 Returns a string containing the xml representation of the file.
498  
499 =back
500  
501 =cut
502  
503 sub save {
504 my ($o, %opts) = @_;
505  
506 my $fname;
507 if ( $opts{filename} ) { $fname = $o->set_filename( $opts{filename} ) }
508 else { $fname = $o->set_filename() }
509 croak 'no filename found, provide one with set_filename() or use key \'filename\'' unless $fname;
510 croak "$fname already exists" if -f $fname and !$opts{force};
511  
512 my ($tags_before_lap, $tags_after_lap) = $o->_prep_tags( indent => $opts{indent} );
513 my $str = $tags_before_lap;
514 if ($o->is_course) { $str .= '<Name>' . $o->{tag_name} . '</Name>' }
515 else { $str .= '<Id>' . $o->{tag_id} . '</Id>' }
516  
517 my ($str_activity_laps, $str_course_laps, $str_course_tracks);
518 for my $lap ($o->laps) {
519 my $str_lap = $lap->xml_string( indent => $opts{indent} );
520  
521 if ($lap->is_course) {
522 # for courses, the xml track tags are not nested within the lap
523 # tags but follow them instead. Yah, weird. So need to collect
524 # the strings seperately then assemble after the loop
525 if ( $str_lap =~ s,\s*(<Lap>.*</Lap>)\s*(<Track>.*</Track>)\s*,,s ) {
526 $str_course_laps .= $1;
527 $str_course_tracks .= $2
528 } else { croak "cannot find lap or track tags in Laps object" }
529 } else {
530 $str_activity_laps .= $str_lap
531 }
532 }
533  
534 # Flatten the course tracks into a a single track
535 $str_course_tracks =~ s,</Track>\s*<Track>,,s;
536  
537 if ($o->is_course) { $str .= $str_course_laps . $str_course_tracks }
538 else { $str .= $str_activity_laps }
539  
540 $str .= $tags_after_lap;
541  
542 open(my $fh, '>', $fname) or die "can't open $fname $!";
543 print $fh $str;
544 return $str
545 }
546  
547 sub _prep_tags {
548 my ($o, %opts) = @_;
549  
550 # identical to save_laps()
551 my ($newline, $tab, $as_course);
552 $newline = $opts{indent} ? "\n" : '';
553 $tab = $opts{indent} ? ' ' : '';
554 $as_course = 1 if $o->is_course or $opts{course};
555  
556 #
557 # Prepare the mark-up that appears *outside* the laps (therefore will be common to all saved laps)
558  
559 # These tag collection blocks could be shortened but it might not become more legible.
560 # The many variables help for debugging as the resulting string can be an extremely
561 # long flat string
562  
563 # we first collect the tags we need, we assemble them later
564 # we need these 3 pairs of tags so declare in a block
565 my ($tag_open_trainctrdb, $tag_close_trainctrdb);
566 my ($tag_open_activity_or_course_plural, $tag_close_activity_or_course_plural );
567 my ($tag_open_activity_or_course_singular, $tag_close_activity_or_course_singular);
568  
569 if ($o->{tag_trainingcenterdatabase} =~ /(<TrainingCenterDatabase[^>]*>)/) {
570 $tag_open_trainctrdb = $1;
571 $tag_close_trainctrdb = '</TrainingCenterDatabase>'
572 } else { croak 'can\'t find the expected <TrainingCenterDatabase ...> tag' }
573  
574 # in history files (in mine at least), these tags ever appear only once, nesting all of the data within them
575 # <Activities><Activity Sport="Biking">
576 # <Courses><Course>
577 # Activity is nested within Activities and similarly Course is nested within Courses
578  
579 if ($o->{tag_activities}) {
580 if ( $o->{tag_activities} =~ /(<Activities[^>]*>)/) {
581 $tag_open_activity_or_course_plural = $1
582 } else { croak 'can\'t find the expected <Activities> tag' }
583 if ( $o->{tag_activity} =~ /(<Activity[^>]*>)/ ) {
584 $tag_open_activity_or_course_singular = $1
585 } else { croak 'can\'t find the expected <Activity Sport="..."> tag' }
586 ($tag_close_activity_or_course_singular, $tag_close_activity_or_course_plural) = ('</Activity>', '</Activities>')
587 }
588 if ($o->{tag_courses}) {
589 if ( $o->{tag_courses} =~ /(<Courses[^>]*>)/) {
590 $tag_open_activity_or_course_plural = $1
591 } else { croak 'can\'t find the expected <Courses> tag' }
592 if ( $o->{tag_course} =~ /(<Course(?!s)[^>]*>)/ ) {
593 $tag_open_activity_or_course_singular = $1
594 } else { croak 'can\'t find the expected <Course> tag' }
595 ($tag_close_activity_or_course_singular, $tag_close_activity_or_course_plural) = ('</Course>', '</Courses>')
596 }
597 if ($as_course and !$o->{tag_courses}) { # i.e. when saving an activity as a course
598 $tag_open_activity_or_course_plural = '<Courses>';
599 $tag_open_activity_or_course_singular = '<Course>';
600 ($tag_close_activity_or_course_singular, $tag_close_activity_or_course_plural) = ('</Course>', '</Courses>')
601 }
602  
603 # assembling the tags to get the mark-up that appears *before* the laps
604 my $tags_before_lap = '';
605 $tags_before_lap = $o->{tag_xml_version} . "\n";
606 $tags_before_lap .= $tag_open_trainctrdb;
607 $tags_before_lap .= $newline . $tab . $tag_open_activity_or_course_plural;
608 $tags_before_lap .= $newline . ($tab x 2) . $tag_open_activity_or_course_singular;
609 $tags_before_lap .= $newline . ($tab x 3);
610  
611 # assembling the tags to get the mark-up that appears *after* the laps
612 my ($tags_after_lap) = '';
613 $tags_after_lap = $newline . ($tab x 3) . $o->{tag_creator} if $o->{tag_creator};
614 $tags_after_lap .= $newline . ($tab x 2) . $tag_close_activity_or_course_singular;
615 $tags_after_lap .= $newline . $tab . $tag_close_activity_or_course_plural;
616 $tags_after_lap .= $newline . $tab . $o->{tag_author} if $o->{tag_author};
617 $tags_after_lap .= $newline . $tag_close_trainctrdb;
618  
619 return $tags_before_lap, $tags_after_lap
620 }
621  
622 =over 4
623  
624 =item set_filename( $filename )
625  
626 Sets/gets the filename. Returns the name of the file with the complete path.
627  
628 =back
629  
630 =cut
631  
632 sub set_filename {
633 my ($o, $fname) = (shift, shift);
634 return $o->{_fileABSOLUTENAME} unless $fname;
635 croak 'set_filename() takes only a single name as argument' if @_;
636 my $wd;
637 if ($o->_is_wd_defined) { $wd = $o->set_wd }
638 # set_filename gets called before set_wd by new() so can't access work_dir until initialized
639  
640 my ($name, $path, $ext);
641 ($name, $path, $ext) = fileparse( $fname, '\..*' );
642 if ($wd) {
643 if ( ! ($fname =~ /^\// ) ) {
644 # ie if fname is not an abolsute path, adjust $path to be relative to work_dir
645 ($name, $path, $ext) = fileparse( $wd . $fname, '\..*' )
646 }
647 }
648 $o->{_fileABSOLUTEPATH} = abs_path( $path ) . '/';
649 $o->{_fileABSOLUTENAME} = $o->{_fileABSOLUTEPATH} . $name . $ext;
650 croak 'directory ' . $o->{_fileABSOLUTEPATH} . ' doesn\'t exist' unless -d $o->{_fileABSOLUTEPATH};
651 $o->{_fileNAME} = $name;
652 $o->{_filePATH} = $path;
653 $o->{_fileEXT} = $ext;
654 $o->{_filePARSEDNAME} = $fname;
655 # _file* keys only for debugging, should not be used anywhere else
656 return $o->{_fileABSOLUTENAME}
657 }
658  
659 =over 4
660  
661 =item set_wd( $folder )
662  
663 Sets/gets the working directory and checks the validity of that path. Relative paths are supported for setting but only full paths are returned or internally stored.
664  
665 The previous working directory is also stored in memory; can call <set_wd('-')> to switch back and forth between two directories.
666  
667 Note that it does not call L<chdir>, it simply sets the path for the eventual saving of files.
668  
669 =back
670  
671 =cut
672  
673 sub set_wd {
674 my ($o, $dir) = (shift, shift);
675 croak 'set_wd() takes only a single folder as argument' if @_;
676 my $first_call = ! $o->_is_wd_defined; # ie if called for 1st time -- at construction by new()
677  
678 if (! $dir) {
679 return $o->{work_dir} unless $first_call;
680 my $fname = $o->set_filename;
681 if ($fname) {
682 my ($name, $path, $ext) = fileparse( $fname );
683 $o->set_wd( $path )
684 } else { $o->set_wd( cwd ) }
685 } else {
686 $dir =~ s/^\s+|\s+$//g; # some clean-up
687 $dir =~ s/~/$ENV{'HOME'}/ if $dir =~ /^~/;
688 $dir = $o->_set_wd_old if $dir eq '-';
689  
690 if ($dir =~ m,^[^/], ) { # convert rel path to full
691 $dir = $first_call ? cwd . '/' . $dir : $o->{work_dir} . $dir
692 }
693 $dir =~ s,/*$,/,; # some more cleaning
694 1 while ( $dir =~ s,/\./,/, ); # support '.'
695 1 while ( $dir =~ s,[^/]+/\.\./,, ); # and '..'
696 croak "$dir not a valid directory" unless -d $dir;
697  
698 if ($first_call) { $o->_set_wd_old( $dir ) }
699 else { $o->_set_wd_old( $o->{work_dir} ) }
700 $o->{work_dir} = $dir
701 }
702 return $o->{work_dir}
703 }
704  
705 # if ($o->set_filename) { $o->set_wd() } # if we have a filename
706 # else { $o->set_wd( cwd ) } # if we don't
707  
708 sub _set_wd_old {
709 my ($o, $dir) = @_;
710 $o->{work_dir_old} = $dir if $dir;
711 return $o->{work_dir_old}
712 }
713  
714 sub _is_wd_defined { return defined shift->{work_dir} }
715  
716 =over 4
717  
718 =item is_activity()
719  
720 =item is_course()
721  
722 True if the C<Geo::TCX> instance is a of the type indicated by the method, false otherwise.
723  
724 =back
725  
726 =cut
727  
728 sub is_activity { return defined shift->{tag_activity} }
729 sub is_course { return defined shift->{tag_course} }
730  
731 =over 4
732  
733 =item activity( $string )
734  
735 Gets/sets the Activity type as detected from C<\<Activity Sport="*"\>>, sets it to I<$string> if provided. Garmin devices (at least the Edge) record activities as being of types 'Running', 'Biking', 'MultiSport', etc.
736  
737 =back
738  
739 =cut
740  
741 sub activity {
742 my ($o, $activity) = @_;
743 # should I check what activity types are allowed? Must they be single words?
744 if ($activity) {
745 $o->{tag_activity} =~ s,(\<Activity Sport=)"[^"]*",$1"$activity",;
746 return $o->activity
747 }
748 $activity = $1 if $o->{tag_activity} =~ /<Activity Sport="([^"]*)"/;
749 return $activity
750 }
751  
752 =over 4
753  
754 =item author( key/value )
755  
756 Gets/sets the fields of the Author tag. Supported keys are C<Name>, C<LangID>, C<PartNumber> and all excpect a string as value.
757  
758 The C<Build> field can also be accesses but the intent is to set it, the string supplied should be in the form of an xml string in the way this tag appears in a *.tcx file (e.g. Version, VersionMajor, VersionMinor, Type, …). Simply access that key of the returned hash ref to see what is should look like.
759  
760 Returns a hash reference of key/value pairs.
761  
762 This method is under development and behaviour could change in the future.
763  
764 =back
765  
766 =cut
767  
768 # the only purpose I have for this at this stage is to set the name mostly, we'll see if I have a need for other, but will take the Build key as is and not set up sub-keys yet.
769 # I mostly want to use this method so that I can set it if I want for any *.tcx I generate (Courses, save laps), with the version number of my module as well
770 # the Build entries contain integers but I am not supporting this at this point
771 #
772 # <Author xsi:type="Application_t"
773 # <Name>string</Name>
774 # <Build containis
775 # <Version>
776 # VersionMajor
777 # VersionMinor
778 # BuildMajor
779 # BuildMinor
780 # </Version>
781 # <Type>Release<Type>
782 # </Build>
783 # <LangID>EN</LangID>
784 # <PartNumber>digit and dash string</PartNumber>
785 # </Author>
786  
787 my %possible_author_keys;
788 my @author_keys = qw/ Name Build LangID PartNumber /;
789 $possible_author_keys{$_} = 1 for @author_keys;
790  
791 # NB: similar to the _file* keys, the _Author href can not exist at any time
792 sub _parse_author_tag {
793 my $o = shift;
794 $o->{_Author} = {};
795 my $href = $o->{_Author};
796 my $author_xml;
797 if ( $o->{tag_author} =~ m,<Author\s+([^=]+="[^"]+")>(.*)<\/Author>, ) {
798 $href->{string_inside_author_tag} = $1;
799 $author_xml = $2
800 }
801 for my $key (@author_keys) {
802 $href->{$key} = $1 if $author_xml =~ m,<$key>(.+)</$key>,
803 }
804 return $o->{tag_author}
805 }
806  
807 sub _update_author_tag {
808 my $o = shift;
809 my $href = $o->{_Author};
810  
811 my $str = '<Author ' . $href->{string_inside_author_tag} . '>';
812 for my $key (@author_keys) {
813 $str .= "<$key>" . $href->{$key} . "</$key>" if defined $href->{key}
814 }
815 $str .= '</Author>';
816 $o->{tag_author} = $str;
817 return $o->{tag_author}
818 }
819  
820 sub author {
821 my ($o, %keys_values) = @_;
822 my $href = $o->{_Author};
823 croak 'no author tag found in object' if (!%keys_values and ! $href);
824 if (%keys_values) {
825 for my $key (keys %keys_values) {
826 croak 'unsupported Author field' unless $possible_author_keys{$key};
827 $href->{$key} = $keys_values{$key}
828 }
829 $o->_update_author_tag
830 }
831 return $href
832 }
833  
834 # returns the actual lap number if a negative index is passed to count from the end
835 sub _lap_number {
836 my ($o, $lap_i, $n, %exists) = (shift, shift);
837 $n = $o->laps;
838 $lap_i += $n + 1 if $lap_i < 0;
839 $exists{$_} = 1 for (1 .. $n);
840 croak "Lap $lap_i does not exist" unless $exists{$lap_i};
841 return $lap_i
842 }
843  
844 =head1 EXAMPLES
845  
846 Coming soon.
847  
848 =head1 BUGS
849  
850 Nothing to report yet.
851  
852 =head1 AUTHOR
853  
854 Patrick Joly
855  
856 =head1 VERSION
857  
858 1.00
859  
860 =head1 LICENCE AND COPYRIGHT
861  
862 Copyright (c) 2022, Patrick Joly C<< <patjol@cpan.org> >>. All rights reserved.
863  
864 This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L<perlartistic>.
865  
866 =head1 SEE ALSO
867  
868 L<Geo::Gpx>
869  
870 =head1 DISCLAIMER OF WARRANTY
871  
872 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
873 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
874 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
875 PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
876 EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
877 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
878 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
879 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
880 NECESSARY SERVICING, REPAIR, OR CORRECTION.
881  
882 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
883 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
884 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
885 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
886 INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
887 INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF
888 DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR
889 THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER
890 SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
891 POSSIBILITY OF SUCH DAMAGES.
892  
893 =cut
894  
895 1;
« Build ↑ Summary blib/lib/Geo/TCX/Track.pm »