File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.39: download - view: text, annotated - select for diffs
Fri Jan 11 16:34:06 2002 UTC (22 years, 4 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Changes to use edit::start_spanning_row and edit::end_row instead of using
<dt colspan="3"> and other such nonsense.

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

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