File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.35: download - view: text, annotated - select for diffs
Wed Jan 9 16:51:51 2002 UTC (22 years, 4 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Bugfix for reading in colors of curves, removed a few unusable linestyles,
added a few comments.

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

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