File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.43: download - view: text, annotated - select for diffs
Mon Jan 21 17:23:31 2002 UTC (22 years, 3 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Ever so minor change to make key labels appear nicer.

    1: # The LearningOnline Network with CAPA
    2: # Dynamic plot
    3: #
    4: # $Id: lonplot.pm,v 1.43 2002/01/21 17:23:31 matthew Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # 12/15/01 Matthew
   29: # 12/17 12/18 12/19 12/20 12/21 12/27 12/28 12/30 12/31 Matthew
   30: # 01/01/02 Matthew
   31: # 01/02 01/03 01/04 01/07 01/08 01/09 Matthew
   32: # 01/21 Matthew
   33: 
   34: package Apache::lonplot;
   35: 
   36: use strict;
   37: use Apache::File;
   38: use Apache::response;
   39: use Apache::lonxml;
   40: use Apache::edit;
   41: 
   42: BEGIN {
   43:   &Apache::lonxml::register('Apache::lonplot',('plot'));
   44: }
   45: 
   46: ## 
   47: ## Description of data structures:
   48: ##
   49: ##  %plot       %key    %axis
   50: ## --------------------------
   51: ##  height      title   color
   52: ##  width       box     xmin
   53: ##  bgcolor     pos     xmax
   54: ##  fgcolor             ymin
   55: ##  transparent         ymax
   56: ##  grid
   57: ##  border
   58: ##  font
   59: ##  align
   60: ##
   61: ##  @labels: $labels[$i] = \%label
   62: ##           %label: text, xpos, ypos, justify
   63: ##
   64: ##  @curves: $curves[$i] = \%curve
   65: ##           %curve: name, linestyle, ( function | data )
   66: ##
   67: ##  $curves[$i]->{'data'} = [ [x1,x2,x3,x4],
   68: ##                            [y1,y2,y3,y4] ]
   69: ##
   70: 
   71: ###################################################################
   72: ##                                                               ##
   73: ##        Tests used in checking the validitity of input         ##
   74: ##                                                               ##
   75: ###################################################################
   76: 
   77: my $max_str_len = 50;    # if a label, title, xlabel, or ylabel text
   78:                          # is longer than this, it will be truncated.
   79: 
   80: my %linestyles = 
   81:     (
   82:      lines          => 2,     # Maybe this will be used in the future
   83:      linespoints    => 2,     # to check on whether or not they have 
   84:      dots	    => 2,     # supplied enough <data></data> fields
   85:      points         => 2,     # to use the given line style.  But for
   86:      steps	    => 2,     # now there are more important things 
   87:      fsteps	    => 2,     # for me to deal with.
   88:      histeps        => 2,
   89:      errorbars	    => 3,
   90:      xerrorbars	    => [3,4],
   91:      yerrorbars	    => [3,4],
   92:      xyerrorbars    => [4,6],
   93:      boxes          => 3,
   94: #     boxerrorbars   => [3,4,5],
   95: #     boxxyerrorbars => [4,6,7],
   96: #     financebars    => 5,
   97: #     candlesticks   => 5,
   98:      vector	    => 4
   99:     );		    
  100: 
  101: my $int_test       = sub {$_[0]=~s/\s+//g;$_[0]=~/^\d+$/};
  102: my $real_test      = 
  103:     sub {$_[0]=~s/\s+//g;$_[0]=~/^[+-]?\d*\.?\d*([eE][+-]\d+)?$/};
  104: my $color_test     = sub {$_[0]=~s/\s+//g;$_[0]=~/^x[\da-f]{6}$/};
  105: my $onoff_test     = sub {$_[0]=~/^(on|off)$/};
  106: my $key_pos_test   = sub {$_[0]=~/^(top|bottom|right|left|outside|below| )+$/};
  107: my $sml_test       = sub {$_[0]=~/^(small|medium|large)$/};
  108: my $linestyle_test = sub {exists($linestyles{$_[0]})};
  109: my $words_test     = sub {$_[0]=~s/\s+/ /g;$_[0]=~/^([\w\(\)]+ ?)+$/};
  110: 
  111: ###################################################################
  112: ##                                                               ##
  113: ##                      Attribute metadata                       ##
  114: ##                                                               ##
  115: ###################################################################
  116: my @plot_edit_order = 
  117:     qw/bgcolor fgcolor height width font transparent grid border align/;
  118: my %plot_defaults = 
  119:     (
  120:      height       => {
  121: 	 default     => 200,
  122: 	 test        => $int_test,
  123: 	 description => 'height of image (pixels)',
  124:       	 edit_type   => 'entry',
  125: 	 size        => '10'
  126: 	 },
  127:      width        => {
  128: 	 default     => 200,
  129: 	 test        => $int_test,
  130: 	 description => 'width of image (pixels)',
  131: 	 edit_type   => 'entry',
  132: 	 size        => '10'
  133: 	 },
  134:      bgcolor      => {
  135: 	 default     => 'xffffff',
  136: 	 test        => $color_test, 
  137: 	 description => 'background color of image (xffffff)',
  138: 	 edit_type   => 'entry',
  139: 	 size        => '10'
  140: 	 },
  141:      fgcolor      => {
  142: 	 default     => 'x000000',
  143: 	 test        => $color_test,
  144: 	 description => 'foreground color of image (x000000)',
  145: 	 edit_type   => 'entry',
  146: 	 size        => '10'
  147: 	 },
  148:      transparent  => {
  149: 	 default     => 'off',
  150: 	 test        => $onoff_test, 
  151: 	 description => 'Transparent image',
  152: 	 edit_type   => 'on_off'
  153: 	 },
  154:      grid         => {
  155: 	 default     => 'off',
  156: 	 test        => $onoff_test, 
  157: 	 description => 'Display grid',
  158: 	 edit_type   => 'on_off'
  159: 	 },
  160:      border       => {
  161: 	 default     => 'on',
  162: 	 test        => $onoff_test, 
  163: 	 description => 'Draw border around plot',
  164: 	 edit_type   => 'on_off'
  165: 	 },
  166:      font         => {
  167: 	 default     => 'medium',
  168: 	 test        => $sml_test,
  169: 	 description => 'Size of font to use',
  170: 	 edit_type   => 'choice',
  171: 	 choices     => ['small','medium','large']
  172: 	 },
  173:      align        => {
  174: 	 default     => 'left',
  175: 	 test        => sub {$_[0]=~/^(left|right|center)$/},
  176: 	 description => 'alignment for image in html',
  177: 	 edit_type   => 'choice',
  178: 	 choices     => ['left','right','center']
  179: 	 } 
  180:      );
  181: 
  182: my %key_defaults = 
  183:     (
  184:      title => { 
  185: 	 default => '',
  186: 	 test => $words_test,
  187: 	 description => 'Title of key',
  188: 	 edit_type   => 'entry',
  189: 	 size        => '40'
  190: 	 },
  191:      box   => { 
  192: 	 default => 'off',
  193: 	 test => $onoff_test,
  194: 	 description => 'Draw a box around the key?',
  195: 	 edit_type   => 'on_off'
  196: 	 },
  197:      pos   => { 
  198: 	 default => 'top right', 
  199: 	 test => $key_pos_test, 
  200: 	 description => 'position of the key on the plot',
  201: 	 edit_type   => 'choice',
  202: 	 choices     => ['top left','top right','bottom left','bottom right',
  203: 			 'outside','below']
  204: 	 }
  205:      );
  206: 
  207: my %label_defaults = 
  208:     (
  209:      xpos    => {
  210: 	 default => 0,
  211: 	 test => $real_test,
  212: 	 description => 'x position of label (graph coordinates)',
  213: 	 edit_type   => 'entry',
  214: 	 size        => '10'
  215: 	 },
  216:      ypos    => {
  217: 	 default => 0, 
  218: 	 test => $real_test,
  219: 	 description => 'y position of label (graph coordinates)',
  220: 	 edit_type   => 'entry',
  221: 	 size        => '10'
  222: 	 },
  223:      justify => {
  224: 	 default => 'left',    
  225: 	 test => sub {$_[0]=~/^(left|right|center)$/},
  226: 	 description => 'justification of the label text on the plot',
  227: 	 edit_type   => 'choice',
  228: 	 choices     => ['left','right','center']
  229:      }
  230:      );
  231: 
  232: my %axis_defaults = 
  233:     (
  234:      color   => {
  235: 	 default => 'x000000', 
  236: 	 test => $color_test,
  237: 	 description => 'color of axes (x000000)',
  238: 	 edit_type   => 'entry',
  239: 	 size        => '10'
  240: 	 },
  241:      xmin      => {
  242: 	 default => '-10.0',
  243: 	 test => $real_test,
  244: 	 description => 'minimum x-value shown in plot',
  245: 	 edit_type   => 'entry',
  246: 	 size        => '10'
  247: 	 },
  248:      xmax      => {
  249: 	 default => ' 10.0',
  250: 	 test => $real_test,
  251: 	 description => 'maximum x-value shown in plot',	 
  252: 	 edit_type   => 'entry',
  253: 	 size        => '10'
  254: 	 },
  255:      ymin      => {
  256: 	 default => '-10.0',
  257: 	 test => $real_test,
  258: 	 description => 'minimum y-value shown in plot',	 
  259: 	 edit_type   => 'entry',
  260: 	 size        => '10'
  261: 	 },
  262:      ymax      => {
  263: 	 default => ' 10.0',
  264: 	 test => $real_test,
  265: 	 description => 'maximum y-value shown in plot',	 
  266: 	 edit_type   => 'entry',
  267: 	 size        => '10'
  268: 	 }
  269:      );
  270: 
  271: my %curve_defaults = 
  272:     (
  273:      color     => {
  274: 	 default => 'x000000',
  275: 	 test => $color_test,
  276: 	 description => 'color of curve (x000000)',
  277: 	 edit_type   => 'entry',
  278: 	 size        => '10'
  279: 	 },
  280:      name      => {
  281: 	 default => '',
  282: 	 test => $words_test,
  283: 	 description => 'name of curve to appear in key',
  284: 	 edit_type   => 'entry',
  285: 	 size        => '20'
  286: 	 },
  287:      linestyle => {
  288: 	 default => 'lines',
  289: 	 test => $linestyle_test,
  290: 	 description => 'Line style',
  291: 	 edit_type   => 'choice',
  292: 	 choices     => [keys(%linestyles)]
  293: 	 }
  294:      );
  295: 
  296: ###################################################################
  297: ##                                                               ##
  298: ##                    parsing and edit rendering                 ##
  299: ##                                                               ##
  300: ###################################################################
  301: my (%plot,%key,%axis,$title,$xlabel,$ylabel,@labels,@curves);
  302: 
  303: sub start_plot {
  304:     %plot    = ();      %key     = ();      %axis   = (); 
  305:     $title   = undef;   $xlabel  = undef;   $ylabel = undef;
  306:     $#labels = -1;      $#curves = -1;
  307:     #
  308:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  309:     my $result='';
  310:     &Apache::lonxml::register('Apache::lonplot',
  311: 	     ('title','xlabel','ylabel','key','axis','label','curve'));
  312:     push (@Apache::lonxml::namespace,'lonplot');
  313:     if ($target eq 'web') {
  314: 	my $inside = &Apache::lonxml::get_all_text("/plot",$$parser[-1]);
  315: 	$inside=&Apache::run::evaluate($inside,$safeeval,$$parstack[-1]);
  316: 	&Apache::lonxml::newparser($parser,\$inside);
  317: 	&get_attributes(\%plot,\%plot_defaults,$parstack,$safeeval,
  318: 			$tagstack->[-1]);
  319:     } elsif ($target eq 'edit') {
  320: 	$result .= &Apache::edit::tag_start($target,$token,'Plot');
  321: 	$result .= &edit_attributes($target,$token,\%plot_defaults,
  322: 				    \@plot_edit_order);
  323:     } elsif ($target eq 'modified') {
  324: 	my $constructtag=&Apache::edit::get_new_args
  325: 	    ($token,$parstack,$safeeval,keys(%plot_defaults));
  326: 	if ($constructtag) {
  327: 	    $result = &Apache::edit::rebuild_tag($token);
  328: 	}
  329:     }
  330:     return $result;
  331: }
  332: 
  333: sub end_plot {
  334:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  335: 
  336:     pop @Apache::lonxml::namespace;
  337:     &Apache::lonxml::deregister('Apache::lonplot',
  338: 	('title','xlabel','ylabel','key','axis','label','curve'));
  339:     my $result = '';
  340:     if ($target eq 'web') {
  341: 	&check_inputs(); # Make sure we have all the data we need
  342: 	##
  343: 	## Determine filename
  344: 	my $tmpdir = '/home/httpd/perl/tmp/';
  345: 	my $filename = $ENV{'user.name'}.'_'.$ENV{'user.domain'}.
  346: 	    '_'.time.'_'.$$.int(rand(1000)).'_plot.data';
  347: 	## Write the plot description to the file
  348: 	&write_gnuplot_file($tmpdir,$filename);
  349: 	## return image tag for the plot
  350: 	$result .= <<"ENDIMAGE";
  351: <img src    = "/cgi-bin/plot.gif?$filename" 
  352:      width  = "$plot{'width'}" 
  353:      height = "$plot{'height'}"
  354:      align  = "$plot{'align'}"
  355:      alt    = "/cgi-bin/plot.gif?$filename" />
  356: ENDIMAGE
  357:     } elsif ($target eq 'edit') {
  358: 	$result.=&Apache::edit::tag_end($target,$token);
  359:     }
  360:     return $result;
  361: }
  362: 
  363: ##----------------------------------------------------------------- key
  364: sub start_key {
  365:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  366:     my $result='';
  367:     if ($target eq 'web') {
  368: 	&get_attributes(\%key,\%key_defaults,$parstack,$safeeval,
  369: 		    $tagstack->[-1]);
  370:     } elsif ($target eq 'edit') {
  371: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Key');
  372: 	$result .= &edit_attributes($target,$token,\%key_defaults);
  373:     } elsif ($target eq 'modified') {
  374: 	my $constructtag=&Apache::edit::get_new_args
  375: 	    ($token,$parstack,$safeeval,keys(%key_defaults));
  376: 	if ($constructtag) {
  377: 	    $result = &Apache::edit::rebuild_tag($token);
  378: 	}
  379:     }
  380:     return $result;
  381: }
  382: 
  383: sub end_key {
  384:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  385:     my $result = '';
  386:     if ($target eq 'web') {
  387:     } elsif ($target eq 'edit') {
  388: 	$result.=&Apache::edit::tag_end($target,$token);
  389:     }
  390:     return $result;
  391: }
  392: 
  393: ##------------------------------------------------------------------- title
  394: sub start_title {
  395:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  396:     my $result='';
  397:     if ($target eq 'web') {
  398: 	$title = &Apache::lonxml::get_all_text("/title",$$parser[-1]);
  399: 	if (length($title) > $max_str_len) {
  400: 	    $title = substr($title,0,$max_str_len);
  401: 	}
  402:     } elsif ($target eq 'edit') {
  403: 	$result.=&Apache::edit::tag_start($target,$token,'Plot Title');
  404: 	my $text=&Apache::lonxml::get_all_text("/title",$$parser[-1]);
  405: 	$result.=&Apache::edit::end_row().
  406: 	    &Apache::edit::start_spanning_row().
  407: 	    &Apache::edit::editfield('',$text,'',60,1);
  408:     } elsif ($target eq 'modified') {
  409: 	my $text=$$parser[-1]->get_text("/title");
  410: 	$result.=&Apache::edit::rebuild_tag($token);
  411: 	$result.=&Apache::edit::modifiedfield($token);
  412:     }
  413:     return $result;
  414: }
  415: 
  416: sub end_title {
  417:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  418:     my $result = '';
  419:     if ($target eq 'web') {
  420:     } elsif ($target eq 'edit') {
  421: 	$result.=&Apache::edit::tag_end($target,$token);
  422:     }
  423:     return $result;
  424: }
  425: ##------------------------------------------------------------------- xlabel
  426: sub start_xlabel {
  427:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  428:     my $result='';
  429:     if ($target eq 'web') {
  430: 	$xlabel = &Apache::lonxml::get_all_text("/xlabel",$$parser[-1]);
  431: 	if (length($xlabel) > $max_str_len) {
  432: 	    $xlabel = substr($xlabel,0,$max_str_len);
  433: 	}
  434:     } elsif ($target eq 'edit') {
  435: 	$result.=&Apache::edit::tag_start($target,$token,'Plot Xlabel');
  436: 	my $text=&Apache::lonxml::get_all_text("/xlabel",$$parser[-1]);
  437: 	$result.=&Apache::edit::end_row().
  438: 	    &Apache::edit::start_spanning_row().
  439: 	    &Apache::edit::editfield('',$text,'',60,1);
  440:     } elsif ($target eq 'modified') {
  441: 	my $text=$$parser[-1]->get_text("/xlabel");
  442: 	$result.=&Apache::edit::rebuild_tag($token);	
  443: 	$result.=&Apache::edit::modifiedfield($token);
  444:     }
  445:     return $result;
  446: }
  447: 
  448: sub end_xlabel {
  449:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  450:     my $result = '';
  451:     if ($target eq 'web') {
  452:     } elsif ($target eq 'edit') {
  453: 	$result.=&Apache::edit::tag_end($target,$token);
  454:     }
  455:     return $result;
  456: }
  457: 
  458: ##------------------------------------------------------------------- ylabel
  459: sub start_ylabel {
  460:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  461:     my $result='';
  462:     if ($target eq 'web') {
  463: 	$ylabel = &Apache::lonxml::get_all_text("/ylabel",$$parser[-1]);
  464: 	if (length($ylabel) > $max_str_len) {
  465: 	    $ylabel = substr($ylabel,0,$max_str_len);
  466: 	}
  467:     } elsif ($target eq 'edit') {
  468: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Ylabel');
  469: 	my $text = &Apache::lonxml::get_all_text("/ylabel",$$parser[-1]);
  470: 	$result .= &Apache::edit::end_row().
  471: 	    &Apache::edit::start_spanning_row().
  472: 	    &Apache::edit::editfield('',$text,'',60,1);
  473:     } elsif ($target eq 'modified') {
  474: 	my $text=$$parser[-1]->get_text("/ylabel");
  475: 	$result.=&Apache::edit::rebuild_tag($token);
  476: 	$result.=&Apache::edit::modifiedfield($token);
  477:     }
  478:     return $result;
  479: }
  480: 
  481: sub end_ylabel {
  482:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  483:     my $result = '';
  484:     if ($target eq 'web') {
  485:     } elsif ($target eq 'edit') {
  486: 	$result.=&Apache::edit::tag_end($target,$token);
  487:     }
  488:     return $result;
  489: }
  490: 
  491: ##------------------------------------------------------------------- label
  492: sub start_label {
  493:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  494:     my $result='';
  495:     if ($target eq 'web') {
  496: 	my %label;
  497: 	&get_attributes(\%label,\%label_defaults,$parstack,$safeeval,
  498: 		    $tagstack->[-1]);
  499: 	my $text = &Apache::lonxml::get_all_text("/label",$$parser[-1]);
  500: 	$text = substr($text,0,$max_str_len) if (length($text) > $max_str_len);
  501: 	$label{'text'} = $text;
  502: 	push(@labels,\%label);
  503:     } elsif ($target eq 'edit') {
  504: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Label');
  505: 	$result .= &edit_attributes($target,$token,\%label_defaults);
  506: 	my $text = &Apache::lonxml::get_all_text("/label",$$parser[-1]);
  507: 	$result .= &Apache::edit::end_row().
  508: 	    &Apache::edit::start_spanning_row().
  509: 	    &Apache::edit::editfield('',$text,'',60,1);
  510:     } elsif ($target eq 'modified') {
  511: 	&Apache::edit::get_new_args
  512: 	    ($token,$parstack,$safeeval,keys(%label_defaults));
  513: 	$result.=&Apache::edit::rebuild_tag($token);
  514: 	my $text=$$parser[-1]->get_text("/label");
  515: 	$result.=&Apache::edit::modifiedfield($token);
  516:     }
  517:     return $result;
  518: }
  519: 
  520: sub end_label {
  521:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  522:     my $result = '';
  523:     if ($target eq 'web') {
  524:     } elsif ($target eq 'edit') {
  525: 	$result.=&Apache::edit::tag_end($target,$token);
  526:     }
  527:     return $result;
  528: }
  529: 
  530: ##------------------------------------------------------------------- curve
  531: sub start_curve {
  532:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  533:     my $result='';
  534:     &Apache::lonxml::register('Apache::lonplot',('function','data'));
  535:     push (@Apache::lonxml::namespace,'curve');
  536:     if ($target eq 'web') {
  537: 	my %curve;
  538: 	&get_attributes(\%curve,\%curve_defaults,$parstack,$safeeval,
  539: 		    $tagstack->[-1]);
  540: 	push (@curves,\%curve);
  541:     } elsif ($target eq 'edit') {
  542: 	$result .= &Apache::edit::tag_start($target,$token,'Curve');
  543: 	$result .= &edit_attributes($target,$token,\%curve_defaults);
  544:     } elsif ($target eq 'modified') {
  545: 	my $constructtag=&Apache::edit::get_new_args
  546: 	    ($token,$parstack,$safeeval,keys(%curve_defaults));
  547: 	if ($constructtag) {
  548: 	    $result = &Apache::edit::rebuild_tag($token);
  549: 	    $result.= &Apache::edit::handle_insert();
  550: 	}
  551:     }
  552:     return $result;
  553: }
  554: 
  555: sub end_curve {
  556:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  557:     my $result = '';
  558:     pop @Apache::lonxml::namespace;
  559:     &Apache::lonxml::deregister('Apache::lonplot',('function','data'));
  560:     if ($target eq 'web') {
  561:     } elsif ($target eq 'edit') {
  562: 	$result.=&Apache::edit::tag_end($target,$token);
  563:     }
  564:     return $result;
  565: }
  566: 
  567: ##------------------------------------------------------------ curve function
  568: sub start_function {
  569:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  570:     my $result='';
  571:     if ($target eq 'web') {
  572: 	if (exists($curves[-1]->{'data'})) {
  573: 	    &Apache::lonxml::warning('Use of <function> precludes use of <data>.  The <data> will be omitted in favor of the <function> declaration.');
  574: 	    delete $curves[-1]->{'data'} ;
  575: 	}
  576: 	$curves[-1]->{'function'} = 
  577: 	    &Apache::lonxml::get_all_text("/function",$$parser[-1]);
  578:     } elsif ($target eq 'edit') {
  579: 	$result .= &Apache::edit::tag_start($target,$token,'Gnuplot compatible curve function');
  580: 	my $text = &Apache::lonxml::get_all_text("/function",$$parser[-1]);
  581: 	$result .= &Apache::edit::end_row().
  582: 	    &Apache::edit::start_spanning_row().
  583: 	    &Apache::edit::editfield('',$text,'',60,1);
  584:     } elsif ($target eq 'modified') {
  585: 	$result.=&Apache::edit::rebuild_tag($token);
  586: 	my $text=$$parser[-1]->get_text("/function");
  587: 	$result.=&Apache::edit::modifiedfield($token);
  588:     }
  589:     return $result;
  590: }
  591: 
  592: sub end_function {
  593:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  594:     my $result = '';
  595:     if ($target eq 'web') {
  596:     } elsif ($target eq 'edit') {
  597: 	$result .= &Apache::edit::end_table();
  598:     }
  599:     return $result;
  600: }
  601: 
  602: ##------------------------------------------------------------ curve  data
  603: sub start_data {
  604:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  605:     my $result='';
  606:     if ($target eq 'web') {
  607: 	if (exists($curves[-1]->{'function'})) {
  608: 	    &Apache::lonxml::warning('Use of <data> precludes use of .'.
  609: 	    '<function>.  The <function> will be omitted in favor of '.
  610:             'the <data> declaration.');
  611: 	    delete($curves[-1]->{'function'});
  612: 	}
  613: 	my $datatext = &Apache::lonxml::get_all_text("/data",$$parser[-1]);
  614: 	# Deal with cases where we're given an array...
  615: 	if ($datatext =~ /^\@/) {
  616: 	    $datatext = &Apache::run::run('return "'.$datatext.'"',
  617: 					  $safeeval,1);
  618: 	}
  619: 	$datatext =~ s/\s+/ /g;  
  620: 	# Need to do some error checking on the @data array - 
  621: 	# make sure it's all numbers and make sure each array 
  622: 	# is of the same length.
  623: 	my @data;
  624: 	if ($datatext =~ /,/) { # comma deliminated
  625: 	    @data = split /,/,$datatext;
  626: 	} else { # Assume it's space seperated.
  627: 	    @data = split / /,$datatext;
  628: 	}
  629: 	for (my $i=0;$i<=$#data;$i++) {
  630: 	    # Check that it's non-empty
  631: 	    if (! defined($data[$i])) {
  632: 		&Apache::lonxml::warning(
  633: 		    'undefined <data> value.  Replacing with '.
  634: 		    ' pi/e = 1.15572734979092');
  635: 		$data[$i] = 1.15572734979092;
  636: 	    }
  637: 	    # Check that it's a number
  638: 	    if (! &$real_test($data[$i]) & ! &$int_test($data[$i])) {
  639: 		&Apache::lonxml::warning(
  640: 		    'Bad <data> value of '.$data[$i].'  Replacing with '.
  641: 		    ' pi/e = 1.15572734979092');
  642: 		$data[$i] = 1.15572734979092;
  643: 	    }
  644: 	}
  645: 	# complain if the number of data points is not the same as
  646: 	# in previous sets of data.
  647: 	if (($curves[-1]->{'data'}) && ($#data != $#{@{$curves[-1]->{'data'}->[0]}})){
  648: 	    &Apache::lonxml::warning
  649: 		('Number of data points is not consistent with previous '.
  650: 		 'number of data points');
  651: 	}
  652: 	push  @{$curves[-1]->{'data'}},\@data;
  653:     } elsif ($target eq 'edit') {
  654: 	$result .= &Apache::edit::tag_start($target,$token,'Comma or space deliminated curve data');
  655: 	my $text = &Apache::lonxml::get_all_text("/data",$$parser[-1]);
  656: 	$result .= &Apache::edit::end_row().
  657: 	    &Apache::edit::start_spanning_row().
  658: 	    &Apache::edit::editfield('',$text,'',60,1);
  659:     } elsif ($target eq 'modified') {
  660: 	$result.=&Apache::edit::rebuild_tag($token);
  661: 	my $text=$$parser[-1]->get_text("/data");
  662: 	$result.=&Apache::edit::modifiedfield($token);
  663:     }
  664:     return $result;
  665: }
  666: 
  667: sub end_data {
  668:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  669:     my $result = '';
  670:     if ($target eq 'web') {
  671:     } elsif ($target eq 'edit') {
  672: 	$result .= &Apache::edit::end_table();
  673:     }
  674:     return $result;
  675: }
  676: 
  677: ##------------------------------------------------------------------- axis
  678: sub start_axis {
  679:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  680:     my $result='';
  681:     if ($target eq 'web') {
  682: 	&get_attributes(\%axis,\%axis_defaults,$parstack,$safeeval,
  683: 			$tagstack->[-1]);
  684:     } elsif ($target eq 'edit') {
  685: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Axes');
  686: 	$result .= &edit_attributes($target,$token,\%axis_defaults);
  687:     } elsif ($target eq 'modified') {
  688: 	my $constructtag=&Apache::edit::get_new_args
  689: 	    ($token,$parstack,$safeeval,keys(%axis_defaults));
  690: 	if ($constructtag) {
  691: 	    $result = &Apache::edit::rebuild_tag($token);
  692: 	}
  693:     }
  694:     return $result;
  695: }
  696: 
  697: sub end_axis {
  698:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  699:     my $result = '';
  700:     if ($target eq 'web') {
  701:     } elsif ($target eq 'edit') {
  702: 	$result.=&Apache::edit::tag_end($target,$token);
  703:     } elsif ($target eq 'modified') {
  704:     }
  705:     return $result;
  706: }
  707: 
  708: ###################################################################
  709: ##                                                               ##
  710: ##        Utility Functions                                      ##
  711: ##                                                               ##
  712: ###################################################################
  713: 
  714: ##----------------------------------------------------------- set_defaults
  715: sub set_defaults {
  716:     my ($var,$defaults) = @_;
  717:     my $key;
  718:     foreach $key (keys(%$defaults)) {
  719: 	$var->{$key} = $defaults->{$key}->{'default'};
  720:     }
  721: }
  722: 
  723: ##------------------------------------------------------------------- misc
  724: sub get_attributes{
  725:     my ($values,$defaults,$parstack,$safeeval,$tag) = @_;
  726:     foreach my $attr (keys(%{$defaults})) {
  727: 	$values->{$attr} = 
  728: 	    &Apache::lonxml::get_param($attr,$parstack,$safeeval);
  729: 	if ($values->{$attr} eq '' | !defined($values->{$attr})) {
  730: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
  731: 	    next;
  732: 	}
  733: 	my $test = $defaults->{$attr}->{'test'};
  734: 	if (! &$test($values->{$attr})) {
  735: 	    &Apache::lonxml::warning
  736: 		($tag.':'.$attr.': Bad value.'.'Replacing your value with : '
  737: 		 .$defaults->{$attr}->{'default'} );
  738: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
  739: 	}
  740:     }
  741:     return ;
  742: }
  743: 
  744: ##------------------------------------------------------- write_gnuplot_file
  745: sub write_gnuplot_file {
  746:     my ($tmpdir,$filename)= @_;
  747:     my $gnuplot_input = '';
  748:     my $curve;
  749:     # Collect all the colors
  750:     my @Colors;
  751:     push @Colors, $plot{'bgcolor'};
  752:     push @Colors, $plot{'fgcolor'}; 
  753:     push @Colors, (defined($axis{'color'})?$axis{'color'}:$plot{'fgcolor'});
  754:     foreach $curve (@curves) {
  755: 	push @Colors, ($curve->{'color'} ne '' ? 
  756: 		       $curve->{'color'}       : 
  757: 		       $plot{'fgcolor'}        );
  758:     }
  759:     # set term
  760:     $gnuplot_input .= 'set term gif ';
  761:     $gnuplot_input .= 'transparent ' if ($plot{'transparent'} eq 'on');
  762:     $gnuplot_input .= $plot{'font'} . ' ';
  763:     $gnuplot_input .= 'size '.$plot{'width'}.','.$plot{'height'}.' ';
  764:     $gnuplot_input .= "@Colors\n";
  765:     # grid
  766:     $gnuplot_input .= 'set grid'.$/ if ($plot{'grid'} eq 'on');
  767:     # border
  768:     $gnuplot_input .= ($plot{'border'} eq 'on'?
  769: 		       'set border'.$/           :
  770: 		       'set noborder'.$/         );    # title, xlabel, ylabel
  771:     $gnuplot_input .= "set output\n";
  772:     $gnuplot_input .= "set title  \"$title\"\n"  if (defined($title)) ;
  773:     $gnuplot_input .= "set xlabel \"$xlabel\"\n" if (defined($xlabel));
  774:     $gnuplot_input .= "set ylabel \"$ylabel\"\n" if (defined($ylabel));
  775:     if (%axis) {
  776: 	$gnuplot_input .= "set xrange \[$axis{'xmin'}:$axis{'xmax'}\]\n";
  777: 	$gnuplot_input .= "set yrange \[$axis{'ymin'}:$axis{'ymax'}\]\n";
  778:     }
  779:     # Key
  780:     if (%key) {
  781: 	$gnuplot_input .= 'set key '.$key{'pos'}.' ';
  782: 	if ($key{'title'} ne '') {
  783: 	    $gnuplot_input .= 'title " '.$key{'title'}.'" ';
  784: 	} 
  785: 	$gnuplot_input .= ($key{'box'} eq 'on' ? 'box ' : 'nobox ').$/;
  786:     } else {
  787: 	$gnuplot_input .= 'set nokey'.$/;
  788:     }
  789:     # labels
  790:     my $label;
  791:     foreach $label (@labels) {
  792: 	$gnuplot_input .= 'set label "'.$label->{'text'}.'" at '.
  793: 	    $label->{'xpos'}.','.$label->{'ypos'}.' '.$label->{'justify'}.$/ ;
  794:     }
  795:     # curves
  796:     $gnuplot_input .= 'plot ';
  797:     for (my $i = 0;$i<=$#curves;$i++) {
  798: 	$curve = $curves[$i];
  799: 	$gnuplot_input.= ', ' if ($i > 0);
  800: 	if (exists($curve->{'function'})) {
  801: 	    $gnuplot_input.= 
  802: 		$curve->{'function'}.' title "'.
  803: 		$curve->{'name'}.'" with '.
  804: 		$curve->{'linestyle'};
  805: 	} elsif (exists($curve->{'data'})) {
  806: 	    # Store data values in $datatext
  807: 	    my $datatext = '';
  808: 	    #   get new filename
  809: 	    my $datafilename = "$tmpdir/$filename.$i";
  810: 	    my $fh=Apache::File->new(">$datafilename");
  811: 	    # Compile data
  812: 	    my @Data = @{$curve->{'data'}};
  813: 	    my @Data0 = @{$Data[0]};
  814: 	    for (my $i =0; $i<=$#Data0; $i++) {
  815: 		my $dataset;
  816: 		foreach $dataset (@Data) {
  817: 		    $datatext .= $dataset->[$i] . ' ';
  818: 		}
  819: 		$datatext .= $/;
  820: 	    }
  821: 	    #   write file
  822: 	    print $fh $datatext;
  823: 	    close ($fh);
  824: 	    #   generate gnuplot text
  825: 	    $gnuplot_input.= '"'.$datafilename.'" title "'.
  826: 		$curve->{'name'}.'" with '.
  827: 		$curve->{'linestyle'};
  828: 	}
  829:     }
  830:     # Write the output to a file.
  831:     my $fh=Apache::File->new(">$tmpdir$filename");
  832:     print $fh $gnuplot_input;
  833:     close($fh);
  834:     # That's all folks.
  835:     return ;
  836: }
  837: 
  838: #---------------------------------------------- check_inputs
  839: sub check_inputs {
  840:     ## Note: no inputs, no outputs - this acts only on global variables.
  841:     ## Make sure we have all the input we need:
  842:     if (! %plot) { &set_defaults(\%plot,\%plot_defaults); }
  843:     if (! %key ) {} # No key for this plot, thats okay
  844: #    if (! %axis) { &set_defaults(\%axis,\%axis_defaults); }
  845:     if (! defined($title )) {} # No title for this plot, thats okay
  846:     if (! defined($xlabel)) {} # No xlabel for this plot, thats okay
  847:     if (! defined($ylabel)) {} # No ylabel for this plot, thats okay
  848:     if ($#labels < 0) { }      # No labels for this plot, thats okay
  849:     if ($#curves < 0) { 
  850: 	&Apache::lonxml::warning("No curves specified for plot!!!!");
  851: 	return '';
  852:     }
  853:     my $curve;
  854:     foreach $curve (@curves) {
  855: 	if (!defined($curve->{'function'})&&!defined($curve->{'data'})){
  856: 	    &Apache::lonxml::warning("One of the curves specified did not contain any <data> or <function> declarations\n");
  857: 	    return '';
  858: 	}
  859:     }
  860: }
  861: 
  862: #------------------------------------------------ make_edit
  863: sub edit_attributes {
  864:     my ($target,$token,$defaults,$keys) = @_;
  865:     my ($result,@keys);
  866:     if ($keys && ref($keys) eq 'ARRAY') {
  867:         @keys = @$keys;
  868:     } else {
  869: 	@keys = sort(keys(%$defaults));
  870:     }
  871:     foreach my $attr (@keys) {
  872: 	# append a ' ' to the description if it doesn't have one already.
  873: 	my $description = $defaults->{$attr}->{'description'};
  874: 	$description .= ' ' if ($description !~ / $/);
  875: 	if ($defaults->{$attr}->{'edit_type'} eq 'entry') {
  876: 	    $result .= &Apache::edit::text_arg
  877: 		($description,$attr,$token,
  878: 		 $defaults->{$attr}->{'size'});
  879: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'choice') {
  880: 	    $result .= &Apache::edit::select_arg
  881: 		($description,$attr,$defaults->{$attr}->{'choices'},$token);
  882: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'on_off') {
  883: 	    $result .= &Apache::edit::select_arg
  884: 		($description,$attr,['on','off'],$token);
  885: 	}
  886: 	$result .= '<br />';
  887:     }
  888:     return $result;
  889: }
  890: 
  891: 
  892: ###################################################################
  893: ##                                                               ##
  894: ##           Insertion functions for editing plots               ##
  895: ##                                                               ##
  896: ###################################################################
  897: 
  898: #------------------------------------------------ insert_xxxxxxx
  899: sub insert_plot {
  900:     my $result = '';
  901:     #  plot attributes
  902:     $result .= "<plot \n";
  903:     foreach my $attr (keys(%plot_defaults)) {
  904: 	$result .= "     $attr=\"$plot_defaults{$attr}->{'default'}\"\n";
  905:     }
  906:     $result .= ">\n";
  907:     # Add the components
  908:     $result .= &insert_key();
  909:     $result .= &insert_axis();
  910:     $result .= &insert_title();    
  911:     $result .= &insert_xlabel();    
  912:     $result .= &insert_ylabel();    
  913:     $result .= &insert_curve();
  914:     # close up the <plot>
  915:     $result .= "</plot>\n";
  916:     return $result;
  917: }
  918: 
  919: sub insert_key {
  920:     my $result;
  921:     $result .= "    <key \n";
  922:     foreach my $attr (keys(%key_defaults)) {
  923: 	$result .= "         $attr=\"$key_defaults{$attr}->{'default'}\"\n";
  924:     }
  925:     $result .= "   />\n";
  926:     return $result;
  927: }
  928: 
  929: sub insert_axis{
  930:     my $result;
  931:     $result .= '    <axis ';
  932:    foreach my $attr (keys(%axis_defaults)) {
  933: 	$result .= "         $attr=\"$axis_defaults{$attr}->{'default'}\"\n";
  934:     }
  935:     $result .= "   />\n";
  936:     return $result;
  937: }
  938: 
  939: sub insert_title { return "    <title></title>\n"; }
  940: sub insert_xlabel { return "    <xlabel></xlabel>\n"; }
  941: sub insert_ylabel { return "    <ylabel></ylabel>\n"; }
  942: 
  943: sub insert_label {
  944:     my $result;
  945:     $result .= '    <label ';
  946:     foreach my $attr (keys(%label_defaults)) {
  947: 	$result .= '         '.$attr.'="'.
  948: 	    $label_defaults{$attr}->{'default'}."\"\n";
  949:     }
  950:     $result .= "   ></label>\n";
  951:     return $result;
  952: }
  953: 
  954: sub insert_curve {
  955:     my $result;
  956:     $result .= "\n    <curve ";
  957:     foreach my $attr (keys(%curve_defaults)) {
  958: 	$result .= '         '.$attr.'="'.
  959: 	    $curve_defaults{$attr}->{'default'}."\"\n";
  960:     }
  961:     $result .= "    >\n";
  962:     $result .= &insert_data().&insert_data()."</curve>\n";
  963: }
  964: 
  965: sub insert_function {
  966:     my $result;
  967:     $result .= "<function></function>\n";
  968:     return $result;
  969: }
  970: 
  971: sub insert_data {
  972:     my $result;
  973:     $result .= "     <data></data>\n";
  974:     return $result;
  975: }
  976: 
  977: ##----------------------------------------------------------------------
  978: 1;
  979: __END__
  980: 
  981: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>