blib/lib/Bio/Graphics/Browser2/TrackDumper.pm untested

filter: Statementstmt 0.0% 0 / 545 Branchbran 0.0% 0 / 238 Conditioncond 0.0% 0 / 146 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 59 Podpod 0.0% 0 / 50 totaltotal 0.0% 0 / 1038 CC 120 SCAR 43.2
CC
120
Cov
0%
guess_dump_method
306.0
_dump_gff3
182.0
dump_sam
182.0
CRAP 75.0
1 package Bio::Graphics::Browser2::TrackDumper;
2  
3 ###################################################################
4 #
5 # This package holds the majority of code from the gbgff script.
6 # It is used to output GFF3 to allow for track sharing.
7 #
8 ###################################################################
9  
10 # $Id$
11  
12 # Simple track dumper, suitable for a lightweight replacement to DAS.
13 # Call this way:
14 # http://my.host/cgi-bin/gb2/gbrowse/volvox?gbgff=1;q=ctgA:1..2000;l=Genes%5EExampleFeatures
15 #
16 # From within the "Add Remote Annotations" section, you can say:
17 # http://my.host/cgi-bin/gb2/gbrowse/volvox?gbgff=1;q=$segment;l=Genes%5EExampleFeatures
18 #
19 # Note that the track name delimiter has changed to %5E, and the option is "l".
20 # The old method of separating with + signs had to abandoned because of spaces in the
21 # track label names.
22 #
23 # To share uploads, do this:
24 # http://my.host/cgi-bin/gb2/gbrowse/volvox?gbgff=1;q=ctgA:1..2000;\
25 # l=Genes%5EExampleFeatures%5Efile:my_upload.txt;id=session_id
26  
27 use strict;
28  
29 use CGI 'param', 'path_info', 'header';
30 use Bio::Graphics::Browser2;
31 use Bio::Graphics::FeatureFile;
32 use Bio::Graphics::Browser2::RegionSearch;
33 use Bio::Graphics::Browser2::Shellwords;
34 use Bio::Graphics::Browser2::Util 'modperl_request';
35 use Bio::Graphics::Browser2::TrackDumper::RichSeqMaker;
36 use Bio::SeqIO;
37  
38 sub new {
39 my $class = shift;
40 my %options = @_;
41 my $self = bless {
42 data_source => $options{-data_source},
43 stylesheet => $options{-stylesheet},
44 'dump' => $options{'-dump'}, # in quotes because "dump" is a perl keyword
45 labels => $options{-labels},
46 mimetype => $options{-mimetype},
47 format => $options{-format},
48 requested_segment => $options{-segment},
49 },
50 ref $class || $class;
51  
52 $self->check_source() or return;
53 $self->get_segment($options{-segment}) or return
54 if $options{-segment};
55  
56 return $self;
57 }
58  
59 sub forced_format { shift->{format} }
60  
61 sub add_prefix {
62 my $self = shift;
63 return $self->{'.prefix'} if exists $self->{'.prefix'};
64 my $datasource = $self->data_source;
65 return $self->{'.prefix'} = $datasource->seqid_prefix;
66 }
67  
68 sub print_stylesheet {
69 my $self = shift;
70 my ($segment,$labels) = @_;
71  
72 $segment||= $self->get_segment;
73 $labels ||= $self->get_labels;
74 my $types = $labels ? $self->labels_to_types($labels,eval{$segment->length}) : undef;
75 my $files = $labels ? $self->labels_to_files($labels,eval{$segment->length}) : undef;
76  
77 $self->print_configuration( $self->data_source(), $labels );
78 $self->print_configuration( $_, [ $_->labels ] ) for @$files;
79 }
80  
81 sub dump_track {
82 my $self = shift;
83 my ($label,$segment) = @_;
84  
85 my $source = $self->data_source;
86 my $key = $source->setting($label=>'key');
87 my $db = $source->open_database($label);
88 my @types = shellwords($source->setting($label=>'feature'));
89  
90 my $dump_method = $self->guess_dump_method($db,$label);
91 local $SIG{PIPE} = sub {die 'aborted track dump due to sigPIPE'};
92 $self->$dump_method($db,$segment,\@types,$label);
93 }
94  
95 sub dump_gff3_autowig {
96 shift->_dump_gff3(@_,1);
97 }
98  
99 sub dump_gff3 {
100 shift->_dump_gff3(@_);
101 }
102  
103 sub dump_vista_peaks {
104 shift->_dump_gff3(@_,1,1); # magic number==1 means print peaks only
105 }
106  
107 sub dump_vista_wiggle {
108 shift->_dump_gff3(@_,1,2); # magic number==2 means print signal data only
109 }
110  
111 sub dump_vista {
112 shift->_dump_gff3(@_,1,3); # magic number==3 means print peaks + signal data
113 }
114  
115 sub dump_fasta {
116 my $self = shift;
117 my ($db,$segment,$types,$label) = @_;
118 my $out = new Bio::SeqIO(-format=>'fasta',-fh=>\*STDOUT);
119 for my $seg ($self->get_segs($db,$segment)) {
120 my $seq = $seg->seq;
121 $out->write_seq($seq);
122 }
123 }
124  
125 sub dump_genbank {
126 my $self = shift;
127 my ($db,$segment,$types,$label) = @_;
128 my $out = new Bio::SeqIO(-format=>'genbank',-fh=>\*STDOUT);
129 for my $seg ($self->get_segs($db,$segment)) {
130 my $seq = $self->get_rich_seq($db,$seg,$types);
131 $out->write_seq($seq);
132 }
133 }
134  
135 sub get_segs {
136 my $self = shift;
137 my ($db,$segment) = @_;
138 return $segment if $segment;
139 my @segs = eval {
140 map {$db->segment($_)} $db->seq_ids;
141 };
142 return @segs if @segs;
143 my $default = $self->data_source->open_database(); # try default
144 return eval {
145 map {$default->segment($_)} $default->seq_ids;
146 };
147 }
148  
149 sub get_rich_seq {
150 my $self = shift;
151 my ($db,$segment,$types) = @_;
152 my @args = $segment ? (-seq_id=> $segment->seq_id,
153 -start => $segment->start,
154 -end => $segment->end)
155 : ();
156  
157 my $iterator = $db->get_seq_stream(@args,-type=>$types);
158 return Bio::Graphics::Browser2::TrackDumper::RichSeqMaker->stream_to_rich_seq($segment,$iterator);
159 }
160  
161 sub _dump_gff3 {
162 my $self = shift;
163 my ($db,$segment,$types,$label,$autowig,$vista) = @_;
164  
165 my @args = $segment ? (-seq_id=> $segment->seq_id,
166 -start => $segment->start,
167 -end => $segment->end)
168 : ();
169  
170 my $iterator = $db->get_seq_stream(@args,-type=>$types);
171  
172 # The logic here is as follows:
173 # 1) if the features contain the 'wigfile' attribute, then we
174 # defer printing to the end and produce a facsimile of
175 # a UCSC wigfile upload (using bedgraph format).
176 # 2) otherwise we print out a valid gff3 file
177 my ($gff3_header,$bed_header,%peaks,%wigs,%bigwigs);
178 while (my $f = $iterator->next_seq) {
179 if (($autowig || $vista) && (my ($wig) = $f->get_tag_values('wigfile'))) {
180 my ($start,$end) = ($f->start,$f->end);
181 $start = $segment->start if $segment && $start < $segment->start;
182 $end = $segment->end if $segment && $end > $segment->end;
183 if (my $base = $self->data_source->setting($label=>'basedir')) {
184 $wig = File::Spec->rel2abs($wig,$base);
185 }
186 my $w = $wig =~ /\.bw$/ ? \%bigwigs : \%wigs;
187 my $trackname = $f->display_name || $f->type;
188 $trackname .= " (Signal)" if $vista;
189 $w->{$trackname}{$f->seq_id}{$wig} = [$start,$end];
190 } else {
191 $self->print_gff3_header($segment) unless $gff3_header++;
192 $self->print_feature($f);
193 }
194 if ($vista && (my ($peaks) = $f->get_tag_values('peak_type'))) {
195 $peaks{$f->display_name || $f->type}{$peaks} = [$segment->seq_id,$segment->start,$segment->end];
196 }
197 }
198  
199 $vista ||= 3;
200 $self->print_peaks($db,\%peaks,$label) if %peaks && $vista==1 or $vista == 3;
201 $self->print_bio_graphics_wigs(\%wigs,$label) if %wigs && $vista==2 or $vista == 3;
202 $self->print_bigwigs(\%bigwigs,$label) if %bigwigs && $vista==2 or $vista == 3;
203 }
204  
205 sub dump_sam {
206 my $self = shift;
207 my ($db,$segment,$types,$label) = @_;
208  
209 my @args = $segment ? (-seq_id => $segment->seq_id,
210 -start => $segment->start,
211 -end => $segment->end)
212 : ();
213  
214 my $key = $self->data_source->setting($label=>'key');
215 $key ||= $label;
216  
217 my $header = $db->header;
218  
219 my $prefix = $self->add_prefix;
220  
221 print $header->text;
222 print "\@CO\t$key\n";
223 print "\@CO\tGenerated by GBrowse from ",$self->origin($label),"\n";
224 if ($segment) {
225 my $seq_id = $segment->seq_id;
226 $seq_id = "$prefix$seq_id" if $prefix;
227 print "\@CO\tSequence-region ",$seq_id,':',$segment->start,'..',$segment->end,"\n" if $segment;
228 }
229  
230 # there are problems with the filehandle-based conversion of
231 # BAM to TAM because the low-level functions write to STDOUT directly
232 # which are munged in modperl and fastcgi environments.
233  
234 # in the case of modperl, we revert to doing the conversion at the perl level
235 # which may be slower
236 if (modperl_request()) {
237 if (Bio::DB::Bam::AlignWrapper->can('tam_line')) {
238 my $iterator = $db->features(@args,-iterator=>1);
239 while ($_ = $iterator->next_seq) {
240 my $tam_line = $_->tam_line;
241 $tam_line =~ s/^([^\t]+)\t([^\t}+)\t([^\t+])/$1\t$2\t$prefix$3/ if $prefix;
242 print $tam_line,"\n";
243 }
244 } else {
245 print "## Bio::DB::SamTools 1.19 or higher required for printing SAM data when running under mod_perl\n";
246 }
247 return;
248 }
249  
250  
251 # With FastCGI, we can handle this by piping the result to ourselves.
252 if (Bio::Graphics::Browser2::Render->fcgi_request()) {
253 eval "use IO::Pipe" unless IO::Pipe->can('new');
254 my $pipe = IO::Pipe->new;
255 my $child = Bio::Graphics::Browser2::Render->fork();
256 if ($child) {
257 $pipe->reader();
258 while (<$pipe>) {
259 s/^([^\t]+)\t([^\t]+)\t([^\t]+)/$1\t$2\t$prefix$3/ if $prefix;
260 print $_;
261 }
262 } else {
263 $pipe->writer();
264 my $fh = $db->features(@args,-fh => 1);
265 while (<$fh>) {
266 print $pipe $_ ;
267 }
268 exit 0;
269 }
270 return;
271 }
272  
273 # CGI scripts simply do it directly.
274 my $fh = $db->features(@args,-fh => 1);
275 while (<$fh>) {
276 s/^([^\t]+)\t([^\t]+)\t([^\t]+)/$1\t$2\t$prefix$3/ if $prefix;
277 print $_;
278 }
279 }
280  
281 sub dump_bigwig {
282 my $self = shift;
283 my ($db,$segment,$types,$label) = @_;
284 my @types = shellwords($self->data_source->setting($label=>'feature'));
285 my $key = $self->data_source->setting($label=>'key');
286 $key ||= $label;
287  
288 my @location_args = $segment ? (-seq_id => $segment->seq_id,
289 -start => $segment->start,
290 -end => $segment->end)
291 : ();
292  
293 my @type_args = @types ? (-type => \@types)
294 : ();
295  
296 my $iterator = $db->get_seq_stream(@location_args,@type_args);
297  
298 my $origin = $self->origin($label);
299  
300 my $last_type = '';
301 my $last_name = '';
302  
303 while (my $f = $iterator->next_seq) {
304 my $type = $f->type;
305 my $name = $f->display_name;
306  
307 if ($type ne $last_type or $name ne $last_name) {
308 print "\n" if $last_type or $last_name;
309 $name ||= $type;
310 print qq(track type=bedGraph name="$key ($name)" description="Generated by GBrowse from $origin"\n);
311 $last_type = $type;
312 }
313  
314 if ($f->can('get_seq_stream')) { # a summary type; need to do recursive iteration
315 my $i = $f->get_seq_stream(@location_args);
316 while (my $g = $i->next_seq) { $self->print_bed_score($g) }
317 }
318 else {
319 $self->print_bed_score($f);
320 }
321 }
322 }
323  
324 sub print_peaks {
325 my $self = shift;
326 my ($db,$peaks,$label) = @_;
327 for my $trackname (keys %$peaks) {
328 $self->print_bed_header("$trackname (Peaks)");
329 for my $type (keys %{$peaks->{$trackname}}) {
330 my ($seqid,$start,$end) = @{$peaks->{$trackname}{$type}};
331 my $iterator = $db->get_seq_stream(-seq_id=> $seqid,
332 -start => $start,
333 -end => $end,
334 -type => $type,
335 );
336 while (my $f = $iterator->next_seq) {
337 $self->print_bed_score($f);
338 }
339
340 }
341 print "\n";
342 }
343 }
344  
345 sub print_bed_header {
346 my $self = shift;
347 my $label = shift;
348 print "track name=\"$label\"\n";
349 }
350  
351 sub print_bed_score {
352 my $self = shift;
353 my $f = shift;
354 my $score = defined $f->score ? sprintf("%.4f",$f->score) : '';
355 $score =~ s/\.?0+$//;
356 my $seq_id = $f->seq_id;
357 if (my $prefix = $self->add_prefix) {
358 $seq_id = "$prefix$seq_id";
359 }
360
361 print join ("\t",$seq_id,$f->start,$f->end,$score),"\n";
362 }
363  
364 sub available_formats {
365 my $class = shift;
366 my ($source,$label) = @_;
367 my $db = $source->open_database($label);
368 my $glyph = $source->code_setting($label => 'glyph');
369  
370 my @formats = qw(fasta);
371 push @formats,qw(gff3 genbank) unless $db->isa('Bio::DB::Bam')
372 or $db->isa('Bio::DB::Sam')
373 or $db->isa('Bio::DB::BigWig')
374 or $glyph =~ /wiggle|xyplot|density/;
375 push @formats,'vista','vista_wiggle','vista_peaks' if $glyph =~ /vista/i;
376 push @formats,'sam' if $db->isa('Bio::DB::Bam') or $db->isa('Bio::DB::Sam');
377 push @formats,'bed' if $db->isa('Bio::DB::BigWig') or $db->isa('Bio::DB::BigWigSet');
378 push @formats, qw(gff3 bed) if $db->isa('Bio::DB::BigBed');
379 push @formats,'bed' if $glyph =~ /wiggle|xyplot|density/;
380 my %seenit;
381 return grep {!$seenit{$_}++} @formats;
382 }
383  
384 sub guess_dump_method {
385 my $self = shift;
386 my $db = shift;
387 my $label= shift;
388  
389 return 'dump_gff3' if $self->forced_format eq 'gff3';
390 return 'dump_fasta' if $self->forced_format eq 'fasta';
391 return 'dump_genbank' if $self->forced_format eq 'genbank';
392 return 'dump_sam' if $self->forced_format eq 'sam';
393 return 'dump_bigwig' if $self->forced_format eq 'bed';
394 return 'dump_vista' if $self->forced_format eq 'vista';
395 return 'dump_vista_wiggle' if $self->forced_format eq 'vista_wiggle';
396 return 'dump_vista_peaks' if $self->forced_format eq 'vista_peaks';
397  
398 return 'dump_vista' if $self->data_source->code_setting($label => 'glyph') =~ /vista/i;
399 return 'dump_gff3_autowig' if $db->isa('Bio::DB::SeqFeature::Store');
400 return 'dump_gff3_autowig' if $db->isa('Bio::DB::GFF');
401 return 'dump_gff3_autowig' if $db->isa('Bio::DB::Das::Chado');
402 return 'dump_gff3_autowig' if $db->isa('Bio::DB::DasI');
403 return 'dump_gff3_autowig' if $db->isa('Bio::DB::BigBed');
404  
405 my $type = $self->guess_file_type();
406 return 'dump_sam' if $type eq 'sam';
407 return 'dump_bigwig' if $type eq 'bed';
408 return 'dump_gff3_autowig'
409 }
410  
411 sub print_gff3_header {
412 my $self = shift;
413 my $segment = shift;
414  
415 my $date = localtime;
416 print "##gff-version 3\n";
417 print "##date $date\n";
418 print "##source gbrowse gbgff gff3 dumper\n";
419 if ($segment) {
420 my $prefix = $self->add_prefix;
421 my $seq_id = $segment->seq_id;
422 $seq_id = "$prefix$seq_id" if $prefix;
423 print "##sequence-region ",$seq_id,':',$segment->start,'..',$segment->end,"\n";
424 }
425 }
426  
427 sub origin {
428 my $self = shift;
429 my $label = shift;
430  
431 my $source = $self->data_source;
432 my $origin = CGI::url(-full=>1);
433 $origin .= "/".$source->name;
434 $origin .= "?l=".CGI::escape($label) if $label;
435 return $origin;
436 }
437  
438 sub print_bio_graphics_wigs {
439 my $self = shift;
440 my ($wigs,$label) = @_;
441  
442 my $source = $self->data_source;
443  
444 # may need the relative pathname to get the wigs (sometimes)
445 my $basedir = $source->code_setting($label=>'basedir');
446 $basedir = $basedir->() if $basedir && ref($basedir) eq 'CODE'; # a bit awkward here
447  
448 eval "use Bio::Graphics::Wiggle"
449 unless Bio::Graphics::Wiggle->can('new');
450  
451 for my $track_name (keys %$wigs) {
452 my $origin = $self->origin($label);
453 print qq(track type=bedGraph name="$track_name" description="Generated by GBrowse from $origin; precision limited to 255 levels"\n);
454 for my $seqid (keys %{$wigs->{$track_name}}) {
455 for my $wigfile (keys %{$wigs->{$track_name}{$seqid}}) {
456 my ($start,$end) = @{$wigs->{$track_name}{$seqid}{$wigfile}};
457 my $path = File::Spec->rel2abs($wigfile,$basedir);
458 my $wig = Bio::Graphics::Wiggle->new($path) or next;
459 $wig->export_to_bedgraph($start,$end,\*STDOUT);
460 }
461 }
462 print "\n";
463 }
464 }
465  
466 sub print_bigwigs {
467 my $self = shift;
468 my ($wigs,$label) = @_;
469 my $source = $self->data_source;
470  
471 # may need the relative pathname to get the wigs (sometimes)
472 my $basedir = $source->code_setting($label=>'basedir');
473 $basedir = $basedir->() if $basedir && ref($basedir) eq 'CODE'; # a bit awkward here
474  
475 eval "use Bio::DB::BigWig"
476 unless Bio::DB::BigWig->can('new');
477  
478 for my $track_name (keys %$wigs) {
479 for my $seqid (keys %{$wigs->{$track_name}}) {
480 for my $wigfile (keys %{$wigs->{$track_name}{$seqid}}) {
481 my ($start,$end) = @{$wigs->{$track_name}{$seqid}{$wigfile}};
482 my $path = File::Spec->rel2abs($wigfile,$basedir);
483 my $wig = Bio::DB::BigWig->new($path) or next;
484 my $segment = Bio::Graphics::Feature->new(-seq_id=>$seqid,-start=>$start,-end=>$end);
485 $self->dump_bigwig($wig,$segment,[],$track_name);
486 print "\n";
487 }
488 }
489 }
490 }
491  
492 sub print_datafile {
493 my $self = shift;
494  
495 my $labels = $self->get_labels;
496 my $segment= $self->get_segment;
497  
498 $self->print_stylesheet($segment,$labels)
499 if $self->get_do_stylesheet;
500  
501 if (@$labels == 1) {
502 $self->dump_track($labels->[0],$segment);
503 return;
504 }
505  
506 # We don't handle heterogeneous downloads (multiple tracks with different database backends)
507 # well, so we default to a uniform GFF3 dump. In the future, this should be replaced with
508 # TAR file generation.
509 my $types = $labels ? $self->labels_to_types($labels,eval{$segment->length}) : undef;
510 my $files = $labels ? $self->labels_to_files($labels,eval{$segment->length}) : undef;
511  
512 my %filters
513 = map { $_ => $self->data_source->setting( $_ => 'filter' ) || undef }
514 @$labels;
515  
516 $self->print_gff3_header($segment);
517 $self->print_gff3_data($_, $types, \%filters ) for $self->db;
518 $self->print_gff3_data($_) for @$files;
519 }
520  
521 sub print_fasta {
522 my $self = shift;
523 my $segment = $self->get_segment;
524 my $seq = $segment->seq;
525 eval "require Bio::SeqIO" unless Bio::SeqIO->can('new');
526 my $out = Bio::SeqIO->new(-format => 'Fasta');
527 $out->write_seq($seq);
528 }
529  
530 sub data_source { shift->{data_source} }
531  
532 sub db {
533 my $self = shift;
534 return @{$self->{db}} if $self->{db};
535  
536 my $source = $self->data_source;
537 my $tracks = $self->get_labels;
538 $tracks = $self->all_databases unless $tracks;
539  
540 my %seenit;
541 my @dbs = grep {defined($_) && !$seenit{$_}++}
542 map {$source->open_database($_)} ('general',@$tracks);
543 $self->{db} = \@dbs;
544 return @dbs;
545 }
546  
547 sub segment {
548 my $self = shift;
549 my $d = $self->{segment};
550 $self->{segment} = shift if @_;
551 $d;
552 }
553  
554 sub check_source {
555 my $self = shift;
556 my $data_source = $self->{data_source};
557 my $source_name = $data_source->name();
558  
559 $source_name =~ s!^/+!!; # get rid of leading / from path_info()
560 $source_name =~ s!/+$!!; # get rid of trailing / from path_info() !
561  
562 if ($source_name) {
563 unless ( $data_source->globals->valid_source($source_name) ) {
564 print header('text/plain'), "# Invalid source $source_name; "
565 . "you may not have permission to access this data source.\n";
566 return;
567 }
568 }
569  
570 return 1;
571 }
572  
573 sub get_segment {
574 my $self = shift;
575 return $self->{segment} unless @_;
576  
577 my $segment = shift;
578  
579 # check whether someone called us directly by pasting into location box
580 if ($segment =~ /^\$segment/) {
581 print header('text/plain');
582 print "# To share this track, please paste its URL into the \"Enter Remote Annotation\" box\n",
583 "# at the bottom of a GBrowse window and not directly into your browser's Location area.\n";
584 return;
585 }
586  
587 my ( $seqid, $start, $end )
588 = $segment =~ /^([^:]+)(?::([\d-]+)(?:\.\.|,)([\d-]+))?/;
589  
590 unless ( defined $seqid ) {
591 print header('text/plain');
592 print "# Please provide the segment argument.\n";
593 return;
594 }
595  
596 my $datasource = $self->data_source;
597 my $tracks = $self->get_labels;
598 $tracks = $self->all_databases unless $tracks;
599  
600 my $search = Bio::Graphics::Browser2::RegionSearch->new(
601 {
602 source => $datasource,
603 state => $self->state || {},
604 }
605 );
606 $search->init_databases();
607 my ($f) = $search->search_features({-search_term=>$segment});
608 unless ($f) {
609 print header('text/plain'), "# The landmark named $segment was not found.\n";
610 return;
611 }
612 $self->segment($f);
613 return $f;
614 }
615  
616 sub state {
617 my $self = shift;
618 my $d = $self->{state};
619 $self->{state} = shift if @_;
620 $d;
621 }
622  
623 sub all_databases {
624 my $self = shift;
625 my $source = $self->data_source;
626 return [map {"$_:database"} $source->databases];
627 }
628  
629 sub get_labels {
630 my $self = shift;
631 my @labels = @{ $self->{labels} || [] };
632 return \@labels;
633 }
634  
635 sub get_id {
636 my $self = shift;
637 return $self->{id};
638 }
639  
640 sub get_featurefiles {
641 my $self = shift;
642 my @ff = grep {/^file:/} @{ $self->{labels} || [] };
643 return unless @ff;
644 return shellwords(@ff);
645 }
646  
647 sub get_do_stylesheet {
648 my $self = shift;
649 my $doit = $self->{stylesheet};
650 return 0 if defined $doit && $doit =~ /^(no|off|0)$/i;
651 return 1;
652 }
653  
654 sub guess_file_type {
655 my $self = shift;
656 my $labels = $self->get_labels;
657  
658 my $forced = $self->forced_format;
659 return $forced if defined $forced;
660  
661 # Currently we can't deal with heterogeneous downloads,
662 # so if multiple tracks are selected, we default to the
663 # common gff3 format. In the future, we should create a
664 # TAR file for download.
665 if (@$labels > 1) {
666 return 'gff3';
667 }
668 my $label = $labels->[0];
669 my $source = $self->data_source;
670 my $glyph = $source->setting( $label => 'glyph');
671 my $db = $source->open_database($label);
672  
673 if ($glyph && $glyph =~ /vista/i) {
674 return 'bed';
675 }
676  
677 if ($glyph && $glyph =~ /wiggle/) {
678 return 'bed';
679 }
680  
681 if ($db->isa('Bio::DB::Bam') or $db->isa('Bio::DB::Sam')) {
682 return 'sam';
683 }
684  
685 if ($db->isa('Bio::DB::BigWig') or $db->isa('Bio::DB::BigWigSet')) {
686 return 'bed';
687 }
688  
689 return 'gff3';
690  
691 }
692  
693 sub get_file_mime_type {
694 my $self = shift;
695 return $self->{mimetype} if defined $self->{mimetype};
696 my $dump = $self->{'dump'} || '';
697  
698 my $type = $self->guess_file_type;
699 my $x = "application/x-$type";
700  
701 return $type if $dump eq 'edit';
702 return 'application/octet-stream' if $dump eq 'save';
703 return 'text/plain';
704 }
705  
706 sub get_file_extension {
707 my $self = shift;
708 my $type = $self->guess_file_type;
709 return $type;
710 }
711  
712 sub labels_to_types {
713 my $self = shift;
714 my $labels = shift;
715 my $length = shift;
716  
717 my $data_source = $self->data_source;
718  
719 # remove dynamic labels, such as uploads
720 my @labels = grep { /:(overview|region|detail)$/ # keep overview/region sections
721 ||
722 !/^\w+:/x # discard over dynamic sections
723 } @$labels;
724 my @types;
725 for my $l (@labels) {
726 my @f = shellwords( $data_source->semantic_setting( $l => 'feature', $length ) || '' );
727 next unless @f;
728 push @types, @f;
729 }
730 return \@types;
731 }
732  
733 sub labels_to_files {
734 my $self = shift;
735 my $labels = shift;
736 @$labels or return [];
737  
738 # get the feature files, if appropriate
739 my $id = $self->get_id or return [];
740  
741 # first get the main source
742 my $data_source = $self->data_source;
743 my $segment = $self->segment;
744  
745 my @files;
746  
747 my $search = Bio::Graphics::Browser2::RegionSearch->new(
748 {
749 source => $data_source,
750 state => $self->state || {},
751 }
752 );
753 $search->init_databases();
754  
755 my $mapper = $search->coordinate_mapper( $segment, 1 );
756 for my $filename (@$labels) {
757 $filename =~ s/:(detail|overview|region).*$//;
758 my $path = Bio::Graphics::Browser2::UserData->file2path($data_source,$id,$filename);
759 my $featurefile = eval {
760 Bio::Graphics::FeatureFile->new(
761 -file => $path,
762 -smart_features => 1,
763 -map_coords => $mapper,
764 );
765 };
766 warn "Error while loading remote feature file $filename: $@" if $@;
767 push @files, $featurefile if $featurefile;
768 }
769  
770 return \@files;
771 }
772  
773 sub print_feature {
774 my $self = shift;
775 my $f = shift;
776 eval { $f->version(3) };
777 my $s = $f->gff_string(1); # the flag is for GFF3 subfeature recursion
778 chomp $s;
779 if (my $prefix = $self->add_prefix) {
780 $s =~ s/^/$prefix/gm unless $s =~ /^$prefix/m;
781 }
782 $s =~ s/\t\t/\t\.\t/g if $s; # no empty columns
783 $self->do_wigfile_substitution( \$s );
784 print $s, "\n";
785 }
786  
787 sub print_configuration {
788 my $self = shift;
789 my $config = shift;
790 my $labels = shift;
791  
792 my @labels = $labels ? @$labels : $config->labels;
793  
794 for my $l (@labels) {
795  
796 # a special config setting - don't want it to leak through
797 next if $l =~ m/^\w+:/ && $l !~ m/:(overview|region|details?)$/;
798 next if $l =~ m/^_scale/;
799  
800 print "[$l]\n";
801 my @s = $config->_setting($l);
802 for my $s (@s) {
803 my $value = $config->setting( $l => $s );
804 if ( ref $value eq 'CODE' ) {
805 $value
806 = $config->config->can('get_callback_source')
807 ? $config->config->get_callback_source( $l => $s )
808 : $config->setting( 'TRACK DEFAULTS' => $s );
809 defined $value or next;
810 chomp ($value);
811 }
812 next if $s =~ /^balloon/; # doesn't work right
813 print "$s = $value\n";
814 }
815 print "\n";
816 }
817 }
818  
819 sub print_gff3_data {
820 my $self = shift;
821 my $db = shift;
822 my $types = shift;
823 my $filters = shift;
824  
825 my $s = $self->get_segment;
826 my $data_source = $self->data_source;
827 my $len = $s->length;
828  
829 my @args = (
830 -seq_id => $s->seq_id,
831 -start => $s->start,
832 -end => $s->end
833 );
834 push @args, ( -type => $types ) if $types;
835 my $iterator = $db->get_seq_stream(@args);
836  
837 FEATURE:
838 while ( my $f = $iterator->next_seq ) {
839 for my $l ( $data_source->feature2label( $f, $len ) ) {
840 next FEATURE if $filters->{$l} && !$filters->{$l}->($f);
841 }
842 $self->print_feature($f);
843 }
844 }
845  
846 # Because we can't sling whole wigfiles around, we serialize a section
847 # of the wigfile and send just the data and header information in "wif" format.
848 sub do_wigfile_substitution {
849 my $self = shift;
850  
851 my $gff_line_ref = shift;
852 $$gff_line_ref =~ /wigfile=/ or return;
853  
854 my $segment = $self->segment;
855 my ( $start, $end ) = ( $segment->start, $segment->end );
856  
857 eval { # trap all errors, which can be plentiful!
858 eval "use Bio::Graphics::Wiggle"
859 unless Bio::Graphics::Wiggle->can('new');
860 eval "use MIME::Base64" unless MIME::Base64->can('encode');
861  
862 $$gff_line_ref =~ s{wigfile=([^;&\n]+)}
863 {
864 my $wig = Bio::Graphics::Wiggle->new(CGI::unescape($1));
865 my $wif = $wig->export_to_wif($start,$end);
866 'wigdata='.MIME::Base64::encode_base64($wif,'');
867 }exg;
868 };
869 warn $@ if $@;
870 }
871  
872 # Experimental feature:
873 # list all the labels that are marked "discoverable"
874 sub print_scan {
875 my $self = shift;
876 print $self->get_scan;
877 }
878  
879 sub get_scan {
880 my $self = shift;
881 my $config = $self->data_source;
882 my @labels = $config->labels;
883  
884 my $result = '';
885 $result .= "# Discoverable tracks from ".CGI->self_url."\n";
886 for my $l (@labels) {
887 next if $l =~ /^_/;
888 next if $l =~ /:\w+/;
889 next unless $config->fallback_setting($l => 'discoverable');
890 next if $config->code_setting($l=>'global feature');
891 my $key = $config->code_setting($l => 'key') || $l;
892 my $citation = $config->code_setting($l => 'citation');
893 my $data_source = $config->code_setting($l => 'data source');
894 my $track_source = $config->code_setting($l => 'track source');
895 my $subtracks = $config->subtrack_scan_list($l);
896 $result .= <<END;
897 [$l]
898 key = $key
899 END
900 ;
901 $result .= "select = @$subtracks\n" if $subtracks;
902 $result .= "citation = $citation\n" if $citation;
903 $result .= "data source = $data_source\n" if $data_source;
904 $result .= "track source = $track_source\n" if $track_source;
905 $result .= "\n";
906 }
907 return $result;
908 }
909  
910 1;