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

filter: Statementstmt 0.0% 0 / 2450 Branchbran 0.0% 0 / 948 Conditioncond 0.0% 0 / 730 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 256 Podpod 0.0% 0 / 216 totaltotal 0.0% 0 / 4600 CC 476 SCAR 45.1
CC
476
Cov
0%
handle_gff_dump
552.0
reconfigure_track
462.0
run
342.0
CRAP 90.9
1 package Bio::Graphics::Browser2::Render;
2  
3 use strict;
4 use warnings;
5  
6 use JSON;
7 use Digest::MD5 'md5_hex';
8 use CGI qw(:standard param request_method header url iframe img span div br center url_param);
9 use Carp qw(croak cluck);
10 use File::Basename 'dirname','basename';
11 use Text::Tabs;
12 use Data::Dumper;
13 use English;
14  
15 use Bio::Graphics::Browser2::I18n;
16 use Bio::Graphics::Browser2::PluginSet;
17 use Bio::Graphics::Browser2::Shellwords;
18 use Bio::Graphics::Browser2::Action;
19 use Bio::Graphics::Browser2::Region;
20 use Bio::Graphics::Browser2::RegionSearch;
21 use Bio::Graphics::Browser2::RenderPanels;
22 use Bio::Graphics::Browser2::RemoteSet;
23 use Bio::Graphics::Browser2::SubtrackTable;
24 use Bio::Graphics::Browser2::TrackDumper;
25 use Bio::Graphics::Browser2::Util qw[modperl_request url_label];
26 use Bio::Graphics::Browser2::UserTracks;
27 use Bio::Graphics::Browser2::UserDB;
28 use Bio::Graphics::Browser2::Session;
29 use Bio::Graphics::Browser2::Render::SnapshotManager;
30 use POSIX ":sys_wait_h";
31  
32 use constant VERSION => 2.0;
33 use constant DEBUG => 0;
34 use constant TRACE_RUN => 0;
35 use constant TRACE => 0; # shows top level events
36 use constant OVERVIEW_SCALE_LABEL => 'Overview Scale';
37 use constant REGION_SCALE_LABEL => 'Region Scale';
38 use constant DETAIL_SCALE_LABEL => 'Detail Scale';
39 use constant EMPTY_IMAGE_HEIGHT => 12;
40 use constant MAX_SEGMENT => 1_000_000;
41 use constant TOO_MANY_SEGMENTS => 5_000;
42 use constant OVERVIEW_RATIO => 1.0;
43 use constant GROUP_SEPARATOR => "\x1d";
44 use constant LABEL_SEPARATOR => "\x1e";
45  
46 my %PLUGINS; # cache initialized plugins
47 my $FCGI_REQUEST; # stash fastCGI request handle
48 my $FCGI_RUNNING=0; # true if fastCGI is running
49 my $STATE; # stash state for use by callbacks
50  
51 # new() can be called with two arguments: ($data_source,$session)
52 # or with one argument: ($globals)
53 # in the latter case, it will invoke this code:
54 # $session = $globals->authorized_session()
55 # $globals->update_data_source($session)
56 # $source = $globals->create_data_source($session->source)
57  
58 sub new {
59 my $class = shift;
60  
61 my ($data_source, $session, $requested_id, $authority);
62  
63 if (@_ == 2) {
64 ($data_source, $session) = @_;
65 } elsif (@_ == 1) {
66 my $globals = shift;
67 $requested_id = param('id') || CGI::cookie('gbrowse_sess');
68 $authority = param('authority') || CGI::cookie('authority');
69 my $shared_ok = Bio::Graphics::Browser2::Action->shared_lock_ok(param('action'));
70 $session = $globals->authorized_session($requested_id,
71 $authority,
72 $shared_ok);
73 $globals->update_data_source($session);
74 $data_source = $globals->create_data_source($session->source);
75 } else {
76 croak "usage: ".__PACKAGE__."->new(\$globals) or ->new(\$data_source,\$session)";
77 }
78  
79 my $self = bless {},ref $class || $class;
80  
81 $self->data_source($data_source);
82 $self->session($session);
83 $self->state($session->page_settings);
84 $self->set_language();
85 $self->set_signal_handlers();
86 $self;
87 }
88  
89 sub set_signal_handlers {
90 my $self = shift;
91 $SIG{CHLD} = sub {
92 while ((my $kid = waitpid(-1,WNOHANG))>0) {
93 1;
94 }
95 };
96 }
97  
98 sub data_source {
99 my $self = shift;
100 my $d = $self->{data_source};
101 $self->{data_source} = shift if @_;
102 $d;
103 }
104  
105 sub session {
106 my $self = shift;
107 my $d = $self->{session};
108 $self->{session} = shift if @_;
109 warn "d= $d" if DEBUG;
110 warn "self->session= $self->{session}" if DEBUG;
111 $d;
112 }
113  
114 sub state {
115 my $self = shift;
116 my $d = $self->{state};
117 $STATE = $self->{state}= shift if @_;
118 $d;
119 }
120  
121 # this is a STATIC method that can be used by callbacks as
122 # Bio::Graphics::Browser2::Render->request->{name}
123 sub request {
124 return $STATE;
125 }
126  
127 sub error_message {
128 my $self = shift;
129 my $d = $self->{error_message};
130 $self->{error_message} = shift if @_;
131 $d;
132 }
133  
134 sub is_admin {
135 my $self = shift;
136 my $login = $self->session->username or return;
137 my $admin = $self->globals->admin_account or return;
138 return $login eq $admin;
139 }
140  
141 sub userdb {
142 my $self = shift;
143 return $self->{userdb} if exists $self->{userdb};
144 unless ($self->globals->user_accounts) {
145 $self->{userdb} = undef;
146 return;
147 }
148 my $userdb = $self->{userdb} ||= Bio::Graphics::Browser2::UserDB->new($self->globals);
149 return $userdb;
150 }
151  
152 # User Tracks - Returns a list of a user's tracks.
153 sub user_tracks {
154 my $self = shift;
155  
156 # note: Bio::Graphics::Browser2::AdminTracks is a subclass of UserTracks
157 # that is defined within the UserTracks.pm file.
158 my $class = $self->is_admin ? 'Bio::Graphics::Browser2::AdminTracks'
159 : 'Bio::Graphics::Browser2::UserTracks';
160
161 $self->{usertracks} ||= $class->new($self->data_source,$self->session);
162 return $self->{usertracks};
163 }
164  
165 sub get_usertrack_labels {
166 my $self = shift;
167 return $self->{'.user_labels'} if exists $self->{'.user_labels'};
168 my $userdata = $self->user_tracks;
169 my @files = $userdata->tracks; # misnomer -- should be "uploads" or "files"
170 for my $f (@files) {
171 my @labels = $userdata->labels($f);
172 $self->{'.user_labels'}{$_}=$f foreach @labels;
173 }
174 return $self->{'.user_labels'} ||= {};
175 }
176  
177 sub remote_sources {
178 my $self = shift;
179 my $d = $self->{remote_sources};
180 $self->{remote_sources} = shift if @_;
181 $d;
182 }
183  
184 sub db {
185 my $self = shift;
186 my $d = $self->{db};
187 $self->{db} = shift if @_;
188 $d;
189 }
190  
191 sub plugins {
192 my $self = shift;
193 my $d = $self->{plugins};
194 $self->{plugins} = shift if @_;
195 $d;
196 }
197  
198 sub plugin_name {
199 my $self = shift;
200 my $label = shift;
201 #my ($id) = $label =~ /^plugin:(\w+)/;
202 my (undef,$id) = split(/:/,$label);
203 return $self->plugins->plugin($id)->name;
204 }
205  
206 sub debug {
207 my $self = shift;
208 return $self->{debug} if exists $self->{debug};
209 return $self->{debug} = DEBUG || $self->data_source->global_setting('debug');
210 }
211  
212 sub DESTROY {
213 my $self = shift;
214 warn "[$$] $self: destroy she said" if DEBUG;
215 }
216  
217 sub destroy {
218 my $self = shift;
219 # because the login manager maintains a copy of the render object,
220 # we need to explicitly destroy it to avoid memory leaks.
221 if (my $lm = $self->{login_manager}) {
222 $lm->destroy;
223 delete $self->{login_manager};
224 }
225 $self->session->unlock if $self->session;
226 }
227  
228 ###################################################################################
229 #
230 # RUN CODE HERE
231 #
232 ###################################################################################
233 sub run {
234 my $self = shift;
235 my $fh = shift || \*STDOUT;
236 my $old_fh = select($fh);
237  
238 my $debug = $self->debug || TRACE;
239  
240 warn "[$$] RUN(): ",
241 request_method(),': ',
242 url(-path=>1),' ',
243 query_string() if $debug || TRACE_RUN;
244 warn "[$$] session id = ",$self->session->id if $debug;
245  
246 $ENV{FTP_PASSIVE}=1; # so that later calls to LWP will work on ftp:// urls
247  
248 $self->set_source() && return;
249  
250 my $session = $self->session;
251 my $source = $self->data_source;
252 if ($session->private) {
253 $source->set_username($session->username);
254 } else {
255 $source->set_username(undef);
256 }
257  
258 if ($source->must_authenticate) {
259 if ($session->private &&
260 $self->user_authorized_for_source($session->username))
261 {
262 # login session - make sure that the data source has the information needed
263 # to restrict tracks according to policy
264 } else {
265 # authentication required, but not a login session, so initiate authentication request
266 $self->force_authentication;
267 $session->flush;
268 $session->unlock;
269 return;
270 }
271 }
272  
273 warn "[$$] add_user_tracks()" if $debug;
274 $self->add_user_tracks($self->data_source);
275  
276 warn "[$$] testing for asynchronous event()" if $debug;
277 if ($self->run_asynchronous_event) {
278 warn "[$$] asynchronous exit" if $debug;
279 $self->session->unlock;
280 return ;
281 }
282
283 if (my $file = param('share_link')) {
284 $self->share_link($file);
285 }
286  
287 warn "[$$] init()" if $debug;
288 $self->init();
289  
290 warn "[$$] update_state()" if $debug;
291 $self->update_state();
292
293 # EXPERIMENTAL CODE -- GET RID OF THE URL PARAMETERS
294 if ($ENV{QUERY_STRING} && $ENV{QUERY_STRING} =~ /reset/) {
295 print CGI::redirect(CGI::url(-absolute=>1,-path_info=>1));
296 } else {
297 warn "[$$] render()" if $debug;
298 $self->render();
299 }
300  
301 warn "[$$] cleanup" if $debug;
302 $self->cleanup();
303 select($old_fh);
304  
305 warn "[$$] session flush" if $debug;
306 $self->session->flush;
307 $self->session->unlock;
308
309 delete $self->{usertracks};
310 warn "[$$] synchronous exit" if $debug;
311 }
312  
313 sub user_authorized_for_source {
314 my $self = shift;
315 my $username = shift;
316 my $source = $self->data_source;
317 my $globals = $source->globals;
318 my $session = $self->session;
319 my $plugins = $self->init_plugins();
320 $source->set_username($username);
321 return $globals->authorized($source->name,$username,$plugins->auth_plugin)
322 && $source->authorized('general');
323 }
324  
325 sub set_source {
326 my $self = shift;
327  
328 my $source = $self->session->source;
329  
330 if (CGI::unescape(CGI::path_info()) ne CGI::unescape("/$source/")) {
331 my $args = CGI::query_string();
332 my $url = CGI::url(-absolute=>1,-path_info=>0);
333 $url =~ s!(gbrowse[^/]*)(?\!.*gbrowse)/.+$!$1!; # fix CGI/Apache bug
334 $url .= "/$source/";
335 $url .= "?$args" if $args && $args !~ /^source=/;
336 print CGI::redirect($url);
337 return 1;
338 }
339 return;
340 }
341  
342 sub init {
343 my $self = shift;
344 warn "init()" if DEBUG;
345 warn "init_database()" if DEBUG;
346 $self->init_database();
347 warn "init_plugins()" if DEBUG;
348 $self->init_plugins();
349 warn "init_remote_sources()" if DEBUG;
350 $self->init_remote_sources();
351 warn "set_default_state()" if DEBUG;
352 $self->set_default_state();
353 warn "init done" if DEBUG;
354 }
355  
356 # this prints out the HTTP data from an asynchronous event
357 sub run_asynchronous_event {
358 my $self = shift;
359 my ($status, $mime_type, $data, %headers) = $self->asynchronous_event or return;
360  
361 warn "[$$] asynchronous event returning status=$status, mime-type=$mime_type" if TRACE_RUN;
362  
363 # add the cookies!
364 $headers{-cookie} = [$self->state_cookie,$self->auth_cookie];
365  
366 if ($status == 204) { # no content
367 print CGI::header( -status => '204 No Content', %headers );
368 } elsif ($status == 302) { # redirect
369 print CGI::redirect($data);
370 } elsif ($mime_type eq 'application/json') {
371 print CGI::header(
372 -status => $status,
373 -cache_control => 'no-cache',
374 -charset => $self->translate('CHARSET'),
375 -type => $mime_type,
376 %headers),
377 JSON::to_json($data);
378 } else {
379 print CGI::header(
380 -status => $status,
381 -cache_control => 'no-cache',
382 -charset => $self->translate('CHARSET'),
383 -type => $mime_type,
384 %headers),
385 $data;
386 }
387 return 1; # no further processing needed
388 }
389  
390 # handle asynchronous events
391 #
392 # Asynchronous requests. See Bio::Graphics::Browser2::Action for dispatch
393 # table. Each request returns a three element list of format:
394 # ($http_status,$mime_type,$body_data)
395 sub asynchronous_event {
396 my $self = shift;
397 my $settings = $self->state;
398 my $events;
399  
400 warn "[$$] asynchronous event(",query_string(),")" if TRACE_RUN;
401  
402 # TO ADD AN ASYNCHRONOUS REQUEST...
403 # 1. Give the request a unique name, such as "foo"
404 # 2. Arrange for the client to POST or GET the document URL with a CGI
405 # argument list that includes "action=foo".
406 # 3. Modify Bio::Graphics::Browser2::Action to include a method named
407 # ACTION_foo that processes the request. The method will receive
408 # the CGI object as its argument, and is expected to return
409 # a three-item list consisting of the HTTP status code, the MIME type,
410 # and the message contents in the appropriate format for the MIME type.
411 # Within the method call $self->render()
412 # to get this Bio::Graphics::Browser2::Render object.
413  
414 # legacy URLs
415 my $dispatch = Bio::Graphics::Browser2::Action->new($self);
416 if (my @result = $dispatch->handle_legacy_calls($CGI::Q,$self)) {
417 return @result;
418 }
419  
420 if ( my $track_name = param('display_citation') ) {
421 my $html = $self->display_citation($track_name);
422 return ( 200, 'text/html', $html );
423 }
424  
425 elsif (my $action = param('action')) {
426 my $method = "ACTION_${action}";
427 unless ($dispatch->can($method)) {
428 return (401,'text/plain',"invalid action: '$action'");
429 }
430 return $dispatch->$method($CGI::Q);
431 }
432  
433 else {
434 return;
435 }
436 }
437  
438 sub authorize_user {
439 my $self = shift;
440 my ($username,$id,$remember,$using_openid) = @_;
441 my ($session,$error);
442  
443 my $userdb = $self->userdb;
444 return unless $userdb->username_from_sessionid($id) eq $username;
445
446 warn "Checking current session" if DEBUG;
447 my $current = $self->session->id;
448 if ($current eq $id) {
449 warn "Using current session" if DEBUG;
450 $session = $self->session;
451 } elsif ($self->session->private) { # trying to login without logging out?
452 $session = $self->globals->session($id); # create/retrieve session
453 } else {
454 warn "Retrieving old session" if DEBUG;
455 $session = $self->globals->session($id); # create/retrieve session
456 }
457 unless ($session->id eq $id) {
458 warn "fixing probable expired session";
459 FIX: {
460 my $username = $userdb->username_from_sessionid($id) or last FIX;
461 my $userid = $userdb->get_user_id($username) or last FIX;
462 my $uploadsid = $userdb->get_uploads_id($userid) or last FIX;
463 $session->uploadsid($uploadsid);
464 $userdb->set_session_and_uploadsid($userid,$session->id,$uploadsid);
465 $id = $session->id;
466 }
467 }
468  
469 my $nonce = Bio::Graphics::Browser2::Util->generate_id;
470 my $ip = CGI::remote_addr();
471  
472 $session->set_nonce($nonce,$ip,$remember);
473 $session->username($username);
474 $session->using_openid($using_openid);
475  
476 warn "id=$id, username =",$session->username if DEBUG;
477  
478 $session->flush();
479 return ($session->id,$nonce);
480 }
481  
482 sub background_track_render {
483 my $self = shift;
484  
485 $self->session->unlock(); # don't hold session captive on renderers!
486
487 $self->init_plugins();
488 $self->init_remote_sources();
489  
490 $self->segment or return;
491 my $cache_extra = $self->create_cache_extra;
492 my $external = $self->external_data;
493  
494 my $display_details = 1;
495 my $details_msg = '';
496 my %requests;
497  
498 if ( $self->get_panel_renderer($self->segment)->segment_length <= $self->get_max_segment ) {
499 $requests{'detail'} =
500 $self->render_deferred(
501 labels => [ $self->expand_track_names($self->detail_tracks) ],
502 segment => $self->segment,
503 section => 'detail',
504 cache_extra => $cache_extra,
505 external_tracks => $external
506 );
507 } else {
508 $display_details = 0;
509 $details_msg = h1(
510 br(),
511 $self->translate(
512 'TOO_BIG',
513 scalar $self->data_source()->unit_label($self->get_max_segment),
514 )
515 );
516 }
517  
518 $requests{'region'} =
519 $self->render_deferred( labels => [ $self->expand_track_names($self->regionview_tracks) ],
520 segment => $self->region_segment,
521 section => 'region',
522 cache_extra => $cache_extra,
523 external_tracks => $external,
524 )
525 if ( $self->state->{region_size} && $self->data_source->show_section('region') );
526  
527 $requests{'overview'} =
528 $self->render_deferred( labels => [ $self->expand_track_names($self->overview_tracks) ],
529 segment => $self->whole_segment,
530 section => 'overview',
531 cache_extra => $cache_extra,
532 external_tracks => $external,
533 )
534 if ( $self->data_source->show_section('overview') );
535  
536 my (%track_keys,%seenit);
537 for my $section (keys %requests) {
538 my $cache_track_hash = $requests{$section};
539 foreach my $track_label ( keys %{ $cache_track_hash || {} } ) {
540 my $track_id = $self->trackname_to_id($track_label,$section);
541 $track_keys{ $track_id }
542 = $cache_track_hash->{$track_label}->key();
543 }
544 }
545  
546 warn "background_track_render() return track keys ",join ' ',%track_keys if DEBUG;
547  
548 return (\%track_keys, $display_details, $details_msg);
549 }
550  
551 sub share_link {
552 my $self = shift;
553 my $file = shift;
554 my $usertracks = $self->user_tracks;
555 $usertracks->share_link($file);
556 $self->add_user_tracks;
557 my @tracks = $usertracks->labels($file);
558 $self->add_track_to_state($_) foreach @tracks;
559 return \@tracks;
560 }
561  
562 sub add_tracks {
563 my $self = shift;
564 my $track_names = shift;
565  
566 warn "[$$] add_tracks(@$track_names)" if DEBUG;
567  
568 my %track_data;
569 my $segment = $self->segment;
570
571 my $remote;
572 foreach (@$track_names) {
573 $self->add_track_to_state($_);
574 $remote++ if /http|ftp|das/;
575 $remote++ if $self->data_source->setting($_=>'remote feature');
576 }
577  
578 $self->init_remote_sources if $remote;
579
580 if ($segment) {
581 foreach my $track_name ( @$track_names ) {
582  
583 my @track_ids = $self->expand_track_names($track_name);
584
585 for my $track_id (@track_ids) {
586
587 warn "rendering track $track_id" if DEBUG;
588  
589 my ( $track_keys, $display_details, $details_msg )
590 = $self->background_individual_track_render($track_id);
591
592 my $track_key = $track_keys->{$track_id};
593 my $track_section = $self->data_source->get_section_from_label($track_id);
594 my $image_width = $self->get_image_width($self->state);
595 my $image_element_id = $track_name . "_image";
596
597 my $track_html;
598 if ( $track_section eq 'detail' and not $display_details ) {
599 my $image_width = $self->get_image_width($self->state);
600 $track_html .= $self->render_grey_track(
601 track_id => $track_name,
602 image_width => $image_width,
603 image_height => EMPTY_IMAGE_HEIGHT,
604 image_element_id => $track_name . "_image",
605 );
606 }
607 else {
608 $track_html = $self->render_deferred_track(
609 cache_key => $track_key,
610 track_id => $track_id,
611 ) || '';
612 }
613 $track_html = $self->wrap_track_in_track_div(
614 track_id => $track_id,
615 track_name => $track_name,
616 track_html => $track_html,
617 );
618
619 my $panel_id = 'detail_panels';
620 if ( $track_id =~ /:overview$/ ) {
621 $panel_id = 'overview_panels';
622 }
623 elsif ( $track_id =~ /:region$/ ) {
624 $panel_id = 'region_panels';
625 }
626 warn "add_track() returning track_id=$track_id, key=$track_key, name=$track_name, panel_id=$panel_id" if DEBUG;
627
628 $track_data{$track_id} = {
629 track_key => $track_key,
630 track_id => $track_id,
631 track_name => $track_name,
632 track_html => $track_html,
633 track_section => $track_section,
634 image_element_id => $image_element_id,
635 panel_id => $panel_id,
636 display_details => $display_details,
637 details_msg => $details_msg,
638 };
639 }
640 }
641 }
642 return \%track_data;
643 }
644  
645 sub create_cache_extra {
646 my $self = shift;
647 my $settings = $self->state();
648 my @cache_extra = (
649 $settings->{show_tooltips},
650 $settings->{ref},
651 $settings->{start},
652 $settings->{stop},
653 );
654  
655 push @cache_extra,sort map {"$_\@$settings->{h_feat}{$_}"}
656 keys %{$settings->{h_feat}}
657 if $settings->{h_feat};
658  
659 push @cache_extra,sort @{$settings->{h_region}}
660 if $settings->{h_region};
661  
662 push @cache_extra, map { $_->config_hash() } $self->plugins->plugins;
663  
664 return \@cache_extra;
665 }
666  
667 sub background_individual_track_render {
668 my $self = shift;
669 my $label = shift;
670 my $nocache = shift;
671  
672 my $display_details = 1;
673 my $details_msg = '';
674  
675 my $external = $self->external_data;
676 my $source = $self->data_source;
677
678 my $section;
679 my $segment;
680 if ($label =~ /:overview$/){
681 $section = 'overview';
682 $segment = $self->whole_segment();
683 }
684 elsif ($label =~ /:region$/){
685 $section = 'region';
686 $segment = $self->region_segment();
687 }
688 else{
689 $section = 'detail';
690 $segment = $self->segment();
691 }
692  
693 if ($section eq 'detail'
694 && $self->segment
695 && $self->get_panel_renderer($self->segment)->segment_length > $self->get_max_segment() )
696 {
697 $display_details = 0;
698 $details_msg = h1(
699 $self->translate(
700 'TOO_BIG',
701 scalar $source->unit_label(MAX_SEGMENT),
702 )
703 );
704 my %track_keys = ( $label => 0 );
705 return ( \%track_keys, $display_details, $details_msg );
706 }
707
708 my $cache_extra = $self->create_cache_extra();
709  
710 # Start rendering the detail and overview tracks
711 my $cache_track_hash = $self->render_deferred(
712 labels => [ $label, ],
713 segment => $segment,
714 section => $section,
715 cache_extra => $cache_extra,
716 external_tracks => $external,
717 nocache => $nocache,
718 );
719  
720 my %track_keys;
721 foreach my $cache_track_hash ( $cache_track_hash, ) {
722 foreach my $track_label ( keys %{ $cache_track_hash || {} } ) {
723 my $unique_label =
724 $source->is_remotetrack($track_label) ? $track_label
725 : $external->{$track_label} ? "$track_label:$section"
726 : $track_label;
727 $track_keys{ $unique_label }
728 = $cache_track_hash->{$track_label}->key();
729 }
730 }
731  
732 return (\%track_keys, $display_details, $details_msg);
733 }
734  
735 sub render {
736 my $self = shift;
737  
738 warn "[$$] render()" if DEBUG;
739  
740 # NOTE: these handle_* methods will return true
741 # if they want us to exit before printing the header
742 $self->handle_track_dump() && return;
743 $self->handle_gff_dump() && return;
744 $self->handle_plugins() && return;
745 $self->handle_download_userdata() && return;
746  
747 $self->render_header();
748 $self->render_body();
749 }
750  
751 sub render_header {
752 my $self = shift;
753 my $cookie1 = $self->state_cookie();
754 my $cookie2 = $self->auth_cookie();
755 my $header = CGI::header(
756 -cache_control =>'no-cache',
757 -cookie => [$cookie1,$cookie2],
758 -charset => $self->translate('CHARSET'),
759 );
760 print $header;
761 }
762  
763 sub state_cookie {
764 my $self = shift;
765 my $session = $self->session;
766 my $id = shift || $session->id;
767 my $path = url(-absolute => 1);
768 $path =~ s!gbrowse/?$!!;
769 my $globals = $self->globals;
770 my $cookie = CGI::Cookie->new(
771 -name => $CGI::Session::NAME,
772 -value => $id,
773 -path => $path,
774 -expires => '+'.$globals->time2sec($globals->remember_settings_time).'s',
775 );
776 return $cookie;
777 }
778  
779 sub auth_cookie {
780 my $self = shift;
781 my $path = url(-absolute => 1);
782 $path =~ s!gbrowse/?$!!;
783 my $auth = (shift || param('authority')) or return;
784 my $globals = $self->globals;
785 my $remember = $self->session->remember_auth;
786 my @args = (-name => 'authority',
787 -value=> $auth,
788 -path => $path);
789 if ($remember) {
790 push @args,(-expires => '+'.$globals->time2sec($globals->remember_settings_time).'s');
791 }
792 return CGI::Cookie->new(@args);
793 }
794  
795 # for backward compatibility
796 sub create_cookie {
797 my $self = shift;
798 return [
799 $self->state_cookie,
800 $self->auth_cookie
801 ];
802 }
803  
804 # For debugging
805 sub allparams {
806 my $args = {};
807 for my $key (param()) {
808 $args->{$key} = param($key)
809 }
810 "<pre>".Data::Dumper::Dumper($args)."</pre>";
811 }
812 #print "All params:<br>\n".dumperonscreen($self->allparams);
813  
814 sub render_body {
815 my $self = shift;
816  
817 warn "render_body()" if DEBUG;
818  
819 my $region = $self->region;
820 my $features = $region->features;
821 my $settings = $self->state;
822 my $source = $self->data_source;
823  
824 my $title = $self->generate_title($features);
825  
826 my $output;
827 my @post_load = $self->get_post_load_functions;
828 $output .= $self->render_html_start($title,@post_load);
829 $output .= $self->render_user_header;
830 $output .= $self->render_busy_signal;
831 $output .= $self->render_actionmenu;
832 $output .= $self->render_top($title,$features);
833  
834 my $main_page .= $self->render_navbar($region->seg);
835  
836 if ($region->feature_count > 1) {
837 $main_page .= $self->render_multiple_choices($features,$self->state->{name});
838 $main_page .= $self->render_select_track_link;
839 }
840  
841 elsif (my $seg = $region->seg) {
842 $main_page .= $self->render_panels($seg,{overview => $source->show_section('overview'),
843 regionview => $source->show_section('region'),
844 detailview => $source->show_section('detail')});
845 $main_page .= $self->render_galaxy_form($seg);
846 }
847  
848 elsif ($region->feature_count > 0) { # feature but no segment? Admin error
849 my $message = $self->translate('CHROM_NOT_FOUND');
850 my $details = $self->translate('CHROM_NOT_FOUND_DETAILS', $features->[0]->display_name, $features->[0]->seq_id);
851 $main_page .= script({-type=>'text/javascript'},"Controller.show_error('$message','$details')")
852 }
853
854 my $tracks = $self->render_tracks_section;
855 my $snapshots = $self->snapshot_manager->render_snapshots_section;
856 my $community = $self->user_tracks->database? $self->render_community_tracks_section : "";
857 my $custom = $self->render_custom_tracks_section;
858 my $global_config = $self->render_global_config;
859  
860 $output .= $self->render_tabbed_pages($main_page,$tracks,$snapshots,$community,$custom,$global_config);
861 $output .= $self->login_manager->render_confirm;
862 $output .= $self->render_bottom($features);
863  
864 print $output;
865 }
866  
867 sub render_tracks_section {
868 my $self = shift;
869 return $self->render_toggle_track_table;
870 }
871  
872 sub generate_title {
873 my $self = shift;
874 my $features = shift;
875  
876 my $dsn = $self->data_source;
877 my $state = $self->state;
878 my $description = $dsn->description;
879 my $divider = $self->data_source->unit_divider;
880  
881 return $description unless $features;
882 return !$features || !$state->{name} ? $description
883 : @$features == 0 ? $self->translate('NOT_FOUND',$state->{name})
884 : @$features == 1 ? "$description: ".
885 $self->translate('SHOWING_FROM_TO',
886 scalar $dsn->unit_label($state->{view_stop} - $state->{view_start}+1),
887 $state->{ref},
888 $dsn->commas($state->{view_start}),
889 $dsn->commas($state->{view_stop}))
890 : $description;
891 }
892  
893 # Provide segment info for rubberbanding and panning
894 sub segment_info_object {
895 my $self = shift;
896 my $state = $self->state;
897 my $segment = $self->segment;
898 my $whole_segment = $self->whole_segment;
899  
900 my $renderer = $self->get_panel_renderer($segment);
901  
902 my $pad = $self->data_source->global_setting('pad_left')
903 || $renderer->image_padding
904 || 0;
905 my $max = $self->get_max_segment;
906 my $width = ( $state->{width} * OVERVIEW_RATIO );
907 my $image_width = $self->get_image_width($state);
908 my $detail_width = $self->get_detail_image_width($state);
909  
910 my %segment_info_object = (
911 image_padding => $pad,
912 max_segment => $max,
913 overview_start => $whole_segment->start,
914 overview_stop => $whole_segment->end,
915 overview_pixel_ratio => $whole_segment->length / $width,
916 detail_start => $segment->start,
917 detail_stop => $segment->end,
918 'ref' => $segment->seq_id,
919 details_pixel_ratio => $segment->length / ($state->{width} * $self->details_mult()),
920 detail_width => $detail_width,
921 overview_width => $image_width,
922 width_no_pad => $state->{width},
923 details_mult => $self->details_mult(),
924 hilite_fill => $self->data_source->global_setting('hilite fill') || 'red', # Not sure if there's a
925 hilite_outline => $self->data_source->global_setting('hilite outline') || 'gray', # better place for this
926 hilite_height => $self->data_source->global_setting('hilite height') || '400px',
927 flip => $state->{flip},
928 initial_view_start => $state->{view_start},
929 initial_view_stop => $state->{view_stop},
930 length_label => scalar $self->data_source->unit_label($state->{view_stop} - $state->{view_start}+1),
931 description => $self->data_source->description,
932 );
933 if ( $state->{region_size} ) {
934 my ( $rstart, $rend ) = $self->regionview_bounds;
935 my $rlen = abs( $rend - $rstart );
936 my $ratio = $rlen / $width;
937 $segment_info_object{'region_start'} = $rstart;
938 $segment_info_object{'region_stop'} = $rend;
939 $segment_info_object{'region_pixel_ratio'} = $rlen / $width;
940 $segment_info_object{'region_width'} = $image_width;
941 }
942 return \%segment_info_object;
943 }
944  
945 # Returns the HTML for the blank panel for a section (which will later be filled)
946 sub render_panels {
947 my $self = shift;
948 my $seg = shift;
949 my $section = shift;
950  
951 warn "render_panels()" if DEBUG;
952  
953 my $html = '';
954  
955 my $cache_extra = $self->create_cache_extra();
956  
957 # Kick off track rendering
958 if ($section->{'overview'} ) {
959 my $scale_bar_html = $self->scale_bar( $seg, 'overview', );
960 my $panels_html = $self->get_blank_panels( [$self->overview_tracks],
961 'overview' );
962 my $drag_script = $self->drag_script( 'overview_panels', 'track' );
963 $html .= div(
964 $self->toggle({tight=>1},
965 'Overview',
966 div({ -id => 'overview_panels', -class => 'track', -style=>'margin-bottom:3px; overflow: hidden; margin-left:auto; margin-right:auto; position:relative; width:'.$self->get_image_width($self->state).'px' },
967 $scale_bar_html, $panels_html,
968 ))
969 ) . $drag_script;
970 }
971
972 if ( $section->{'regionview'} and $self->state->{region_size} ) {
973  
974 my $scale_bar_html = $self->scale_bar( $seg, 'region' );
975 my $panels_html = $self->get_blank_panels( [$self->regionview_tracks],
976 'region');
977 my $drag_script = $self->drag_script( 'region_panels', 'track' );
978  
979 $html .= div(
980 $self->toggle({tight=>1},
981 'Region',
982 div({ -id => 'region_panels', -class => 'track',
983 -style=>'margin-bottom:3px; overflow: hidden; margin-left:auto; margin-right:auto; position:relative; width:'.$self->get_image_width($self->state).'px' },
984 $scale_bar_html, $panels_html,
985 )
986 )
987 ) . $drag_script;
988 }
989  
990 if ( $section->{'detailview'} ) {
991 my $scale_bar_html = $self->scale_bar( $seg, 'detail' );
992 my $ruler_html = $self->render_ruler_div;
993 my $panels_html = $self->get_blank_panels( [$self->detail_tracks],
994 'detail');
995 my $drag_script = $self->drag_script( 'detail_panels', 'track' );
996 my $details_msg = span({ -id => 'details_msg', },'');
997 my $clear_hilites = $self->clear_highlights;
998 $html .= div(
999 $self->toggle({tight=>1},
1000 'Details',
1001 div({ -id => 'detail_panels', -class => 'track', -style=>'margin-left:auto; margin-right:auto; position:relative; width:'.$self->get_image_width($self->state).'px' },
1002 $details_msg,
1003 $ruler_html,
1004 $scale_bar_html,
1005 $panels_html,
1006 ),
1007 div({-style=>'text-align:center'},
1008 $self->render_select_track_link,
1009 $clear_hilites,
1010 ),
1011 div($self->html_frag('html4',$self->state))
1012 )
1013 ) . $drag_script;
1014 }
1015 return div({-id=>'panels'},$html);
1016 }
1017  
1018 sub get_post_load_functions {
1019 my $self = shift;
1020 my @fun;
1021 if (my $url = param('eurl')) {
1022 my $trackname = $self->user_tracks->escape_url($url);
1023 push @fun,'Controller.select_tab("custom_tracks_page")';
1024 push @fun,"loadURL('$trackname','$url',true)";
1025 }
1026 return @fun;
1027 }
1028  
1029 sub scale_bar {
1030 my $self = shift;
1031 my $seg = shift;
1032 my $this_section = shift || 'detail';
1033 my $extra_args = shift;
1034  
1035 my $label = '';
1036 my ( $url, $height, $width );
1037 my $renderer = $self->get_panel_renderer($seg);
1038 if ( $this_section eq 'overview' ) {
1039 $label = OVERVIEW_SCALE_LABEL;
1040 ( $url, $height, $width ) = $renderer->render_scale_bar(
1041 section => 'overview',
1042 whole_segment => $self->whole_segment,
1043 segment => $seg,
1044 state => $self->state
1045 );
1046 }
1047 elsif ( $this_section eq 'region' ) {
1048 $label = REGION_SCALE_LABEL;
1049 ( $url, $height, $width ) = $renderer->render_scale_bar(
1050 section => 'region',
1051 region_segment => $self->region_segment,
1052 segment => $seg,
1053 state => $self->state
1054 );
1055 }
1056 elsif ( $this_section eq 'detail' ) {
1057 $label = DETAIL_SCALE_LABEL;
1058 ( $url, $height, $width ) = $renderer->render_scale_bar(
1059 section => 'detail',
1060 segment => $seg,
1061 state => $self->state,
1062 @$extra_args
1063 );
1064 }
1065 my $html = $renderer->wrap_rendered_track(
1066 label => $label,
1067 area_map => [],
1068 width => $width,
1069 height => $height,
1070 url => $url,
1071 status => '',
1072 section => $this_section,
1073 );
1074 $html = $self->wrap_track_in_track_div(
1075 track_name => $label,
1076 track_id => $label,
1077 track_html => $html,
1078 track_type => 'scale_bar',
1079 );
1080 return $html
1081 }
1082  
1083 sub init_database {
1084 my $self = shift;
1085 return $self->db() if $self->db(); # already done
1086  
1087 my $dsn = $self->data_source;
1088 my $db = $dsn->open_database();
1089  
1090 # I don't know what this is for,
1091 # but it was there in gbrowse and looks like an important hack.
1092 eval {$db->biosql->version($self->state->{version})};
1093  
1094 $self->db($db);
1095 $db;
1096 }
1097  
1098 sub name2segments {
1099 my $self = shift;
1100 my $name = shift;
1101 my $search = $self->get_search_object();
1102 my @features = $search->search_features($name);
1103 return map {$search->segment($_)} map {$search->feature2segment($_)} @features;
1104 }
1105  
1106 sub region {
1107 my $self = shift;
1108  
1109 return $self->{region} if $self->{region};
1110  
1111 my $source = $self->data_source;
1112 my $db = $source->open_database();
1113 my $dbid = $source->db2id($db);
1114  
1115 my $region = Bio::Graphics::Browser2::Region->new(
1116 { source => $self->data_source,
1117 state => $self->state,
1118 db => $db,
1119 searchopts => $source->search_options($dbid),
1120 }
1121 ) or die;
1122  
1123 # run any "find" plugins
1124 my $plugin_action = $self->plugin_action || '';
1125 my $current_plugin = $self->current_plugin;
1126 if ($current_plugin
1127 && $plugin_action eq $self->translate('Find')
1128 || lc $plugin_action eq 'find') {
1129 $region->features($self->plugin_find($current_plugin,$self->state->{name}));
1130 }
1131 elsif ($self->state->{ref}) { # a known region
1132 $region->set_features_by_region(@{$self->state}{'ref','start','stop'});
1133 }
1134 elsif (my $features = $self->plugin_auto_find($self->state->{name})) { # plugins with the auto_find() method defined
1135 $region->features($features);
1136 }
1137 else { # a feature search
1138 my $search = $self->get_search_object();
1139 my $features = $search->search_features();
1140 my $max_feats = $self->data_source->global_setting('max keyword results');
1141 if ($features && @$features > $max_feats) {
1142 $max_feats--;
1143 @$features = $max_feats ? # How many search results?
1144 @{$features}[0..$max_feats] # max is > 1
1145 : ($features->[0]); # max is 1
1146 }
1147 if ($@) {
1148 (my $msg = $@) =~ s/\sat.+line \d+//;
1149 $self->error_message($msg);
1150 $self->state->{name} = ''; # to avoid the error again
1151 }
1152 $region->features($features);
1153 }
1154  
1155 $self->plugins->set_segments($region->segments) if $self->plugins;
1156 $self->state->{valid_region} = $region->feature_count > 0;
1157 return $self->{region} = $region;
1158 }
1159  
1160 sub thin_segment {
1161 my $self = shift;
1162 my $state = $self->state;
1163 if (defined $state->{ref}) {
1164 return Bio::Graphics::Feature->new(-seq_id => $state->{ref},
1165 -start => $state->{start},
1166 -end => $state->{stop});
1167 } else {
1168 return $self->segment;
1169 }
1170 }
1171  
1172 sub thin_whole_segment {
1173 my $self = shift;
1174  
1175 my $state = $self->state;
1176 if (defined $state->{ref} && defined $state->{seg_min}) {
1177 return Bio::Graphics::Feature->new(-seq_id => $state->{ref},
1178 -start => $state->{seg_min},
1179 -end => $state->{seg_max});
1180 } else {
1181 return $self->whole_segment;
1182 }
1183 }
1184  
1185 sub thin_region_segment {
1186 my $self = shift;
1187 my $state = $self->state;
1188 my $thin_segment = $self->thin_segment;
1189 my $thin_whole_segment = $self->thin_whole_segment;
1190  
1191 return Bio::Graphics::Browser2::Region->region_segment(
1192 $thin_segment,
1193 $state,
1194 $thin_whole_segment);
1195 }
1196  
1197 sub segment {
1198 my $self = shift;
1199 my $state = $self->state;
1200 my $region = $self->region or return;
1201 return $region->seg;
1202 }
1203  
1204 sub whole_segment {
1205 my $self = shift;
1206  
1207 return $self->{whole_segment}
1208 if exists $self->{whole_segment};
1209  
1210 my $segment = $self->segment;
1211 my $settings = $self->state;
1212 return $self->{whole_segment} =
1213 $self->region->whole_segment($segment,$settings);
1214 }
1215  
1216 sub region_segment {
1217 my $self = shift;
1218 return $self->{region_segment}
1219 if exists $self->{region_segment};
1220  
1221 my $segment = $self->segment;
1222 my $settings = $self->state;
1223 return $self->{region_segment} =
1224 $self->region->region_segment($segment,$settings,$self->whole_segment);
1225 }
1226  
1227 sub get_search_object {
1228 my $self = shift;
1229 return $self->{searchobj} if defined $self->{searchobj};
1230 my $search = Bio::Graphics::Browser2::RegionSearch->new(
1231 { source => $self->data_source,
1232 state => $self->state,
1233 });
1234 $search->init_databases(
1235 param('dbid') ? [param('dbid')]
1236 :()
1237 );
1238 return $self->{searchobj} = $search;
1239 }
1240  
1241 sub segment_length {
1242 my $self = shift;
1243 my $label = shift;
1244 my $segment = $self->segment;
1245 my $region = $self->region_segment;
1246 my $whole = $self->whole_segment;
1247 my $mult = $self->details_mult;
1248 return $self->_segment_length($label,$segment,$region,$whole,$mult);
1249 }
1250  
1251 sub _segment_length {
1252 my $self = shift;
1253 my ($label,$segment,$region,$whole,$mult) = @_;
1254  
1255 my $section = $label
1256 ? Bio::Graphics::Browser2::DataSource->get_section_from_label($label)
1257 : 'detail';
1258  
1259 my $max = eval {$whole->length } || 9999999999;
1260  
1261 my $length = eval {$section eq 'detail' ? ($segment->length+1)/$mult
1262 :$section eq 'region' ? $region->length
1263 :$section eq 'overview' ? $whole->length
1264 : 0} || 0;
1265 $length = int($length+0.5);
1266 return $length > $max ? $max : $length;
1267 }
1268  
1269 # ========================= plugins =======================
1270 sub init_plugins {
1271 my $self = shift;
1272 my $source = $self->data_source->name;
1273 return $PLUGINS{$source} if $PLUGINS{$source} && $self->{'.plugins_inited'}++;
1274  
1275 my @plugin_path = shellwords($self->data_source->globals->plugin_path);
1276  
1277 my $plugins = $PLUGINS{$source} ||= Bio::Graphics::Browser2::PluginSet->new($self->data_source,@plugin_path);
1278 $self->fatal_error("Could not initialize plugins") unless $plugins;
1279 $plugins->configure($self);
1280 $self->plugins($plugins);
1281 $self->load_plugin_annotators();
1282 $plugins;
1283 }
1284  
1285 # for activating plugins
1286 sub plugin_action {
1287 my $self = shift;
1288 my $action;
1289  
1290 # the logic of this is obscure to me, but seems to have to do with activating plugins
1291 # via the URL versus via fill-out forms, which may go through a translation.
1292 if (param('plugin_do')) {
1293 $action = $self->translate(param('plugin_do')) || $self->translate('Go');
1294 }
1295  
1296 $action ||= param('plugin_action');
1297 $action ||= 'find' if param('plugin_find');
1298  
1299 return $action;
1300 }
1301  
1302 sub current_plugin {
1303 my $self = shift;
1304 my $plugin_base = param('plugin') || param('plugin_find') or return;
1305 $self->plugins->plugin($plugin_base);
1306 }
1307  
1308 sub plugin_auto_find {
1309 my $self = shift;
1310 my $search_string = shift;
1311 return if Bio::Graphics::Browser2::Region->is_chromosome_region($search_string);
1312 my (@results,$found_one);
1313 my $plugins = $self->plugins or return;
1314  
1315 for my $plugin ($plugins->plugins) { # not a typo
1316 next unless $plugin->type eq 'finder' && $plugin->can('auto_find');
1317 my $f = $plugin->auto_find($search_string);
1318 next unless $f;
1319 $found_one++;
1320 push @results,@$f;
1321 }
1322 return $found_one ? \@results : undef;
1323 }
1324  
1325 sub plugin_find {
1326 my $self = shift;
1327 my ($plugin,$search_string) = @_;
1328  
1329 my $settings = $self->state;
1330 my $plugin_name = $plugin->name;
1331 my ($results,$keyword) = $plugin->can('auto_find') && defined $search_string
1332 ? $plugin->auto_find($search_string)
1333 : $plugin->find();
1334  
1335 # nothing returned, so plug the keyword into the search box to save user's search
1336 unless ($results && @$results) {
1337 $settings->{name} = $keyword ? $keyword : $self->translate('Plugin_search_2',$plugin_name);
1338 return;
1339 }
1340  
1341 # Write informative information into the search box - not sure if this is the right thing to do.
1342 $settings->{name} = defined($search_string) ? $self->translate('Plugin_search_1',$search_string,$plugin_name)
1343 : $self->translate('Plugin_search_2',$plugin_name);
1344 # do we really want to do this?!!
1345 $self->write_auto($results);
1346 return $results;
1347 }
1348  
1349 # Handle plug-ins that aren't taken care of asynchronously
1350 # http://localhost/cgi-bin/gb2/gbrowse/yeast/?fetch=gff3 gff3 dump as text/plain
1351 # http://localhost/cgi-bin/gb2/gbrowse/yeast/?fetch=save+gff3 gff3 dump as attachment
1352 # http://localhost/cgi-bin/gb2/gbrowse/yeast/?fetch=save+gff3 gff3 dump as attachment
1353 # http://localhost/cgi-bin/gb2/gbrowse/yeast/?fetch=gff3+trackdef gff3 plus trackdefs
1354 # add q=chr:start..end to filter by region (otherwise uses current session)
1355 # add t=track1+track2+track3... to select tracks
1356  
1357 sub handle_gff_dump {
1358 my $self = shift;
1359  
1360 my $gff_action;
1361
1362 # new API
1363 if (my $action = param ('f') || param('fetch')) {
1364 $gff_action = $action;
1365 } elsif ($action = param('gbgff')||param('download_track')) {
1366 $gff_action = 'scan' if $action eq 'scan';
1367 $gff_action = 'datafile' if $action eq '1';
1368 $gff_action = 'save datafile' if $action =~ /save/i;
1369 $gff_action = 'save fasta' if $action =~ /fasta/i;
1370 $gff_action .= " trackdef" if param('s') or param('stylesheet');
1371 }
1372 return unless $gff_action;
1373  
1374 my %actions = map {$_=>1} split /\s+/,$gff_action;
1375  
1376 my $segment = param('q') || param('segment') || undef;
1377  
1378 my @labels = $self->split_labels_correctly(param('l'));
1379 @labels = $self->split_labels((param('type'),param('t'))) unless @labels;
1380 @labels = $self->visible_tracks unless @labels;
1381  
1382 $self->state->{preferred_dump_format} = param('format') if param('format');
1383  
1384 my $dumper = Bio::Graphics::Browser2::TrackDumper->new(
1385 -data_source => $self->data_source(),
1386 -stylesheet => $actions{trackdef} || 'no',
1387 '-dump' => param('d') || undef,
1388 -labels => \@labels,
1389 -segment => $segment || undef,
1390 -mimetype => param('m') || undef,
1391 -format => param('format') || undef,
1392 ) or return 1;
1393  
1394 # so that another user's tracks are added if requested
1395 $self->add_user_tracks($self->data_source,param('uuid')) if param('uuid');
1396  
1397 my @l = @labels;
1398 foreach (@l) {s/[^a-zA-Z0-9_]/_/g};
1399  
1400 my $title = @l ? join('+',@l) : '';
1401 $title .= $title ? "_$segment" : $segment if $segment;
1402 $title ||= $self->data_source->name;
1403  
1404 if ($actions{scan}) {
1405 print header('text/plain');
1406 $dumper->print_scan();
1407 }
1408 else {
1409 $dumper->state($self->state);
1410 my $mime = $dumper->get_file_mime_type;
1411 my $ext = $dumper->get_file_extension;
1412  
1413 if ($actions{save} && ($actions{datafile}||$actions{gff3})) {
1414 print header( -type => $mime,
1415 -content_disposition => "attachment; filename=$title.$ext");
1416 $dumper->print_datafile() ;
1417 }
1418 elsif ($actions{fasta}) {
1419 my $build = $self->data_source->build_id;
1420 $title .= "_$build" if $build;
1421 print header( -type => $mime =~ /x-/ ? 'application/x-fasta' : $mime,
1422 -content_disposition => "attachment; filename=$title.fa");
1423 $dumper->print_fasta();
1424 }
1425 elsif ($actions{datafile}) {
1426 print header( -type => $mime);
1427 $dumper->print_datafile();
1428 } elsif ($actions{trackdef}) {
1429 print header( -type => 'text/plain');
1430 $dumper->print_stylesheet();
1431 } else {
1432 print header( -type => $mime,
1433 -content_disposition => "attachment; filename=$title.$ext");
1434 $dumper->print_datafile() ;
1435 }
1436 }
1437  
1438 return 1;
1439 }
1440  
1441 sub track_filter_plugin {
1442 my $self = shift;
1443 my $plugins = $self->plugins;
1444 my ($filter) = grep {$_->type eq 'trackfilter'} $plugins->plugins;
1445 return $filter;
1446 }
1447  
1448 # track dumper
1449 sub handle_track_dump {
1450 my $self = shift;
1451 my $source = $self->data_source;
1452  
1453 param('show_tracks') or return;
1454 print header('text/plain');
1455
1456 my (%ts,%ds,@labels_to_dump);
1457 if (my @labels = $source->track_source_to_label(shellwords param('ts'))) {
1458 %ts = map {$_=>1} @labels;
1459 }
1460 if (my @labels = $source->data_source_to_label(shellwords param('ds'))) {
1461 %ds = map {$_=>1} @labels;
1462 }
1463 if (param('ts') && param('ds')) { # intersect
1464 @labels_to_dump = grep {$ts{$_}} keys %ds;
1465 } elsif (param('ts') or param('ds')) { #union
1466 @labels_to_dump = (keys %ts,keys %ds);
1467 } else {
1468 @labels_to_dump = $source->labels;
1469 }
1470  
1471 print '#',join("\t",qw(TrackLabel DataSource TrackSource Description)),"\n";
1472 for my $l (@labels_to_dump) {
1473 next if $l =~ /_scale/;
1474 next if $l =~ /(plugin|file):/;
1475 print join("\t",
1476 $l,
1477 $source->setting($l=>'data source'),
1478 $source->setting($l=>'track source'),
1479 $source->setting($l=>'key')),"\n";
1480 }
1481 return 1;
1482 }
1483  
1484 # Handle plug-ins that aren't taken care of asynchronously
1485 sub handle_plugins {
1486 my $self = shift;
1487  
1488 my $plugin_base = param('plugin');
1489 return unless ($plugin_base);
1490  
1491 $self->init_plugins();
1492 my ($id) = $plugin_base =~ /^plugin:(\w+)/;
1493 $id ||= $plugin_base;
1494 my $plugin = $self->plugins->plugin($id);
1495 warn "an operation was requested on plugin $id, but this plugin has not been configured"
1496 unless $plugin;
1497 return unless $plugin;
1498  
1499 my $plugin_type = $plugin->type();
1500  
1501 my $plugin_action = param('plugin_action') || '';
1502  
1503 # for activating the plugin by URL
1504 if ( param('plugin_do') ) {
1505 $plugin_action = $self->translate( param('plugin_do') ) || $self->translate('Go');
1506 }
1507
1508 my $state = $self->state();
1509 my $cookie = $self->create_cookie();
1510  
1511 ### CONFIGURE ###############################################
1512 if ($plugin_action eq $self->translate('Configure')) {
1513 $self->plugin_configuration_form($plugin);
1514 return 1;
1515 }
1516
1517  
1518 ### FIND #####################################################
1519 if ( $plugin_action eq $self->translate('Find') ) {
1520 #$self->do_plugin_find( $state, $plugin_base, $features )
1521 # or ( $plugin_action = 'Configure' ); #reconfigure
1522 return;
1523 }
1524  
1525 ### DUMP #####################################################
1526 # Check to see whether one of the plugin dumpers was invoked. We have to
1527 # do this first before printing the header because the plugins are
1528 # responsible for generating the header. NOTE THE return 1 HERE IF THE
1529 # DUMP IS SUCCESSFUL!
1530  
1531 my $segment = $self->segment();
1532 if ( $plugin_type eq 'dumper'
1533 and $plugin_action eq $self->translate('Go')
1534 and ( $segment
1535 or param('plugin_config')
1536 or $plugin->verb eq ( $self->translate('Import') || 'Import' ) )
1537 )
1538 {
1539 $segment->{start} = param('view_start') || $segment->{start}; # We only care about the segment the user is actually
1540 $segment->{stop} = param('view_stop') || $segment->{stop}; # viewing, not the whole segment that he/she has loaded
1541 $segment->{end} = param('view_stop') || $segment->{end}; #
1542  
1543 my $search = $self->get_search_object();
1544 my $metasegment = $search->segment($segment);
1545 $self->do_plugin_header( $plugin, $cookie );
1546 $self->do_plugin_dump( $plugin, $metasegment, $state )
1547 && return 1;
1548 }
1549  
1550 if ($plugin_type eq 'annotator' && $plugin_action eq $self->translate('Go')) {
1551 warn "HERE I AM";
1552 return 1;
1553 }
1554  
1555 return;
1556 }
1557  
1558 sub do_plugin_header {
1559 my $self = shift;
1560 my $plugin = shift;
1561 my $cookie = shift;
1562  
1563 # Defined in HTML.pm
1564 }
1565  
1566 sub do_plugin_dump {
1567 my $self = shift;
1568 my $plugin = shift;
1569 my $segment = shift;
1570 my $state = shift;
1571 my @additional_feature_sets;
1572  
1573 $plugin->dump( $segment, @additional_feature_sets );
1574 return 1;
1575 }
1576  
1577 #======================== remote sources ====================
1578 sub init_remote_sources {
1579 my $self = shift;
1580 warn "init_remote_sources()" if DEBUG;
1581 my $remote_sources = Bio::Graphics::Browser2::RemoteSet->new($self->data_source,
1582 $self->state,
1583 $self->language,
1584 $self->session->uploadsid,
1585 );
1586 $remote_sources->add_files_from_state;
1587 $self->remote_sources($remote_sources);
1588 return $remote_sources;
1589 }
1590  
1591 # this generates the form that is sent to Galaxy
1592 # defined in HTML.pm
1593 sub render_galaxy_form {
1594 my $self = shift;
1595 my $seg = shift;
1596 $self->wrap_in_div('galaxy_form',
1597 $self->galaxy_form($seg));
1598 }
1599  
1600 # to be inherited
1601 sub galaxy_form { }
1602  
1603 sub delete_uploads {
1604 my $self = shift;
1605 my $userdata = $self->user_tracks;
1606 my @files = $userdata->tracks;
1607 for my $file (@files) {
1608 my @tracks = $userdata->labels($file);
1609 $userdata->delete_file($file);
1610 $self->remove_track_from_state($_) foreach @tracks;
1611 }
1612 $self->data_source->clear_usertracks();
1613 }
1614  
1615 sub cleanup {
1616 my $self = shift;
1617 warn "cleanup()" if DEBUG;
1618 $self->plugins->destroy;
1619 my $state = $self->state;
1620 $state->{name} = $self->region_string if $state->{ref}; # to remember us by :-)
1621 }
1622  
1623 sub add_remote_tracks {
1624 my $self = shift;
1625 my $urls = shift;
1626  
1627 my $user_tracks = $self->user_tracks;
1628  
1629 warn "ADD_REMOTE_TRACKS(@$urls)" if DEBUG;
1630  
1631 my @tracks;
1632  
1633 for my $url (@$urls) {
1634 my $name = $user_tracks->create_track_folder($url);
1635 my ($result,$msg,$tracks)
1636 = $user_tracks->mirror_url($name,$url,1,$self);
1637 warn "[$$] $url: result=$result, msg=$msg, tracks=@$tracks" if DEBUG;
1638 push @tracks,@$tracks;
1639 }
1640  
1641 push @tracks,$self->add_user_tracks($self->data_source);
1642 warn "[$$] adding tracks @tracks" if DEBUG;
1643 $self->add_track_to_state($_) foreach @tracks;
1644 $self->init_remote_sources();
1645 }
1646  
1647 sub write_auto {
1648 my $self = shift;
1649 my $features = shift;
1650 my $styles = shift;
1651 my $setting = $self->state();
1652 return unless @$features;
1653  
1654 my $user_tracks = $self->user_tracks;
1655  
1656 # ideally we should fork here and pass our child's STDOUT
1657 # to $user_tracks->upload_file(), but I'm scared...
1658 # So we create the file in core.
1659 my $feature_file = '';
1660  
1661 $styles ||= [];
1662 for my $style (@$styles) {
1663 my ( $type, @options ) = shellwords($style);
1664 $feature_file .= "[$type]\n";
1665 $feature_file .= join "\n", @options;
1666 $feature_file .= "\n";
1667 }
1668  
1669 my %seenit;
1670 for my $f (@$features) {
1671 my $reference = $f->can('seq_id') ? $f->seq_id : $f->seq_id;
1672 my $type = $f->primary_tag;
1673 my $name = $f->seqname;
1674 my $position
1675 = $f->sub_SeqFeature
1676 ? join( ',',
1677 map { $_->start . '..' . $_->end } $f->sub_SeqFeature )
1678 : $f->start . '..' . $f->end;
1679 $name .= "($seenit{$name})" if $seenit{$name}++;
1680 $feature_file .= "\nreference=$reference\n";
1681 $feature_file .= join( "\t", qq("$type"), qq("$name"), $position ). "\n";
1682 }
1683  
1684 my ($result,$msg,$tracks)
1685 = $user_tracks->upload_data('My Track',$feature_file,'text/plain','overwrite');
1686 warn $msg unless $result;
1687  
1688 $self->add_user_tracks($self->data_source);
1689 $self->add_track_to_state($_) foreach @$tracks;
1690 }
1691  
1692 sub handle_download_userdata {
1693 my $self = shift;
1694 my $ftype = param('userdata_download') or return;
1695 my $file = param('track') or return;
1696  
1697 my $userdata = $self->user_tracks;
1698 my $download = $ftype eq 'conf' ? $userdata->track_conf($file)
1699 : $userdata->data_path($file, $ftype);
1700  
1701 my $fname = basename($download);
1702 my $is_text = -T $download;
1703  
1704 print CGI::header(-attachment => $fname,
1705 -charset => $self->translate('CHARSET'), # 'US-ASCII' ?
1706 -type => $is_text ? 'text/plain' : 'application/octet-stream');
1707  
1708 my $f = $ftype eq 'conf' ? $userdata->conf_fh($file)
1709 : IO::File->new($download);
1710 $f or croak "$download: $!";
1711  
1712 if ($is_text) {
1713 # try to make the file match the native line endings
1714 # not necessary?
1715 my $eol = $self->guess_eol();
1716 while (<$f>) {
1717 # print;
1718 s/[\r\n]+$//;
1719 print $_,$eol;
1720 }
1721 } else {
1722 my $buffer;
1723 while (read($f,$buffer,1024)) {
1724 print $buffer;
1725 }
1726 }
1727 close $f;
1728 return 1;
1729 }
1730  
1731 sub guess_eol {
1732 my $self = shift;
1733 my $agent = CGI->user_agent;
1734 return "\012" if $agent =~ /linux/i;
1735 return "\015" if $agent =~ /macintosh/i;
1736 return "\015\012" if $agent =~ /windows/i;
1737 return "\n"; # default
1738 }
1739  
1740 sub handle_quickie {
1741 my $self = shift;
1742 my $data = shift;
1743 my $styles = shift;
1744 return unless $data;
1745  
1746 # format of quickie data is
1747 # reference+type+name+start..end,start..end,start..end
1748 my @features;
1749 foreach my $d (@$data) {
1750 my ( $reference, $type, $name, @segments )
1751 = $self->parse_feature_str($d);
1752 push @features,
1753 Bio::Graphics::Feature->new(
1754 -ref => $reference || '',
1755 -type => $type || '',
1756 -name => $name || '',
1757 -segments => \@segments,
1758 );
1759 }
1760 $self->write_auto( \@features, $styles );
1761 }
1762  
1763 sub parse_feature_str {
1764 my $self = shift;
1765 my $f = shift;
1766 my ( $reference, $type, $name, @position );
1767 my @args = shellwords( $f || '' );
1768 if ( @args > 3 ) {
1769 ( $reference, $type, $name, @position ) = @args;
1770 }
1771 elsif ( @args > 2 ) {
1772 ( $reference, $name, @position ) = @args;
1773 }
1774 elsif ( @args > 1 ) {
1775 ( $reference, @position ) = @args;
1776 }
1777 elsif ( $f =~ /^(.+):(\d+.+)$/ ) {
1778 ( $reference, @position ) = ( $1, $2 );
1779 }
1780 elsif ( $f =~ /^(.+)/ ) {
1781 $reference = $1;
1782 @position = '1..1';
1783 }
1784 return unless $reference;
1785  
1786 $type = 'region' unless defined $type;
1787 $name = "Feature " . ++$self->{added_features} unless defined $name;
1788  
1789 my @segments
1790 = map { [/(-?\d+)(?:-|\.\.)(-?\d+)/] } map { split ',' } @position;
1791 ( $reference, $type, $name, @segments );
1792 }
1793  
1794 ###################################################################################
1795 #
1796 # SETTINGS CODE HERE
1797 #
1798 ###################################################################################
1799  
1800 sub globals {
1801 my $self = shift;
1802 $self->data_source->globals;
1803 }
1804  
1805 # the setting method either calls the DATA_SOURCE's global_setting or setting(), depending
1806 # on the number of arguments used.
1807 sub setting {
1808 my $self = shift;
1809 my $data_source = $self->data_source;
1810  
1811 if (@_ == 1) {
1812 return $data_source->global_setting(@_);
1813 }
1814  
1815 else {
1816 # otherwise we get the data_source-specific settings
1817 return $data_source->setting(@_);
1818 }
1819 }
1820  
1821 =head2 plugin_setting()
1822  
1823 $value = = $browser->plugin_setting("option_name");
1824  
1825 When called in the context of a plugin, returns the setting for the
1826 requested option. The option must be placed in a [PluginName:plugin]
1827 configuration file section:
1828  
1829 [MyPlugin:plugin]
1830 foo = bar
1831  
1832 Now within the MyPlugin.pm plugin, you may call
1833 $browser->plugin_setting('foo') to return value "bar".
1834  
1835 =cut
1836  
1837 sub plugin_setting {
1838 my $self = shift;
1839 my $caller_package = caller();
1840 my ($last_name) = $caller_package =~ /(\w+)$/;
1841 my $option_name = "${last_name}:plugin";
1842 $self->setting($option_name => @_);
1843 }
1844  
1845 # dealing with external DAS sources?
1846 sub get_external_presets {
1847 my $self = shift;
1848 my $presets = $self->setting('remote sources') or return;
1849 my @presets = shellwords($presets||'');
1850 my (@labels,@urls);
1851 while (@presets) {
1852 my ($label,$url) = splice(@presets,0,2);
1853 next unless $url && $url =~ /^(http|ftp)/;
1854 push @labels,$label;
1855 push @urls,$url;
1856 }
1857 return unless @labels;
1858 return (\@labels,\@urls) if wantarray;
1859 my %presets;
1860 @presets{@urls} = @labels;
1861 return \%presets;
1862 }
1863  
1864 ##################################################################3
1865 #
1866 # AUTHENTICATION
1867 #
1868 ##################################################################3
1869 sub force_authentication {
1870 my $self = shift;
1871  
1872 # asynchronous event -- only allow the ones needed for authentication
1873 if (Bio::Graphics::Browser2::Action->is_authentication_event) {
1874 $self->run_asynchronous_event;
1875 $self->session->unlock;
1876 return;
1877 }
1878  
1879 if (param('action')) {
1880 print CGI::header(-status => '403 Forbidden');
1881 return;
1882 }
1883  
1884 # render main page
1885 $self->init();
1886 $self->render_header();
1887  
1888 my $confirm = param('confirm') || param('openid_confirm');
1889  
1890 my $action;
1891 if ($self->data_source->auth_plugin) {
1892 $action = "GBox.showTooltip(event,'url:?action=plugin_login',true)";
1893 } else {
1894 $action = $self->login_manager->login_script();
1895 }
1896 $action .= ";login_blackout(true,'')";
1897  
1898 my $output = $self->render_html_start('GBrowse Login Required',
1899 $self->get_post_load_functions,
1900 ($confirm ? '' : $action));
1901 $output .= div({-id=>'source_form'},$self->source_form());
1902 if ($confirm) {
1903 $output .= $self->login_manager->render_confirm;
1904 } else {
1905 $output .= $self->render_login_required($action);
1906 }
1907 $output .= "<hr>";
1908 $output .= $self->render_bottom();
1909 print $output;
1910 }
1911  
1912 ##################################################################3
1913 #
1914 # STATE CODE HERE
1915 #
1916 ##################################################################3
1917  
1918 sub set_default_state {
1919 my $self = shift;
1920 my $state = $self->state;
1921 $self->default_state if !$state->{tracks} # always set in one form or another
1922 or param('reset');
1923 }
1924  
1925 sub update_state {
1926 my $self = shift;
1927 warn "[$$] update_state()" if DEBUG;
1928 return if param('gbgff'); # don't let gbgff requests update our coordinates!!!
1929 # return if url() =~ /gbrowse_img/; # don't let gbrowse_img requests update our coordinates either!!
1930 $self->_update_state;
1931 }
1932  
1933 sub _update_state {
1934 my $self = shift;
1935  
1936 my $state = $self->state;
1937  
1938 $self->update_state_from_cgi;
1939 warn "[$$] CGI updated" if DEBUG;
1940 if (my $seg = $self->segment) {
1941 # A reset won't have a segment, so we need to test for that before we use
1942 # one in whole_segment().
1943 my $whole_segment = $self->whole_segment;
1944 $state->{seg_min} = $whole_segment->start;
1945 $state->{seg_max} = $whole_segment->end;
1946
1947 $state->{ref} ||= $seg->seq_id;
1948 $state->{view_start} ||= $seg->start; # The user has selected the area that they want to see. Therefore, this
1949 $state->{view_stop} ||= $seg->end; # will be the view_start and view_stop, rather than just start and stop.
1950 # asynchronous_update_coordinates will multiply this by the correct factor
1951 # to find the size of the segment to load
1952  
1953 $state->{start} ||= $seg->start; # Set regular start and stop as well, just to be safe
1954 $state->{stop} ||= $seg->end; #
1955
1956 # Automatically open the tracks with found features in them
1957 $self->auto_open();
1958 }
1959 $self->cleanup_dangling_uploads($state);
1960 warn "[$$] update_state() done" if DEBUG;
1961 }
1962  
1963 sub default_state {
1964 my $self = shift;
1965 my $state = $self->state;
1966 my $data_source = $self->data_source;
1967 %$state = ();
1968 @$state{'name','ref','start','stop','flip','version'} = ('','','','','',100);
1969 $state->{width} = $self->setting('default width');
1970 $state->{source} = $data_source->name;
1971 $state->{cache} = $data_source->cache_time>0;
1972 $state->{region_size} = $self->setting('region segment');
1973 $state->{'max segment'}= $self->setting('max segment');
1974 $state->{v} = VERSION;
1975 $state->{stp} = 1;
1976 $state->{ins} = 1;
1977 $state->{head} = 1;
1978 $state->{show_tooltips}= 1;
1979 $state->{ks} = 'between';
1980 $state->{grid} = 1;
1981 $state->{sk} = $self->setting("default varying") ? "unsorted" : "sorted";
1982  
1983 # if no name is specified but there is a "initial landmark" defined in the
1984 # config file, then we default to that.
1985 $state->{name} ||= $self->setting('initial landmark')
1986 if defined $self->setting('initial landmark');
1987  
1988 $self->default_tracks();
1989 $self->default_category_open();
1990 $self->session->unlock();
1991 }
1992  
1993 sub default_category_open {
1994 my $self = shift;
1995 my $state = $self->state;
1996  
1997 my $categories = $self->data_source->category_open;
1998 for my $c (keys %$categories) {
1999 $state->{section_visible}{$c} = $categories->{$c};
2000 }
2001 }
2002  
2003 sub default_tracks {
2004 my $self = shift;
2005 my $state = $self->state;
2006 # my @labels = $self->data_source->labels;
2007 my @labels = $self->potential_tracks;
2008  
2009 $state->{tracks} = \@labels;
2010  
2011 $state->{features}{$_} = {visible=>0,options=>0,limit=>0}
2012 foreach @labels;
2013 $state->{features}{$_}{visible} = 1
2014 foreach $self->data_source->default_labels;
2015  
2016 # set collapse state here
2017 my $source = $self->data_source;
2018 for my $label (@labels) {
2019 my $visibility = $source->setting($label => 'visible');
2020 next unless defined $visibility;
2021 $visibility = lc $visibility;
2022 $state->{features}{$label}{visible} = 1 if $visibility eq 'show'
2023 or $visibility eq 'collapse';
2024 $state->{features}{$label}{visible} = 0 if $visibility eq 'hide';
2025 $state->{track_collapsed}{$label} = 1 if $visibility eq 'collapse';
2026 }
2027 }
2028  
2029 # Open Automatically the tracks with features in them
2030 sub auto_open {
2031 my $self = shift;
2032 my $features = $self->region()->features() || return;
2033 @$features <= 1 or return; # don't autoopen multiple hits!!
2034 my $state = $self->state;
2035  
2036 for my $feature (@$features) {
2037 # the next step optimizes away the case in which the feature type
2038 # is a chromosome region
2039 next if $feature->type eq 'region' || $feature->type eq 'segment';
2040  
2041 my @desired_labels = $self->data_source()->feature2label($feature);
2042 @desired_labels || next ;
2043 warn "desired labels = @desired_labels" if DEBUG;
2044 for my $desired_label (@desired_labels) {
2045 warn "auto_open(): add_track_to_state($desired_label)" if DEBUG;
2046 $self->add_track_to_state($desired_label);
2047 $state->{h_feat} = {};
2048 my $h_color = $self->data_source->global_setting('hilite color') || 'yellow';
2049 $state->{h_feat}{ lc $feature->display_name } = $h_color
2050 unless param('h_feat') && param('h_feat') eq '_clear_';
2051 }
2052 }
2053 }
2054  
2055 # remove upload markers that are no longer relevant
2056 sub cleanup_dangling_uploads {
2057 my $self = shift;
2058 my $state = shift;
2059
2060 my %name_to_id;
2061 for my $id (keys %{$state->{uploads}}) {
2062 unless ($state->{uploads}{$id}[0]) {
2063 delete $state->{uploads}{$id};
2064 next;
2065 }
2066 $name_to_id{$state->{uploads}{$id}[0]}{$id}++;
2067 }
2068  
2069 my $usertracks = $self->user_tracks;
2070 my %tracks = map {$_=>1} $usertracks->tracks();
2071  
2072 for my $k (keys %name_to_id) {
2073 unless (exists $tracks{$k}) {
2074 delete $state->{uploads}{$_} foreach keys %{$name_to_id{$k}};
2075 }
2076 }
2077  
2078 }
2079  
2080 sub add_track_to_state {
2081 my $self = shift;
2082 my $label = shift;
2083 my $state = $self->state;
2084  
2085 warn '[',Bio::Graphics::Browser2::Session->time,'] ',"[$$] add_track_to_state($label)" if DEBUG;
2086  
2087 return unless length $label; # refuse to add empty tracks!
2088  
2089 # don't add invalid track
2090 my %potential_tracks = map {$_=>1} $self->potential_tracks;
2091 warn "invalid track $label" if DEBUG && !$potential_tracks{$label};
2092 return unless $potential_tracks{$label};
2093  
2094 # my %current = map {$_=> 1} @{$state->{tracks}};
2095 # unshift @{$state->{tracks}},$label unless $current{$label}; # on top (better)
2096  
2097 # experimental -- force track to go to top
2098 @{$state->{tracks}} = grep {$_ ne $label} @{$state->{tracks}};
2099 unshift @{$state->{tracks}},$label;
2100  
2101 warn "[$$]ADD TRACK TO STATE WAS: ",
2102 join ' ',grep {$state->{features}{$_}{visible}} sort keys %{$state->{features}},"\n" if DEBUG;
2103  
2104 if ($state->{features}{$label}) {
2105 $state->{features}{$label}{visible}=1;
2106 }
2107 else{
2108 $state->{features}{$label}{visible} = {visible=>1,options=>0,limit=>0};
2109 }
2110  
2111 warn "[$$] ADD TRACK TO STATE NOW: ",
2112 join ' ',grep {$state->{features}{$_}{visible}} sort keys %{$state->{features}},"\n" if DEBUG;
2113 }
2114  
2115 sub remove_track_from_state {
2116 my $self = shift;
2117 my $label = shift;
2118 warn '[',Bio::Graphics::Browser2::Session->time,'] ',"[$$] remove_track_from_state($label)" if DEBUG;
2119 delete $self->state->{features}{$label};
2120 }
2121  
2122 sub track_visible {
2123 my $self = shift;
2124 my $label = shift;
2125 return $self->state->{features}{$label}{visible};
2126 }
2127  
2128 sub update_state_from_cgi {
2129 my $self = shift;
2130 my $state = $self->state;
2131 warn "state = $state" if DEBUG;
2132 $self->update_options($state);
2133 $self->update_coordinates($state);
2134 $self->update_region($state);
2135  
2136 if (param('revert')) {
2137 $self->default_tracks($state);
2138 }
2139 else {
2140 $self->remove_invalid_tracks($state);
2141 $self->update_tracks($state);
2142 }
2143  
2144 $self->update_section_visibility($state);
2145 $self->update_galaxy_url($state);
2146 }
2147  
2148 sub create_subtrack_manager {
2149 my $self = shift;
2150 my $label = shift;
2151 my $source = shift || $self->data_source;
2152 my $state = shift || $self->state;
2153
2154 my ($dimensions,$rows,$aliases)
2155 = Bio::Graphics::Browser2::SubtrackTable->infer_settings_from_source($source,$label)
2156 or return;
2157  
2158 my $key = $source->setting($label => 'key');
2159 my $selected = $state->{subtracks}{$label};
2160 my $comment = $source->setting($label => 'brief comment');
2161  
2162 my $stt = Bio::Graphics::Browser2::SubtrackTable->new(-columns=>$dimensions,
2163 -rows =>$rows,
2164 -label => $label,
2165 -key => $key||$label,
2166 -aliases => $aliases,
2167 -comment => $comment);
2168 $stt->set_selected($selected) if $selected;
2169 eval {$stt->overlap(($state->{features}{$label}{options}||0)==4)}; # options == 4 means "overlap", for legacy reasons
2170 return $stt;
2171 }
2172  
2173 # Handle returns from the track configuration form
2174 sub reconfigure_track {
2175 my $self = shift;
2176  
2177 my $q = shift; # CGI object
2178 my $label = shift;
2179  
2180 my $state = $self->state();
2181 my $source = $self->data_source;
2182  
2183 $state->{features}{$label}{options} = $q->param('format_option');
2184 my $dynamic = $self->translate('DYNAMIC_VALUE');
2185 my $mode = $q->param('mode') || 'details';
2186  
2187 my $length = ($q->param('segment_length')||0);
2188 my $semantic_low = ($q->param('apply_semantic_low')||0);
2189 my $semantic_hi = ($q->param('apply_semantic_hi')||0) || $self->get_max_segment;
2190 my $delete_semantic = $q->param('delete_semantic');
2191 my $summary = $q->param('summary_mode');
2192  
2193 $state->{features}{$label}{summary_mode_len} = $summary if defined $summary;
2194  
2195 ($semantic_low,$semantic_hi) = ($semantic_hi,$semantic_low) if $semantic_low > $semantic_hi;
2196 $self->clip_override_ranges($state->{features}{$label}{semantic_override},
2197 $semantic_low,
2198 $semantic_hi)
2199 if $length;
2200  
2201 my $o = $mode eq 'summary' ? $state->{features}{$label}{summary_override} ||= {}
2202 : $state->{features}{$label}{semantic_override}{"$semantic_low:$semantic_hi"} ||= {};
2203  
2204 my $glyph = $q->param('conf_glyph') || '';
2205 for my $s ( grep {/^conf_/} $q->param()) {
2206 my @values = $q->param($s);
2207 my $value = $values[-1]; # last one wins
2208 $s =~ s/^conf_//;
2209 next unless defined $value;
2210  
2211 if ($s =~ /(\w+)_subtype/) {
2212 next unless $1 eq $glyph;
2213 $s = 'glyph_subtype';
2214 }
2215 elsif ($s =~ /(\w+)_graphtype/) {
2216 next unless $1 eq $glyph;
2217 $s = 'graph_type';
2218 } elsif ($s =~ /(\w+)_autoscale/) {
2219 my $g = $1;
2220 next if $g eq 'wiggle' && $glyph !~ /wiggle|vista|hybrid/;
2221 next if $g eq 'xyplot' && $glyph !~ /xyplot|density|hybrid/;
2222 $s = 'autoscale';
2223 }
2224  
2225 # semantic setting for this configured length
2226 my $configured_value = $source->semantic_fallback_setting($label=>$s,$semantic_low+1);
2227  
2228 if ($value eq $dynamic) {
2229 delete $o->{$s};
2230 } elsif ($s eq 'bicolor_pivot' && $value eq 'value') {
2231 my $bp = $q->param('bicolor_pivot_value');
2232 $o->{$s} = $bp if !defined $configured_value or $bp != $configured_value;
2233 } else {
2234 $o->{$s} = $value if !defined $configured_value or !defined $o->{$s} or $value ne $configured_value;
2235 if ($glyph eq 'wiggle_whiskers') {# workarounds for whisker options
2236 $o->{"${s}_neg"} = $value if $s =~ /^(mean_color|stdev_color)/;
2237 $o->{min_color} = $value if $s eq 'max_color';
2238 }
2239 }
2240 }
2241 if (defined $o->{autoscale} && $o->{autoscale}=~/local|global|chromosome/) {
2242 undef $o->{min_score};
2243 undef $o->{max_score}
2244 }
2245 }
2246  
2247 # low hi
2248 # <---------------------> current
2249 # <-----------> A
2250 # <-------------> B
2251 # <---------------------------------------------> C
2252 # <---------> D
2253 #
2254 sub clip_override_ranges {
2255 my $self = shift;
2256 my ($semconf,$low,$hi) = @_;
2257  
2258 # legacy representation of bounds
2259 for my $k (keys %$semconf) {
2260 unless ($k =~ /:/) {
2261 $semconf->{"$k:999999999"} = $semconf->{$k};
2262 delete $semconf->{$k};
2263 }
2264 }
2265  
2266 my @ranges = map {
2267 my ($l,$h) = split ':';
2268 $l ||= 0;
2269 $h ||= 1_000_000_000;
2270 [$l,$h];
2271 } keys %$semconf;
2272 @ranges = sort {$a->[0]<=>$b->[0]} @ranges;
2273 for my $r (@ranges) {
2274 my $key = "$r->[0]:$r->[1]";
2275 my $conf = $semconf->{$key};
2276 delete $semconf->{$key};
2277 my $overlap;
2278  
2279 if ($r->[0] <= $low && $r->[1] >= $hi) { # case C
2280 $semconf->{$r->[0] . ':' . ($low-1)} = $conf unless $r->[0] >= $low-1;
2281 $semconf->{$hi . ':' . $r->[1] } = $conf unless $hi >= $r->[1];
2282 $overlap++;
2283 }
2284  
2285 if ($r->[0] > $low && $r->[1] < $hi) { # case D
2286 $overlap++;
2287 # delete
2288 }
2289
2290 if ($r->[1] >= $low && $r->[0] <= $low) { # case A
2291 $r->[1] = $low-1;
2292 $semconf->{"$r->[0]:$r->[1]"} = $conf
2293 unless $r->[0] >= $r->[1];
2294 $overlap++;
2295 }
2296  
2297 if ($r->[1] >= $hi && $r->[0] <= $hi) { # case B
2298 $r->[0] = $hi;
2299 $semconf->{"$r->[0]:$r->[1]"} = $conf
2300 unless $r->[0] >= $r->[1];
2301 $overlap++;
2302 }
2303  
2304 unless ($overlap) {
2305 $semconf->{$key} = $conf;
2306 }
2307 }
2308 }
2309  
2310 sub find_override_bounds {
2311 my $self = shift;
2312 my ($semconf,$length) = @_;
2313 my @ranges = sort {$a->[0]<=>$b->[0]}
2314 map { my @a = split ':';
2315 \@a
2316 } keys %$semconf;
2317 my ($low,$hi);
2318 for my $r (@ranges) {
2319 next unless @$r == 2;
2320 if ($length >= $r->[0] && $length < $r->[1]) {
2321 return @$r;
2322 }
2323 $low = $r->[1]+1 if $r->[1] < $length;
2324 $hi = $r->[0]-1 if $r->[0] > $length;
2325 }
2326 return ($low,$hi);
2327 }
2328  
2329 sub find_override_region {
2330 my $self = shift;
2331 my ($semconf,$length) = @_;
2332 my @ranges = keys %$semconf;
2333 for my $r (@ranges) {
2334 my ($low,$hi) = split ':',$r;
2335 return $r if $length >= $low && (!defined $hi || $length < $hi);
2336 }
2337 return;
2338 }
2339  
2340 sub update_options {
2341 my $self = shift;
2342 my $state = shift || $self->state;
2343 my $data_source = shift || $self->data_source;
2344  
2345 # return unless param('width'); # not submitted
2346 $state->{width} ||= $self->setting('default width'); # working around a bug during development
2347  
2348 $state->{grid} = 1 unless exists $state->{grid}; # to upgrade from older settings
2349 $state->{flip} = 0; # obnoxious for this to persist
2350  
2351 $state->{version} ||= param('version') || '';
2352 do {$state->{$_} = param($_) if defined param($_) }
2353 foreach qw(name source plugin stp ins head ks sk version
2354 grid flip width region_size show_tooltips cache
2355 );
2356  
2357 if (my @features = shellwords(param('h_feat'))) {
2358 $state->{h_feat} = {};
2359 for my $hilight (@features) {
2360 last if $hilight eq '_clear_';
2361 my ($featname,$color) = split '@',$hilight;
2362 $state->{h_feat}{lc $featname} = $color || 'yellow';
2363 }
2364 }
2365  
2366 if (my @regions = shellwords(param('h_region'))) {
2367 $state->{h_region} = [];
2368 foreach (@regions) {
2369 last if $_ eq '_clear_';
2370 $_ = "$state->{ref}:$_" unless /^[^:]+:-?\d/; # add reference if not there
2371 push @{$state->{h_region}},$_;
2372 }
2373 }
2374  
2375 # Process the magic "q" parameter, which overrides everything else.
2376 if (my @q = param('q')) {
2377 delete $state->{$_} foreach qw(name ref h_feat h_region);
2378 $state->{q} = [map {split /[+-]/} @q];
2379 }
2380  
2381 else {
2382 $state->{name} ||= '';
2383 $state->{name} =~ s/^\s+//; # strip leading
2384 $state->{name} =~ s/\s+$//; # and trailing whitespace
2385 }
2386 $self->session->modified;
2387 }
2388  
2389 sub update_tracks {
2390 my $self = shift;
2391 my $state = shift;
2392  
2393 if (my @add = param('add')) {
2394 my @style = param('style');
2395 $self->handle_quickie(\@add,\@style);
2396 }
2397  
2398 # selected tracks can be set by the 'l', 'label' or 't' parameter
2399 # the preferred parameter is 'l', because it implements correct
2400 # semantics for the label separator
2401 if (my @l = param('l')) {
2402 $self->set_tracks($self->split_labels_correctly(@l));
2403 }
2404 elsif (@l = param('label')) {
2405 $self->set_tracks($self->split_labels(@l));
2406 } #... the 't' parameter
2407 elsif (my @t = param('t')) {
2408 $self->set_tracks($self->split_labels(@t));
2409 } #... the 'ds' (data source) or the 'ts' (track source) parameter
2410 elsif ((my @ds = shellwords param('ds')) || (my @ts = shellwords param('ts'))) {
2411 my @main_l = @ds ? $self->data_source->data_source_to_label(@ds) : $self->data_source->track_source_to_label(@ts);
2412 if (!@ds && @ts) {
2413 my %ds = ();
2414 foreach my $label (@main_l) {
2415 my @tracks = grep {!/^#/} shellwords $self->setting($label=>'track source');
2416 my @datasr = grep {!/^#/} shellwords $self->setting($label=>'data source');
2417  
2418 for (my $i = 0; $i <@tracks; $i++) {
2419 map{$ds{$datasr[$i]}++ if $_ == $tracks[$i] && $datasr[$i]} (@ts);
2420 }
2421 }
2422 @ds = keys %ds;
2423 }
2424  
2425 foreach my $label (@main_l) {
2426 my @subs = grep {!/^#/} shellwords $self->setting($label=>'select');
2427 shift @subs;
2428
2429 my @matched;
2430 foreach my $s (@subs) {
2431 map {push(@matched,$`) if ($s=~/\D(\d+)\;*$/i && $1 == $_)} @ds;
2432 map {s/\s*//} @matched; #**
2433 }
2434 $label.="/".join("+",@matched) if @matched;
2435 }
2436
2437 $self->set_tracks(@main_l);
2438 }
2439
2440 if (my @selected = $self->split_labels_correctly(param('enable'))) {
2441 $self->add_track_to_state($_) foreach @selected;
2442 }
2443
2444 if (my @selected = $self->split_labels_correctly(param('disable'))) {
2445 $self->remove_track_from_state($_) foreach @selected;
2446 }
2447
2448 }
2449  
2450 # update coordinates logic
2451 # 1. A fresh session will have a null {ref,start,stop} state, a previous session will have {ref,start,stop,seg_min,seg_max} defined
2452 # 2. If param('ref'),param('start') and param('stop') are defined, or if param('q') is defined, then we
2453 # reset {ref,start,stop}
2454 # 3. Otherwise, if {ref,start,stop} are defined, then
2455 # 2a. interrogate param('span'). If span != (stop-start+1) then user has changed the zoom popup menu and we do a zoom.
2456 # 2b. interrogate /left|right|zoom|nav|regionview|overview/, which define the various zoom and scroll buttons.
2457 # If any of them exist, then we do the appropriate coordinate adjustment
2458 # 3. If we did NOT change the coordinates, then we look for param('name') and use that to set the coordinates
2459 # using a database search.
2460 # 4. set {name} to "ref:start..stop"
2461  
2462 sub update_coordinates {
2463 my $self = shift;
2464 my $state = shift || $self->state;
2465  
2466 delete $self->{region}; # clear cached region
2467 my $position_updated;
2468  
2469 if (param('ref')) {
2470 $state->{ref} = param('ref');
2471 $state->{view_start} = param('start') if defined param('start') && param('start') =~ /^[\d-]+/;
2472 $state->{view_stop} = param('stop') if defined param('stop') && param('stop') =~ /^[\d-]+/;
2473 $state->{view_stop} = param('end') if defined param('end') && param('end') =~ /^[\d-]+/;
2474 $position_updated++;
2475 }
2476  
2477 # quench uninit variable warning
2478 my $current_span = length($state->{view_stop}||'') ? ($state->{view_stop} - $state->{view_start} + 1)
2479 : 0;
2480 my $new_span = param('span');
2481 if ($new_span && $current_span != $new_span) {
2482 $self->zoom_to_span($state,$new_span);
2483 $position_updated++;
2484 }
2485 elsif (my ($scroll_data) = grep {/^(?:left|right) \S+/} param()) {
2486 $self->scroll($state,$scroll_data);
2487 $position_updated++;
2488 }
2489 elsif (my ($zoom_data) = grep {/^zoom (?:out|in) \S+/} param()) {
2490 $self->zoom($state,$zoom_data);
2491 $position_updated++;
2492 }
2493 elsif (my $position_data = param('overview.x')) {
2494 $self->position_from_overview($state,$position_data);
2495 $position_updated++;
2496 }
2497 elsif ($position_data = param('regionview.x')) {
2498 $self->position_from_regionview($state,$position_data);
2499 $position_updated++;
2500 }
2501  
2502 if ($position_updated) { # clip and update param
2503 if (defined $state->{seg_min} && $state->{view_start} < $state->{seg_min}) {
2504 my $delta = $state->{seg_min} - $state->{view_start};
2505 $state->{view_start} += $delta;
2506 $state->{view_stop} += $delta;
2507 }
2508  
2509 if (defined $state->{seg_max} && $state->{view_stop} > $state->{seg_max}) {
2510 my $delta = $state->{view_stop} - $state->{seg_max};
2511 $state->{view_start} -= $delta;
2512 $state->{view_stop} -= $delta;
2513 }
2514  
2515 # Take details multiplier into account
2516 $self->update_state_from_details_mult;
2517  
2518 # update our "name" state and the CGI parameter
2519 $state->{name} = $self->region_string;
2520 param(name => $state->{name});
2521  
2522 warn "name = $state->{name}" if DEBUG;
2523 }
2524  
2525 elsif (param('name') || param('q')) {
2526 $state->{backup_region} =
2527 [$state->{ref},$state->{start},$state->{stop},$state->{view_start},$state->{view_stop}] if $state->{ref};
2528 undef $state->{ref}; # no longer valid
2529 undef $state->{start};
2530 undef $state->{stop};
2531 undef $state->{view_start};
2532 undef $state->{view_stop};
2533 $state->{name} = $state->{search_str} = param('name') || param('q');
2534 $state->{dbid} = param('dbid'); # get rid of this
2535 }
2536 }
2537  
2538 sub asynchronous_update_overview_scale_bar {
2539 my $self = shift;
2540 my $seg = $self->segment;
2541  
2542 my $renderer = $self->get_panel_renderer($seg);
2543 my ( $url, $height, $width ) = $renderer->render_scale_bar(
2544 section => 'overview',
2545 whole_segment => $self->whole_segment,
2546 segment => $seg,
2547 state => $self->state
2548 );
2549  
2550 my $image_id = OVERVIEW_SCALE_LABEL."_image";
2551  
2552 return {
2553 url => $url,
2554 height => $height,
2555 width => $width,
2556 image_id => $image_id,
2557 };
2558 }
2559  
2560 sub debug_visible {
2561 my $self = shift;
2562 my $state = shift;
2563 warn "[$$] ",join ' ',map {
2564 $_ . '=>' . $state->{features}{$_}{visible}
2565 }
2566 @{$state->{tracks}};
2567 }
2568  
2569 sub asynchronous_update_region_scale_bar {
2570 my $self = shift;
2571 my $seg = $self->segment;
2572  
2573 my $renderer = $self->get_panel_renderer($seg);
2574 my ( $url, $height, $width ) = $renderer->render_scale_bar(
2575 section => 'region',
2576 region_segment => $self->region_segment,
2577 segment => $seg,
2578 state => $self->state
2579 );
2580  
2581 my $image_id = REGION_SCALE_LABEL."_image";
2582  
2583 return {
2584 url => $url,
2585 height => $height,
2586 width => $width,
2587 image_id => $image_id,
2588 };
2589 }
2590  
2591 sub asynchronous_update_detail_scale_bar {
2592 my $self = shift;
2593 my $seg = $self->segment;
2594  
2595 my $renderer = $self->get_panel_renderer($seg);
2596 my ( $url, $height, $width ) = $renderer->render_scale_bar(
2597 section => 'detail',
2598 segment => $seg,
2599 state => $self->state
2600 );
2601  
2602 my $image_id = DETAIL_SCALE_LABEL . "_image";
2603  
2604 my ($scale_size, $scale_label) = $renderer->calculate_scale_size($seg->length/$self->details_mult, $width/$self->details_mult);
2605  
2606 return {
2607 url => $url,
2608 height => $height,
2609 width => $width,
2610 view_width => $self->get_image_width($self->state),
2611 image_id => $image_id,
2612 scale_size => $scale_size,
2613 scale_label => $scale_label,
2614 };
2615 }
2616  
2617 sub asynchronous_update_sections {
2618 my $self = shift;
2619 my $section_names = shift;
2620  
2621 # avoid unecessary database inits
2622 # $self->init_database();
2623  
2624 my $source = $self->data_source;
2625 my $return_object = {};
2626  
2627 my %handle_section_name = map { $_ => 1 } @{ $section_names || [] };
2628  
2629 # Init Plugins if need be
2630 if ( $handle_section_name{'plugin_configure_div'}
2631 || $handle_section_name{'tracks_panel'}
2632 || $handle_section_name{'plugin_form'})
2633 {
2634 $self->init_plugins();
2635 }
2636  
2637 # Page Title
2638 if ( $handle_section_name{'page_title'} ) {
2639 my $segment = $self->thin_segment; # avoids a db open
2640 my $dsn = $self->data_source;
2641 my $description = $dsn->description;
2642 $return_object->{'page_title'} = $self->generate_title([$segment]);
2643 }
2644  
2645 # Span that shows the range
2646 if ( $handle_section_name{'span'} ) {
2647 my $container
2648 = $self->slidertable();
2649 $return_object->{'span'} = $container;
2650 }
2651  
2652 # Unused Search Field
2653 if ( $handle_section_name{'search_form_objects'} ) {
2654 $return_object->{'search_form_objects'}
2655 = $self->render_search_form_objects();
2656 }
2657  
2658 if ($handle_section_name{'login_menu'}) {
2659 $return_object->{login_menu} = $self->login_manager->render_login();
2660 }
2661  
2662 # Plugin Configuration Form
2663 # A params is used to determine the plugin
2664 if ( $handle_section_name{'plugin_configure_div'} ) {
2665 my $plugin_base = param('plugin_base');
2666 if ($plugin_base) {
2667 my $plugin = $self->plugins->plugin($plugin_base);
2668 if ($plugin) {
2669 $return_object->{'plugin_configure_div'}
2670 = $self->wrap_plugin_configuration( $plugin_base,
2671 $plugin );
2672 }
2673 else {
2674 $return_object->{'plugin_configure_div'}
2675 = $self->translate('NOT_RECOGNIZED_PLUGIN',$plugin_base)||'' . "\n";
2676 }
2677 }
2678 else {
2679 $return_object->{'plugin_configure_div'}
2680 = $self->translate('NO_PLUGIN_SPECIFIED')||'' . "\n";
2681 }
2682 }
2683  
2684 # Galaxy form
2685 if ( $handle_section_name{'galaxy_form'} ) {
2686 $return_object->{'galaxy_form'} = $self->galaxy_form($self->thin_segment);
2687 }
2688  
2689 # Plugin form
2690 if ( $handle_section_name{'plugin_form'} ) {
2691 $return_object->{'plugin_form'} = $self->plugin_form();
2692 }
2693  
2694 # Track Checkboxes
2695 if ( $handle_section_name{'tracks_panel'} ) {
2696 $return_object->{'tracks_panel'} = $self->render_track_table();
2697 }
2698  
2699 # New Custom Tracks Section
2700 if ( $handle_section_name{'custom_tracks'}) {
2701 $return_object->{'custom_tracks'} = $self->render_custom_track_listing();
2702 }
2703
2704 # Community Tracks Section
2705 if ( $handle_section_name{'community_tracks'}) {
2706 $return_object->{'community_tracks'} = $self->render_community_track_listing(@_); #Passing on any search terms.
2707 }
2708  
2709 # Saved Snapshot Section
2710 if ( $handle_section_name{'snapshots_page'}) {
2711 $return_object->{'snapshots_page'} = $self->snapshot_manager->render_snapshots_listing($self);
2712 }
2713  
2714 # Handle Remaining and Undefined Sections
2715 foreach my $section_name ( keys %handle_section_name ) {
2716 next if ( defined $return_object->{$section_name} );
2717 $return_object->{$section_name} = 'Unknown element: ' . $section_name;
2718 }
2719 return $return_object;
2720 }
2721  
2722 # asynchronous_update_element has been DEPRECATED
2723 # in favor of asynchronous_update_sections
2724 sub asynchronous_update_element {
2725 my $self = shift;
2726 my $element = shift;
2727 $self->init_database();
2728 my $source = $self->data_source;
2729  
2730 if ( $element eq 'page_title' ) {
2731 my $segment = $self->segment;
2732 my $dsn = $self->data_source;
2733 my $description = $dsn->description;
2734 my $divider = $dsn->unit_divider;
2735 return $description . '<br>'
2736 . $self->translate(
2737 'SHOWING_FROM_TO',
2738 scalar $source->unit_label( $segment->length ),
2739 $segment->seq_id,
2740 $source->commas( $segment->start/$divider ),
2741 $source->commas( $segment->end/$divider )
2742 );
2743 }
2744 elsif ( $element eq 'span' ) { # this is the popup menu that shows ranges
2745 my $container
2746 = $self->zoomBar( $self->segment, $self->whole_segment );
2747 $container =~ s/<\/?select.+//g;
2748 return $container;
2749 }
2750 elsif ( $element eq 'landmark_search_field' ) {
2751 return $self->state->{name};
2752 }
2753 elsif ( $element eq 'overview_panels' ) {
2754 return "<b>some day this will be the overview showing "
2755 . $self->state->{name} . "</b>";
2756 }
2757 elsif ( $element eq 'detail_panels' ) {
2758 $self->init_plugins();
2759 $self->init_remote_sources();
2760 return join ' ',
2761 $self->render_detailview_panels( $self->region->seg );
2762 }
2763 elsif ( $element eq 'plugin_configure_div' ) {
2764 $self->init_plugins();
2765 my $plugin_base = param('plugin_base');
2766 my $plugin = $self->plugins->plugin($plugin_base)
2767 or return "$plugin_base is not a recognized plugin\n";
2768  
2769 return $self->wrap_plugin_configuration($plugin_base,$plugin);
2770 }
2771 elsif ( $element eq 'external_utility_div' ) {
2772 if ( my $file_name = param('edit_file') ) {
2773 $file_name = CGI::unescape($file_name);
2774 return $self->edit_uploaded_file($file_name);
2775 }
2776 elsif ( param('new_edit_file') ) {
2777 my $file_name = $self->uploaded_sources->new_file_name();
2778 return $self->edit_uploaded_file($file_name);
2779 }
2780 }
2781  
2782 # Track Checkboxes
2783 elsif ( $element eq 'tracks_panel' ) {
2784 $self->init_plugins();
2785 return $self->render_track_table();
2786 }
2787 # External Data Form
2788 elsif ( $element eq 'upload_tracks_panel' ) {
2789 return $self->render_external_table();
2790 }
2791  
2792 return 'Unknown element: ' . $element;
2793 }
2794  
2795 sub asynchronous_update_coordinates {
2796 my $self = shift;
2797 my $action = shift;
2798  
2799 my $state = $self->state;
2800  
2801 my $whole_segment_start = $state->{seg_min};
2802 my $whole_segment_stop = $state->{seg_max};
2803  
2804 my $position_updated;
2805 if ($action =~ /left|right/) {
2806 $self->scroll($state,$action);
2807 $position_updated++;
2808 }
2809 if ($action =~ /zoom/) {
2810 $self->zoom($state,$action);
2811 $position_updated++;
2812 }
2813 if ($action =~ /set span/) {
2814 $self->zoom_to_span($state,$action);
2815 $position_updated++;
2816 }
2817 if ($action =~ /set segment/) {
2818 $self->move_segment($state,$action);
2819 $position_updated++;
2820 }
2821 if ($action =~ /reload segment/) {
2822 $position_updated++;
2823 }
2824 if ( $action =~ /flip (\S+)/ ) {
2825 if ( $action =~ /name/) {
2826 $self->move_to_name($state, $action);
2827 $position_updated++;
2828 }
2829 if ( $1 eq 'true' ) {
2830 $state->{'flip'} = 1;
2831 }
2832 else {
2833 $state->{'flip'} = 0;
2834 }
2835 }
2836  
2837 if ($position_updated) { # clip and update param
2838 if (defined $whole_segment_start && $state->{view_start} < $whole_segment_start) {
2839 my $delta = $whole_segment_start - $state->{view_start};
2840 $state->{view_start} += $delta;
2841 $state->{view_stop} += $delta;
2842 }
2843  
2844 if (defined $whole_segment_stop && $state->{view_stop} > $whole_segment_stop) {
2845 my $delta = $state->{view_stop} - $whole_segment_stop;
2846 $state->{view_start} -= $delta;
2847 $state->{view_stop} -= $delta;
2848  
2849 if ($state->{view_start} < 0) {
2850 # Segment requested is larger than the whole segment
2851 $state->{view_start} = $whole_segment_start;
2852 $state->{view_stop} = $whole_segment_stop;
2853 }
2854 }
2855  
2856 # Take details multiplier into account
2857 $self->update_state_from_details_mult;
2858  
2859 unless (defined $state->{ref}) {
2860 warn "Reverting coordinates to last known good region (user probably hit 'back' button).";
2861 if ($state->{backup_region}) { # last known working region
2862 @{$state}{'ref','start','stop','view_start','view_stop'} = @{$state->{backup_region}};
2863 } else {
2864 $state->{name} = param('name') || param('q') || url_param('name') || url_param('q'); # get the region somehow!!
2865 if (my $seg = $self->segment) {
2866 $state->{ref} = $seg->seq_id;
2867 $state->{start} = $seg->start;
2868 $state->{stop} = $seg->stop;
2869 }
2870 }
2871 }
2872  
2873 # update our "name" state and the CGI parameter
2874 $state->{name} = $self->region_string;
2875 }
2876 $position_updated;
2877 }
2878  
2879 sub update_state_from_details_mult {
2880 my $self = shift;
2881 my $state = $self->state;
2882  
2883 my $view_start = $state->{view_start} || 0;
2884 my $view_stop = $state->{view_stop} || 0;
2885  
2886 my $details_mult = $self->details_mult;
2887  
2888 my $length = $view_stop - $view_start;
2889 my $length_to_load = int($length * $details_mult);
2890  
2891 my $start_to_load = int($view_start - $length * ($details_mult - 1) / 2);
2892  
2893 if (defined $state->{seg_min} && $start_to_load < $state->{seg_min}) {
2894 $start_to_load = $state->{seg_min};
2895 }
2896  
2897 my $stop_to_load = $start_to_load + $length_to_load;
2898  
2899 if (defined $state->{seg_max} && $stop_to_load > $state->{seg_max}) {
2900 my $delta = $stop_to_load - $state->{seg_max};
2901 $start_to_load -= $delta;
2902 $stop_to_load -= $delta;
2903 }
2904  
2905 $state->{start} = $start_to_load;
2906 $state->{stop} = $stop_to_load;
2907 }
2908  
2909 sub region_string {
2910 my $self = shift;
2911 my $state = $self->state;
2912 my $source = $self->data_source;
2913 my $divider = $source->unit_divider || 1;
2914 $state->{view_start} ||= 0;
2915 $state->{view_stop} ||= 0;
2916 return "$state->{ref}:".
2917 $source->commas($state->{view_start}/$divider).
2918 '..'.
2919 $source->commas($state->{view_stop}/$divider);
2920 }
2921  
2922 sub zoom_to_span {
2923 my $self = shift;
2924 my ($state,$new_span) = @_;
2925  
2926 my ($span) = $new_span =~ /([\d+.-]+)/;
2927  
2928 sub move_to_name {
2929 my $self = shift;
2930 my ( $state, $new_name ) = @_;
2931  
2932 if ( $new_name =~ /:(.*):([\d+.-]+)\.\.([\d+.-]+)/ ) {
2933 my $new_chr = $1;
2934 my $new_start = $2;
2935 my $new_stop = $3;
2936  
2937 $state->{ref} = $new_chr;
2938 $state->{view_start} = $new_start;
2939 $state->{view_stop} = $new_stop;
2940 $self->background_track_render();
2941 }
2942 }
2943  
2944 my $current_span = $state->{view_stop} - $state->{view_start} + 1;
2945 my $center = int(($current_span / 2)) + $state->{view_start};
2946 my $range = int(($span)/2);
2947 $state->{view_start} = $center - $range;
2948 $state->{view_stop } = $state->{view_start} + $span - 1;
2949 }
2950  
2951 sub move_segment {
2952 my $self = shift;
2953 my ( $state, $new_segment ) = @_;
2954  
2955 if ( $new_segment =~ /:([\d+.-]+)\.\.([\d+.-]+)/ ) {
2956 my $new_start = $1;
2957 my $new_stop = $2;
2958  
2959 $state->{view_start} = $new_start;
2960 $state->{view_stop} = $new_stop;
2961 }
2962 }
2963  
2964 sub scroll {
2965 my $self = shift;
2966 my $state = shift;
2967 my $scroll_data = shift;
2968  
2969 my $flip = $state->{flip} ? -1 : 1;
2970  
2971 $scroll_data =~ s/\.[xy]$//; # get rid of imagemap button cruft
2972 my $scroll_distance = $self->unit_to_value($scroll_data);
2973  
2974 $state->{view_start} += $flip * $scroll_distance;
2975 $state->{view_stop} += $flip * $scroll_distance;
2976 }
2977  
2978 sub zoom {
2979 my $self = shift;
2980 my $state = shift;
2981 my $zoom_data = shift;
2982  
2983 $zoom_data =~ s/\.[xy]$//; # get rid of imagemap button cruft
2984 my $zoom_distance = $self->unit_to_value($zoom_data);
2985 my $span = $state->{view_stop} - $state->{view_start} + 1;
2986 my $center = int($span / 2) + $state->{view_start};
2987 my $range = int($span * (1-$zoom_distance)/2);
2988 $range = 1 if $range < 1;
2989  
2990 my $newstart = $center - $range;
2991 my $newstop = $center + $range - 1;
2992
2993 if ($newstart==$state->{view_start} && $newstop==$state->{view_stop}) {
2994 if ($zoom_distance < 0) {$newstart--;$newstop++};
2995 if ($zoom_distance > 0) {$newstart++;$newstop--};
2996 }
2997 if ($newstop-$newstart <=2) {$newstop++} # don't go down to 2 bp level!
2998  
2999 $state->{view_start} = $newstart;
3000 $state->{view_stop} = $newstop;
3001 }
3002  
3003 sub position_from_overview {
3004 my $self = shift;
3005 my $state = shift;
3006 my $position_data = shift;
3007  
3008 return unless defined $state->{seg_max} && defined $state->{seg_min};
3009  
3010 my $segment_length = $state->{seg_max} - $state->{seg_min} + 1;
3011 return unless $segment_length > 0;
3012  
3013 my @overview_tracks = grep {$state->{features}{$_}{visible}}
3014 $self->data_source->overview_tracks;
3015  
3016 my ($padl,$padr) = $self->overview_pad(\@overview_tracks);
3017 my $overview_width = $state->{width} * $self->overview_ratio;
3018  
3019 my $click_position = $state->{seg_min} + $segment_length * ($position_data-$padl)/$overview_width;
3020 my $span = $state->{stop} - $state->{start} + 1;
3021  
3022 $state->{start} = int($click_position - $span/2);
3023 $state->{stop} = $state->{start} + $span - 1;
3024 }
3025  
3026 sub position_from_regionview {
3027 my $self = shift;
3028 my $state = shift;
3029 my $position_data = shift;
3030 return unless defined $state->{seg_max} && defined $state->{seg_min};
3031 return unless $state->{region_size};
3032  
3033 my @regionview_tracks = grep {$state->{features}{$_}{visible}}
3034 $self->data_source->regionview_tracks;
3035  
3036 my ($padl,$padr) = $self->overview_pad(\@regionview_tracks) or return;
3037 my $regionview_width = ($state->{width} * $self->overview_ratio);
3038  
3039 my $click_position = $state->{region_size} * ($position_data-$padl)/$regionview_width;
3040 my $span = $state->{stop} - $state->{start} + 1;
3041  
3042 my ($regionview_start, $regionview_end) = $self->regionview_bounds();
3043  
3044 $state->{start} = int($click_position - $span/2 + $regionview_start);
3045 $state->{stop} = $state->{start} + $span - 1;
3046 }
3047  
3048 sub update_region {
3049 my $self = shift;
3050 my $state = shift || $self->state;
3051  
3052 if ($self->setting('region segment')) {
3053 $state->{region_size} = param('region_size')
3054 if defined param('region_size');
3055 $state->{region_size} = $self->setting('region segment')
3056 unless defined $state->{region_size};
3057 }
3058 else {
3059 delete $state->{region_size};
3060 }
3061 }
3062  
3063 sub update_section_visibility {
3064 my $self = shift;
3065 my $state = shift;
3066  
3067 for my $div (grep {/^div_visible_/} CGI::cookie()) {
3068 my ($section) = $div =~ /^div_visible_(\w+)/ or next;
3069 my $visibility = CGI::cookie($div);
3070 $state->{section_visible}{$section} = $visibility;
3071 }
3072 }
3073  
3074 sub update_galaxy_url {
3075 my $self = shift;
3076 my $state = shift;
3077 if (my $url = param('GALAXY_URL')) {
3078 warn "[$$] setting galaxy" if DEBUG;
3079 $state->{GALAXY_URL} = $url;
3080 } elsif (param('clear_galaxy')) {
3081 warn "clearing galaxy" if DEBUG;
3082 delete $state->{GALAXY_URL};
3083 }
3084 }
3085  
3086 ##################################################################3
3087 #
3088 # SHARED RENDERING CODE HERE
3089 #
3090 ##################################################################3
3091  
3092 # overview_ratio and overview_pad moved to RenderPanels.pm
3093  
3094 sub set_language {
3095 my $self = shift;
3096  
3097 my $data_source = $self->data_source;
3098  
3099 my $lang = Bio::Graphics::Browser2::I18n->new($data_source->globals->language_path);
3100 my $default_language = $data_source->setting('language') || 'POSIX';
3101  
3102 my $accept = CGI::http('Accept-language') || '';
3103 my @languages = $accept =~ /([a-z]{2}-?[a-z]*)/ig;
3104 push @languages,$default_language if $default_language;
3105  
3106 return unless @languages;
3107 $lang->language(@languages);
3108 $self->language($lang);
3109 Bio::Graphics::Browser2::Util->set_language($lang);
3110 }
3111  
3112 sub language {
3113 my $self = shift;
3114 my $d = $self->{lang};
3115 $self->{lang} = shift if @_;
3116 $d;
3117 }
3118  
3119 # Returns the language code, but only if we have a translate table for it.
3120 sub language_code {
3121 my $self = shift;
3122 my $lang = $self->language;
3123 my $table= $lang->tr_table($lang->language);
3124 return unless %$table;
3125 return $lang->language;
3126 }
3127  
3128 ##### language stuff
3129 sub label2key {
3130 my $self = shift;
3131 my $label = shift;
3132 my $source = $self->data_source;
3133 my $key;
3134  
3135 # make URL labels a bit nicer
3136 if ($label =~ /^ftp|^http/) {
3137 $key = $source->setting($label => 'key') || url_label($label);
3138 }
3139 elsif ($label =~ /^plugin/) {
3140 ($key = $label) =~ s/^plugin://;
3141 }
3142  
3143 my $presets = $self->get_external_presets || {};
3144 for my $l ($self->language->language) {
3145 $key ||= $source->setting($label=>"key:$l");
3146 }
3147 $key ||= $source->setting($label => 'key');
3148 $key ||= $key if defined $key;
3149 $key ||= $label;
3150 $key;
3151 }
3152  
3153 # convert Mb/Kb back into bp... or a ratio
3154 sub unit_to_value {
3155 my $self = shift;
3156 my $string = shift;
3157 my $sign = $string =~ /out|left/ ? '-' : '+';
3158 my ($value,$units) = $string =~ /([\d.]+)(\s*\S+)?/;
3159 return unless defined $value;
3160 $units ||= 'bp';
3161 $value /= 100 if $units eq '%'; # percentage;
3162 $value *= 1000 if $units =~ /kb/i;
3163 $value *= 1e6 if $units =~ /mb/i;
3164 $value *= 1e9 if $units =~ /gb/i;
3165 return "$sign$value";
3166 }
3167  
3168 sub get_zoomincrement {
3169 my $self = shift;
3170 my $zoom = $self->setting('fine zoom');
3171 return $zoom;
3172 }
3173  
3174 sub get_max_segment {
3175 my $self = shift;
3176 my $divisor = $self->setting('unit_divider') || 1;
3177 my $max_seg = $self->setting('max segment');
3178 if (!$max_seg) {
3179 return MAX_SEGMENT;
3180 } elsif ($divisor == 1 ) {
3181 return $max_seg
3182 } else {
3183 return $max_seg * $divisor;
3184 }
3185 }
3186  
3187  
3188 #############################################################################
3189 #
3190 # HANDLING SEGMENTS
3191 #
3192 #############################################################################
3193 sub regionview_bounds {
3194 my $self = shift;
3195 my $segment = $self->thin_region_segment;
3196 return ($segment->start,$segment->end);
3197 }
3198  
3199 # this version handles labels with embedded hyphens correctly
3200 sub split_labels_correctly {
3201 my $self = shift;
3202 return map {split LABEL_SEPARATOR,$_} @_;
3203 }
3204  
3205 # this version does not handle labels with embedded "+" or "-"
3206 # unless the hyphen is escaped with %01d
3207 sub split_labels {
3208 my $self = shift;
3209 my @results;
3210  
3211 for (@_) {
3212  
3213 # pass URLs through unmodified
3214 if (/^(http|ftp|das)/) {
3215 push @results,$_;
3216 next;
3217 }
3218 push @results, split /[+-]/;
3219 }
3220  
3221 my $group_separator = GROUP_SEPARATOR;
3222 foreach (@results) {
3223 s/$group_separator/-/g; # unescape hyphens
3224 s/$;/-/g; # unescape hyphens -backward compatibility
3225 }
3226  
3227 @results;
3228 }
3229  
3230 # remove any tracks that the client still thinks are valid
3231 # but which have been removed from the config file
3232 sub remove_invalid_tracks {
3233 my $self = shift;
3234 my $state = shift;
3235  
3236 my %potential = map {$_=>1} $self->potential_tracks;
3237 my @defunct = grep {!$potential{$_}} keys %{$state->{features}};
3238 delete $state->{features}{$_} foreach @defunct;
3239 $state->{tracks} = [grep {$potential{$_}} @{$state->{tracks}}];
3240 }
3241  
3242 sub set_tracks {
3243 my $self = shift;
3244 my @labels = @_;
3245 my $state = $self->state;
3246  
3247 my %potential = map {$_=>1} $self->potential_tracks;
3248  
3249 my @main;
3250 for my $label (@labels) {
3251 my ($main,$subtracks) = split '/',$label;
3252 $subtracks ||= '';
3253 my @subtracks = shellwords($subtracks);
3254 foreach (@subtracks) {s/#.+$//} # get rid of comments
3255 push @main,$main;
3256 $state->{subtracks}{$main} = \@subtracks if @subtracks;
3257 }
3258  
3259 my %seenit;
3260  
3261 $state->{tracks} = [grep {$potential{$_} && !$seenit{$_}++} @main];
3262 $self->load_plugin_annotators(\@main);
3263 $state->{features}{$_}{visible} = 0 foreach $self->data_source->labels;
3264 $state->{features}{$_}{visible} = 1 foreach @main;
3265 }
3266  
3267 sub load_plugin_annotators {
3268 my ($self,$visible_labels) = @_;
3269  
3270 my %label_visible = map { $_ => 1 } @{ $visible_labels || [] };
3271 my $state = $self->state;
3272 my $source = $self->data_source;
3273 my %default_plugin = map {$_=>1} map {s/^plugin:// && $_}
3274 grep {/^plugin:/} $source->default_labels;
3275  
3276 my %listed = $state->{tracks} ? map {$_=>1} @{$state->{tracks}} : (); # are we already on the list?
3277 my %listed_in_source = map {$_=>1} $source->configured_types; # are we already on the list?
3278  
3279 for my $plugin ($self->plugins->plugins) {
3280 next unless $plugin->type eq 'annotator';
3281 my $name = $plugin->id; # use the ID "RestrictionAnnotator" rather than the name "Restriction Annotator"
3282 $name = "plugin:$name";
3283 $source->add_type($name,{}) unless $listed_in_source{$name}++;
3284 $state->{features}{$name} ||= {visible=>$label_visible{$name}||0,options=>0,limit=>0};
3285 }
3286 }
3287  
3288 sub detail_tracks {
3289 my $self = shift;
3290 my $external = $self->external_data;
3291 my %files_in_details = map {$_=>1} $self->featurefiles_in_section('detail','expand');
3292 my @tracks = grep {$files_in_details{$_}
3293 || !/:(overview|region)$/} $self->visible_tracks;
3294 return @tracks;
3295 }
3296  
3297 sub overview_tracks {
3298 my $self = shift;
3299 my @tracks = grep {/:overview$/} $self->visible_tracks;
3300 my @files_in_overview = $self->featurefiles_in_section('overview');
3301 my %seen;
3302 return grep {!$seen{$_}++} (@tracks,@files_in_overview);
3303 }
3304  
3305 sub regionview_tracks {
3306 my $self = shift;
3307 my @tracks = grep {/:region$/} $self->visible_tracks;
3308 my @files_in_region = $self->featurefiles_in_section('region');
3309 my %seen;
3310 return grep {!$seen{$_}++} (@tracks,@files_in_region);
3311
3312 }
3313  
3314 # all tracks currently in our state; this MAY go out of date if the
3315 # configuration file changes.
3316 sub all_tracks {
3317 my $self = shift;
3318 my $state = $self->state;
3319 my $source = $self->data_source;
3320 return grep {$source->authorized($_)} @{$state->{tracks}};
3321 }
3322  
3323 # all potential tracks; this is guaranteed to be up to date with the
3324 # configuration file.
3325 sub potential_tracks {
3326 my $self = shift;
3327 my $source = $self->data_source;
3328 my %seenit;
3329 return grep {!$seenit{$_}++
3330 && !/^_/} ($source->detail_tracks,
3331 $source->overview_tracks,
3332 $source->plugin_tracks,
3333 $source->regionview_tracks,
3334 );
3335 }
3336  
3337 sub visible_tracks {
3338 my $self = shift;
3339 my $state = $self->state;
3340 my @tracks = grep {$state->{features}{$_}{visible}
3341 && !/^_/
3342 } $self->all_tracks;
3343 return @tracks;
3344 }
3345  
3346 sub featurefiles_in_section {
3347 my $self = shift;
3348 my $desired_section = shift;
3349 my $expand = shift;
3350  
3351 my $external = $self->external_data;
3352 my $state = $self->state;
3353 my %found;
3354  
3355 for my $label (keys %$external) {
3356 $state->{features}{$label}{visible} or next;
3357 my $file = $external->{$label} or next;
3358 my %sections = map {$_=>1} $self->featurefile_sections($label);
3359 $label .= ":".lc $desired_section if $expand;
3360 $found{$label}++ if $sections{lc $desired_section};
3361 }
3362 return keys %found;
3363 }
3364  
3365 sub featurefile_sections {
3366 my $self = shift;
3367 my $label = shift;
3368 my $ff = $self->external_data->{$label} or return;
3369 return $self->_featurefile_sections($ff);
3370 }
3371  
3372 sub _featurefile_sections {
3373 my $self = shift;
3374 my $ff = shift;
3375 return 'detail' if $ff->isa('Bio::Das::Segment');
3376  
3377 my %sections;
3378  
3379 # we prefer to read the labels from the feature file,
3380 # but some of the featurefile types don't support this.
3381 my @labels = eval {$ff->labels};
3382 for my $label (@labels) {
3383 my $section = $1 if $label =~ /:(overview|region|details?)$/i;
3384 $section ||= $ff->setting($label => 'section');
3385 $section ||= 'detail';
3386 $section =~ s/details/detail/; # foo!
3387 $sections{lc $_}++ for $section =~ /(\w+)/g;
3388 }
3389  
3390 # probe for unconfigured types, which will go into detail section by default
3391 my @unconfigured = eval {grep{!$ff->type2label($_)} $ff->types};
3392 $sections{detail}++ if @unconfigured;
3393  
3394 # last chance!
3395 $sections{detail}++ unless %sections;
3396 return keys %sections;
3397 }
3398  
3399 # given a set of track names append the section names
3400 # to those that correspond to file uploads
3401 sub expand_track_names {
3402 my $self = shift;
3403 my @tracks = @_;
3404  
3405 my $external = $self->external_data;
3406 my $source = $self->data_source;
3407 my @results;
3408  
3409 for my $t (@tracks) {
3410 if ($source->code_setting($t=>'remote feature')) {
3411 push @results,$t;
3412 }
3413 elsif ($external->{$t}) {
3414 my @sections = $self->featurefile_sections($t);
3415 @sections = ('detail') unless @sections;
3416 push @results,"$t:$_" foreach @sections;
3417 }
3418 else {
3419 push @results,$t;
3420 }
3421 }
3422  
3423 return @results;
3424 }
3425  
3426 # This turns track names into IDs for use at the client side.
3427 # This is necessary because tracks from external files/URLs
3428 # may generate more than one track
3429 sub trackname_to_id {
3430 my $self = shift;
3431 my ($name,$section) = @_;
3432 $self->data_source->is_remotetrack($name) ? $name
3433 :$self->external_data->{$name} ? "$name:$section"
3434 : $name;
3435 }
3436  
3437 ################## get renderer for this segment #########
3438 sub get_panel_renderer {
3439 my $self = shift;
3440 my $seg = shift || $self->segment;
3441 my $whole = shift || $self->whole_segment;
3442 my $region = shift || $self->region_segment;
3443  
3444 return Bio::Graphics::Browser2::RenderPanels->new(-segment => $seg,
3445 -whole_segment => $whole,
3446 -region_segment => $region,
3447 -source => $self->data_source,
3448 -settings => $self->state,
3449 -language => $self->language,
3450 -render => $self,
3451 );}
3452  
3453 ################## image rendering code #############
3454  
3455 # render_detailview is now obsolete, but we retain it
3456 # because it is handy for regression testing.
3457 sub render_detailview {
3458 my $self = shift;
3459 my $seg = shift or return;
3460 my @panels = $self->render_detailview_panels($seg);
3461 my $drag_script = $self->drag_script('detail_panels','track');
3462 local $^W = 0; # quash uninit variable warning
3463 return div($self->toggle('Details',
3464 div({-id=>'detail_panels',-class=>'track'},
3465 @panels
3466 )
3467 )
3468 ).$drag_script;
3469 }
3470  
3471 sub render_detailview_panels {
3472 my $self = shift;
3473 my $seg = shift;
3474  
3475 my @labels = $self->detail_tracks;
3476 my $renderer = $self->get_panel_renderer($seg);
3477 my $panels = $renderer->render_panels(
3478 {
3479 labels => \@labels,
3480 external_features => $self->external_data,
3481 section => 'detail',
3482 }
3483 );
3484
3485 return map {$panels->{$_}} @labels;
3486 }
3487  
3488 sub get_blank_panels {
3489 my $self = shift;
3490 my $track_names = shift;
3491 my $section = shift;
3492  
3493 my $settings = $self->state;
3494  
3495 my $html = '';
3496 my $image_width = $self->get_image_width($settings);
3497 foreach my $track_name ( @{ $track_names || [] } ) {
3498  
3499 my $divname = $self->trackname_to_id($track_name,$section);
3500  
3501 warn "$track_name => $divname" if DEBUG;
3502  
3503 my $track_html = $self->render_grey_track(
3504 track_id => $track_name,
3505 image_width => $image_width,
3506 image_height => EMPTY_IMAGE_HEIGHT,
3507 image_element_id => $track_name . "_image",
3508 );
3509 $track_html = $self->wrap_track_in_track_div(
3510 track_name => $track_name,
3511 track_id => $divname,
3512 track_html => $track_html,
3513 );
3514 $html .= $track_html;
3515 }
3516 return $html;
3517  
3518 }
3519  
3520 sub get_image_width {
3521 my $self = shift;
3522 my $state = shift;
3523 my $image_width = $state->{'width'} + $self->get_total_pad_width;
3524 return int($image_width);
3525 }
3526  
3527 sub get_detail_image_width {
3528 my $self = shift;
3529 my $state = shift;
3530 my $image_width = $state->{'width'} * $self->details_mult + $self->get_total_pad_width;
3531 return int($image_width);
3532 }
3533  
3534 sub get_total_pad_width {
3535 my $self = shift;
3536 my $source = $self->data_source;
3537 my $renderer = $self->get_panel_renderer($self->thin_segment,
3538 $self->thin_whole_segment,
3539 $self->thin_region_segment,
3540 );
3541 my $padl = $source->global_setting('pad_left');
3542 my $padr = $source->global_setting('pad_right');
3543 my $image_pad = $renderer->image_padding;
3544 $padl = $image_pad unless defined $padl;
3545 $padr = $image_pad unless defined $padr;
3546 return $padl + $padr;
3547 }
3548  
3549 sub set_details_multiplier {
3550 my $self = shift;
3551 my $mult = shift || 1;
3552 $self->{'.details_mult'} = $mult;
3553 }
3554  
3555 sub details_mult {
3556 my $self = shift;
3557 $self->{'.details_mult'} ||= $self->_details_mult;
3558 return $self->{'.details_mult'};
3559 }
3560  
3561 sub _details_mult {
3562 my $self = shift;
3563 my $state = $self->state;
3564 return $self->data_source->details_multiplier($state);
3565 }
3566  
3567 sub render_deferred {
3568 my $self = shift;
3569  
3570 my %args = @_;
3571  
3572 my $labels = $args{labels} || [ $self->detail_tracks ];
3573 my $seg = $args{segment} || $self->thin_segment;
3574 my $section = $args{section} || 'detail';
3575 my $cache_extra = $args{cache_extra} || $self->create_cache_extra();
3576 my $external = $args{external_tracks} || $self->external_data;
3577 my $nocache = $args{nocache};
3578
3579 warn '(render_deferred(',join(',',@$labels),') for section ',$section,' nocache=',$nocache if DEBUG;
3580  
3581 my $renderer = $self->get_panel_renderer($seg,
3582 $self->thin_whole_segment,
3583 $self->thin_region_segment
3584 );
3585  
3586 my $h_callback = $self->make_hilite_callback();
3587 my $requests = $renderer->request_panels(
3588 { labels => $labels,
3589 section => $section,
3590 deferred => 1,
3591 whole_segment => $self->thin_whole_segment(),
3592 external_features=> $external,
3593 hilite_callback => $h_callback || undef,
3594 cache_extra => $cache_extra,
3595 nocache => $nocache || 0,
3596 remotes => $self->remote_sources,
3597 render => $self,
3598 flip => ( $section eq 'detail' ) ? $self->state()->{'flip'} : 0,
3599 }
3600 );
3601  
3602 return $requests;
3603 }
3604  
3605 sub render_grey_track {
3606 my $self = shift;
3607 my %args = @_;
3608 my $image_width = $args{'image_width'};
3609 my $image_height = $args{'image_height'};
3610 my $image_element_id = $args{'image_element_id'};
3611 my $track_id = $args{'track_id'};
3612  
3613 my $renderer = $self->get_panel_renderer($self->thin_segment,
3614 $self->thin_whole_segment,
3615 $self->thin_region_segment,
3616 );
3617 my $url = $renderer->source->globals->button_url() . "/grey.png";
3618  
3619 my $html = $renderer->wrap_rendered_track(
3620 label => $track_id,
3621 area_map => [],
3622 width => $image_width,
3623 height => $image_height,
3624 url => $url,
3625 section => 'detail',
3626 status => '',
3627 );
3628  
3629 return $html;
3630 }
3631  
3632 sub render_error_track {
3633 my $self = shift;
3634 my %args = @_;
3635 my $image_width = $args{'image_width'};
3636 my $image_height = $args{'image_height'} * 3;
3637 my $image_element_id = $args{'image_element_id'};
3638 my $track_id = $args{'track_id'};
3639 my $error_message = $args{'error_message'};
3640  
3641 my $gd = GD::Image->new($image_width,$image_height);
3642 my $black = $gd->colorAllocate(0,0,0);
3643 my $white = $gd->colorAllocate(255,255,255);
3644 my $pink = $gd->colorAllocate(255,181,197);
3645 $gd->filledRectangle(0,0,$image_width,$image_height,$pink);
3646 my $font = GD->gdMediumBoldFont;
3647 my ($swidth,$sheight) = ($font->width * length($error_message),$font->height);
3648 my $xoff = ($image_width - $swidth)/2;
3649 my $yoff = ($image_height - $sheight - 3);
3650 $gd->string($font,$xoff,$yoff,$error_message,$black);
3651 my ($url,$path) = $self->data_source->generate_image($gd);
3652  
3653 return $self->get_panel_renderer->wrap_rendered_track(
3654 label => $track_id,
3655 area_map => [],
3656 width => $image_width,
3657 height => $image_height,
3658 url => $url,
3659 section => 'detail',
3660 status => '',
3661 );
3662 }
3663  
3664 sub render_deferred_track {
3665 my $self = shift;
3666 my %args = @_;
3667 my $cache_key = $args{'cache_key'};
3668 my $track_id = $args{'track_id'};
3669  
3670 my $renderer = $self->get_panel_renderer($self->thin_segment,
3671 $self->thin_whole_segment,
3672 $self->thin_region_segment
3673 );
3674  
3675 my $base = $renderer->get_cache_base();
3676 my $cache = Bio::Graphics::Browser2::CachedTrack->new(
3677 -cache_base => $base,
3678 -key => $cache_key,
3679 -cache_time => ($self->state->{cache}
3680 ? $self->data_source->cache_time
3681 : 0),
3682 );
3683 my $status_html = "<!-- " . $cache->status . " -->";
3684  
3685 warn "render_deferred_track(): $track_id: status = $status_html" if DEBUG;
3686  
3687 my $result_html = '';
3688 if ( $cache->status eq 'AVAILABLE' ) {
3689 my $result = $renderer->render_tracks( { $track_id => $cache } );
3690 $result_html = $result->{$track_id};
3691 }
3692 elsif ($cache->status eq 'ERROR') {
3693 warn "[$$] rendering error track: ",$cache->errstr; # if DEBUG;
3694 my $image_width = $track_id =~ /overview|region/ ? $self->get_image_width($self->state)
3695 : $self->get_detail_image_width($self->state);
3696 $result_html .= $self->render_error_track(
3697 track_id => $track_id,
3698 image_width => $image_width,
3699 image_height => EMPTY_IMAGE_HEIGHT,
3700 image_element_id => $track_id . "_image",
3701 error_message => 'Track rendering error: '.$cache->errstr)
3702 } else {
3703 my $image_width = $self->get_detail_image_width($self->state);
3704 $result_html .= $self->render_grey_track(
3705 track_id => $track_id,
3706 image_width => $image_width,
3707 image_height => EMPTY_IMAGE_HEIGHT,
3708 image_element_id => $track_id . "_image",
3709 );
3710 }
3711 $result_html .= ''; # to prevent uninit warning
3712 warn "[$$] $track_id=>",$cache->status if DEBUG;
3713 return $status_html . $result_html;
3714 }
3715  
3716  
3717 # returns the fragment we need to use the scriptaculous drag 'n drop code
3718 sub drag_script {
3719 my $self = shift;
3720 my $div_name = shift;
3721 my $div_part = shift;
3722  
3723 return <<END;
3724 <script type="text/javascript">
3725 // <![CDATA[
3726 create_drag('$div_name','$div_part');
3727 // ]]>
3728 </script>
3729 END
3730 }
3731  
3732 ##################### utilities #####################
3733  
3734 sub make_hilite_callback {
3735 my $self = shift;
3736 my $state = $self->state();
3737 my @hiliters = grep {$_->type eq 'highlighter'} $self->plugins()->plugins;
3738 return unless @hiliters or ($state->{h_feat} && %{$state->{h_feat}});
3739 return sub {
3740 my $feature = shift;
3741 my $color;
3742  
3743 # run through the set of hilite plugins and give each one
3744 # a chance to choose the highlighting for its feature
3745 foreach (@hiliters) {
3746 $color ||= $_->highlight($feature);
3747 }
3748 return $color if $color;
3749
3750 # if we get here, we select the search term for highlighting
3751 my %names = map
3752 {lc $_=> 1} grep { defined $_ }
3753 $feature->display_name,
3754 eval{$feature->get_tag_values('Alias')};
3755 return unless %names;
3756 $color ||= $state->{h_feat}{$_} foreach keys %names;
3757 return $color;
3758 }
3759 }
3760  
3761 sub categorize_track {
3762 my $self = shift;
3763 my $label = shift;
3764  
3765 my $user_labels = $self->get_usertrack_labels;
3766  
3767 return $self->translate('OVERVIEW') if $label =~ /:overview$/;
3768 return $self->translate('REGION') if $label =~ /:region$/;
3769 return $self->translate('EXTERNAL') if $label =~ /^(http|ftp|file):/;
3770 return $self->translate('ANALYSIS') if $label =~ /^plugin:/;
3771  
3772 if ($user_labels->{$label}) {
3773 my $cat = $self->user_tracks->is_mine($user_labels->{$label})
3774 ? $self->translate('UPLOADED_TRACKS_CATEGORY')
3775 : $self->translate('SHARED_WITH_ME_CATEGORY');
3776 return "$cat:".$self->user_tracks->title($user_labels->{$label});
3777 }
3778  
3779 my $category;
3780 for my $l ($self->language->language) {
3781 $category ||= $self->setting($label=>"category:$l");
3782 }
3783 $category ||= $self->setting($label => 'category');
3784 $category ||= ''; # prevent uninit variable warnings
3785 $category =~ s/^["']//; # get rid of leading quotes
3786 $category =~ s/["']$//; # get rid of trailing quotes
3787 return $category ||= $self->translate('GENERAL');
3788 }
3789  
3790 sub is_safari {
3791 return (CGI::user_agent||'') =~ /safari/i;
3792 }
3793  
3794 sub external_data {
3795 my $self = shift;
3796 my $segment = $self->segment or return { };
3797 my $state = $self->state;
3798  
3799 return $self->{feature_files} if exists $self->{feature_files};
3800  
3801 # $f will hold a feature file hash in which keys are human-readable names of
3802 # feature files and values are FeatureFile objects.
3803 my $f = {};
3804 my $max_segment = $self->get_max_segment;
3805 my $search = $self->get_search_object;
3806 my $meta_segment = $search->segment($segment);
3807 my $too_big = $segment && ($self->get_panel_renderer($segment)->segment_length > $max_segment);
3808 if (!$too_big && $segment) {
3809 my $search = $self->get_search_object;
3810 my $rel2abs = $search->coordinate_mapper($segment,1);
3811 my $rel2abs_slow = $search->coordinate_mapper($segment,0);
3812 my $plugins = $self->plugins;
3813 eval {
3814 $_->annotate($meta_segment,$f,
3815 $rel2abs,$rel2abs_slow,$max_segment,
3816 $self->whole_segment,$self->region_segment);
3817 } foreach ($self->plugins,$self->remote_sources);
3818 }
3819 return $self->{feature_files} = $f;
3820 }
3821 #
3822 # Supplement data source with user uploads
3823 sub add_user_tracks {
3824 my $self = shift;
3825 my ($data_source,$uuid) = @_;
3826 $data_source ||= $self->data_source;
3827 my $files = $self->user_tracks;
3828 my $userdb = $self->userdb;
3829 my $session = $self->session;
3830  
3831 return if $self->is_admin; # admin user's tracks are already in main config file.
3832 $self->session->uploadsid;
3833  
3834 my $userdata = $self->user_tracks;
3835 my @user_tracks = $userdata->tracks;
3836  
3837 for my $track (@user_tracks) {
3838 my $config_path = $userdata->track_conf($track);
3839 eval {$data_source->parse_user_file($config_path)};
3840 }
3841  
3842 return @user_tracks;
3843 }
3844  
3845 # Delete the segments so that they can be recreated with new parameters
3846 sub delete_stored_segments {
3847 my $self = shift;
3848  
3849 delete $self->{region};
3850 delete $self->{region_segment};
3851 delete $self->{whole_segment};
3852 }
3853  
3854 ###################### link generation ##############
3855 sub annotation_help {
3856 return shift->globals->url_base."/annotation_help.html";
3857 }
3858  
3859 sub general_help {
3860 return shift->globals->url_base."/general_help.html";
3861 }
3862  
3863 sub join_selected_tracks {
3864 my $self = shift;
3865 my $state = $self->state;
3866  
3867 my @selected = $self->visible_tracks;
3868 for (@selected) { # escape hyphens
3869 if ((my $filter = $state->{features}{$_}{filter}{values})) {
3870 my @subtracks = grep {$filter->{$_}} keys %{$filter};
3871 $_ .= "/@subtracks";
3872 }
3873 }
3874 return $self->join_tracks(\@selected);
3875 }
3876  
3877 sub join_tracks {
3878 my $self = shift;
3879 my $tracks = shift;
3880 return join LABEL_SEPARATOR,@$tracks;
3881 }
3882  
3883 sub bookmark_link {
3884 my $self = shift;
3885 my $settings = shift;
3886  
3887 my $q = new CGI('');
3888 my @keys = qw(start stop ref width version flip grid);
3889 foreach (@keys) {
3890 $q->param(-name=>$_, -value=>$settings->{$_});
3891 }
3892 $q->param(-name=>'id', -value=>$settings->{userid}); # slight inconsistency here
3893 $q->param(-name=>'l', -value=>$self->join_selected_tracks);
3894  
3895 $q->param(-name=>'h_region',-value=>$settings->{h_region}) if $settings->{h_region};
3896 my @h_feat= map {"$_\@$settings->{h_feat}{$_}"} keys %{$settings->{h_feat}};
3897 $q->param(-name=>'h_feat', -value=>\@h_feat) if @h_feat;
3898 return "?".$q->query_string();
3899 }
3900  
3901 sub gff_dump_link {
3902 my $self = shift;
3903 my $fasta = shift;
3904  
3905 my $state = $self->state;
3906 my $upload_id = $self->session->uploadsid;
3907 my $segment = $self->thin_segment or return '';
3908  
3909 my $q = new CGI('');
3910 if ($fasta) {
3911 $q->param(-name=>'gbgff', -value=>'Fasta');
3912 $q->param(-name=>'m', -value=>'application/x-fasta');
3913 } else {
3914 $q->param(-name=>'gbgff', -value=>'Save');
3915 $q->param(-name=>'m', -value=>'application/x-gff3');
3916 }
3917  
3918 # This will now be detemined and added on the client side
3919 #$q->param('q'=>$segment->seq_id.':'.$segment->start.'..'.$segment->end);
3920  
3921 # we probably need this ?
3922 $q->param(-name=>'id', -value=>$upload_id);
3923  
3924 # handle external urls
3925 return "?".$q->query_string();
3926 }
3927  
3928 sub dna_dump_link {
3929 my $self = shift;
3930 my $link = $self->gff_dump_link('fastaonly');
3931 return $link;
3932 }
3933  
3934 sub galaxy_link {
3935 my $self = shift;
3936 my $settings = shift || $self->state;
3937  
3938 my $galaxy_url = $settings->{GALAXY_URL}
3939 || $self->data_source->global_setting('galaxy outgoing');
3940  
3941 warn "[$$] galaxy_link = $galaxy_url" if DEBUG;
3942 return '' unless $galaxy_url;
3943 my $clear_it = $self->galaxy_clear;
3944 my $submit_it = q(document.galaxyform.submit()); #}) - Syntax highlight fixing.
3945 return "$clear_it;$submit_it";
3946 }
3947  
3948 sub galaxy_clear {
3949 return q(new Ajax.Request(document.URL,{method:'post',postBody:'clear_galaxy=1'}));
3950 }
3951  
3952  
3953 sub image_link {
3954 my $self = shift;
3955 my $settings = shift;
3956 my $format = shift;
3957  
3958 $format = 'GD' unless $format && $format=~ /^(GD|GD::SVG|PDF)$/;
3959  
3960 my $source = $self->data_source->name;
3961 my $id = $self->session->id;
3962 my $flip = $settings->{flip} || param('flip') || 0;
3963 my $keystyle = $settings->{ks};
3964 my $grid = $settings->{grid} || 0;
3965 my ($base,$s) = $self->globals->gbrowse_base;
3966 my $url = "$base/gbrowse_img/$s";
3967 my $tracks = $settings->{tracks};
3968 my $width = param('view_width') || $settings->{width};
3969 my $start = param('view_start') || $settings->{view_start};
3970 my $stop = param('view_stop') || $settings->{view_stop};
3971 $stop++;
3972 my $name = "$settings->{ref}:$start..$stop";
3973 my $selected = $self->join_selected_tracks;
3974 my $options = join '+',map { join '+', CGI::escape($_),$settings->{features}{$_}{options}
3975 } map {/\s/?"$_":$_}
3976 grep {
3977 $settings->{features}{$_}{options}
3978 } @$tracks;
3979 $id ||= ''; # to prevent uninit variable warnings
3980 my $img_url = "$url/?name=$name;l=$selected;width=$width;id=$id";
3981 $img_url .= ";flip=$flip" if $flip;
3982 $img_url .= ";options=$options" if $options;
3983 $img_url .= ";format=$format" if $format;
3984 $img_url .= ";keystyle=$keystyle" if $keystyle;
3985 $img_url .= ";grid=$grid";
3986 $self->add_hilites($settings,\$img_url);
3987  
3988 return $img_url
3989 }
3990  
3991 sub add_hilites {
3992 my $self = shift;
3993  
3994 my $settings = shift;
3995 my $img_url = shift;
3996  
3997 # add feature hilighting
3998 if ($settings->{h_feat} && ref $settings->{h_feat} eq 'HASH') {
3999 for my $h (keys %{$settings->{h_feat}}) {
4000 $$img_url .= ";h_feat=$h\@$settings->{h_feat}{$h}";
4001 }
4002 }
4003 # add region hilighting
4004 if ($settings->{h_region} && ref $settings->{h_region} eq 'ARRAY') {
4005 for my $h (@{$settings->{h_region}}) {
4006 $$img_url .= ";h_region=$h";
4007 }
4008 }
4009 }
4010  
4011 sub svg_link {
4012 my $self = shift;
4013 my $settings = shift;
4014 return "?help=svg_image;flip=".($settings->{flip}||0);
4015 }
4016  
4017 sub fcgi_request {
4018 my $self = shift;
4019 return $FCGI_REQUEST if defined $FCGI_REQUEST;
4020  
4021 unless (eval 'require FCGI;1') {
4022 return $FCGI_REQUEST = 0;
4023 }
4024  
4025 my $request = FCGI::Request(\*STDIN,\*STDOUT,\*STDERR,\%ENV,0,FCGI::FAIL_ACCEPT_ON_INTR());
4026 $FCGI_REQUEST = ($request && $request->IsFastCGI ? $request : 0);
4027  
4028 $FCGI_RUNNING++ if $FCGI_REQUEST;
4029 return $FCGI_REQUEST;
4030 }
4031  
4032 sub fcgi_running { return $FCGI_RUNNING }
4033  
4034 sub fork {
4035 my $self = shift;
4036
4037 $self->prepare_modperl_for_fork();
4038 $self->prepare_fcgi_for_fork('starting');
4039  
4040 my $child = CORE::fork();
4041 print STDERR "forked $child" if DEBUG;
4042 die "Couldn't fork: $!" unless defined $child;
4043  
4044 if ($child) { # parent process
4045 $self->session->was_forked('parent') if ref $self;
4046 $self->prepare_fcgi_for_fork('parent');
4047 }
4048  
4049 else {
4050 $self->session->was_forked('child') if ref $self;
4051 Bio::Graphics::Browser2::DataBase->clone_databases();
4052 Bio::Graphics::Browser2::Render->prepare_fcgi_for_fork('child');
4053 if (ref $self) {
4054 $self->userdb->clone_database() if $self->userdb;
4055 $self->user_tracks->clone_database() if $self->user_tracks;
4056 }
4057 }
4058  
4059 return $child;
4060 }
4061  
4062 sub prepare_modperl_for_fork {
4063 my $self = shift;
4064 my $r = modperl_request() or return;
4065 if ($ENV{MOD_PERL_API_VERSION} < 2) {
4066 eval {
4067 require Apache::SubProcess;
4068 $r->cleanup_for_exec()
4069 }
4070 };
4071 }
4072  
4073 sub prepare_fcgi_for_fork {
4074 my $self = shift;
4075 my $state = shift;
4076 my $req = $self->fcgi_request() or return;
4077 if ($state eq 'starting') {
4078 $req->Detach();
4079 } elsif ($state eq 'parent') {
4080 $req->Attach();
4081 } elsif ($state eq 'child') {
4082 $req->LastCall();
4083 $FCGI_REQUEST = 0;
4084 undef *FCGI::DESTROY;
4085 }
4086 }
4087  
4088 # try to generate a chrom sizes file
4089 sub chrom_sizes {
4090 my $self = shift;
4091 my $source = $self->data_source;
4092 my $mtime = $source->mtime;
4093 my $name = $source->name;
4094 my $sizes = File::Spec->catfile($self->globals->tmpdir('chrom_sizes'),"$name.sizes");
4095 if (-e $sizes && (stat(_))[9] >= $mtime) {
4096 return $sizes;
4097 }
4098 $self->generate_chrom_sizes($sizes) or return;
4099 return $sizes;
4100 }
4101  
4102 sub generate_chrom_sizes {
4103 my $self = shift;
4104 my $sizes = shift;
4105  
4106 my $source = $self->data_source;
4107  
4108 open my $s,'>',$sizes or die "Can't open $sizes for writing: $!";
4109  
4110 # First, try to query the default database for the
4111 # seq_ids it knows about.
4112 my $db = $source->open_database or return;
4113  
4114 # Bio::DB::SeqFeature has a seq_ids method.
4115 if (my @seqids = eval {$db->seq_ids}) {
4116 for (@seqids) {
4117 my $segment = $db->segment($_) or die "Can't find chromosome $_ in default database";
4118 print $s "$_\t",$segment->length,"\n";
4119 }
4120 close $s;
4121 return 1;
4122 }
4123  
4124 # Bio::DasI objects have an entry_points method
4125 if (my @segs = eval {$db->entry_points}) {
4126 for (@segs) {
4127 print $s $_,"\t",$_->length,"\n";
4128 }
4129 close $s;
4130 return 1;
4131 }
4132  
4133 # Otherwise we search for databases with associated fasta files
4134 # or indexed fasta (fai) files.
4135 my ($fasta,$fastai);
4136 my @dbs = $source->databases;
4137 for my $db (@dbs) {
4138 my ($dbid,$adaptor,%args) = $source->db2args($db);
4139 my $fasta = $args{-fasta} or next;
4140 if (-e "$fasta.fai") {
4141 $fastai ||= "$fasta.fai";
4142 } elsif (-e $fasta && -w dirname($fasta)) {
4143 $fasta ||= $fasta;
4144 }
4145 }
4146  
4147 return unless $fasta or $fastai;
4148  
4149 if (!$fastai && eval "require Bio::DB::Sam;1") {
4150 Bio::DB::Sam::Fai->load($fasta);
4151 $fastai = "$fasta.fai";
4152 }
4153  
4154 if ($fastai) { # fai file -- copy to sizes
4155 open my $f,$fastai or die "Can't open $fasta: $!";
4156 while (<$f>) {
4157 my ($seqid,$length) = split /\s+/;
4158 print $s "$seqid\t$length\n";
4159 }
4160 close $f;
4161 }
4162  
4163 elsif (eval "require Bio::DB::Fasta; 1") {
4164 my $fa = Bio::DB::Fasta->new($fasta);
4165 my @ids = $fa->ids;
4166 for my $i (@ids) {
4167 print $s $i,"\t",$fa->length($i),"\n";
4168 }
4169 undef $fa;
4170 }
4171  
4172 close $s;
4173 return 1;
4174 }
4175  
4176 # Change IDs (Old Uploads ID, New Uploads ID, Old UserID, New User ID) - Sometimes the user's session (as stored by the ID) is unretrievable - this changes the session to a new one so that a user's login is still valid.
4177 sub change_ids {
4178 my $self = shift;
4179 my $old_uploadsid = shift;
4180 my $new_uploadsid = shift;
4181 my $old_userid = shift;
4182 my $new_userid = shift;
4183 my $usertracks = $self->user_tracks;
4184 $usertracks->change_ids($old_uploadsid, $new_uploadsid, $old_userid, $new_userid);
4185 my $userdb = $self->{userdb};
4186 $userdb->change_ids($old_uploadsid, $new_uploadsid, $old_userid, $new_userid);
4187 }
4188  
4189 # The following functions are implemented in HTML.pm (or any other Render subclass), are never called, and are here for debugging.
4190 sub format_autocomplete {
4191 croak "implement in subclass";
4192 }
4193  
4194 sub render_actionmenu {
4195 my $self = shift;
4196 croak "implement in subclass";
4197 }
4198  
4199 sub render_tabbed_pages {
4200 my $self = shift;
4201 my ($main,$upload_share,$config) = @_;
4202 croak "implement in subclass";
4203 }
4204  
4205 sub render_select_track_link {
4206 croak "implement in subclass";
4207 }
4208  
4209 sub render_upload_share_section {
4210 croak "implement in subclass";
4211 }
4212  
4213 sub render_top {
4214 my $self = shift;
4215 my $title = shift;
4216 croak "render_top() should not be called in parent class";
4217 }
4218  
4219 sub render_title {
4220 my $self = shift;
4221 my $title = shift;
4222 croak "render_title() should not be called in parent class";
4223 }
4224  
4225 sub render_navbar {
4226 my $self = shift;
4227 my $seg = shift;
4228 croak "render_navbar() should not be called in parent class";
4229 }
4230  
4231 sub clear_highlights { croak 'implement in subclass' }
4232  
4233 sub render_toggle_track_table {
4234 my $self = shift;
4235 croak "render_toggle_track_table() should not be called in parent class";
4236 }
4237  
4238 sub render_track_table {
4239 my $self = shift;
4240 croak "render_track_table() should not be called in parent class";
4241 }
4242  
4243 sub render_instructions {
4244 my $self = shift;
4245 my $title = shift;
4246 croak "render_instructions() should not be called in parent class";
4247 }
4248 sub render_multiple_choices {
4249 my $self = shift;
4250 croak "render_multiple_choices() should not be called in parent class";
4251 }
4252  
4253 sub render_global_config {
4254 my $self = shift;
4255 croak "render_global_config() should not be called in parent class";
4256 }
4257  
4258 sub render_toggle_external_table {
4259 my $self = shift;
4260 croak "render_toggle_external_table() should not be called in parent class";
4261 }
4262  
4263 sub render_toggle_userdata_table {
4264 my $self = shift;
4265 croak "render_toggle_userdata_table() should not be called in parent class";
4266 }
4267  
4268 sub render_bottom {
4269 my $self = shift;
4270 my $features = shift;
4271 croak "render_bottom() should not be called in parent class";
4272 }
4273  
4274 sub html_frag {
4275 my $self = shift;
4276 croak "html_frag() should not be called in parent class";
4277 }
4278  
4279 sub fatal_error {
4280 my $self = shift;
4281 my @msg = @_;
4282 croak 'Please call fatal_error() for a subclass of Bio::Graphics::Browser2::Render';
4283 }
4284  
4285 sub zoomBar {
4286 my $self = shift;
4287 croak 'Please define zoomBar() in a subclass of Bio::Graphics::Browser2::Render';
4288 }
4289  
4290 sub track_config {
4291 my $self = shift;
4292 my $track_name = shift;
4293 croak "track_config() should not be called in parent class";
4294 }
4295  
4296 sub select_subtracks {
4297 my $self = shift;
4298 my $track_name = shift;
4299 croak "select_subtracks() should not be called in parent class";
4300 }
4301  
4302 sub share_track {
4303 my $self = shift;
4304 my $track_name = shift;
4305 croak "share_track() should not be called in parent class";
4306 }
4307  
4308 sub render_ruler_div {
4309 my $self = shift;
4310 croak "render_ruler_div() should not be called in parent class";
4311 }
4312  
4313 ########## note: "sub tr()" makes emacs' syntax coloring croak, so place this function at end
4314 sub translate {
4315 my $self = shift;
4316 my $lang = $self->language or return @_;
4317 $lang->translate(@_);
4318 }
4319  
4320 sub login_manager {
4321 my $self = shift;
4322 return $self->{login_manager} if exists $self->{login_manager};
4323 eval "require Bio::Graphics::Browser2::Render::Login" unless
4324 Bio::Graphics::Browser2::Render::Login->can('new');
4325 return $self->{login_manager} = Bio::Graphics::Browser2::Render::Login->new($self);
4326 }
4327  
4328 sub snapshot_manager {
4329 my $self = shift;
4330 return $self->{snapshot_manager} ||= Bio::Graphics::Browser2::Render::SnapshotManager->new($self);
4331 }
4332  
4333 sub feature_summary_message {
4334 my $self = shift;
4335 my ($event_type,$label) = @_;
4336 my $sticky = $event_type eq 'mousedown' || 0;
4337 my $message= $self->data_source->setting($label=>'key'). ' '.lc($self->tr('FEATURE_SUMMARY'));
4338 return "GBubble.showTooltip(event,'$message',$sticky)";
4339 }
4340  
4341 sub feature_interaction {
4342 my $self = shift;
4343 my ($event_type,$label,$feature) = @_;
4344 my $source = $self->data_source;
4345 my $settings = $self->state;
4346 my $tips = $source->global_setting('balloon tips') && $settings->{'show_tooltips'};
4347 my $renderer = $self->get_panel_renderer($self->segment);
4348  
4349 if ($tips) {
4350 my $sticky = $source->setting($label,'balloon sticky');
4351 my $height = $source->setting($label,'balloon height') || 300;
4352  
4353 my $stick = defined $sticky ? $sticky : $event_type eq 'mousedown';
4354 $stick ||= 0;
4355 my ($balloon_style,$balloon_action)
4356 = $renderer->balloon_tip_setting($event_type eq 'mousedown' ? 'balloon click' : 'balloon hover',$label,$feature,undef,undef);
4357 $balloon_action ||= $renderer->make_title($feature,undef,$label,undef)
4358 if $source->global_setting('titles are balloons') && $event_type eq 'mouseover';
4359 $balloon_style ||= 'GBubble';
4360 if ($balloon_action) {
4361 my $action = $balloon_action =~ /^(http|ftp):/
4362 ? "$balloon_style.showTooltip(event,'<iframe width='+$balloon_style.maxWidth+' height=$height " .
4363 "frameborder=0 src=$balloon_action></iframe>',$stick,$balloon_style.maxWidth)"
4364 : "$balloon_style.showTooltip(event,'$balloon_action',$stick)";
4365 return ('text/plain',$action)
4366 }
4367 }
4368  
4369 my $link = $renderer->make_link($feature,undef,$label,undef);
4370 my $target = $renderer->make_link_target($feature,undef,$label,undef);
4371 return ('text/plain',$target ? "window.open('$link','$target')" : "document.location='$link'") if $link;
4372 return;
4373 }
4374 sub tr {
4375 my $self = shift;
4376 my $lang = $self->language or return @_;
4377 $lang->translate(@_);
4378 }
4379  
4380 1;
4381