blib/lib/Geo/TCX/Interactive.pm untested

filter: Statementstmt 0.0% 0 / 252 Branchbran 0.0% 0 / 100 Conditioncond 0.0% 0 / 19 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 410 CC 51 SCAR 40.2
CC
51
Cov
0%
way_add_device
182.0
way_add_endpoints
90.0
way_clip
42.0
CRAP 55.9
1 package Geo::TCX::Interactive;
2 use strict;
3 use warnings;
4  
5 our $VERSION = '1.04';
6 our @ISA=qw(Geo::TCX);
7  
8 =encoding utf-8
9  
10 =head1 NAME
11  
12 Geo::TCX::Interactive - Sub-class of Geo::TCX to be used interactively in the debugger
13  
14 =head1 SYNOPSIS
15  
16 perl -d -MGeo::TCX::Interactive -e '$o= Geo::TCX::Interactive->new("~/Data/Src/Garmin/History"); 1'
17  
18 or
19 perl -d -MGeo::TCX::Interactive -e 0
20 $o = Geo::TCX::Interactive->new('~/Data/Src/Garmin/History', work_dir => '~/Data/Garmin/');
21  
22 or in a script as
23  
24 use Geo::TCX::Interactive;
25 use Geo::Gpx;
26 $o= Geo::TCX::Interactive->new( $sr_dir, recent => $recent, work_dir => $wk_dir );
27  
28 =head1 DESCRIPTION
29  
30 A sub-class of L<Geo::TCX>, this module provides methods to manage TCX files interactively in the debugger, e.g. with prompts to select which recent file to edit, modify, and save.
31  
32 C<Geo::TCX::Interactive> also enables the interactive management and editing of waypoints using L<Geo::Gpx>, that is, by loading/saving *.gpx files, retrieving waypoints from devices, and comparing these points with L<Geo::TCX> Activity and Course files.
33  
34 There are no return values for a few methods that prompt the user for a response before performing certain actions. This may change in the future if sensible return values can be identified. All values actually returned are documented below.
35  
36 =cut
37  
38 use Geo::TCX;
39 use File::Basename;
40 use File::Temp qw/ tempfile /;
41 use IPC::System::Simple qw(system);
42 use Carp qw(confess croak cluck);
43 use Cwd;
44  
45 =head2 Constructor Methods
46  
47 =over 4
48  
49 =item new( $foldername, key/values )
50  
51 Expects a folder as main argument instead of a file name. The user is then prompted to select a file from a list of the most recent ones modified in that folder before returning an instance of the class. Many convenience methods can then be used interactively, particularly if used in the perl debugger.
52  
53 I<key/values> (all are optional)
54  
55 Z<> C<< recent => # >> : specifies how many recent files to display, the default being 25.
56 Z<> C<< work_dir => $folder >>: specifies where to save any working files, such as with the save_laps() method.
57  
58 =back
59  
60 =cut
61  
62 sub new {
63 my ($proto, $dir) = (shift, shift);
64 if ($dir) {
65 $dir =~ s/~/$ENV{'HOME'}/ if $dir =~ /^~/;
66 $dir =~ s,/*$,/,
67 }
68 croak 'first argument must be a folder' unless $dir and -d $dir;
69 my %opts = @_;
70 my $recent_n = $opts{recent} || 25;
71 my $class = ref($proto) || $proto;
72  
73 my $fname;
74 $fname = _select_file_from_dir( $dir, '.tcx', $recent_n );
75 my $o = $class->SUPER::new( $fname, work_dir => $opts{work_dir} );
76 return $o
77 }
78  
79 =head2 Object Methods
80  
81 =cut
82  
83 =over 4
84  
85 =item prompt_and_set_wd( $folder )
86  
87 Prompts for a choice between existing folders in the current working directory and calls C<set_wd> to set it as the working directory. Returns the path to that working directory.
88  
89 =back
90  
91 =cut
92  
93 sub prompt_and_set_wd {
94 my $o = shift;
95 croak 'set_wd() expects no arguments' if @_;
96 my $wd = $o->set_wd;
97 my ($i, @folders) = (0);
98 opendir my($dirhandle), $wd;
99 for( readdir $dirhandle ) {
100 if (-d $wd . "$_" ) {
101 next if (m/^[.]/);
102 print "(" . ++$i . ") " . $_ . "\n";
103 push @folders, $_
104 }
105 }
106 croak "There are no folders to choose from in the current working directory" unless( @folders );
107 print "please select which folder to use (#): ";
108 my $folder = <STDIN>;
109 $folder = $folders[$folder-1];
110 return $o->set_wd( $wd . $folder )
111 }
112  
113 =over 4
114  
115 =item save_laps( %options )
116  
117 is identical to C<< save_laps() >> in L<Geo::TCX> but will prompt the user to confirm the intention to save the laps before continuing. It expects the same I<%options> and returns the same value, except that it returns false if the user does not answer yes at the prompt.
118  
119 =back
120  
121 =cut
122  
123 sub save_laps {
124 my $o = shift;
125 print "Do you want to save the laps as individual files: ";
126 my $answer = _prompt_yes_no();
127 if ($answer =~ m/^y|ye|yes$/i) {
128 my $ret_val = $o->SUPER::save_laps(@_);
129 return $ret_val
130 }
131 return 0
132 }
133  
134 =over 4
135  
136 =item gpx_load( $file )
137  
138 Loads a Gpx file into the TCX object. If a directory is specified instead of a file, prompts for a choice among the gpx files found in that directory.
139  
140 Return a reference to the C<Geo::Gpx> object loaded.
141  
142 =back
143  
144 =cut
145  
146 sub gpx_load {
147 my ($o, $file_or_dir) = (shift, shift);
148 $file_or_dir =~ s/~/$ENV{'HOME'}/ if $file_or_dir =~ /^~/;
149 my $fname;
150 if (-d $file_or_dir ) {
151 my $dir = $file_or_dir;
152 $dir =~ s,/*$,/,;
153 $fname = _select_file_from_dir( $dir, '.gpx' )
154 } elsif (-f $file_or_dir ) {
155 $fname = $file_or_dir;
156 my ($name,$path,$ext) = fileparse($fname,'\..*');
157 croak 'Gpx file must have a *.gpx extension' unless $ext eq '.gpx'
158 } else { croak 'first argument must be a filename or directory' };
159 return $o->{gpx} = Geo::Gpx->new( input => $fname );
160 }
161  
162 =over 4
163  
164 =item way_add_endpoints( tolerance_meters => # )
165  
166 Compare the end points of each lap with all waypoints read in the L<Geo::Gpx> instance (by C<< gpx_load() >> and, if the distance is less than C<tolerance_meters>, prompts whether the waypoint should be added to it.
167  
168 In the affirmative, prompts what name and description should be given to the new waypoint. Set C<tolerance_meters> to 0 to compare all start/end points of laps with waypoints, or to another desired value.
169  
170 The default C<tolerance_meters> is 10. Returns true.
171  
172 =back
173  
174 =cut
175  
176 sub way_add_endpoints {
177 my ($o, %opts) = @_;
178 $opts{tolerance_meters} = 10 unless defined $opts{tolerance_meters}; # could be zero
179 my $gpx = $o->gpx;
180  
181 for my $i (1 .. $o->laps) {
182 my $pass = 0;
183 while ($pass++ < 2 ) {
184 my ($order, $index);
185 $order = ($pass == 1) ? 'first' : 'last';
186 $index = ($pass == 1) ? 1 : -1;
187 my $end_pt = $o->lap($i)->trackpoint( $index );
188 my $has_latitude = $end_pt->LatitudeDegrees;
189  
190  
191 my ($closest_wpt, $distance);
192 ($closest_wpt, $distance) = $gpx->waypoint_closest_to( $end_pt ) if $has_latitude;
193 if ($distance > $opts{tolerance_meters} ) {
194 print "\n$order point of lap $i is ", sprintf('%.1f', $distance), " meters from Waypoint \'";
195 print $closest_wpt->name, "\'\n --> do you want to add that point ? ";
196  
197 print "$order point of lap $i info:\n";
198 $end_pt->summ;
199 print $end_pt->LatitudeDegrees . " " . $end_pt->LongitudeDegrees;
200 print "\n\n";
201  
202 print $closest_wpt->name, " info:\n";
203 $closest_wpt->summ;
204 print $closest_wpt->lat . " " . $closest_wpt->lon;
205 print "\n\n";
206  
207 my $answer = _prompt_yes_no();
208 if ( $answer eq 'y' ) {
209 my $gpx_pt = $end_pt->to_gpx();
210 my ($name, $desc, $cmt) = _prompt_for_waypoint_fields(qw/ name desc cmt /);
211 $gpx_pt->desc( $desc ) if $desc;
212 $gpx_pt->cmt( $cmt ) if $cmt;
213 while ( ! $name ) {
214 print "Waypoint name is required\n";
215 $name = _prompt_for_waypoint_fields('name');
216 }
217 $gpx_pt->name( $name );
218  
219 $gpx->waypoints_add($gpx_pt)
220 } else { next }
221 }
222 }
223 }
224 return 1
225 }
226  
227 =over 4
228  
229 =item way_add_device( $directory_on_device )
230  
231 Prompts the user whether they wish to look for waypoints saved on a GPS device and compare them to the waypoints read in the C<Geo::TCX> instance by C<< gpx_load() >>. The device must be currently plugged in with a USB cable.
232  
233 In the affirmative, compares each waypoint from the device to those in the instance and, if the distance is greater than 1 meter, prompts whether the waypoint should be added to the waypoints in the object.
234  
235 If no directory is provided, tries to guess where that directory might be (provided the device is plugged in). Returns false if the directory or waypoints file cannot be found (does not die) or if the user responds no at the initial prompt. Otherwise returns true.
236  
237 =back
238  
239 =cut
240  
241 sub way_add_device {
242 my ($o, $loc_dir) = (shift, shift);
243 print "Do you want to search for waypoints saved on your device and add any new ones to the gpx file?\n";
244 print " - first ensure the device is plugged in with a USB cable\n";
245 print " - note that you will be prompted before adding any new waypoints\n - ";
246 my $answer = _prompt_yes_no();
247 return 0 unless $answer =~ m/^y|ye|yes$/i;
248  
249 if ($loc_dir) {
250 croak "$loc_dir cannot be found" unless -d $loc_dir
251 } else {
252 my @try_these = (
253 "/media/$ENV{USER}/GARMIN/Garmin/Locations/",
254 "/media/$ENV{USER}/GARMIN/Garmin/GPX/current/"
255 );
256 for (@try_these) {
257 $loc_dir = $_ if -d $_;
258 last if $loc_dir
259 }
260 }
261 unless (defined $loc_dir) {
262 print "No Locations/Waypoints folder found on the device\n";
263 print " - is the device plugged in?\n";
264 print " - skipping adding waypoints from the device for now\n";
265 print " - the location of the directory on the device can also be specified with --loc_dir=<path>\n";
266 return 0
267 }
268  
269 my $fname;
270 $fname = ($loc_dir =~ /Locations/) ? $loc_dir . '/Locations.fit' : $loc_dir . '/current.gpx';
271 unless (-f $fname) {
272 print "No Locations/Waypoints file found on the device\n";
273 print " - is the device plugged in?\n";
274 print " - skipping adding waypoints from the device for now\n";
275 return 0
276 }
277 if ($loc_dir =~ /Locations/) {
278 my ($fh, $tmp_fname) = tempfile();
279 _convert_locations_to_gpx( $fname, $tmp_fname );
280 $fname = $tmp_fname
281 }
282  
283 my $gpx = $o->gpx;
284  
285 my $device = Geo::Gpx->new( input => $fname );
286  
287 my $iter = $device->iterate_waypoints();
288 while ( my $pt = $iter->() ) {
289 my ($closest_wpt, $distance) = $gpx->waypoint_closest_to( $pt );
290 if ($distance > 1 ) {
291 print "Point '", $pt->name, "' from the device is ";
292 print sprintf('%.1f', $distance), " meters from Waypoint \'", $closest_wpt->name;
293 print "\'\n --> do you want to add that point? ";
294 print "If so please type 'Y' (or type a new name to rename it), ";
295 print "otherwise just press 'N' or return:\n";
296 my $answer = <STDIN>;
297 chomp $answer;
298 $answer =~ s,^ *,,;
299 $answer =~ s, *$,,;
300 if ($answer =~ m/^y|ye|yes$/i) {
301 $gpx->waypoints_add( $pt )
302 } elsif ($answer =~ m/^n|no*$/i) {
303 next
304 } else {
305 $pt->name( $answer );
306 $gpx->waypoints_add( $pt )
307 }
308 }
309 }
310 return 1
311 }
312  
313 =over 4
314  
315 =item gpx_save( )
316  
317 Save the gpx file. The same options as C<Geo::Gpx->save()> are expected but will prompt the user whether to overwrite an existing file if C<$force> is false.
318  
319 Returns true if the file was saved, false otherwise.
320  
321 =back
322  
323 =cut
324  
325 sub gpx_save {
326 my ($o, %opts) = @_;
327 if (-f $o->gpx->set_filename and ! $opts{force} ) {
328 print "Overwrite " . $o->gpx->set_filename . ": ";
329 my $answer = _prompt_yes_no();
330 if ($answer =~ m/^y|ye|yes$/i) {
331 $opts{force} = 1
332 } else { return 0 }
333 }
334 $o->gpx->save( %opts );
335 return 1
336 }
337  
338 =over 4
339  
340 =item gpx( )
341  
342 Returns the L<Geo::Gpx> instance currently referenced in the object. Croaks if none is found.
343  
344 =back
345  
346 =cut
347  
348 sub gpx {
349 my $o = shift;
350 my $class = ref $o;
351 croak "no waypoint file loaded in $class object" unless defined $o->{gpx};
352 return $o->{gpx}
353 }
354  
355 =over 4
356  
357 =item way_clip( $name | $regex | LIST )
358  
359 Sends the coordinates of waypoints whose name is either C<$name> or matches C<$regex> to the clipboard (all points found are sent to the clipboard). Returns an array of points found.
360  
361 By default, the regex is case-sensitive; specify C<qr/(?i:...)/> to ignore case.
362  
363 Alternatively, an array of C<Geo::GXP::Points> can be supplied such that we can call C<< $o->way_clip( $o->gpx->search_desc( qr/(?i:Sunset)/ ) >>.
364  
365 This method is only supported on unix-based systems that have the C<xclip> utility installed (see BUGS AND LIMITATIONS).
366  
367 =back
368  
369 =cut
370  
371 sub way_clip {
372 my $gpx = shift->gpx;
373  
374 my @points;
375 if ( ref $_[0] and $_[0]->isa('Geo::Gpx::Point' )) {
376 @points = @_
377 } else {
378 my $first_arg = shift;
379 if ( ref( $first_arg ) eq 'Regexp' ) {
380 @points = $gpx->waypoints_search( name => $first_arg )
381 } else {
382 my $match = $gpx->waypoints( name => $first_arg );
383 push @points, $match if $match
384 }
385 croak 'no point matches the supplied regex' unless @points
386 }
387 my @points_reversed = reverse @points;
388  
389 for my $pt (@points_reversed) {
390 croak 'way_clip() expects list of Geo::Gpx::Point objects' unless $pt->isa('Geo::Gpx::Point');
391 my $coords = $pt->lat . ', ';
392 $coords .= $pt->lon;
393 system("echo $coords | xclip -selection clipboard")
394 }
395 return @points
396 }
397  
398 =over 4
399  
400 =item way_device_send()
401  
402 Send the waypoints to a GPS device, overwriting any existing file. The device must be plugged in.
403  
404 Some devices have a limit of a 100 waypoints, it will keep the first 100 in the order that they appear in the file. Returns true.
405  
406 =back
407  
408 =cut
409  
410 sub way_device_send {
411 my $clone = shift->gpx->clone;
412 croak "device_dir not defined" unless $clone->{device_dir};
413 # TODO: use proper method once they have been created
414 $clone->{tracks} = [];
415 $clone->{routes} = [];
416 $clone->set_wd( $clone->{device_dir} );
417 $clone->save( filename => 'Temp.GPX', force => 1 );
418 return 1
419 }
420  
421 =over 4
422  
423 =item lap_summary( # )
424  
425 prints summary data for a given lap number. Returns true.
426  
427 =back
428  
429 =cut
430  
431 sub lap_summary {
432 my ($o, $lap_i) = @_;
433 my $lap = $o->{Laps}[$lap_i-1];
434 print "----> Lap ", $lap_i, " <----:\n\n";
435 for my $key (sort keys %$lap) {
436 next if $key eq 'Track';
437 next if $key eq 'Temp'; # delete this one too
438 print $key, ":", $lap->{$key}, "\n"
439 }
440 print "\n";
441 return 1
442 }
443  
444 our $FitConvertPl;
445 sub _convert_locations_to_gpx {
446 require Geo::FIT;
447 my ( $fname, $tmp_fname ) = @_;
448 if (!defined $FitConvertPl) {
449 for (split /:/, $ENV{PATH} ) {
450 $FitConvertPl = $_ . '/locations2gpx.pl';
451 last if -f $FitConvertPl
452 }
453 }
454 my @args = ('--outfile=' . $tmp_fname, '--force', $fname);
455 system($^X, $FitConvertPl, @args);
456 return 1
457 }
458  
459 sub _select_file_from_dir {
460 my ($dir, $ext, $recent) = @_;
461  
462 my $dh;
463 # prompt user to select a file from recent *.tcx files showed
464 opendir($dh, $dir || die "can't opendir $dir $!");
465 my @files = grep { /.*$ext$/i } readdir $dh;
466 closedir $dh;
467 my @sorted_files = sort { -M ($dir . $a) <=> -M ($dir . $b) } @files;
468  
469 my $i = 0;
470 $recent ||= @sorted_files; # kludge as I now (v 1.5) made $recent non-mandatory
471 print $sorted_files[$i++], "\t ($i)\n" while ( $i < $recent );
472 print "please select which file to use (#): ";
473 my $fileno = <STDIN>;
474 return $dir . $sorted_files[$fileno-1]
475 }
476  
477 sub _prompt_for_waypoint_fields {
478 my @values;
479 print "Please specify waypoint fields...\n";
480 for (@_) {
481 print $_ . ": ";
482 my $input = <STDIN>;
483 chomp $input;
484 push @values, $input
485 }
486 return @values if wantarray;
487 return $values[0]
488 }
489  
490 # internal function, so no integrity check
491 sub _prompt_yes_no {
492 my %opts = @_;
493 my $default = $opts{default};
494 my $prompt_str = ($default) ? "Y/N [". $default . "]?" : "Y/N? ";
495 my $answer;
496 while( 1 ) {
497 print $prompt_str;
498 my $answer = <STDIN>;
499 return 'y' if ($answer =~ m/^ *(y|ye|yes) *$/i);
500 return 'n' if ($answer =~ m/^ *(n|no) *$/i);
501 return $default if ($answer eq '');
502 print "\n"
503 }
504 }
505  
506 =head1 EXAMPLES
507  
508 Coming soon.
509  
510 =head1 DEPENDENCIES
511  
512 L<Geo::FIT> is also required to parse FIT files and to add waypoints from a GPS device (except for some older models).
513  
514 The C<< way_clip() >> method is only supported on unix-based systems that have the C<xclip> utility installed. On Debian based system, you may install it as
515  
516 aptitude show xlip
517 sudo apt install xclip
518  
519 See your package manager's instructions for information on how to install it on other systems.
520  
521 =head1 SEE ALSO
522  
523 L<Geo::TCX>, L<Geo::Gpx>, L<Geo::FIT>, xclip(1).
524  
525 =head1 BUGS
526  
527 No bugs have been reported yet.
528  
529 =head1 AUTHOR
530  
531 Patrick Joly
532  
533 =head1 VERSION
534  
535 1.04
536  
537 =cut
538  
539 1;