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

filter: Statementstmt 0.0% 0 / 1459 Branchbran 0.0% 0 / 576 Conditioncond 0.0% 0 / 503 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 99 Podpod 0.0% 0 / 69 totaltotal 0.0% 0 / 2706 CC 289 SCAR 55.6
CC
289
Cov
0%
run_local_requests
1122.0
add_features_to_track
756.0
wrap_rendered_track
600.0
CRAP 260.4
1 package Bio::Graphics::Browser2::RenderPanels;
2 use strict;
3 use warnings;
4  
5 use GD 'gdTransparent','gdStyled';
6  
7 use Bio::Graphics;
8 use Digest::MD5 'md5_hex';
9 use Carp 'croak','cluck';
10 use Bio::Graphics::Browser2::Render;
11 use Bio::Graphics::Browser2::CachedTrack;
12 use Bio::Graphics::Browser2::Util qw[shellwords url_label];
13 use Bio::Graphics::Browser2::Render::Slave::Status;
14 use IO::File;
15 use Time::HiRes 'sleep','time';
16 use Data::Dumper;
17 use POSIX 'WNOHANG','setsid';
18 use CGI qw(:standard param escape unescape);
19  
20 use constant TRUE => 1;
21 use constant DEBUG => 0;
22 use constant DEBUGGING_RECTANGLES => 0; # outline the imagemap
23 use constant BENCHMARK => 0;
24 use constant SLAVE_RETRIES => 2;
25  
26 use constant DEFAULT_EMPTYTRACKS => 0;
27 use constant PAD_DETAIL_SIDES => 10;
28 use constant RULER_INTERVALS => 20;
29 use constant PAD_OVERVIEW_BOTTOM => 5;
30 use constant TRY_CACHING_CONFIG => 1;
31 use constant MAX_PROCESSES => 4;
32 use constant MAX_TITLE_LEN => 50;
33  
34 # when we load, we set a global indicating the LWP::UserAgent is available
35 my $LPU_AVAILABLE;
36 my $STO_AVAILABLE;
37  
38 sub new {
39 my $class = shift;
40 my %options = @_;
41 my $segment = $options{-segment};
42 my $whole_segment = $options{-whole_segment};
43 my $region_segment= $options{-region_segment};
44 my $data_source = $options{-source};
45 my $page_settings = $options{-settings};
46 my $language = $options{-language};
47 my $render = $options{-render};
48  
49 my $self = bless {},ref $class || $class;
50 $self->segment($segment);
51 $self->whole_segment($whole_segment);
52 $self->region_segment($region_segment);
53 $self->source($data_source);
54 $self->settings($page_settings);
55 $self->language($language);
56 $self->render($render);
57  
58 return $self;
59 }
60  
61 sub segment {
62 my $self = shift;
63 my $d = $self->{segment};
64 $self->{segment} = shift if @_;
65 return $d;
66 }
67  
68 sub whole_segment {
69 my $self = shift;
70 my $d = $self->{whole_segment};
71 $self->{whole_segment} = shift if @_;
72 return $d;
73 }
74  
75 sub region_segment {
76 my $self = shift;
77 my $d = $self->{region_segment};
78 $self->{region_segment} = shift if @_;
79 return $d;
80 }
81  
82 sub source {
83 my $self = shift;
84 my $d = $self->{source};
85 $self->{source} = shift if @_;
86 return $d;
87 }
88  
89 sub settings {
90 my $self = shift;
91 my $d = $self->{settings};
92 $self->{settings} = shift if @_;
93 return $d;
94 }
95  
96 sub language {
97 my $self = shift;
98 my $d = $self->{language};
99 $self->{language} = shift if @_;
100 return $d;
101 }
102  
103 sub render {
104 my $self = shift;
105 my $d = $self->{render};
106 $self->{render} = shift if @_;
107 return $d;
108 }
109  
110 # NOTE: This is essentially the same as render_panels() in the 'stable' Browser.pm
111 # This renders the named tracks and returns the HTML needed to display them.
112 # Caching and distribution across multiple databases is implemented.
113 #
114 # input args:
115 # {labels => [array of track labels],
116 # external_features => [third party annotations (Bio::DasI objects)],
117 # deferred => generate in background
118 # };
119 # output
120 # if deferred => false...
121 # { label1 => html1, label2 => html2...} where HTML is the <div> for the named track
122 #
123 # if deferred => true
124 # { label1 => CachedTrack1, label2 => CachedTrack2...}
125 # where CachedTrack is a Bio::Graphics::Panel::CachedTrack object that will eventually
126 # receive the data. Poll this object for its data.
127 #
128 sub request_panels {
129 my $self = shift;
130 my $args = shift;
131  
132 my $data_destinations = $self->make_requests($args);
133 my $render = $args->{render};
134  
135 # sort the requests out into local and remote ones
136 my ($local_labels,
137 $remote_labels) = $self->sort_local_remote($data_destinations);
138  
139 warn "[$$] request_panels(): section = $args->{section}; local labels = @$local_labels, remote labels = @$remote_labels" if DEBUG;
140  
141 # If we don't call clone_databases early, then we can have
142 # a race condition where the parent hits the DB before the child
143 # NOTE: commented out because clone logic has changed - may need to reenable this
144 # for postgresql databases
145 # Bio::Graphics::Browser2::DataBase->clone_databases();
146  
147 my $do_local = @$local_labels;
148 my $do_remote = @$remote_labels;
149  
150 # In the case of a deferred request we fork.
151 # Parent returns the list of requests.
152 # Child processes the requests in the background.
153 # If both local and remote requests are needed, then we
154 # fork a second time and process them in parallel.
155 if ($args->{deferred}) {
156  
157 # precache local databases into cache
158 my $length = $self->segment_length;
159 my $source = $self->source;
160 for my $l (@$local_labels) {
161 my $db = eval { $source->open_database($l,$length)};
162 }
163  
164 my $child = $render->fork();
165  
166 if ($child) {
167 warn "[$$] Forked new rendering panel $child for $args->{section}" if DEBUG;
168 return $data_destinations;
169 }
170  
171 open STDIN, "</dev/null" or die "Couldn't reopen stdin";
172 open STDOUT,">/dev/null" or die "Couldn't reopen stdout";
173  
174 if ( $do_local && $do_remote ) {
175 if ( $render->fork() ) {
176 $self->run_local_requests( $data_destinations,
177 $args,
178 $local_labels );
179 }
180 else {
181 $self->run_remote_requests( $data_destinations,
182 $args,
183 $remote_labels );
184 }
185 }
186 elsif ($do_local) {
187 warn "[$$] run_local_requests (@$local_labels)" if DEBUG;
188 $self->run_local_requests( $data_destinations, $args,$local_labels );
189 }
190 elsif ($do_remote) {
191 $self->run_remote_requests( $data_destinations, $args,$remote_labels );
192 }
193  
194 warn "[$$] $args->{section} RENDERER EXITING" if DEBUG;
195 CORE::exit 0;
196 }
197  
198 else { # not deferred
199 $self->run_local_requests($data_destinations,$args,$local_labels);
200 $self->run_remote_requests($data_destinations,$args,$remote_labels);
201 return $data_destinations;
202 }
203 }
204  
205 sub render_panels {
206 my $self = shift;
207 my $args = shift;
208 delete $args->{deferred}; # deferred execution incompatible with this call
209 my $requests = $self->request_panels($args);
210 return $self->render_tracks($requests,$args);
211 }
212  
213  
214 # this method returns a hashref in which the keys are track labels
215 # and the values are hashrefs with the keys 'gd' and 'map'. The former
216 # is a GD object, and the latter is the raw map data.
217 # Raw map data is tab-delimited in the format
218 # <feature name><x1><y1><x2><y2><key1><value1><key2><value2>...
219 # use map_html() to make HTML out of the thing
220 sub render_track_images {
221 my $self = shift;
222 my $args = shift;
223  
224 delete $args->{deferred}; # deferred execution incompatible with this call
225 my $requests = $self->request_panels($args);
226  
227 my %results;
228 my %still_pending = map {$_=>1} keys %$requests;
229 my $k = 1.25;
230 my $delay = 0.1;
231 while (%still_pending) {
232 for my $label (keys %$requests) {
233 my $data = $requests->{$label};
234 $data->cache_time(0) if $data->cache_time < 0;
235 next if $data->status eq 'PENDING';
236 next if $data->status eq 'EMPTY';
237 if ($data->status eq 'AVAILABLE') {
238 my ($gd,$map) = eval{($data->gd,$data->map)};
239 $results{$label}{gd} = $gd;
240 $results{$label}{map} = $map;
241 }
242 delete $still_pending{$label};
243 }
244 sleep $delay if %still_pending;
245 $delay *= $k; # sleep a little longer each time using an exponential backoff
246 }
247 return \%results;
248 }
249  
250  
251 # return a hashref in which the keys are labels and the values are
252 # CachedTrack objects that are ready to accept data.
253 sub make_requests {
254 my $self = shift;
255 my $args = shift;
256 my $source = $self->source;
257 my $settings=$self->settings;
258  
259 my $feature_files = $args->{external_features};
260 my $labels = $args->{labels};
261  
262 warn "[$$] MAKE_REQUESTS, labels = ",join ',',@$labels if DEBUG;
263  
264 my $base = $self->get_cache_base();
265 my @panel_args = $self->create_panel_args($args);
266 my @cache_extra = @{ $args->{cache_extra} || [] };
267 my %d;
268  
269 warn "panel_args = @panel_args, cache_extra=@cache_extra" if DEBUG;
270  
271 foreach my $label ( @{ $labels || [] } ) {
272  
273 my @track_args = $self->create_track_args( $label, $args );
274 my (@filter_args,@featurefile_args,@subtrack_args);
275  
276 my $format_option = $settings->{features}{$label}{options};
277  
278 my $filter = $settings->{features}{$label}{filter};
279 @filter_args = %{$filter->{values}} if $filter->{values};
280 @subtrack_args = @{$settings->{subtracks}{$label}}
281 if $settings->{subtracks}{$label};
282 my $ff_error;
283  
284 # get config data from the feature files
285 (my $track = $label) =~ s/:(overview|region|details?)$//;
286 if ($feature_files && exists $feature_files->{$track}) {
287  
288 # some broken logic here...
289 my $feature_file = $feature_files->{$track} || $feature_files->{$label};
290  
291 unless (ref $feature_file) { # upload problem!
292 my $cache_object = Bio::Graphics::Browser2::CachedTrack->new(
293 -cache_base => $base,
294 -panel_args => \@panel_args,
295 -track_args => \@track_args,
296 -extra_args => [ @cache_extra,
297 @filter_args,
298 @featurefile_args,
299 @subtrack_args,
300 $format_option,
301 $label ],
302 );
303
304 my $msg = eval {$args->{remotes}->error($track)};
305 $cache_object->flag_error($msg || "Could not fetch data for $track");
306 $d{$track} = $cache_object;
307 next;
308 }
309
310 # broken logic here?
311 # next unless $label =~ /:$args->{section}$/;
312 @featurefile_args = eval {
313 $feature_file->isa('Bio::Das::Segment')||$feature_file->types,
314 $feature_file->mtime;
315 };
316 }
317  
318 warn "[$$] creating CachedTrack for $label, nocache = $args->{nocache}" if DEBUG;
319 my $cache_time = $args->{nocache} ? -1
320 : $settings->{cache} ? $source->cache_time
321 : -1;
322  
323 my $cache_object = Bio::Graphics::Browser2::CachedTrack->new(
324 -cache_base => $base,
325 -panel_args => \@panel_args,
326 -track_args => \@track_args,
327 -extra_args => [ @cache_extra,
328 @filter_args,
329 @featurefile_args,
330 @subtrack_args,
331 $format_option,
332 $label ],
333 -cache_time => $cache_time
334 );
335  
336 $d{$label} = $cache_object;
337 }
338  
339 return \%d;
340 }
341  
342 sub use_renderfarm {
343 my $self = shift;
344 return $self->{use_renderfarm} if exists $self->{use_renderfarm};
345  
346 #comment out to force remote rendering (kludge)
347 $self->source->global_setting('renderfarm') or return;
348  
349 $LPU_AVAILABLE = eval { require LWP::UserAgent; } unless defined $LPU_AVAILABLE;
350 $STO_AVAILABLE = eval { require Storable; 1; } unless defined $STO_AVAILABLE;
351 $Storable::Deparse = 1;
352  
353 $self->{use_renderfarm} = $LPU_AVAILABLE && $STO_AVAILABLE;
354 return $self->{use_renderfarm} if $self->{use_renderfarm};
355 warn "The renderfarm setting requires the LWP::UserAgent and Storable modules,
356 but one or both are missing. Reverting to local rendering.\n";
357 return;
358 }
359  
360 sub drag_and_drop {
361 my $self = shift;
362 my $override = shift;
363 return if defined $override && !$override;
364 my $source = $self->source;
365 return unless $source->global_setting('drag and drop'); # drag and drop turned off
366 return if $source->global_setting('postgrid'); # postgrid forces drag and drop off
367 1;
368 }
369  
370 # Returns the full HTML listing of all requested tracks.
371 sub render_tracks {
372 my $self = shift;
373 my $requests = shift;
374 my $args = shift;
375 my %result;
376  
377 for my $label ( keys %$requests ) {
378 my $data = $requests->{$label};
379 my $gd = eval{$data->gd} or next;
380 my $map = $data->map;
381 my $titles = $data->titles;
382 my $width = $data->width;
383 my $height = $data->height;
384 my $url = $self->source->generate_image($gd);
385  
386 # for debugging
387 my $status = $data->status;
388  
389 $result{$label} = $self->wrap_rendered_track(
390 label => $label,
391 area_map => $map,
392 width => $width,
393 height => $height,
394 url => $url,
395 titles => $titles,
396 status => $status,
397 section => $args->{section},
398 );
399 }
400
401 return \%result;
402
403 }
404  
405 # Returns the HMTL to show a track with controls, title, arrows, etc.
406 sub wrap_rendered_track {
407 my $self = shift;
408 my %args = @_;
409 my $label = $args{'label'};
410 my $map = $args{'area_map'};
411 my $width = $args{'width'};
412 my $height = $args{'height'};
413 my $url = $args{'url'};
414 my $titles = $args{'titles'};
415
416 # track_type Used in register_track() javascript method
417 my $track_type = $args{'track_type'} || 'standard';
418 my $status = $args{'status'}; # for debugging
419  
420 my $buttons = $self->source->globals->button_url;
421 my $plus = "$buttons/plus.png";
422 my $minus = "$buttons/minus.png";
423 my $kill = "$buttons/ex.png";
424 my $share = "$buttons/share.png";
425 my $help = "$buttons/query.png";
426 my $pop_in = "$buttons/pop_in.png";
427 my $pop_out = "$buttons/pop_out.png";
428 my $download = "$buttons/download.png";
429 my $configure= "$buttons/tools.png";
430 my $menu = "$buttons/menu.png";
431 my $favicon = "$buttons/fmini.png";
432 my $favicon_2= "$buttons/fmini_2.png";
433 my $add_or_remove = $self->language->translate('ADDED_TO') || 'Add track to favorites';
434
435 my $settings = $self->settings;
436 my $source = $self->source;
437  
438 my $collapsed = $settings->{track_collapsed}{$label};
439 my $img_style = $collapsed ? "display:none" : "display:inline";
440  
441 # commented out alt because it interferes with balloon tooltips is IE
442 my $map_id = "${label}_map";
443  
444 # Work around bug in google chrome which is manifested by the <area> link information
445 # on all EVEN reloads of the element by ajax calls. Weird.
446 my $agent = CGI->user_agent || '';
447 $map_id .= "_".int(rand(1000)) ;
448  
449 my $img = img(
450 { -src => $url,
451 -usemap => "#${map_id}",
452 -width => $width,
453 -id => "${label}_image",
454 -height => $height,
455 -border => 0,
456 -name => $label,
457 -class => 'track_image',
458 -style => $img_style
459
460 }
461 );
462  
463 my $icon = $collapsed ? $plus : $minus;
464 my $show_or_hide = $self->language->translate('SHOW_OR_HIDE_TRACK')
465 || "Show or Hide";
466 my $kill_this_track = $self->language->translate('KILL_THIS_TRACK')
467 || "Turn off this track.";
468 my $share_this_track = $self->language->translate('SHARE_THIS_TRACK')
469 || "Share this track";
470  
471 my $download_this_track = '';
472 $download_this_track .= $self->language->translate('DOWNLOAD_THIS_TRACK')
473 || "<b>Download this track</b>";
474  
475 my $configure_this_track = '';
476 $configure_this_track .= $self->language->translate('CONFIGURE_THIS_TRACK')
477 || "Configure this track";
478  
479 my $about_this_track = '';
480 $about_this_track .= $self->language->translate('ABOUT_THIS_TRACK',$label)
481 || "<b>About this track</b>";
482  
483 my $popout = '';
484 $popout .= $self->language->translate('POP_OUT')
485 || "<b>Pop out/in</b>";
486  
487 my $escaped_label = CGI::escape($label);
488  
489 # The inline config will go into a box 500px wide by 500px tall
490 # scrollbars will appear if there is overflow. The box should shrink
491 # to fit if the contents are smaller than 500 x 500
492 my $config_click;
493 if ( $label =~ /^plugin:/ ) {
494 my $config_url = "url:?plugin=$escaped_label;plugin_do=Configure";
495 $config_click
496 = "GBox.showTooltip(event,'$config_url',true)";
497 }
498  
499 elsif ( $label =~ /^file:/ ) {
500 my $escaped_file = CGI::escape($label);
501 $config_click = qq[Controller.edit_upload('$escaped_file')];
502 }
503  
504 else {
505 my $config_url = "url:?action=configure_track;track=$escaped_label";
506 $config_click
507 = "GBox.showTooltip(event,'$config_url',true)";
508 }
509  
510 my $help_url = "url:?action=cite_track;track=$escaped_label";
511 my $help_click = "GBox.showTooltip(event,'$help_url',1)";
512  
513 my $download_click = "GBox.showTooltip(event,'url:?action=download_track_menu;track=$escaped_label;view_start='+TrackPan.get_start()+';view_stop='+TrackPan.get_stop(),true)" unless $label =~ /^(http|ftp)/;
514  
515 my $title;
516 if ($label =~ /^file:/) {
517 $title = $label;
518 }
519 elsif ($label =~ /^(http|ftp):/) {
520 $title = url_label($label);
521  
522 }
523 elsif ($label =~ /^plugin/) {
524 $title = $self->render->plugin_name($label);
525 }
526 else {
527 (my $l = $label) =~ s/:\w+$//;
528 $title = $source->setting( $label => 'key') || $l;
529 }
530 $title =~ s/:(overview|region|detail)$//;
531
532 my $balloon_style = $source->global_setting('balloon style') || 'GBubble';
533 my $favorite = $settings->{favorites}{$label};
534 my $starIcon = $favorite ? $favicon_2 : $favicon;
535 my $starclass = $favorite ? "toolbarStar favorite" : "toolbarStar";
536 (my $l = $label) =~ s/:detail$//;
537 my $fav_click = "toggle_titlebar_stars('$l')";
538  
539 my @images = (
540 $fav_click ? img({ -src => $starIcon,
541 -id =>"barstar_${l}",
542 -class => $starclass,
543 -style => 'cursor:pointer',
544 -onmousedown => $fav_click,
545 $self->if_not_ipad(-onMouseOver => "$balloon_style.showTooltip(event,'$add_or_remove')"),
546 })
547 : '',
548 img({ -src => $icon,
549 -id => "${label}_icon",
550 -onClick => "collapse('$label')",
551 -style => 'cursor:pointer',
552 $self->if_not_ipad(-onMouseOver => "$balloon_style.showTooltip(event,'$show_or_hide')"),
553 }
554 ),
555  
556 img({ -src => $kill,
557 -id => "${label}_kill",
558 -onClick => "ShowHideTrack('$l',false)",
559 -style => 'cursor:pointer',
560 $self->if_not_ipad(-onMouseOver => "$balloon_style.showTooltip(event,'$kill_this_track')"),
561 }
562 ),
563 img({ -src => $share,
564 -style => 'cursor:pointer',
565 -onMousedown => "Controller.get_sharing(event,'url:?action=share_track;track=$escaped_label',true)",
566 $self->if_not_ipad(-onMouseOver =>
567 "$balloon_style.showTooltip(event,'$share_this_track')"),
568 }
569 ),
570  
571 $download_click ? img({ -src => $download,
572 -style => 'cursor:pointer',
573 -onmousedown => $download_click,
574 $self->if_not_ipad(-onMouseOver =>
575 "$balloon_style.showTooltip(event,'$download_this_track')"),
576 })
577 : '',
578  
579 $config_click ? img({ -src => $configure,
580 -style => 'cursor:pointer',
581 -onmousedown => $config_click,
582 $self->if_not_ipad(-onMouseOver => "$balloon_style.showTooltip(event,'$configure_this_track')"),
583 })
584 : '',
585 );
586  
587 my $help_img = img({ -src => $help,
588 -style => 'cursor:pointer',
589 -onmousedown => $help_click,
590 -onMouseOver =>
591 "$balloon_style.showTooltip(event,'$about_this_track')",
592 });
593
594 my $pin_img = img({ -src => $pop_out,
595 -class => 'pin_button',
596 -onmousedown => 'Controller.ghost_track(this)',
597 -onmouseover => "$balloon_style.showTooltip(event,'$popout')",
598 }
599 );
600
601 my $ipad_collapse = $collapsed ? 'Expand':'Collapse';
602 my $cancel_ipad = 'Turn off';
603 my $share_ipad = 'Share';
604 my $configure_ipad = 'Configure';
605 my $download_ipad = 'Download';
606 my $about_ipad = 'About track';
607  
608 my $bookmark = 'Favorite';
609 my $menuicon = img ({-src => $menu,
610 -style => 'padding-right:15px;',},),
611
612 my $popmenu = $self->if_ipad(
613 div({-id =>"popmenu_${title}", -style => 'display:none'},
614 div({-class => 'ipadtitle', -id => "${label}_title",}, $title ),
615 div({-class => 'ipadcollapsed',
616 -id => "${label}_icon",
617 -onClick => "collapse('$label')",
618 },
619 div({-class => 'linkbg',
620 -onClick => "swap(this,'Collapse','Expand')",
621 -id => "${label}_expandcollapse", },$ipad_collapse)),
622 div({-class => 'ipadcollapsed',
623 -id => "${label}_kill",
624 -onClick => "ShowHideTrack('$label',false)",
625 }, div({-class => 'linkbg',},
626 $cancel_ipad)),
627 div({-class => 'ipadcollapsed',
628 -onMousedown => "Controller.get_sharing(event,'url:?action=share_track;track=$escaped_label',true)",},
629 div({-class => 'linkbg',},$share_ipad)),
630 div({-class => 'ipadcollapsed', -
631 onmousedown => $config_click,}, div({-class => 'linkbg',},$configure_ipad)),
632 div({-class => 'ipadcollapsed',
633 -onmousedown => $fav_click,},
634 div({-class => 'linkbg', -onClick => "swap(this,'Favorite','Unfavorite')"},$bookmark)),
635 div({-class => 'ipadcollapsed',
636 -onmousedown => $download_click,},
637 div({-class => 'linkbg',},$download_ipad)),
638 div({-class => 'ipadcollapsed',
639 -style => 'width:200px',
640 -onmousedown => $help_click,},
641 div({-class => 'linkbg', -style => 'position:relative; left:30px;',},$about_ipad)),
642 ));
643 $popmenu ||= ''; # avoid uninit variable warning
644
645 my $clipped_title = $title;
646 $clipped_title = substr($clipped_title,0,MAX_TITLE_LEN-3).'...' if length($clipped_title) > MAX_TITLE_LEN;
647  
648 # modify the title if it is a track with subtracks
649 $self->select_features_menu($label,\$clipped_title);
650
651 my $titlebar =
652 span(
653 { -class => $collapsed ? 'titlebar_inactive' : 'titlebar',
654 -id => "${label}_title",
655 },
656 $self->if_not_ipad(@images),
657 $self->if_ipad(span({-class => 'menuclick', -onClick=> "GBox.showTooltip(event,'load:popmenu_${title}')"}, $menuicon,)),
658 span({-class => 'drag_region'},
659 span({-style=>'display:inline-block;width:32px'},'&nbsp;'),
660 $clipped_title.'&nbsp;'.$help_img.span({-style=>'display:inline-block;width:32px'},'&nbsp;').$pin_img)
661 );
662 my $show_titlebar
663 = ( ( $source->setting( $label => 'key' ) || '' ) ne 'none' );
664 my $is_scalebar = $label =~ /scale/i;
665 my $is_detail = $label !~ /overview|region/i;
666 $show_titlebar &&= !$is_scalebar;
667  
668 my $map_html = $self->map_html($map,$map_id);
669  
670 # the padding is a little bit of empty track that is displayed only
671 # when the track is collapsed. Otherwise the track labels get moved
672 # to the center of the page!
673 my $pad = $self->render_image_pad(
674 $args{section}||Bio::Graphics::Browser2::DataSource->get_section_from_label($label),
675 );
676 my $pad_url = $self->source->generate_image($pad);
677 my $pad_img = img(
678 { -src => $pad_url,
679 -width => $pad->width,
680 -border => 0,
681 -id => "${label}_pad",
682 -class => 'track_image',
683 -style => $collapsed ? "display:inline" : "display:none",
684 }
685 );
686  
687 my $overlay_div = '';
688  
689 # Add arrows for panning to details scalebar panel
690 if ($is_scalebar && $is_detail) {
691 my $style = 'opacity:0.35;position:absolute;border:none;cursor:pointer';
692 my $pan_left = img({
693 -style => $style . ';left:5px',
694 -class => 'panleft',
695 -src => "$buttons/panleft.png",
696 -onClick => "Controller.scroll('left',0.5)"
697 });
698  
699 my $pan_right = img({
700 -style => $style . ';right:5px',
701 -class => 'panright',
702 -src => "$buttons/panright.png",
703 -onClick => "Controller.scroll('right',0.5)",
704 });
705
706 my $scale_div = div( { -id => "detail_scale_scale",
707 -style => "position:absolute; top:12px", }, "" );
708  
709 $overlay_div = div( { -id => "${label}_overlay_div",
710 -style => "position:absolute; top:0px; width:100%; left:0px", }, $pan_left . $pan_right . $scale_div);
711 }
712  
713 my $inner_div = div( { -id => "${label}_inner_div",-class=>'inner_div' }, $img . $pad_img ); #Should probably improve this
714  
715  
716 my $subtrack_labels = join '',map {
717 my ($label,$left,$top,undef,undef,$color) = @$_;
718 $left -= $source->global_setting('pad_left') + PAD_DETAIL_SIDES;
719 $left = 3 if $left < 3;
720 my ($r,$g,$b,$a) = $color =~ /rgba\((\d+),(\d+),(\d+),([\d.]+)/;
721 $a = 0.60 if $a > 0.75;
722 my $fgcolor = $a <= 0.5 ? 'black' : ($r+$g+$b)/3 > 128 ? 'black' : 'white';
723 div({-class=>'subtrack',-style=>"top:${top}px;left:${left}px;color:$fgcolor;background-color:rgba($r,$g,$b,$a)"},$label);
724 } @$titles;
725  
726 my $html = div({-class=>'centered_block',
727 -style=>"position:relative;overflow:hidden"
728 },
729 ($show_titlebar ? $titlebar : '' ) . $popmenu . $subtrack_labels . $inner_div . $overlay_div ) . ( $map_html || '' );
730 return $html;
731 }
732  
733 sub if_not_ipad {
734 my $self = shift;
735 my @args = @_;
736 my $agent = CGI->user_agent || '';
737 my $probably_ipad = $agent =~ /Mobile.+Safari/i;
738 return if $probably_ipad;
739 return @args;
740 }
741  
742 sub if_ipad {
743 my $self = shift;
744 my @args = @_;
745 my $agent = CGI->user_agent || '';
746 my $probably_ipad = $agent =~ /Mobile.+Safari/i;
747 return if !$probably_ipad;
748 return @args;
749 }
750 # This routine is called to hand off the rendering to a remote renderer.
751 # The remote processor does not have to have a copy of the config file installed;
752 # the entire DataSource object is sent to it in serialized form via
753 # POST. It returns a serialized hash consisting of the GD object and the imagemap.
754 #
755 # INPUT $renderers_hashref
756 # $renderers_hashref->{$remote_url}{$track}
757 #
758 # RETURN NOTHING (data will be stored in track cache for later retrieval)
759 #
760 # POST outgoing arguments:
761 # datasource => serialized Bio::Graphics::Browser2::DataSource
762 # settings => serialized state hash (from the session)
763 # tracks => serialized list of track names to render
764 #
765 # POST result: serialized { label1 => {image,map,width,height,file,gd,boxes}... }
766 #
767 # reminder: segment can be found in the settings as $settings->{ref,start,stop,flip}
768 sub run_remote_requests {
769 my $self = shift;
770 my ($requests,$args,$labels) = @_;
771  
772 warn "[$$] run_remote_requests on @$labels" if DEBUG;
773 my $render = $args->{render};
774  
775 my @labels_to_generate = @$labels;
776 return unless @labels_to_generate;
777  
778 eval { use HTTP::Request::Common; } unless HTTP::Request::Common->can('POST');
779  
780 my $source = $self->source;
781 my $settings = $self->settings;
782 my $lang = $self->language;
783 my %env = map {$_=>$ENV{$_}} grep /^(GBROWSE|HTTP)/,keys %ENV;
784 my %args = map {$_=>$args->{$_}} grep /^-/,keys %$args; #/
785  
786 $args{$_} = $args->{$_} foreach ('section','image_class','cache_extra');
787  
788 # serialize the data source and settings
789 my $s_set = Storable::nfreeze($settings);
790 my $s_lang = Storable::nfreeze($lang);
791 my $s_env = Storable::nfreeze(\%env);
792 my $s_args = Storable::nfreeze(\%args);
793 my $s_mtime = 0;
794  
795 my $frozen_source = Storable::nfreeze($source);
796 my $s_dsn;
797  
798 if (TRY_CACHING_CONFIG) {
799 $s_dsn = undef;
800 $s_mtime = $source->mtime;
801 } else {
802 $s_dsn = Storage::nfreeze($source);
803 }
804  
805 # sort requests by their renderers
806 my $slave_status = $self->slave_status;
807  
808 my %renderers;
809 for my $label (@labels_to_generate) {
810 my $url = $source->remote_renderer($label) or next;
811 my @urls = shellwords($url);
812 $url = $slave_status->select(@urls);
813 warn "label => $url (selected)" if DEBUG;
814 unless ($url) {
815 # the status monitor indicates that there are no "up" servers for this
816 # track, so flag an error immediately and don't attempt to retrieve.
817 # after a suitable time interval has passed, we will try this server again
818 $requests->{$label}->flag_error('no slave servers are marked up');
819 } else {
820 $renderers{$url}{$label}++;
821 }
822 }
823  
824 my $ua = LWP::UserAgent->new;
825 my $timeout = $source->global_setting('slave_timeout')
826 || $source->global_setting('global_timeout')
827 || 30;
828 $ua->timeout($timeout);
829  
830 for my $url (keys %renderers) {
831  
832 my $child = Bio::Graphics::Browser2::Render->fork();
833 next if $child;
834  
835 my $total_time = time();
836  
837 # THIS PART IS IN THE CHILD
838 my @labels = keys %{$renderers{$url}};
839 warn "REMOTE FETCH ON @labels" if DEBUG;
840 my $s_track = Storable::nfreeze(\@labels);
841  
842 foreach (@labels) {
843 $requests->{$_}->lock(); # flag that request is in process
844 }
845
846 my $tries = 0;
847 FETCH: {
848 my $request = POST ($url,
849 Content_Type => 'form-data',
850 Content => [
851 operation => 'render_tracks',
852 panel_args => $s_args,
853 tracks => $s_track,
854 settings => $s_set,
855 datasource => $s_dsn||'',
856 data_name => $source->name,
857 data_mtime => $s_mtime,
858 language => $s_lang,
859 env => $s_env,
860 ]);
861  
862 my $time = time();
863 my $response = $ua->request($request);
864 my $elapsed = time() - $time;
865  
866 warn "$url=>@labels: ",$response->status_line," ($elapsed s)" if DEBUG;
867  
868 if ($response->is_success) {
869 my $contents = Storable::thaw($response->content);
870 for my $label (keys %$contents) {
871 my $map = $contents->{$label}{map}
872 or die "Expected a map from remote server, but got nothing!";
873 my $titles = $contents->{$label}{titles}
874 or die "Expected titles from remote server, but got nothing!";
875 my $gd2 = $contents->{$label}{imagedata}
876 or die "Expected imagedata from remote server, but got nothing!";
877 $requests->{$label}->put_data($gd2,$map,$titles);
878 }
879 $slave_status->mark_up($url);
880 }
881 elsif ($response->status_line =~ /REQUEST DATASOURCE/) {
882 $s_dsn = Storable::nfreeze($source);
883 $s_mtime = 0;
884 redo FETCH;
885 }
886 else {
887 my $uri = $request->uri;
888 my $response_line = $response->status_line;
889 $slave_status->mark_down($url);
890
891 # try to recover from a transient slave failure; this only works
892 # right if all of the tracks there are multiple equivalent slaves for the tracks
893 my %urls = map {$_=>1}
894 map {
895 shellwords($source->remote_renderer)
896 } @labels;
897 my $alternate_url = $slave_status->select(keys %urls);
898 if ($alternate_url) {
899 warn "[$$] retrying fetch of @labels with $alternate_url";
900 $url = $alternate_url;
901 redo FETCH if $tries++ < SLAVE_RETRIES;
902 }
903  
904 $response_line =~ s/^\d+//; # get rid of status code
905 $requests->{$_}->flag_error($response_line) foreach keys %{$renderers{$uri}};
906 }
907 }
908  
909 my $elapsed = time() - $total_time;
910 warn "[$$] total_time = $elapsed s" if DEBUG;
911  
912 CORE::exit(0); # from CHILD
913 }
914 }
915  
916 sub slave_status {
917 my $self = shift;
918 my $source = $self->source;
919 return $self->{slave_status} ||=
920 Bio::Graphics::Browser2::Render::Slave::Status->new(
921 $source->globals->slave_status_path
922 );
923 }
924  
925 # Sort requests into those to be performed locally
926 # and remotely. Returns two arrayrefs (\@local_labels,\@remote_labels)
927 # Our algorithm is very simple. It is a remote request if the "remote renderer"
928 # option is set, local otherwise. This means that a "remote renderer" of "localhost"
929 # will be treated as a remote renderer request.
930 sub sort_local_remote {
931 my $self = shift;
932 my $requests = shift;
933  
934 warn "requests = ",join ' ',keys %$requests if DEBUG;
935  
936 my @uncached;
937 if ($self->settings->{cache}){
938 @uncached = grep {$requests->{$_}->needs_refresh} keys %$requests;
939 }
940 else{
941 @uncached = keys %$requests;
942 }
943  
944 my $source = $self->source;
945 my $use_renderfarm = $self->use_renderfarm;
946  
947 unless ($use_renderfarm) {
948 return (\@uncached,[]);
949 }
950
951 my $slave_status = $self->slave_status;
952  
953 my $url;
954 my %is_remote = map { $_ => (
955 !/plugin:/ &&
956 !/file:/ &&
957 !/^(ftp|http|das):/ &&
958 !$source->is_usertrack($_) &&
959 !$source->is_remotetrack($_) &&
960 (($url = $source->remote_renderer($_)||0) &&
961 ($url ne 'none') &&
962 ($url ne 'local') &&
963 $slave_status->select(shellwords($url))))
964 } @uncached;
965  
966 my @remote = grep {$is_remote{$_} } @uncached;
967 my @local = grep {!$is_remote{$_}} @uncached;
968  
969 return (\@local,\@remote);
970 }
971  
972 #moved from Render.pm
973 sub overview_ratio {
974 my $self = shift;
975 return 1.0; # for now
976 }
977  
978 sub overview_pad {
979 my $self = shift;
980 my $tracks = shift;
981  
982 my $source = $self->source;
983  
984 $tracks ||= [$source->overview_tracks];
985 my $max = 0;
986 foreach (@$tracks) {
987 my $key = $source->setting($_=>'key');
988 next unless defined $key;
989 $max = length $key if length $key > $max;
990 }
991 foreach (@_) { #extra
992 $max = length if length > $max;
993 }
994  
995 # Tremendous kludge! Not able to generate overview maps in GD yet
996 # This needs to be cleaned...
997 my $image_class = 'GD';
998 eval "use $image_class";
999 my $pad = $source->min_overview_pad;
1000 return ($pad,$pad) unless $max;
1001 return ($max * $image_class->gdMediumBoldFont->width + 3,$pad);
1002 }
1003  
1004 # Handle the rendering of all three types of scale bars
1005 sub render_scale_bar {
1006 my $self = shift;
1007 my %args = @_;
1008 my $segment = $args{'segment'};
1009 my $state = $args{'state'};
1010 my $section = $args{'section'} || 'detail';
1011 my $gd;
1012  
1013 # Temporary kludge until I can figure out a more
1014 # sane way of rendering overview with SVG...
1015 my $image_class = 'GD';
1016 eval "use $image_class";
1017  
1018 my $source = $self->source;
1019  
1020 my ( $wide_segment, $bgcolor, $pad_bottom, %add_track_extra_args, );
1021  
1022 if ( $section eq 'overview' ) {
1023 $wide_segment = $args{'whole_segment'} or return ( '', 0, 0 );
1024 %add_track_extra_args = (
1025 -bgcolor => $source->global_setting('overview bgcolor')
1026 || 'wheat',
1027 -pad_bottom => 0,
1028 -label => $wide_segment->seq_id,
1029 -label_font => $image_class->gdMediumBoldFont,
1030 );
1031 }
1032 elsif ( $section eq 'region' ) {
1033 $wide_segment = $args{'region_segment'} or return ( '', 0, 0 );
1034 %add_track_extra_args = (
1035 -bgcolor => $source->global_setting('region bgcolor') || 'wheat',
1036 -pad_bottom => 0,
1037 );
1038 }
1039 else {
1040 $wide_segment = $segment;
1041 %add_track_extra_args = (
1042 -bgcolor => $source->global_setting('detail bgcolor') || 'wheat',
1043 -pad_top => 18,
1044 -pad_bottom => 0,
1045 -label_font => $image_class->gdMediumBoldFont,
1046 -label => eval{$segment->seq_id.
1047 ': '
1048 .$self->source->unit_label($segment->length)
1049 }||'', # intermittent bug here with undefined $segment
1050 );
1051 }
1052  
1053 my $flip = ( $section eq 'detail' and $state->{'flip'} ) ? 1 : 0;
1054  
1055 $add_track_extra_args{'-postgrid'} = $args{'postgrid'} if $args{'postgrid'};
1056  
1057 my @panel_args = $self->create_panel_args(
1058 { section => $section,
1059 segment => $wide_segment,
1060 flip => $flip,
1061 %add_track_extra_args
1062 }
1063 );
1064  
1065  
1066 my $panel = Bio::Graphics::Panel->new( @panel_args, );
1067  
1068 my $width = ($section eq 'detail')? $self->render->get_detail_image_width($state) : $self->render->get_image_width($state);
1069  
1070 # no cached data, so do it ourselves
1071 unless ($gd) {
1072 my $units = $source->global_setting('units') || '';
1073 my $no_tick_units = $source->global_setting('no tick units');
1074  
1075  
1076 $panel->add_track(
1077 $wide_segment,
1078 -glyph => 'arrow',
1079 -double => 1,
1080 -tick => 2,
1081 -units_in_label => $no_tick_units,
1082 -units => $units,
1083 -unit_divider => $source->unit_divider,
1084 %add_track_extra_args,
1085 );
1086  
1087 if (my $feats = $args{'tracks'}) {
1088  
1089 my @feature_types = $feats->types;
1090  
1091 for my $type (@feature_types) {
1092 my $features = $feats->features($type);
1093 my %options = $feats->style($type);
1094 $panel->add_track($features,%options);
1095 }
1096  
1097 }
1098  
1099 # add uploaded files that have the "(over|region)view" option set
1100  
1101 $gd = $panel->gd;
1102 }
1103  
1104 my ( $y1, $y2 ) = ( 0, ( $gd->getBounds )[1] );
1105  
1106 eval { $panel->finished }; # should quash memory leaks when used in conjunction with bioperl 1.4
1107  
1108 my $url = $self->source->generate_image($gd);
1109 my $height = $y2 - $y1; # + 1;
1110  
1111 return ( $url, $height, $width, );
1112 }
1113  
1114 sub render_image_pad {
1115 my $self = shift;
1116 my ($section,$segment) = @_;
1117  
1118 $segment ||= $section eq 'overview' ? $self->whole_segment
1119 :$section eq 'region' ? $self->region_segment
1120 :$self->segment;
1121  
1122 my @panel_args = $self->create_panel_args({
1123 section => $section,
1124 segment => $segment,
1125 }
1126 );
1127 my @track_args = ();
1128 my @extra_args = ($self->settings->{start},
1129 $self->settings->{stop});
1130 my $cache = Bio::Graphics::Browser2::CachedTrack->new(
1131 -cache_base => $self->get_cache_base,
1132 -panel_args => \@panel_args,
1133 -track_args => \@track_args,
1134 -extra_args => \@extra_args,
1135 );
1136 unless ($cache->status eq 'AVAILABLE') {
1137 my $panel = Bio::Graphics::Panel->new(@panel_args);
1138 $cache->lock;
1139 my $gd = $panel->gd;
1140 $cache->put_data($gd,'',[]);
1141 }
1142  
1143 my $gd = $cache->gd;
1144 return $gd;
1145 }
1146  
1147 sub bump_density {
1148 my $self = shift;
1149 my $conf = $self->source;
1150 my $bd = $conf->global_setting('bump density')
1151 || $conf->setting('TRACK DEFAULTS' =>'bump density')
1152 || 50;
1153 return int($bd * $self->details_mult);
1154 }
1155  
1156 sub label_density {
1157 my $self = shift;
1158 my $conf = $self->source;
1159 my $ld = $conf->global_setting('label density')
1160 || $conf->setting('TRACK DEFAULTS' =>'label density')
1161 || 10;
1162 return int($ld * $self->details_mult);
1163 }
1164  
1165 sub calculate_scale_size {
1166 my $self = shift;
1167 my ($length,$width) = @_;
1168  
1169 # how long is 1/5 of the width?
1170 my $scale = $length/$width;
1171 my $guesstimate = $scale * ($width/5);
1172  
1173 # turn into multiples of 10
1174 my $exp = 10 ** int log10($guesstimate);
1175 my $base = ($guesstimate/$exp);
1176 if ($base < 1) { $base = 1 }
1177 elsif ($base < 2) { $base = 2 }
1178 elsif ($base < 5) { $base = 5 }
1179 else { $base = 10};
1180 $guesstimate = $base * $exp;
1181 my $label = $self->source->unit_label($guesstimate);
1182  
1183 return ($guesstimate, $label);
1184 }
1185  
1186 sub log10 { return eval {log(shift)/log(10)} || 0 }
1187  
1188 # Deprecated. This method was used to add the scale to the detail scale track. This is now done in javascript.
1189 sub make_scale_feature {
1190 my $self = shift;
1191 my ($segment,$width) = @_;
1192 return unless $segment;
1193  
1194 my $length = $segment->length;
1195  
1196 my ($guesstimate, $label) = $self->calculate_scale_size($length, $width);
1197  
1198 my $scale = $segment->length/$width;
1199  
1200 $label .= ' '; # more attractive
1201 my $size = $guesstimate/$scale;
1202 my $left = ($width-$size)/2;
1203 my $start = int (($segment->start + $segment->end)/2 - $guesstimate/2);
1204 my $end = $start + $guesstimate - 1;
1205  
1206 return Bio::Graphics::Feature->new(-display_name => $label,
1207 -start => $start,
1208 -end => $end,
1209 -seq_id => $segment->seq_id);
1210 }
1211  
1212 sub make_map {
1213 my $self = shift;
1214 my ($boxes,$panel,$label,$trackmap,$first_box_is_scale) = @_;
1215 my @map = ($label);
1216  
1217 my $source = $self->source;
1218  
1219 my $length = $self->segment_length;
1220 my $settings = $self->settings;
1221 my $flip = $panel->flip;
1222 my ($track_dbid) = $source->db_settings($label,$length);
1223  
1224 local $^W = 0; # avoid uninit variable warnings due to poor coderefs
1225  
1226 push @map, $self->make_centering_map(shift @$boxes,$flip,0,$first_box_is_scale)
1227 if $first_box_is_scale;
1228  
1229 my $inline = $source->use_inline_imagemap($label,$length);
1230 my $inline_options = {};
1231  
1232 if ($inline) {
1233 $inline_options = {tips => $source->global_setting('balloon tips') && $settings->{'show_tooltips'} || 0,
1234 summary => $source->show_summary($label,$length,$self->settings) || 0,
1235 use_titles_for_balloons => $source->global_setting('titles are balloons') || 0,
1236 balloon_style => $source->global_setting('balloon style') || 'GBubble',
1237 balloon_sticky => $source->semantic_fallback_setting($label,'balloon sticky',$length) || 0,
1238 balloon_height => $source->semantic_fallback_setting($label,'balloon height',$length) || 300,
1239 }
1240 }
1241  
1242 foreach my $box (@$boxes){
1243 my $feature = $box->[0];
1244 next unless $feature->can('primary_tag');
1245  
1246 my $attributes = $inline ? $self->make_imagemap_element_inline($feature,$panel,$label,$box->[5],$inline_options)
1247 : $self->make_imagemap_element_callback($feature,$track_dbid);
1248 $attributes or next;
1249 my $fname = eval {$feature->display_name} || eval{$box->[0]->name} || 'unnamed';
1250 my $ftype = $feature->primary_tag || 'feature';
1251 $ftype = "$ftype:$fname";
1252 my $line = join("\t",$ftype,@{$box}[1..4]);
1253 for my $att (keys %$attributes) {
1254 next unless defined $attributes->{$att} && length $attributes->{$att};
1255 $line .= "\t$att\t$attributes->{$att}";
1256 }
1257 push @map, $line;
1258 }
1259 return \@map;
1260 }
1261  
1262 sub make_imagemap_element_callback {
1263 my $self = shift;
1264 my ($feature,$dbid) = @_;
1265 my $id = eval {CGI::escape($feature->primary_id || $feature->name)};
1266 $id ||= '*summary*' if eval {$feature->has_tag('coverage')};
1267 return unless $id;
1268 return {
1269 dbid => $dbid,
1270 fid => $id,
1271 href => 'javascript:void(0)',
1272 };
1273 }
1274  
1275 sub make_imagemap_element_inline {
1276 my $self = shift;
1277 my ($feature,$panel,$label,$track,$options) = @_;
1278  
1279 my $tips = $options->{tips};
1280 my $use_titles_for_balloons = $options->{use_titles_for_balloons};
1281 my $balloon_style = $options->{balloon_style};
1282 my $sticky = $options->{balloon_sticky};
1283 my $height = $options->{balloon_height};
1284 my $summary = $options->{summary};
1285  
1286 if ($summary) {
1287 return {onmouseover => $self->feature_summary_message('mouseover',$label),
1288 onmouseeown => $self->feature_summary_message('mousedown',$label),
1289 href => 'javascript:void(0)',
1290 inline => 1
1291 }
1292 }
1293 my $source = $self->source;
1294 my $href = $self->make_link($feature,$panel,$label,$track);
1295 my $title = unescape($self->make_title($feature,$panel,$label,$track));
1296 my $target = $self->make_link_target($feature,$panel,$label,$track);
1297  
1298 my ($mouseover,$mousedown,$style);
1299  
1300 if ($tips) {
1301 #retrieve the content of the balloon from configuration files
1302 # if it looks like a URL, we treat it as a URL.
1303 my ($balloon_ht,$balloonhover) =
1304 $self->balloon_tip_setting('balloon hover',$label,$feature,$panel,$track,'inline');
1305 my ($balloon_ct,$balloonclick) =
1306 $self->balloon_tip_setting('balloon click',$label,$feature,$panel,$track,'inline');
1307  
1308 $balloonhover ||= $title if $use_titles_for_balloons;
1309 $balloon_ht ||= $balloon_style;
1310 $balloon_ct ||= $balloon_ht;
1311  
1312 if ($balloonhover) {
1313 my $stick = defined $sticky ? $sticky : 0;
1314 $mouseover = $balloonhover =~ /^(https?|ftp):/
1315 ? "$balloon_ht.showTooltip(event,'<iframe width='+$balloon_ct.maxWidth+' height=$height frameborder=0 " .
1316 "src=$balloonhover></iframe>',$stick)"
1317 : "$balloon_ht.showTooltip(event,'$balloonhover',$stick)";
1318 undef $title;
1319 }
1320 if ($balloonclick) {
1321 my $stick = defined $sticky ? $sticky : 1;
1322 $style = "cursor:pointer";
1323 $mousedown = $balloonclick =~ /^(http|ftp):/
1324 ? "$balloon_ct.showTooltip(event,'<iframe width='+$balloon_ct.maxWidth+' height=$height " .
1325 "frameborder=0 src=$balloonclick></iframe>',$stick,$balloon_ct.maxWidth)"
1326 : "$balloon_ct.showTooltip(event,'$balloonclick',$stick)";
1327 undef $href;
1328 undef $target;
1329 }
1330 }
1331  
1332 # workarounds to accomodate observation that some browsers don't respect cursor:pointer styles in
1333 # <area> tags unless there is an href defined
1334 $href ||= 'javascript:void(0)';
1335  
1336 my %attributes = (
1337 title => $title,
1338 href => $href,
1339 target => $target,
1340 onmouseover => $mouseover,
1341 onmousedown => $mousedown,
1342 style => $style,
1343 inline => 1,
1344 );
1345  
1346 return \%attributes;
1347 }
1348  
1349 # BUG: This is cut-and-paste from Render.pm due to encapsulation failure.
1350 # (no render object available to slave, so slave is broken)
1351 sub feature_summary_message {
1352 my $self = shift;
1353 my ($event_type,$label) = @_;
1354 my $sticky = $event_type eq 'mousedown' || 0;
1355 my $message= $self->source->setting($label=>'key'). ' '.lc($self->language->translate('FEATURE_SUMMARY'));
1356 return "GBubble.showTooltip(event,'$message',$sticky)";
1357 }
1358  
1359 # this creates image map for rulers and scales, where clicking on the scale
1360 # should center the image on the scale.
1361 sub make_centering_map {
1362 my $self = shift;
1363 my ($ruler,$flip,$label,$scale_map_type) = @_;
1364 my @map = $label ? ($label) : ();
1365  
1366 return if $ruler->[3]-$ruler->[1] == 0;
1367  
1368 my $length = $ruler->[0]->length;
1369 my $offset = $ruler->[0]->start;
1370 my $end = $ruler->[0]->end;
1371 my $scale = $length/($ruler->[3]-$ruler->[1]);
1372 my $pl = $ruler->[-1]->panel->pad_left;
1373  
1374 my $ruler_intervals = RULER_INTERVALS;
1375  
1376 if ($scale_map_type eq 'interval_map' && $length/RULER_INTERVALS > $self->get_max_segment) {
1377 my $max = $self->get_max_segment/5; # usually a safe guess
1378 $ruler_intervals = int($length/$max);
1379 }
1380  
1381 # divide into RULER_INTERVAL intervals
1382 my $portion = ($ruler->[3]-$ruler->[1])/$ruler_intervals;
1383 my $ref = $ruler->[0]->seq_id;
1384 my $source = $self->source;
1385  
1386 for my $i (0..$ruler_intervals-1) {
1387 my $x1 = int($portion * $i+0.5);
1388 my $x2 = int($portion * ($i+1)+0.5);
1389  
1390 my ($start,$stop);
1391 if ($scale_map_type eq 'centering_map') {
1392 # put the middle of the sequence range into the middle of the picture
1393 my $middle = $flip ? $end - $scale * ($x1+$x2)/2 : $offset + $scale * ($x1+$x2)/2;
1394 $start = int($middle - $length/2);
1395 $stop = int($start + $length - 1);
1396 }
1397 elsif ($scale_map_type eq 'interval_map') {
1398 # center on the interval
1399 $start = int($flip ? $end - $scale * $x1 : $offset + $scale * $x1);
1400 $stop = int($start + $portion * $scale);
1401 }
1402  
1403 $x1 += $pl;
1404 $x2 += $pl;
1405  
1406 my $url = "?ref=$ref;start=$start;stop=$stop";
1407 $url .= ";flip=1" if $flip;
1408 push @map, join("\t",'ruler',$x2, $ruler->[2], $x2, $ruler->[4],
1409 href => $url, title => 'recenter', alt => 'recenter');
1410 }
1411 return $label ? \@map : @map;
1412 }
1413  
1414 # this is the routine that actually does the work!!!!
1415 # input
1416 # arg1: request hashref
1417 # {label => Bio::Graphics::Browser2::CachedTrack}
1418 # arg2: arguments hashref
1419 # {
1420 # external_features => [list of external features, plugins]
1421 # noscale => (get rid of this?)
1422 # do_map => (get rid of this?)
1423 # cache_extra => (get rid of this?)
1424 # section => (get rid of this?)
1425 # }
1426 # arg3: labels arrayref (optional - uses keys %$request otherwise)
1427 #
1428 # output
1429 # { label1 => $track_cache_object,
1430 # label2 => $track_cache_object....
1431 # }
1432  
1433 sub run_local_requests {
1434 my $self = shift;
1435 my $requests = shift; # a hash of labels => Bio::Graphics::Browser2::CachedTrack objects
1436 my $args = shift;
1437 my $labels = shift;
1438  
1439 my $time = time();
1440  
1441 warn "[$$] run_local_requests on @$labels" if DEBUG;
1442  
1443 $labels ||= [keys %$requests];
1444  
1445 my $noscale = $args->{noscale};
1446 my $do_map = $args->{do_map};
1447 my $cache_extra = $args->{cache_extra} || [];
1448 my $section = $args->{section} || 'detail';
1449 my $nocache = $args->{nocache};
1450 my $render = $args->{render};
1451  
1452 my $settings = $self->settings;
1453 my $segment = $self->segment;
1454 my $length = $self->segment_length;
1455  
1456 my $source = $self->source;
1457 my $lang = $self->language;
1458  
1459 my $base = $self->get_cache_base;
1460  
1461 my $feature_files = $args->{external_features};
1462  
1463 # FIXME: this has to be set somewhere
1464 my $hilite_callback= undef;
1465  
1466 $segment->factory->debug(1) if DEBUG;
1467  
1468 #---------------------------------------------------------------------------------
1469 # Track and panel creation
1470
1471 my %seenit; # avoid error of putting track on list multiple times
1472 my %results; # hash of {$label}{gd} and {$label}{map}
1473 my %feature_file_offsets;
1474  
1475 my @labels_to_generate = @$labels;
1476 my @ordinary_tracks = grep {!$feature_files->{$_}} @labels_to_generate;
1477 my @feature_tracks = grep {$feature_files->{$_} } @labels_to_generate;
1478  
1479 # create all the feature filters for each track
1480 my $filters = $self->generate_filters($settings,$source,\@labels_to_generate);
1481  
1482 my (%children,%reaped);
1483  
1484 local $SIG{CHLD} = sub {
1485 while ((my $pid = waitpid(-1, WNOHANG)) > 0) {
1486 print STDERR "[$$] reaped render child $pid" if DEBUG;
1487 $reaped{$pid}++;
1488 delete $children{$pid} if $children{$pid};
1489 }
1490 };
1491 local $SIG{TERM} = sub { warn "[$$] GBrowse render process terminated"; exit 0; };
1492  
1493 my $max_processes = $self->source->global_setting('max_render_processes')
1494 || MAX_PROCESSES;
1495  
1496 for my $label (@labels_to_generate) {
1497  
1498 # this shouldn't happen, but let's be paranoid
1499 next if $seenit{$label}++;
1500  
1501 # don't let there be more than this many processes
1502 # running simultaneously
1503 while ((my $c = keys %children) >= $max_processes) {
1504 warn "[$$] too many processes ($c), sleeping" if DEBUG;
1505 sleep 1;
1506 }
1507  
1508 $render ||= 'Bio::Graphics::Browser2::Render';
1509 my $child = $render->fork();
1510 croak "Can't fork: $!" unless defined $child;
1511 if ($child) {
1512 warn "[$$] Launched rendering process $child for $label" if DEBUG;
1513 $children{$child}++ unless $reaped{$child}; # in case child was reaped before it was sown
1514 next;
1515 }
1516  
1517 (my $base = $label) =~ s/:(overview|region|details?)$//;
1518 warn "label=$label, base=$base, file=$feature_files->{$base}" if DEBUG;
1519  
1520 my $multiple_tracks = $base =~ /^(http|ftp|file|das|plugin):/
1521 || $source->code_setting($base=>'remote feature');
1522  
1523 my @keystyle = ( -key_style => 'between',
1524 )
1525 if $multiple_tracks;
1526  
1527 my $key = $source->setting( $base => 'key' ) || '' ;
1528 my @nopad = ();
1529 my $panel_args = $requests->{$label}->panel_args;
1530
1531 my $panel
1532 = Bio::Graphics::Panel->new( @$panel_args, @keystyle, @nopad );
1533  
1534 my %trackmap;
1535  
1536 my $timeout = $source->global_setting('global_timeout');
1537
1538 my $oldaction;
1539 my $time = time();
1540 eval {
1541 local $SIG{ALRM} = sub { warn "alarm clock"; die "timeout" };
1542 alarm($timeout);
1543  
1544 $requests->{$label}->lock();
1545 my ($gd,$map,$titles);
1546  
1547 if (my $hide = $source->semantic_setting($label=>'hide',$self->segment_length)) {
1548 $gd = $self->render_hidden_track($hide,$args);
1549 $map = [];
1550 $titles = [];
1551 }
1552  
1553 else {
1554  
1555 if ( exists $feature_files->{$base} ) {
1556 my $file = $feature_files->{$base};
1557  
1558 # Add feature files, including remote annotations
1559 my $featurefile_select = $args->{featurefile_select}
1560 || $self->feature_file_select($section);
1561
1562 if ( ref $file and $panel ) {
1563 $self->add_feature_file(
1564 file => $file,
1565 panel => $panel,
1566 position => $feature_file_offsets{$label} || 0,
1567 options => {},
1568 select => $featurefile_select,
1569 );
1570 %trackmap = map { $_ => $file } @{ $panel->{tracks} || [] };
1571 }
1572 }
1573 else {
1574 my $track_args = $requests->{$label}->track_args;
1575 my $track = $panel->add_track(@$track_args);
1576  
1577 warn "track_setup($label): ",time()-$time," seconds " if BENCHMARK;
1578  
1579 # == populate the tracks with feature data ==
1580 $self->add_features_to_track(
1581 -labels => [ $label, ],
1582 -tracks => { $label => $track },
1583 -filters => $filters,
1584 -segment => $segment,
1585 -fsettings => $settings->{features},
1586 );
1587  
1588 warn "add_features($label): ",time()-$time," seconds " if BENCHMARK;
1589  
1590 %trackmap = ($track=>$label);
1591 }
1592  
1593 # == generate the images and maps in background==
1594 $gd = $panel->gd;
1595 warn "render gd($label): ",time()-$time," seconds " if BENCHMARK;
1596  
1597 $titles = $panel->key_boxes;
1598 foreach (@$titles) {
1599 $_->[0] = substr($_->[0],0,MAX_TITLE_LEN-3).'...' if length($_->[0])>MAX_TITLE_LEN;
1600 my $index = $_->[5]->bgcolor; # record track config bgcolor
1601 my ($r,$g,$b) = $gd->rgb($index);
1602 my $alpha = 1;
1603 if ($_->[5]->can('default_opacity')) {
1604 $alpha = $_->[5]->default_opacity;
1605 }
1606 $_->[5] = "rgba($r,$g,$b,$alpha)";
1607 } # don't want to store all track config data to cache!
1608  
1609 $self->debugging_rectangles($gd,scalar $panel->boxes)
1610 if DEBUGGING_RECTANGLES;
1611 warn "render titles($label): ",time()-$time," seconds " if BENCHMARK;
1612  
1613 my $boxes = $panel->boxes;
1614 warn "boxes($label): ",time()-$time," seconds " if BENCHMARK;
1615  
1616 $map = $self->make_map( $boxes,
1617 $panel, $label,
1618 \%trackmap, 0 );
1619 warn "make_map($label): ",time()-$time," seconds " if BENCHMARK;
1620 }
1621  
1622 $requests->{$label}->put_data($gd, $map, $titles );
1623 };
1624 alarm(0);
1625  
1626 my $elapsed = time()-$time;
1627 warn "render($label): $elapsed seconds ", ($@ ? "(error)" : "(ok)") if BENCHMARK;
1628
1629 if ($@) {
1630 warn "RenderPanels error: $@";
1631 if ($@ =~ /timeout/) {
1632 $requests->{$label}->flag_error('Timeout; Try turning off tracks or looking at a smaller region.');
1633 } else {
1634 $requests->{$label}->flag_error($@);
1635 }
1636 }
1637 CORE::exit 0; # in child;
1638 }
1639 warn "[$$] waiting for children" if DEBUG;
1640 if ($ENV{MOD_PERL}) {
1641 $SIG{CHLD}->(); # hacky workaround
1642 } else {
1643 sleep while %children;
1644 }
1645 warn "done waiting" if DEBUG;
1646  
1647 my $elapsed = time() - $time;
1648 warn "[$$] run_local_requests (@$labels): $elapsed seconds" if DEBUG;
1649  
1650 # make sure requests are populated
1651 # the "1" argument turns off expiration checking
1652 $requests->{$_}->get_data(1) foreach keys %$requests;
1653 }
1654  
1655 sub render_hidden_track {
1656 my $self = shift;
1657 my ($message,$args) = @_;
1658 $message = 'Track not shown at this magnification' if $message eq '1';
1659 my $gd = $self->render_image_pad($args->{section});
1660 my $font = GD->gdMediumBoldFont;
1661 my $len = $font->width * length($message);
1662 my ($wid) = $gd->getBounds;
1663 my $black = $gd->colorClosest(0,0,0);
1664 $gd->string(GD->gdMediumBoldFont,($wid-$len)/2,0,$message,$black);
1665 return $gd;
1666 }
1667  
1668 sub select_features_menu {
1669 my $self = shift;
1670 my $label = shift;
1671 my $titleref = shift;
1672 my $stt = $self->subtrack_manager($label) or return;
1673 my ($selected,$total) = $stt->counts;
1674 my $escaped_label = CGI::escape($label);
1675 my $subtrack_over = "GBubble.showTooltip(event,'url:?action=show_subtracks;track=$escaped_label',false)";
1676 my $subtrack_click = "GBox.showTooltip(event,'url:?action=select_subtracks;track=$escaped_label',true)";
1677  
1678 # modify the title to show that some subtracks are hidden
1679 $$titleref .= " ".span({-class =>'clickable',
1680 -onMouseOver => "GBubble.showTooltip(event,'" . $self->language->translate('CLICK_MODIFY_SUBTRACK_SEL') . "')",
1681 -onClick => $subtrack_click
1682 },
1683 $self->language->translate('SHOWING_SUBTRACKS',$selected,$total)); #;
1684
1685 }
1686  
1687 sub generate_filters {
1688 my $self = shift;
1689 my ($settings,$source,$label_list) = @_;
1690 my %filters;
1691 for my $l (@$label_list) {
1692 my %conf = $source->style($l);
1693  
1694 if (my $filter = $conf{'-filter'}) {
1695 $filters{$l} = $filter;
1696 }
1697  
1698 else {
1699 $filters{$l} = $self->subtrack_select_filter($settings,$l);
1700 }
1701 }
1702 return \%filters;
1703 }
1704  
1705 sub subtrack_select_filter {
1706 my $self = shift;
1707 my ($settings,$label) = @_;
1708  
1709 # new method via SubtrackTable:
1710 my $stt = $self->subtrack_manager($label) or return;
1711 return $stt->filter_feature_sub;
1712 }
1713  
1714  
1715 # this routine is too long and needs to be modularized
1716 sub add_features_to_track {
1717 my $self = shift;
1718 my %args = @_;
1719  
1720 my $labels = $args{-labels} or die "programming error";
1721 my $segment = $args{-segment} or die "programming error";
1722 my $tracks = $args{-tracks} or die "programming error";
1723 my $filters = $args{-filters} or die "programming error";
1724 my $fsettings = $args{-fsettings} or die "programming error";
1725  
1726 warn "[$$] add_features_to_track @{$args{-labels}}" if DEBUG;
1727  
1728 my $max_labels = $self->label_density;
1729 my $max_bump = $self->bump_density;
1730  
1731 my $length = $self->segment_length;
1732 my $source = $self->source;
1733  
1734 # sort tracks by the database they come from
1735 my (%db2label,%db2db);
1736 for my $label (@$labels) {
1737 my $db = eval { $source->open_database($label,$length)};
1738 unless ($db) { warn "Couldn't open database for $label: $@"; next; }
1739 $db2label{$db}{$label}++;
1740 $db2db{$db} = $db; # cache database object
1741 }
1742  
1743 my (%iterators,%iterator2dbid,%is_summary,%type2label);
1744 for my $db (keys %db2db) {
1745 my @labels = keys %{$db2label{$db}};
1746  
1747 my (@full_types,@summary_types);
1748 for my $l (@labels) {
1749 my @types = $source->label2type($l,$length) or next;
1750 if ($source->show_summary($l,$length,$self->settings)) {
1751 $is_summary{$l}++;
1752 push @summary_types,@types;
1753 } else {
1754 push @full_types,@types;
1755 }
1756 $type2label{$_}{$l}++ foreach @types;
1757 }
1758 $self->{_type2label}=\%type2label;
1759
1760 warn "[$$] RenderPanels->get_iterator(@full_types)" if DEBUG;
1761 warn "[$$] RenderPanels->get_summary_iterator(@summary_types)" if DEBUG;
1762 if (@summary_types &&
1763 (my $iterator = $self->get_summary_iterator($db2db{$db},$segment,\@summary_types))) {
1764 $iterators{$iterator} = $iterator;
1765 $iterator2dbid{$iterator} = $source->db2id($db);
1766 }
1767  
1768 if (@full_types && (my $iterator = $self->get_iterator($db2db{$db},$segment,\@full_types))) {
1769 $iterators{$iterator} = $iterator;
1770 $iterator2dbid{$iterator} = $source->db2id($db);
1771 }
1772 }
1773  
1774 my (%groups,%feature_count,%group_pattern,%group_field);
1775  
1776 # The effect of this loop is to fetch a feature from each iterator in turn
1777 # using a queueing scheme. This allows streaming iterators to parallelize a
1778 # bit. This may not be worth the effort.
1779 my (%feature2dbid,%classes,%limit_hit,%has_subtracks);
1780  
1781 while (keys %iterators) {
1782 for my $iterator (values %iterators) {
1783  
1784 my $feature;
1785  
1786 unless ($feature = $iterator->next_seq) {
1787 delete $iterators{$iterator};
1788 next;
1789 }
1790  
1791 $source->add_dbid_to_feature($feature,$iterator2dbid{$iterator});
1792 my @labels = $self->feature2label($feature);
1793  
1794 warn "[$$] $iterator->next_seq() returns $feature, will assign to @labels" if DEBUG;
1795  
1796 for my $l (@labels) {
1797  
1798 $l =~ s/:\d+//; # get rid of semantic zooming tag
1799  
1800 my $track = $tracks->{$l} or next;
1801  
1802 my $stt = $self->subtrack_manager($l);
1803 my $is_summary = $is_summary{$l};
1804  
1805 $filters->{$l}->($feature) or next if $filters->{$l} && !$is_summary;
1806 $feature_count{$l}++;
1807  
1808 # -----------------------------------------------------------------------------
1809 # GROUP CODE
1810 # Handle name-based groupings.
1811 unless (exists $group_pattern{$l}) {
1812 $group_pattern{$l} = $source->semantic_setting($l => 'group_pattern',$length);
1813 $group_pattern{$l} =~ s!^/(.+)/$!$1!
1814 if $group_pattern{$l}; # clean up regexp delimiters
1815 }
1816
1817 # Handle generic grouping (needed for GFF3 database)
1818 $group_field{$l} = $source->semantic_setting($l => 'group_on',$length)
1819 unless exists $group_field{$l};
1820
1821 if (my $pattern = $group_pattern{$l}) {
1822 my $name = $feature->name or next;
1823 (my $base = $name) =~ s/$pattern//i;
1824 $groups{$l}{$base} ||= Bio::Graphics::Feature->new(-type => 'group',
1825 -name => $feature->display_name,
1826 -strand => $feature->strand,
1827 );
1828 $groups{$l}{$base}->add_segment($feature);
1829 next;
1830 }
1831
1832 if (my $field = $group_field{$l}) {
1833 my $base = eval{$feature->$field};
1834 if (defined $base) {
1835 $groups{$l}{$base} ||= Bio::Graphics::Feature->new(-name => $feature->display_name,
1836 -start => $feature->start,
1837 -end => $feature->end,
1838 -strand => $feature->strand,
1839 -type => $feature->primary_tag);
1840 $groups{$l}{$base}->add_SeqFeature($feature);
1841 next;
1842 }
1843 }
1844  
1845 if (!$is_summary && $stt && (defined (my $id = $stt->feature_to_id_sub->($feature)))) {
1846 $groups{$l}{$id} ||= Bio::Graphics::Feature->new(-type => 'group',
1847 -primary_id => $id,
1848 -name => $stt->id2label($id),
1849 -start => $segment->start,
1850 -end => $segment->end,
1851 -seq_id => $segment->seq_id,
1852 );
1853 $has_subtracks{$l}++;
1854 $groups{$l}{$id}->add_segment($feature);
1855 next;
1856 }
1857  
1858 $track->add_feature($feature);
1859 }
1860 }
1861 }
1862 warn "[$$] RenderPanels finished iteration fetch" if DEBUG;
1863  
1864 # ------------------------------------------------------------------------------------------
1865 # fixups
1866  
1867 # fix up %group features
1868 # the former creates composite features based on an arbitrary method call
1869 # the latter is traditional name-based grouping based on a common prefix/suffix
1870  
1871 for my $l (keys %groups) {
1872 my $track = $tracks->{$l};
1873 my $g = $groups{$l} or next;
1874  
1875 # add empty subtracks if needed
1876 if ($has_subtracks{$l} && !$source->semantic_setting($l => 'hide empty subtracks',$length)) {
1877 my $stt = $self->subtrack_manager($l);
1878 my @ids = $stt->selected_ids;
1879 $g->{$_} ||= Bio::Graphics::Feature->new(-type => 'group',
1880 -primary_id => $_,
1881 -name => $stt->id2label($_),
1882 -start => $segment->start,
1883 -end => $segment->end,
1884 -seq_id => $segment->seq_id)
1885 foreach @ids
1886 }
1887  
1888 $track->add_feature($_) foreach values %$g;
1889 $feature_count{$l} += keys %$g;
1890 }
1891  
1892 # now reconfigure the tracks based on their counts
1893 for my $l (keys %$tracks) {
1894 next unless $feature_count{$l};
1895  
1896 $fsettings->{$l}{options} ||= 0;
1897  
1898 my $count = $feature_count{$l};
1899 my $limit = $fsettings->{$l}{limit};
1900 $count = $limit if defined($limit) && $limit > 0 && $limit < $count;
1901 my $pack_options = $fsettings->{$l}{options};
1902  
1903 my $do_bump = $self->do_bump($l,
1904 $pack_options,
1905 $count,
1906 $max_bump,
1907 $length);
1908  
1909 my $do_label = $self->do_label($l,
1910 $pack_options,
1911 $count,
1912 $max_labels,
1913 $length);
1914  
1915 my $do_description = $self->do_description($l,
1916 $pack_options,
1917 $count,
1918 $max_labels,
1919 $length);
1920  
1921 $tracks->{$l}->configure(-bump => $do_bump,
1922 -label => $do_label,
1923 -description => $do_description,
1924 );
1925 $tracks->{$l}->configure(-label => 0 ) if !$do_bump;
1926 $tracks->{$l}->configure(-bump_limit => $limit)
1927 if $limit && $limit > 0;
1928  
1929 # essentially make label invisible if we are going to get the label position
1930 $tracks->{$l}->configure(-fontcolor => 'white:0.0')
1931 if $tracks->{$l}->parts->[0]->record_label_positions;
1932  
1933 if (eval{$tracks->{$l}->features_clipped}) { # may not be present in older Bio::Graphics
1934 my $max = $tracks->{$l}->feature_limit;
1935 my $count = $tracks->{$l}->feature_count;
1936 my $message = $count == $self->source->globals->max_features ? 'FEATURES_CLIPPED_MAX' : 'FEATURES_CLIPPED';
1937 $tracks->{$l}->panel->key_style('between');
1938 $tracks->{$l}->configure(-key => $self->language->translate($message,$max,$count));
1939 }
1940 }
1941  
1942 }
1943  
1944 sub get_iterator {
1945 my $self = shift;
1946 my ($db,$segment,$feature_types) = @_;
1947  
1948 # The Bio::DB::SeqFeature::Store database supports correct
1949 # semantics for directly retrieving features that overlap
1950 # a range. All the others require you to get a segment first
1951 # and then to query the segment! This is a problem, because it
1952 # means that the reference sequence (e.g. the chromosome) is
1953 # repeated in each database, even if it isn't the primary one :-(
1954 my $max = $self->source->globals->max_features;
1955 if ($db->can('get_seq_stream')) {
1956 my @args = (-type => $feature_types,
1957 -seq_id => $segment->seq_id,
1958 -start => $segment->start,
1959 -end => $segment->end);
1960 push @args,(-max_features => $max) if $max > 0; # some adaptors allow this
1961 return $db->get_seq_stream(@args);
1962 }
1963  
1964 my $db_segment;
1965 if (eval{$segment->factory||'' eq $db}) {
1966 $db_segment = $segment;
1967 } else {
1968 ($db_segment) = $db->segment($segment->seq_id,$segment->start,$segment->end);
1969 }
1970  
1971 unless ($db_segment) {
1972 warn "Couldn't get segment $segment from database $db; id=",
1973 $self->source->db2id($db);
1974 return;
1975 }
1976  
1977 return $db_segment->get_seq_stream(-type=>$feature_types);
1978 }
1979  
1980 sub get_summary_iterator {
1981 my $self = shift;
1982 my ($db,$segment,$feature_types) = @_;
1983  
1984 my @args = (-type => $feature_types,
1985 -seq_id => $segment->seq_id,
1986 -start => $segment->start,
1987 -end => $segment->end,
1988 -bins => $self->get_detail_width_no_pad,
1989 -iterator=>1,
1990 );
1991 return $db->feature_summary(@args);
1992 }
1993  
1994  
1995 =head2 add_feature_file
1996  
1997 Internal use: render a feature file into a panel
1998  
1999 =cut
2000  
2001 sub add_feature_file {
2002 my $self = shift;
2003 my %args = @_;
2004
2005 my $file = $args{file} or return;
2006 my $options = $args{options} or return;
2007 my $select = $args{select} or return;
2008  
2009 my $name = $file->name || '';
2010 $options->{$name} ||= 0;
2011  
2012 eval {
2013 $file->render(
2014 $args{panel},
2015 $args{position},
2016 $options->{$name},
2017 $self->bump_density,
2018 $self->label_density,
2019 $select,
2020 $self->segment,
2021 );
2022 };
2023  
2024 warn "error while rendering ",$args{file}->name,": $@" if $@;
2025 }
2026  
2027  
2028 =head2 create_panel_args()
2029  
2030 @args = $self->create_panel_args($section,$args);
2031  
2032 Return arguments need to create a Bio::Graphics::Panel.
2033 $section is one of 'detail','overview', or 'region'
2034 $args is a hashref that contains the keys:
2035  
2036 keystyle
2037 title
2038 image_class
2039 postgrid
2040 background
2041  
2042 =cut
2043  
2044 sub create_panel_args {
2045 my $self = shift;
2046 my $args = shift;
2047  
2048 my $segment = $args->{segment} || $self->segment;
2049 my ($seg_start,$seg_stop,$flip) = $self->segment_coordinates($segment,
2050 $args->{flip});
2051  
2052 my $image_class = $args->{image_class} || 'GD';
2053 eval "use $image_class" unless "${image_class}::Image"->can('new');
2054  
2055 my $settings = $self->settings;
2056 my $source = $self->source;
2057  
2058 my $section = $args->{section} || 'detail';
2059  
2060 my $postgrid = '';
2061 my $detail_start = $settings->{start};
2062 my $detail_stop = $settings->{stop};
2063 my $h_region_str = '';
2064  
2065 if (1 && ($section eq 'overview' or $section eq 'region')){
2066 $postgrid = hilite_regions_closure(
2067 [$detail_start,
2068 $detail_stop,
2069 $self->loaded_segment_fill(),
2070 $self->loaded_segment_outline()
2071 ]);
2072 }
2073 elsif ($section eq 'detail'){
2074 $postgrid = make_postgrid_callback($settings);
2075 $h_region_str = join(':', @{$settings->{h_region}||[]});
2076 }
2077  
2078 my $keystyle = 'none';
2079  
2080 my @pass_thru_args = map {/^-/ ? ($_=>$args->{$_}) : ()} keys %$args;
2081 my @argv = (
2082 -grid => $section eq 'detail' ? $settings->{'grid'} : 0,
2083 -seqid => $segment->seq_id,
2084 -start => $seg_start,
2085 -end => $seg_stop,
2086 -stop => $seg_stop, #backward compatibility with old bioperl
2087 -key_color => $source->global_setting('key bgcolor') || 'moccasin',
2088 -bgcolor => $source->global_setting("$section bgcolor") || 'wheat',
2089 -width => $section eq 'detail'? $self->get_detail_width_no_pad : $settings->{width},
2090 -key_style => $keystyle,
2091 -suppress_key => 1,
2092 -empty_tracks => $source->global_setting('empty_tracks') || DEFAULT_EMPTYTRACKS,
2093 -pad_top => $image_class->gdMediumBoldFont->height+2,
2094 -pad_bottom => 3,
2095 -image_class => $image_class,
2096 -postgrid => $postgrid,
2097 -background => $args->{background} || '',
2098 -truecolor => $source->global_setting('truecolor') || 0,
2099 -truetype => $source->global_setting('truetype') || 0,
2100 -extend_grid => 1,
2101 -gridcolor => $source->global_setting('grid color') || 'lightcyan',
2102 -gridmajorcolor => $source->global_setting('grid major color') || 'cyan',
2103 @pass_thru_args, # position is important here to allow user to override settings
2104 );
2105 push @argv, -flip => 1 if $flip;
2106 my $p = $self->image_padding;
2107 my $pl = $source->global_setting('pad_left');
2108 my $pr = $source->global_setting('pad_right');
2109 $pl = $p unless defined $pl;
2110 $pr = $p unless defined $pr;
2111  
2112 push @argv,(-pad_left =>$pl, -pad_right=>$pr) if $p;
2113  
2114 return @argv;
2115 }
2116  
2117 sub image_padding {
2118 my $self = shift;
2119 my $source = $self->source;
2120 return defined $source->global_setting('image_padding')
2121 ? $source->global_setting('image_padding')
2122 : PAD_DETAIL_SIDES;
2123 }
2124  
2125 =head2 segment_coordinates()
2126  
2127 ($start,$stop,$flip) = $self->segment_coordinates($segment,$flip)
2128  
2129 Method to correct for rare case in which start and stop are flipped.
2130  
2131 =cut
2132  
2133 sub segment_coordinates {
2134 my $self = shift;
2135 my $segment = shift;
2136 my $flip = shift;
2137  
2138 return unless $segment;
2139  
2140 # Create the tracks that we will need
2141 my ($seg_start,$seg_stop ) = ($segment->start,$segment->end);
2142 if ($seg_stop < $seg_start) {
2143 ($seg_start,$seg_stop) = ($seg_stop,$seg_start);
2144 $flip = 1;
2145 }
2146 return ($seg_start,$seg_stop,$flip);
2147 }
2148  
2149 # this returns semantically-correct override configuration
2150 # as a hash ref
2151 sub override_settings {
2152 my $self = shift;
2153 my $label = shift;
2154 my $source = $self->source;
2155 my $state = $self->settings;
2156 my $length = eval {$self->segment_length} || 0;
2157 my $is_summary = $source->show_summary($label,$length,$state);
2158 my $semantic_override = Bio::Graphics::Browser2::Render->find_override_region(
2159 $state->{features}{$label}{semantic_override},
2160 $length);
2161 return $is_summary ? $state->{features}{$label}{summary_override}
2162 : $semantic_override ? $state->{features}{$label}{semantic_override}{$semantic_override}
2163 : {};
2164 }
2165  
2166 =head2 create_track_args()
2167  
2168 @args = $self->create_track_args($label,$args);
2169  
2170 Return arguments need to create a Bio::Graphics::Track.
2171 $label is a config file stanza label for the track.
2172  
2173 =cut
2174  
2175 sub create_track_args {
2176 my $self = shift;
2177 my ($label,$args) = @_;
2178  
2179 my $segment = $self->segment;
2180 my $length = $self->segment_length($label);
2181  
2182 my $source = $self->source;
2183 my $lang = $self->language;
2184  
2185 my $is_summary = $source->show_summary($label,$length,$self->settings);
2186 my $overlaps = ($self->settings->{features}{$label}{options}||0) == 4
2187 || ($source->semantic_setting($label => 'bump',$length)||'') eq 'overlap';
2188  
2189 my $override = $self->override_settings($label);
2190 my @override = map {'-'.$_ => $override->{$_}} keys %$override;
2191  
2192 push @override,(-feature_limit => $override->{limit}) if $override->{limit};
2193 push @override,(-opacity => 1.0) unless $overlaps;
2194  
2195 my @summary_args = ();
2196 if ($is_summary) {
2197 @summary_args = $source->Bio::Graphics::FeatureFile::setting("$label:summary")
2198 ? $source->i18n_style("$label:summary",$lang)
2199 : (-glyph => 'wiggle_density',
2200 -height => 15,
2201 -min_score => 0,
2202 -autoscale => 'local',
2203 );
2204 }
2205 my $hilite_callback = $args->{hilite_callback};
2206  
2207 my @default_args = (-glyph => 'generic');
2208 push @default_args,(-key => $label) unless $label =~ /^\w+:/;
2209 push @default_args,(-hilite => $hilite_callback) if $hilite_callback;
2210  
2211 if (my $stt = $self->subtrack_manager($label)) {
2212 push @default_args,(-connector => '');
2213 my $left_label =
2214 $source->semantic_setting($label=>'label_position',$length)||'' eq 'left';
2215  
2216 $left_label++
2217 if $source->semantic_setting($label=>'label_transcripts',$length);
2218  
2219 my $group_label = $source->semantic_setting($label=>'glyph',$length) !~ /xyplot|wiggle|density|whisker|vista/;
2220  
2221 push @default_args,(
2222 -group_label => $group_label||0,
2223 -group_label_position => $left_label ? 'top' : 'left',
2224 -group_subtracks => !$overlaps,
2225 );
2226 push @default_args,$stt->track_args;
2227 }
2228  
2229 my @args;
2230 if ($source->semantic_setting($label=>'global feature',$length)) {
2231 eval { # honor the database indicated in the track config
2232 my $db = $self->source->open_database($label,$length);
2233 my $class = eval {$segment->seq_id->class} || eval{$db->refclass};
2234 ($segment)= $db->segment(-name => $segment->seq_id,
2235 -start => $segment->start,
2236 -end => $segment->end,
2237 -class => $class);
2238 };
2239 warn $@ if $@;
2240 @args = ($segment,
2241 @default_args,
2242 $source->default_style,
2243 $source->i18n_style($label,$lang),
2244 @summary_args,
2245 @override,
2246 );
2247 } else {
2248 @args = (@default_args,
2249 $source->default_style,
2250 $source->i18n_style($label,$lang,$length),
2251 @summary_args,
2252 @override,
2253 );
2254 }
2255  
2256 if (my $stt = $self->subtrack_manager($label)) {
2257 my $sub = $stt->sort_feature_sub;
2258 push @args,(-sort_order => $sub);
2259 }
2260  
2261 return @args;
2262 }
2263  
2264 sub subtrack_manager {
2265 my $self = shift;
2266 my $label = shift;
2267 return $self->{_stt}{$label} if exists $self->{_stt}{$label};
2268 return $self->{_stt}{$label} = undef
2269 if $self->source->show_summary($label,$self->segment_length,$self->settings);
2270 return $self->{_stt}{$label} = Bio::Graphics::Browser2::Render->create_subtrack_manager($label,
2271 $self->source,
2272 $self->settings);
2273 }
2274  
2275 sub debugging_rectangles {
2276 my $self = shift;
2277 my ($image,$boxes) = @_;
2278 my $red = $image->colorClosest(255,0,0);
2279 foreach (@$boxes) {
2280 my @rect = @{$_}[1,2,3,4];
2281 $image->rectangle(@{$_}[1,2,3,4],$red);
2282 }
2283 }
2284  
2285 sub get_cache_base {
2286 my $self = shift;
2287 my $path = $self->source->globals->cache_dir($self->source->name);
2288 return $path;
2289 }
2290  
2291 # Returns the HTML image map from the cached image map data.
2292 sub map_html {
2293 my $self = shift;
2294 my $map = shift;
2295 my $id = shift;
2296  
2297 my @data = @$map;
2298  
2299 my $name = shift @data or return '';
2300 $id ||= "${name}_map";
2301  
2302 my $html = qq(\n<map name="$id" id="$id">\n);
2303 for (@data) {
2304 my (undef,$x1,$y1,$x2,$y2,%atts) = split "\t";
2305 $x1 or next;
2306 my $coords = join(',',$x1,$y1,$x2,$y2);
2307 $html .= qq(<area shape="rect" coords="$coords" );
2308 for my $att (keys %atts) {
2309 $html .= qq($att="$atts{$att}" );
2310 }
2311 $html .= qq(/>\n);
2312 }
2313 $html .= qq(</map>\n);
2314 return $html;
2315 }
2316  
2317 # this returns a coderef that will indicate whether an added (external) feature is placed
2318 # in the overview, region or detailed panel. It is necessary to avoid one section's features
2319 # from being placed in another section's track.
2320 sub feature_file_select {
2321 my $self = shift;
2322 my $required_section = shift;
2323  
2324 my $undef_defaults_to_true;
2325 if ($required_section =~ /detail/) {
2326 $undef_defaults_to_true++;
2327 }
2328  
2329 return sub {
2330 my $file = shift;
2331 my $type = shift;
2332  
2333 my $section = $file->setting($type=>'section')
2334 || $file->setting(general=>'section');
2335 my ($modifier) = $type =~ /:(overview|region}detail)$/;
2336 $section ||= $modifier;
2337  
2338 return $undef_defaults_to_true
2339 if !defined $section;
2340  
2341 return $section =~ /$required_section/;
2342 };
2343 }
2344  
2345 sub do_bump {
2346 my $self = shift;
2347 my ($track_name,$option,$count,$max,$length) = @_;
2348  
2349 my $source = $self->source;
2350 my $maxb = $source->code_setting($track_name => 'bump density');
2351 $maxb = $max unless defined $maxb;
2352  
2353 my $maxed_out = $count <= $maxb;
2354 my $conf_bump = $source->semantic_setting($track_name => 'bump',$length);
2355 $option ||= 0;
2356 return defined $conf_bump ? $conf_bump
2357 : $option == 0 ? $maxed_out
2358 : $option == 1 ? 0
2359 : $option == 2 ? 1
2360 : $option == 3 ? 1
2361 : $option == 4 ? 'overlap'
2362 : 0;
2363 }
2364  
2365 sub do_label {
2366 my $self = shift;
2367 my ($track_name,$option,$count,$max_labels,$length) = @_;
2368  
2369 my $source = $self->source;
2370  
2371 my $maxl = $source->semantic_setting($track_name => 'label density', $length);
2372 $maxl = $max_labels unless defined $maxl;
2373 my $maxed_out = $count <= $maxl;
2374  
2375 my $conf_label = $source->semantic_setting($track_name => 'label',$length);
2376 $conf_label = 1 unless defined $conf_label;
2377  
2378 my $glyph = $source->semantic_setting($track_name => 'glyph',$length) || 'generic';
2379 my $overlap_label = $glyph =~ /xyplot|vista|wiggle|density/;
2380  
2381 $option ||= 0;
2382 return $option == 0 ? $maxed_out && $conf_label
2383 : $option == 3 ? $conf_label || 1
2384 : $option == 4 ? ($overlap_label ? $conf_label : 0)
2385 : 0;
2386 }
2387  
2388 sub do_description {
2389 my $self = shift;
2390 my ($track_name,$option,$count,$max_labels,$length) = @_;
2391  
2392 my $source = $self->source;
2393  
2394 my $maxl = $source->code_setting($track_name => 'label density');
2395 $maxl = $max_labels unless defined $maxl;
2396 my $maxed_out = $count <= $maxl;
2397  
2398 my $conf_description = $source->semantic_setting($track_name => 'description',$length);
2399 $conf_description = 0 unless defined $conf_description;
2400 $option ||= 0;
2401 return $option == 0 ? $maxed_out && $conf_description
2402 : $option == 3 ? $conf_description || 1
2403 : $option == 5 ? $conf_description || 1
2404 : 0;
2405 }
2406  
2407 sub feature2label {
2408 my $self = shift;
2409 my $feature = shift;
2410 my $type2label = $self->{_type2label} or die "no type2label map defined";
2411 my $type = eval {$feature->type} || eval{$feature->source_tag} || eval{$feature->primary_tag} or return;
2412 (my $basetype = $type) =~ s/:.+$//;
2413 my $labels = $type2label->{$type}||$type2label->{$basetype} or return;
2414 my @labels = keys %$labels;
2415 return @labels;
2416 }
2417  
2418 # override make_link to allow for code references
2419 sub make_link {
2420 my $self = shift;
2421 my ($feature,$panel,$label,$track) = @_;
2422 my $label_fix = $label;
2423  
2424 if (ref $label && $label->{name}){
2425 $label_fix = $label->{name};
2426 if ($label_fix =~/^(plugin)\:/){$label_fix = join(":",($',$1));}
2427 }
2428  
2429 my $data_source = $self->source;
2430 my $ds_name = $data_source->name;
2431  
2432 my $link = $data_source->code_setting($label_fix,'link');
2433  
2434 if (! defined $link) {
2435 if ($feature->can('url')) {
2436 my $link = $feature->url;
2437 return $link if defined $link;
2438 }
2439 return $label->make_link($feature)
2440 if $label
2441 && $label =~ /^[a-zA-Z_]/
2442 && $label->isa('Bio::Graphics::FeatureFile');
2443 }
2444  
2445 $panel ||= 'Bio::Graphics::Panel';
2446 $label ||= eval {$self->feature2label($feature)};
2447 $label ||= 'general';
2448  
2449 # most specific -- a configuration line
2450  
2451 # less specific - a smart feature
2452 $link = $feature->make_link if $feature->can('make_link') && !defined $link;
2453  
2454 # general defaults
2455 $link = $data_source->code_setting('TRACK DEFAULTS'=>'link') unless defined $link;
2456 $link = $data_source->code_setting(general=>'link') unless defined $link;
2457 $link = $data_source->globals->setting(general=>'link') unless defined $link;
2458  
2459 return unless $link;
2460  
2461 if (ref($link) eq 'CODE') {
2462 my $val = eval {$link->($feature,$panel,$track)};
2463 $data_source->_callback_complain($label=>'link') if $@;
2464 return $val;
2465 }
2466 elsif (!$link || $link eq 'AUTO') {
2467 my $n = $feature->display_name || '';
2468 my $c = $feature->seq_id || '';
2469 my $name = CGI::escape("$n"); # workaround CGI.pm bug
2470 my $class = eval {CGI::escape($feature->class)}||'';
2471 my $ref = CGI::escape("$c"); # workaround again
2472 my $start = CGI::escape($feature->start);
2473 my $end = CGI::escape($feature->end);
2474 my $src = CGI::escape(eval{$feature->source} || '');
2475 my $url = CGI->request_uri || '../..';
2476 my $id = eval {CGI::escape($feature->primary_id)};
2477 my $dbid = eval {$feature->gbrowse_dbid} || ($data_source->db_settings($label))[0];
2478 $dbid = CGI::escape($dbid);
2479 $url =~ s/\?.+//;
2480 $url =~ s! /gbrowse[^/]* / [^/]+ /? [^/]* $!!x;
2481 $url .= "/gbrowse_details/$ds_name?ref=$ref;start=$start;end=$end";
2482 $url .= ";name=$name" if defined $name;
2483 $url .= ";class=$class" if defined $class;
2484 $url .= ";feature_id=$id" if defined $id;
2485 $url .= ";db_id=$dbid" if defined $dbid;
2486 return $url;
2487 }
2488 return $data_source->link_pattern($link,$feature,$panel);
2489 }
2490  
2491 # make the title for an object on a clickable imagemap
2492 sub make_title {
2493 my $self = shift;
2494 my ($feature,$panel,$label,$track) = @_;
2495 local $^W = 0; # tired of uninitialized variable warnings
2496 my $source = $self->source;
2497  
2498 my $length = eval {$self->segment_length} || 0;
2499  
2500 my ($title,$key) = ('','');
2501  
2502 TRY: {
2503 if ($label && eval { $label->isa('Bio::Graphics::FeatureFile') }) {
2504 $key = $label->name;
2505 $title = $label->make_title($feature) or last TRY;
2506 return $title;
2507 }
2508  
2509 else {
2510 $label ||= eval {$self->feature2label($feature)} or last TRY;
2511 $key ||= $source->setting($label,'key') || $label;
2512 $key =~ s/s$//;
2513 $key = "source = ".$feature->segment->dsn if $feature->isa('Bio::Das::Feature'); # for DAS sources
2514  
2515 my $length = $self->segment_length($label);
2516  
2517 my $link = $source->semantic_fallback_setting($label,'title',$length);
2518 if (defined $link && ref($link) eq 'CODE') {
2519 $title = eval {$link->($feature,$panel,$track)};
2520 $source->_callback_complain($label=>'title') if $@;
2521 return $title if defined $title;
2522 }
2523 return $source->link_pattern($link,$feature) if defined $link && $link ne 'AUTO';
2524 }
2525 }
2526  
2527 # otherwise, try it ourselves
2528 $title = eval {
2529 if ($feature->can('target') && (my $target = $feature->target)) {
2530 join (' ',
2531 "$key:",
2532 $feature->seq_id.':'.
2533 $feature->start."..".$feature->end,
2534 $feature->target->seq_id.':'.
2535 $feature->target->start."..".$feature->target->end);
2536 } else {
2537 my ($start,$end) = ($feature->start,$feature->end);
2538 ($start,$end) = ($end,$start) if $feature->strand < 0;
2539 my $name = $feature->can('info')
2540 ? $feature->info
2541 : $feature->display_name;
2542 my $result;
2543 $result .= "$key " if defined $key;
2544 $result .= "$name " if defined $name;
2545 $result .= '['.$feature->seq_id.":" if defined $feature->seq_id;
2546 $result .= $feature->start if defined $feature->start;
2547 $result .= '..' . $feature->end if defined $feature->end;
2548 $result .= ']' if defined $feature->seq_id;
2549 $result;
2550 }
2551 };
2552 warn $@ if $@;
2553 return $title;
2554 }
2555  
2556 sub segment_length {
2557 my $self = shift;
2558 my $label = shift;
2559 return Bio::Graphics::Browser2::Render->_segment_length($label,
2560 $self->segment,
2561 $self->region_segment,
2562 $self->whole_segment,
2563 $self->details_mult);
2564 }
2565  
2566 sub make_link_target {
2567 my $self = shift;
2568 my ($feature,$panel,$label,$track) = @_;
2569 my $source = $self->source;
2570  
2571 if ($feature->isa('Bio::Das::Feature')) { # new window
2572 my $dsn = $feature->segment->dsn;
2573 $dsn =~ s/^.+\///;
2574 return $dsn;
2575 }
2576  
2577 $label ||= eval{$self->feature2label($feature)} or return;
2578 my $link_target = $source->code_setting($label,'link_target')
2579 || $source->code_setting('TRACK DEFAULTS' => 'link_target')
2580 || $source->globals->code_setting(general => 'link_target')
2581 || '_blank';
2582 $link_target = eval {$link_target->($feature,$panel,$track)} if ref($link_target) eq 'CODE';
2583 $source->_callback_complain($label=>'link_target') if $@;
2584 return $link_target;
2585 }
2586  
2587 sub balloon_tip_setting {
2588 my $self = shift;
2589 my ($option,$label,$feature,$panel,$track,$inline) = @_;
2590 my $length = $self->segment_length($label);
2591 $option ||= 'balloon tip';
2592 my $source = $self->source;
2593 my $value = $source->semantic_setting($label=>$option,$length||0);
2594 $value = $source->code_setting('TRACK DEFAULTS' => $option) unless defined $value;
2595 $value = $source->code_setting('general' => $option) unless defined $value;
2596  
2597 return unless $value;
2598 my $val;
2599 my $balloon_type = $source->global_setting('balloon style') || 'GBubble';
2600  
2601 if (ref($value) eq 'CODE') {
2602 $val = eval {$value->($feature,$panel,$track)};
2603 $source->_callback_complain($label=>$option) if $@;
2604 } else {
2605 $val = $source->link_pattern($value,$feature,$panel);
2606 }
2607 $val ||= '';
2608  
2609 if ($val=~ /^\s*\[([\w\s]+)\]\s+(.+)/s) {
2610 $balloon_type = $1;
2611 $val = $2;
2612 }
2613 # escape quotes
2614 $val =~ s/'/\\'/g;
2615 if ($inline) {
2616 $val =~ s/"/&quot;/g;
2617 } else {
2618 $val =~ s/"/\\"/g;
2619 }
2620  
2621 return ($balloon_type,$val);
2622 }
2623  
2624 # this generates the callback for highlighting a region
2625 sub make_postgrid_callback {
2626 my $settings = shift;
2627 return unless ref $settings->{h_region};
2628  
2629 my @h_regions = map {
2630 my ( $h_ref, $h_start, $h_end, $h_color )
2631 = /^(.+):(\d+)\.\.(\d+)(?:@(\S+))?/;
2632 defined($h_ref)
2633 && $h_ref eq $settings->{ref}
2634 ? [ $h_start, $h_end, $h_color || 'lightgrey' ]
2635 : ()
2636 } @{ $settings->{h_region} };
2637  
2638 return unless @h_regions;
2639 return hilite_regions_closure(@h_regions);
2640 }
2641  
2642 # this subroutine generates a Bio::Graphics::Panel callback closure
2643 # suitable for hilighting a region of a panel.
2644 # The args are a list of [start,end,bgcolor,fgcolor]
2645 sub hilite_regions_closure {
2646 my @h_regions = @_;
2647  
2648 return sub {
2649 my $gd = shift;
2650 my $panel = shift;
2651 my $left = $panel->pad_left;
2652 my $top = $panel->top;
2653 my $bottom = $panel->bottom+$panel->pad_bottom;
2654 for my $r (@h_regions) {
2655 my ( $h_start, $h_end, $bgcolor, $fgcolor ) = @$r;
2656 my ( $start, $end ) = $panel->location2pixel( $h_start, $h_end );
2657 if ( $end - $start <= 1 ) {
2658 $end++;
2659 $start--;
2660 } # so that we always see something
2661 # assuming top is 0 so as to ignore top padding
2662 $gd->filledRectangle(
2663 $left + $start,
2664 0, $left + $end,
2665 $bottom, $panel->translate_color($bgcolor)
2666 ) if $bgcolor && $bgcolor ne 'none';
2667  
2668 # outline can only be the left and right sides
2669 # -- otherwise it looks funny.
2670 if ( $fgcolor && $fgcolor ne 'none' ) {
2671 my $c = $panel->translate_color($fgcolor);
2672 $gd->setStyle($c,$c,gdTransparent,gdTransparent);#,gdTransparent,gdTransparent,gdTransparent);
2673 $gd->line( $left + $start, 0, $left + $start, $bottom, gdStyled );
2674 $gd->line( $left + $end, 0, $left + $end, $bottom, gdStyled );
2675 }
2676 }
2677  
2678 };
2679 }
2680  
2681 sub loaded_segment_fill {
2682 my $self = shift;
2683 return $self->source->global_setting('loaded segment fill') || 'none';
2684 }
2685  
2686 sub loaded_segment_outline {
2687 my $self = shift;
2688 return $self->source->global_setting('loaded segment outline') || 'gray';
2689 }
2690  
2691 sub details_mult {
2692 my $self = shift;
2693 my $render = $self->render;
2694 return $render->details_mult if $render;
2695  
2696 # workaround for Slave processes, which have no render object
2697 return $self->source->details_multiplier($self->settings);
2698 }
2699  
2700 sub get_detail_width_no_pad {
2701 my $self = shift;
2702 my $settings = $self->settings;
2703 return int($settings->{width} * $self->details_mult);
2704 }
2705  
2706 1;
2707