File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.46: download - view: text, annotated - select for diffs
Wed Jan 30 13:27:51 2002 UTC (22 years, 3 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Minor bugfix for xtics & ytics, added &insert_tics() to insert both, and
cleaned up a bit of the code for insertion of tics.

    1: # The LearningOnline Network with CAPA
    2: # Dynamic plot
    3: #
    4: # $Id: lonplot.pm,v 1.46 2002/01/30 13:27: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: # 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   => 'onoff'
  153: 	 },
  154:      grid         => {
  155: 	 default     => 'off',
  156: 	 test        => $onoff_test, 
  157: 	 description => 'Display grid',
  158: 	 edit_type   => 'onoff'
  159: 	 },
  160:      border       => {
  161: 	 default     => 'on',
  162: 	 test        => $onoff_test, 
  163: 	 description => 'Draw border around plot',
  164: 	 edit_type   => 'onoff'
  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   => 'onoff'
  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 @tic_edit_order = ('location','mirror','start','increment','end');
  233: my %tic_defaults =
  234:     (
  235:      location => {
  236: 	 default => 'border', 
  237: 	 test => sub {$_[0]=~/^(border|axis)$/},
  238: 	 description => 'Location of tick marks',
  239: 	 edit_type   => 'choice',
  240: 	 choices     => ['border','axis']
  241: 	 },
  242:      mirror => {
  243: 	 default => 'on', 
  244: 	 test => $onoff_test,
  245: 	 description => 'mirror ticks on opposite axis?',
  246: 	 edit_type   => 'onoff'
  247: 	 },
  248:      start => {
  249: 	 default => '-10.0',
  250: 	 test => $real_test,
  251: 	 description => 'Start ticks at',
  252: 	 edit_type   => 'entry',
  253: 	 size        => '10'
  254: 	 },
  255:      increment => {
  256: 	 default => '1.0',
  257: 	 test => $real_test,
  258: 	 description => 'Place a tick every',
  259: 	 edit_type   => 'entry',
  260: 	 size        => '10'
  261: 	 },
  262:      end => {
  263: 	 default => ' 10.0',
  264: 	 test => $real_test,
  265: 	 description => 'Stop ticks at ',
  266: 	 edit_type   => 'entry',
  267: 	 size        => '10'
  268: 	 },
  269:      );
  270: 
  271: my %axis_defaults = 
  272:     (
  273:      color   => {
  274: 	 default => 'x000000', 
  275: 	 test => $color_test,
  276: 	 description => 'color of axes (x000000)',
  277: 	 edit_type   => 'entry',
  278: 	 size        => '10'
  279: 	 },
  280:      xmin      => {
  281: 	 default => '-10.0',
  282: 	 test => $real_test,
  283: 	 description => 'minimum x-value shown in plot',
  284: 	 edit_type   => 'entry',
  285: 	 size        => '10'
  286: 	 },
  287:      xmax      => {
  288: 	 default => ' 10.0',
  289: 	 test => $real_test,
  290: 	 description => 'maximum x-value shown in plot',	 
  291: 	 edit_type   => 'entry',
  292: 	 size        => '10'
  293: 	 },
  294:      ymin      => {
  295: 	 default => '-10.0',
  296: 	 test => $real_test,
  297: 	 description => 'minimum y-value shown in plot',	 
  298: 	 edit_type   => 'entry',
  299: 	 size        => '10'
  300: 	 },
  301:      ymax      => {
  302: 	 default => ' 10.0',
  303: 	 test => $real_test,
  304: 	 description => 'maximum y-value shown in plot',	 
  305: 	 edit_type   => 'entry',
  306: 	 size        => '10'
  307: 	 }
  308:      );
  309: 
  310: my %curve_defaults = 
  311:     (
  312:      color     => {
  313: 	 default => 'x000000',
  314: 	 test => $color_test,
  315: 	 description => 'color of curve (x000000)',
  316: 	 edit_type   => 'entry',
  317: 	 size        => '10'
  318: 	 },
  319:      name      => {
  320: 	 default => '',
  321: 	 test => $words_test,
  322: 	 description => 'name of curve to appear in key',
  323: 	 edit_type   => 'entry',
  324: 	 size        => '20'
  325: 	 },
  326:      linestyle => {
  327: 	 default => 'lines',
  328: 	 test => $linestyle_test,
  329: 	 description => 'Line style',
  330: 	 edit_type   => 'choice',
  331: 	 choices     => [keys(%linestyles)]
  332: 	 }
  333:      );
  334: 
  335: ###################################################################
  336: ##                                                               ##
  337: ##                    parsing and edit rendering                 ##
  338: ##                                                               ##
  339: ###################################################################
  340: my (%plot,%key,%axis,$title,$xlabel,$ylabel,@labels,@curves,%xtics,%ytics);
  341: 
  342: sub start_plot {
  343:     %plot    = ();      %key     = ();      %axis   = (); 
  344:     $title   = undef;   $xlabel  = undef;   $ylabel = undef;
  345:     $#labels = -1;      $#curves = -1;
  346:     %xtics    = ();      %ytics    = ();
  347:     #
  348:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  349:     my $result='';
  350:     &Apache::lonxml::register('Apache::lonplot',
  351: 	     ('title','xlabel','ylabel','key','axis','label','curve',
  352: 	      'xtics','ytics'));
  353:     push (@Apache::lonxml::namespace,'lonplot');
  354:     if ($target eq 'web') {
  355: 	my $inside = &Apache::lonxml::get_all_text("/plot",$$parser[-1]);
  356: 	$inside=&Apache::run::evaluate($inside,$safeeval,$$parstack[-1]);
  357: 	&Apache::lonxml::newparser($parser,\$inside);
  358: 	&get_attributes(\%plot,\%plot_defaults,$parstack,$safeeval,
  359: 			$tagstack->[-1]);
  360:     } elsif ($target eq 'edit') {
  361: 	$result .= &Apache::edit::tag_start($target,$token,'Plot');
  362: 	$result .= &edit_attributes($target,$token,\%plot_defaults,
  363: 				    \@plot_edit_order);
  364:     } elsif ($target eq 'modified') {
  365: 	my $constructtag=&Apache::edit::get_new_args
  366: 	    ($token,$parstack,$safeeval,keys(%plot_defaults));
  367: 	if ($constructtag) {
  368: 	    $result = &Apache::edit::rebuild_tag($token);
  369: 	}
  370:     }
  371:     return $result;
  372: }
  373: 
  374: sub end_plot {
  375:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  376: 
  377:     pop @Apache::lonxml::namespace;
  378:     &Apache::lonxml::deregister('Apache::lonplot',
  379: 	('title','xlabel','ylabel','key','axis','label','curve'));
  380:     my $result = '';
  381:     if ($target eq 'web') {
  382: 	&check_inputs(); # Make sure we have all the data we need
  383: 	##
  384: 	## Determine filename
  385: 	my $tmpdir = '/home/httpd/perl/tmp/';
  386: 	my $filename = $ENV{'user.name'}.'_'.$ENV{'user.domain'}.
  387: 	    '_'.time.'_'.$$.int(rand(1000)).'_plot.data';
  388: 	## Write the plot description to the file
  389: 	&write_gnuplot_file($tmpdir,$filename);
  390: 	## return image tag for the plot
  391: 	$result .= <<"ENDIMAGE";
  392: <img src    = "/cgi-bin/plot.gif?$filename" 
  393:      width  = "$plot{'width'}" 
  394:      height = "$plot{'height'}"
  395:      align  = "$plot{'align'}"
  396:      alt    = "/cgi-bin/plot.gif?$filename" />
  397: ENDIMAGE
  398:     } elsif ($target eq 'edit') {
  399: 	$result.=&Apache::edit::tag_end($target,$token);
  400:     }
  401:     return $result;
  402: }
  403: 
  404: 
  405: ##--------------------------------------------------------------- xtics
  406: sub start_xtics {
  407:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  408:     my $result='';
  409:     if ($target eq 'web') {
  410: 	&get_attributes(\%xtics,\%tic_defaults,$parstack,$safeeval,
  411: 		    $tagstack->[-1]);
  412:     } elsif ($target eq 'edit') {
  413: 	$result .= &Apache::edit::tag_start($target,$token,'xtics');
  414: 	$result .= &edit_attributes($target,$token,\%tic_defaults,
  415: 				    \@tic_edit_order);
  416:     } elsif ($target eq 'modified') {
  417: 	my $constructtag=&Apache::edit::get_new_args
  418: 	    ($token,$parstack,$safeeval,keys(%tic_defaults));
  419: 	if ($constructtag) {
  420: 	    $result = &Apache::edit::rebuild_tag($token);
  421: 	}
  422:     }
  423:     return $result;
  424: }
  425: 
  426: sub end_xtics {
  427:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  428:     my $result = '';
  429:     if ($target eq 'web') {
  430:     } elsif ($target eq 'edit') {
  431: 	$result.=&Apache::edit::tag_end($target,$token);
  432:     }
  433:     return $result;
  434: }
  435: 
  436: ##--------------------------------------------------------------- ytics
  437: sub start_ytics {
  438:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  439:     my $result='';
  440:     if ($target eq 'web') {
  441: 	&get_attributes(\%ytics,\%tic_defaults,$parstack,$safeeval,
  442: 		    $tagstack->[-1]);
  443:     } elsif ($target eq 'edit') {
  444: 	$result .= &Apache::edit::tag_start($target,$token,'ytics');
  445: 	$result .= &edit_attributes($target,$token,\%tic_defaults,
  446: 				    \@tic_edit_order);
  447:     } elsif ($target eq 'modified') {
  448: 	my $constructtag=&Apache::edit::get_new_args
  449: 	    ($token,$parstack,$safeeval,keys(%tic_defaults));
  450: 	if ($constructtag) {
  451: 	    $result = &Apache::edit::rebuild_tag($token);
  452: 	}
  453:     }
  454:     return $result;
  455: }
  456: 
  457: sub end_ytics {
  458:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  459:     my $result = '';
  460:     if ($target eq 'web') {
  461:     } elsif ($target eq 'edit') {
  462: 	$result.=&Apache::edit::tag_end($target,$token);
  463:     }
  464:     return $result;
  465: }
  466: 
  467: 
  468: ##----------------------------------------------------------------- key
  469: sub start_key {
  470:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  471:     my $result='';
  472:     if ($target eq 'web') {
  473: 	&get_attributes(\%key,\%key_defaults,$parstack,$safeeval,
  474: 		    $tagstack->[-1]);
  475:     } elsif ($target eq 'edit') {
  476: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Key');
  477: 	$result .= &edit_attributes($target,$token,\%key_defaults);
  478:     } elsif ($target eq 'modified') {
  479: 	my $constructtag=&Apache::edit::get_new_args
  480: 	    ($token,$parstack,$safeeval,keys(%key_defaults));
  481: 	if ($constructtag) {
  482: 	    $result = &Apache::edit::rebuild_tag($token);
  483: 	}
  484:     }
  485:     return $result;
  486: }
  487: 
  488: sub end_key {
  489:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  490:     my $result = '';
  491:     if ($target eq 'web') {
  492:     } elsif ($target eq 'edit') {
  493: 	$result.=&Apache::edit::tag_end($target,$token);
  494:     }
  495:     return $result;
  496: }
  497: 
  498: ##------------------------------------------------------------------- title
  499: sub start_title {
  500:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  501:     my $result='';
  502:     if ($target eq 'web') {
  503: 	$title = &Apache::lonxml::get_all_text("/title",$$parser[-1]);
  504: 	if (length($title) > $max_str_len) {
  505: 	    $title = substr($title,0,$max_str_len);
  506: 	}
  507:     } elsif ($target eq 'edit') {
  508: 	$result.=&Apache::edit::tag_start($target,$token,'Plot Title');
  509: 	my $text=&Apache::lonxml::get_all_text("/title",$$parser[-1]);
  510: 	$result.=&Apache::edit::end_row().
  511: 	    &Apache::edit::start_spanning_row().
  512: 	    &Apache::edit::editfield('',$text,'',60,1);
  513:     } elsif ($target eq 'modified') {
  514: 	my $text=$$parser[-1]->get_text("/title");
  515: 	$result.=&Apache::edit::rebuild_tag($token);
  516: 	$result.=&Apache::edit::modifiedfield($token);
  517:     }
  518:     return $result;
  519: }
  520: 
  521: sub end_title {
  522:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  523:     my $result = '';
  524:     if ($target eq 'web') {
  525:     } elsif ($target eq 'edit') {
  526: 	$result.=&Apache::edit::tag_end($target,$token);
  527:     }
  528:     return $result;
  529: }
  530: ##------------------------------------------------------------------- xlabel
  531: sub start_xlabel {
  532:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  533:     my $result='';
  534:     if ($target eq 'web') {
  535: 	$xlabel = &Apache::lonxml::get_all_text("/xlabel",$$parser[-1]);
  536: 	if (length($xlabel) > $max_str_len) {
  537: 	    $xlabel = substr($xlabel,0,$max_str_len);
  538: 	}
  539:     } elsif ($target eq 'edit') {
  540: 	$result.=&Apache::edit::tag_start($target,$token,'Plot Xlabel');
  541: 	my $text=&Apache::lonxml::get_all_text("/xlabel",$$parser[-1]);
  542: 	$result.=&Apache::edit::end_row().
  543: 	    &Apache::edit::start_spanning_row().
  544: 	    &Apache::edit::editfield('',$text,'',60,1);
  545:     } elsif ($target eq 'modified') {
  546: 	my $text=$$parser[-1]->get_text("/xlabel");
  547: 	$result.=&Apache::edit::rebuild_tag($token);	
  548: 	$result.=&Apache::edit::modifiedfield($token);
  549:     }
  550:     return $result;
  551: }
  552: 
  553: sub end_xlabel {
  554:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  555:     my $result = '';
  556:     if ($target eq 'web') {
  557:     } elsif ($target eq 'edit') {
  558: 	$result.=&Apache::edit::tag_end($target,$token);
  559:     }
  560:     return $result;
  561: }
  562: 
  563: ##------------------------------------------------------------------- ylabel
  564: sub start_ylabel {
  565:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  566:     my $result='';
  567:     if ($target eq 'web') {
  568: 	$ylabel = &Apache::lonxml::get_all_text("/ylabel",$$parser[-1]);
  569: 	if (length($ylabel) > $max_str_len) {
  570: 	    $ylabel = substr($ylabel,0,$max_str_len);
  571: 	}
  572:     } elsif ($target eq 'edit') {
  573: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Ylabel');
  574: 	my $text = &Apache::lonxml::get_all_text("/ylabel",$$parser[-1]);
  575: 	$result .= &Apache::edit::end_row().
  576: 	    &Apache::edit::start_spanning_row().
  577: 	    &Apache::edit::editfield('',$text,'',60,1);
  578:     } elsif ($target eq 'modified') {
  579: 	my $text=$$parser[-1]->get_text("/ylabel");
  580: 	$result.=&Apache::edit::rebuild_tag($token);
  581: 	$result.=&Apache::edit::modifiedfield($token);
  582:     }
  583:     return $result;
  584: }
  585: 
  586: sub end_ylabel {
  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::tag_end($target,$token);
  592:     }
  593:     return $result;
  594: }
  595: 
  596: ##------------------------------------------------------------------- label
  597: sub start_label {
  598:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  599:     my $result='';
  600:     if ($target eq 'web') {
  601: 	my %label;
  602: 	&get_attributes(\%label,\%label_defaults,$parstack,$safeeval,
  603: 		    $tagstack->[-1]);
  604: 	my $text = &Apache::lonxml::get_all_text("/label",$$parser[-1]);
  605: 	$text = substr($text,0,$max_str_len) if (length($text) > $max_str_len);
  606: 	$label{'text'} = $text;
  607: 	push(@labels,\%label);
  608:     } elsif ($target eq 'edit') {
  609: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Label');
  610: 	$result .= &edit_attributes($target,$token,\%label_defaults);
  611: 	my $text = &Apache::lonxml::get_all_text("/label",$$parser[-1]);
  612: 	$result .= &Apache::edit::end_row().
  613: 	    &Apache::edit::start_spanning_row().
  614: 	    &Apache::edit::editfield('',$text,'',60,1);
  615:     } elsif ($target eq 'modified') {
  616: 	&Apache::edit::get_new_args
  617: 	    ($token,$parstack,$safeeval,keys(%label_defaults));
  618: 	$result.=&Apache::edit::rebuild_tag($token);
  619: 	my $text=$$parser[-1]->get_text("/label");
  620: 	$result.=&Apache::edit::modifiedfield($token);
  621:     }
  622:     return $result;
  623: }
  624: 
  625: sub end_label {
  626:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  627:     my $result = '';
  628:     if ($target eq 'web') {
  629:     } elsif ($target eq 'edit') {
  630: 	$result.=&Apache::edit::tag_end($target,$token);
  631:     }
  632:     return $result;
  633: }
  634: 
  635: ##------------------------------------------------------------------- curve
  636: sub start_curve {
  637:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  638:     my $result='';
  639:     &Apache::lonxml::register('Apache::lonplot',('function','data'));
  640:     push (@Apache::lonxml::namespace,'curve');
  641:     if ($target eq 'web') {
  642: 	my %curve;
  643: 	&get_attributes(\%curve,\%curve_defaults,$parstack,$safeeval,
  644: 		    $tagstack->[-1]);
  645: 	push (@curves,\%curve);
  646:     } elsif ($target eq 'edit') {
  647: 	$result .= &Apache::edit::tag_start($target,$token,'Curve');
  648: 	$result .= &edit_attributes($target,$token,\%curve_defaults);
  649:     } elsif ($target eq 'modified') {
  650: 	my $constructtag=&Apache::edit::get_new_args
  651: 	    ($token,$parstack,$safeeval,keys(%curve_defaults));
  652: 	if ($constructtag) {
  653: 	    $result = &Apache::edit::rebuild_tag($token);
  654: 	    $result.= &Apache::edit::handle_insert();
  655: 	}
  656:     }
  657:     return $result;
  658: }
  659: 
  660: sub end_curve {
  661:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  662:     my $result = '';
  663:     pop @Apache::lonxml::namespace;
  664:     &Apache::lonxml::deregister('Apache::lonplot',('function','data'));
  665:     if ($target eq 'web') {
  666:     } elsif ($target eq 'edit') {
  667: 	$result.=&Apache::edit::tag_end($target,$token);
  668:     }
  669:     return $result;
  670: }
  671: 
  672: ##------------------------------------------------------------ curve function
  673: sub start_function {
  674:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  675:     my $result='';
  676:     if ($target eq 'web') {
  677: 	if (exists($curves[-1]->{'data'})) {
  678: 	    &Apache::lonxml::warning('Use of <function> precludes use of <data>.  The <data> will be omitted in favor of the <function> declaration.');
  679: 	    delete $curves[-1]->{'data'} ;
  680: 	}
  681: 	$curves[-1]->{'function'} = 
  682: 	    &Apache::lonxml::get_all_text("/function",$$parser[-1]);
  683:     } elsif ($target eq 'edit') {
  684: 	$result .= &Apache::edit::tag_start($target,$token,'Gnuplot compatible curve function');
  685: 	my $text = &Apache::lonxml::get_all_text("/function",$$parser[-1]);
  686: 	$result .= &Apache::edit::end_row().
  687: 	    &Apache::edit::start_spanning_row().
  688: 	    &Apache::edit::editfield('',$text,'',60,1);
  689:     } elsif ($target eq 'modified') {
  690: 	$result.=&Apache::edit::rebuild_tag($token);
  691: 	my $text=$$parser[-1]->get_text("/function");
  692: 	$result.=&Apache::edit::modifiedfield($token);
  693:     }
  694:     return $result;
  695: }
  696: 
  697: sub end_function {
  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::end_table();
  703:     }
  704:     return $result;
  705: }
  706: 
  707: ##------------------------------------------------------------ curve  data
  708: sub start_data {
  709:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  710:     my $result='';
  711:     if ($target eq 'web') {
  712: 	if (exists($curves[-1]->{'function'})) {
  713: 	    &Apache::lonxml::warning('Use of <data> precludes use of .'.
  714: 	    '<function>.  The <function> will be omitted in favor of '.
  715:             'the <data> declaration.');
  716: 	    delete($curves[-1]->{'function'});
  717: 	}
  718: 	my $datatext = &Apache::lonxml::get_all_text("/data",$$parser[-1]);
  719: 	# Deal with cases where we're given an array...
  720: 	if ($datatext =~ /^\@/) {
  721: 	    $datatext = &Apache::run::run('return "'.$datatext.'"',
  722: 					  $safeeval,1);
  723: 	}
  724: 	$datatext =~ s/\s+/ /g;  
  725: 	# Need to do some error checking on the @data array - 
  726: 	# make sure it's all numbers and make sure each array 
  727: 	# is of the same length.
  728: 	my @data;
  729: 	if ($datatext =~ /,/) { # comma deliminated
  730: 	    @data = split /,/,$datatext;
  731: 	} else { # Assume it's space seperated.
  732: 	    @data = split / /,$datatext;
  733: 	}
  734: 	for (my $i=0;$i<=$#data;$i++) {
  735: 	    # Check that it's non-empty
  736: 	    if (! defined($data[$i])) {
  737: 		&Apache::lonxml::warning(
  738: 		    'undefined <data> value.  Replacing with '.
  739: 		    ' pi/e = 1.15572734979092');
  740: 		$data[$i] = 1.15572734979092;
  741: 	    }
  742: 	    # Check that it's a number
  743: 	    if (! &$real_test($data[$i]) & ! &$int_test($data[$i])) {
  744: 		&Apache::lonxml::warning(
  745: 		    'Bad <data> value of '.$data[$i].'  Replacing with '.
  746: 		    ' pi/e = 1.15572734979092');
  747: 		$data[$i] = 1.15572734979092;
  748: 	    }
  749: 	}
  750: 	# complain if the number of data points is not the same as
  751: 	# in previous sets of data.
  752: 	if (($curves[-1]->{'data'}) && ($#data != $#{@{$curves[-1]->{'data'}->[0]}})){
  753: 	    &Apache::lonxml::warning
  754: 		('Number of data points is not consistent with previous '.
  755: 		 'number of data points');
  756: 	}
  757: 	push  @{$curves[-1]->{'data'}},\@data;
  758:     } elsif ($target eq 'edit') {
  759: 	$result .= &Apache::edit::tag_start($target,$token,'Comma or space deliminated curve data');
  760: 	my $text = &Apache::lonxml::get_all_text("/data",$$parser[-1]);
  761: 	$result .= &Apache::edit::end_row().
  762: 	    &Apache::edit::start_spanning_row().
  763: 	    &Apache::edit::editfield('',$text,'',60,1);
  764:     } elsif ($target eq 'modified') {
  765: 	$result.=&Apache::edit::rebuild_tag($token);
  766: 	my $text=$$parser[-1]->get_text("/data");
  767: 	$result.=&Apache::edit::modifiedfield($token);
  768:     }
  769:     return $result;
  770: }
  771: 
  772: sub end_data {
  773:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  774:     my $result = '';
  775:     if ($target eq 'web') {
  776:     } elsif ($target eq 'edit') {
  777: 	$result .= &Apache::edit::end_table();
  778:     }
  779:     return $result;
  780: }
  781: 
  782: ##------------------------------------------------------------------- axis
  783: sub start_axis {
  784:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  785:     my $result='';
  786:     if ($target eq 'web') {
  787: 	&get_attributes(\%axis,\%axis_defaults,$parstack,$safeeval,
  788: 			$tagstack->[-1]);
  789:     } elsif ($target eq 'edit') {
  790: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Axes');
  791: 	$result .= &edit_attributes($target,$token,\%axis_defaults);
  792:     } elsif ($target eq 'modified') {
  793: 	my $constructtag=&Apache::edit::get_new_args
  794: 	    ($token,$parstack,$safeeval,keys(%axis_defaults));
  795: 	if ($constructtag) {
  796: 	    $result = &Apache::edit::rebuild_tag($token);
  797: 	}
  798:     }
  799:     return $result;
  800: }
  801: 
  802: sub end_axis {
  803:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  804:     my $result = '';
  805:     if ($target eq 'web') {
  806:     } elsif ($target eq 'edit') {
  807: 	$result.=&Apache::edit::tag_end($target,$token);
  808:     } elsif ($target eq 'modified') {
  809:     }
  810:     return $result;
  811: }
  812: 
  813: ###################################################################
  814: ##                                                               ##
  815: ##        Utility Functions                                      ##
  816: ##                                                               ##
  817: ###################################################################
  818: 
  819: ##----------------------------------------------------------- set_defaults
  820: sub set_defaults {
  821:     my ($var,$defaults) = @_;
  822:     my $key;
  823:     foreach $key (keys(%$defaults)) {
  824: 	$var->{$key} = $defaults->{$key}->{'default'};
  825:     }
  826: }
  827: 
  828: ##------------------------------------------------------------------- misc
  829: sub get_attributes{
  830:     my ($values,$defaults,$parstack,$safeeval,$tag) = @_;
  831:     foreach my $attr (keys(%{$defaults})) {
  832: 	$values->{$attr} = 
  833: 	    &Apache::lonxml::get_param($attr,$parstack,$safeeval);
  834: 	if ($values->{$attr} eq '' | !defined($values->{$attr})) {
  835: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
  836: 	    next;
  837: 	}
  838: 	my $test = $defaults->{$attr}->{'test'};
  839: 	if (! &$test($values->{$attr})) {
  840: 	    &Apache::lonxml::warning
  841: 		($tag.':'.$attr.': Bad value.'.'Replacing your value with : '
  842: 		 .$defaults->{$attr}->{'default'} );
  843: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
  844: 	}
  845:     }
  846:     return ;
  847: }
  848: 
  849: ##------------------------------------------------------- write_gnuplot_file
  850: sub write_gnuplot_file {
  851:     my ($tmpdir,$filename)= @_;
  852:     my $gnuplot_input = '';
  853:     my $curve;
  854:     # Collect all the colors
  855:     my @Colors;
  856:     push @Colors, $plot{'bgcolor'};
  857:     push @Colors, $plot{'fgcolor'}; 
  858:     push @Colors, (defined($axis{'color'})?$axis{'color'}:$plot{'fgcolor'});
  859:     foreach $curve (@curves) {
  860: 	push @Colors, ($curve->{'color'} ne '' ? 
  861: 		       $curve->{'color'}       : 
  862: 		       $plot{'fgcolor'}        );
  863:     }
  864:     # set term
  865:     $gnuplot_input .= 'set term gif ';
  866:     $gnuplot_input .= 'transparent ' if ($plot{'transparent'} eq 'on');
  867:     $gnuplot_input .= $plot{'font'} . ' ';
  868:     $gnuplot_input .= 'size '.$plot{'width'}.','.$plot{'height'}.' ';
  869:     $gnuplot_input .= "@Colors\n";
  870:     # set output
  871:     $gnuplot_input .= "set output\n";
  872:     # grid
  873:     $gnuplot_input .= 'set grid'.$/ if ($plot{'grid'} eq 'on');
  874:     # border
  875:     $gnuplot_input .= ($plot{'border'} eq 'on'?
  876: 		       'set border'.$/           :
  877: 		       'set noborder'.$/         );    # title, xlabel, ylabel
  878:     # titles
  879:     $gnuplot_input .= "set title  \"$title\"\n"  if (defined($title)) ;
  880:     $gnuplot_input .= "set xlabel \"$xlabel\"\n" if (defined($xlabel));
  881:     $gnuplot_input .= "set ylabel \"$ylabel\"\n" if (defined($ylabel));
  882:     # tics
  883:     if (%xtics) {    
  884: 	$gnuplot_input .= "set xtics $xtics{'location'} ";
  885: 	$gnuplot_input .= ( $xtics{'mirror'} eq 'on'?"mirror ":"nomirror ");
  886: 	$gnuplot_input .= "$xtics{'start'}, ";
  887: 	$gnuplot_input .= "$xtics{'increment'}, ";
  888: 	$gnuplot_input .= "$xtics{'end'}\n";
  889:     }
  890:     if (%ytics) {    
  891: 	$gnuplot_input .= "set ytics $ytics{'location'} ";
  892: 	$gnuplot_input .= ( $ytics{'mirror'} eq 'on'?"mirror ":"nomirror ");
  893: 	$gnuplot_input .= "$ytics{'start'}, ";
  894: 	$gnuplot_input .= "$ytics{'increment'}, ";
  895:         $gnuplot_input .= "$ytics{'end'}\n";
  896:     }
  897:     # axis
  898:     if (%axis) {
  899: 	$gnuplot_input .= "set xrange \[$axis{'xmin'}:$axis{'xmax'}\]\n";
  900: 	$gnuplot_input .= "set yrange \[$axis{'ymin'}:$axis{'ymax'}\]\n";
  901:     }
  902:     # Key
  903:     if (%key) {
  904: 	$gnuplot_input .= 'set key '.$key{'pos'}.' ';
  905: 	if ($key{'title'} ne '') {
  906: 	    $gnuplot_input .= 'title " '.$key{'title'}.'" ';
  907: 	} 
  908: 	$gnuplot_input .= ($key{'box'} eq 'on' ? 'box ' : 'nobox ').$/;
  909:     } else {
  910: 	$gnuplot_input .= 'set nokey'.$/;
  911:     }
  912:     # labels
  913:     my $label;
  914:     foreach $label (@labels) {
  915: 	$gnuplot_input .= 'set label "'.$label->{'text'}.'" at '.
  916: 	    $label->{'xpos'}.','.$label->{'ypos'}.' '.$label->{'justify'}.$/ ;
  917:     }
  918:     # curves
  919:     $gnuplot_input .= 'plot ';
  920:     for (my $i = 0;$i<=$#curves;$i++) {
  921: 	$curve = $curves[$i];
  922: 	$gnuplot_input.= ', ' if ($i > 0);
  923: 	if (exists($curve->{'function'})) {
  924: 	    $gnuplot_input.= 
  925: 		$curve->{'function'}.' title "'.
  926: 		$curve->{'name'}.'" with '.
  927: 		$curve->{'linestyle'};
  928: 	} elsif (exists($curve->{'data'})) {
  929: 	    # Store data values in $datatext
  930: 	    my $datatext = '';
  931: 	    #   get new filename
  932: 	    my $datafilename = "$tmpdir/$filename.$i";
  933: 	    my $fh=Apache::File->new(">$datafilename");
  934: 	    # Compile data
  935: 	    my @Data = @{$curve->{'data'}};
  936: 	    my @Data0 = @{$Data[0]};
  937: 	    for (my $i =0; $i<=$#Data0; $i++) {
  938: 		my $dataset;
  939: 		foreach $dataset (@Data) {
  940: 		    $datatext .= $dataset->[$i] . ' ';
  941: 		}
  942: 		$datatext .= $/;
  943: 	    }
  944: 	    #   write file
  945: 	    print $fh $datatext;
  946: 	    close ($fh);
  947: 	    #   generate gnuplot text
  948: 	    $gnuplot_input.= '"'.$datafilename.'" title "'.
  949: 		$curve->{'name'}.'" with '.
  950: 		$curve->{'linestyle'};
  951: 	}
  952:     }
  953:     # Write the output to a file.
  954:     my $fh=Apache::File->new(">$tmpdir$filename");
  955:     print $fh $gnuplot_input;
  956:     close($fh);
  957:     # That's all folks.
  958:     return ;
  959: }
  960: 
  961: #---------------------------------------------- check_inputs
  962: sub check_inputs {
  963:     ## Note: no inputs, no outputs - this acts only on global variables.
  964:     ## Make sure we have all the input we need:
  965:     if (! %plot) { &set_defaults(\%plot,\%plot_defaults); }
  966:     if (! %key ) {} # No key for this plot, thats okay
  967: #    if (! %axis) { &set_defaults(\%axis,\%axis_defaults); }
  968:     if (! defined($title )) {} # No title for this plot, thats okay
  969:     if (! defined($xlabel)) {} # No xlabel for this plot, thats okay
  970:     if (! defined($ylabel)) {} # No ylabel for this plot, thats okay
  971:     if ($#labels < 0) { }      # No labels for this plot, thats okay
  972:     if ($#curves < 0) { 
  973: 	&Apache::lonxml::warning("No curves specified for plot!!!!");
  974: 	return '';
  975:     }
  976:     my $curve;
  977:     foreach $curve (@curves) {
  978: 	if (!defined($curve->{'function'})&&!defined($curve->{'data'})){
  979: 	    &Apache::lonxml::warning("One of the curves specified did not contain any <data> or <function> declarations\n");
  980: 	    return '';
  981: 	}
  982:     }
  983: }
  984: 
  985: #------------------------------------------------ make_edit
  986: sub edit_attributes {
  987:     my ($target,$token,$defaults,$keys) = @_;
  988:     my ($result,@keys);
  989:     if ($keys && ref($keys) eq 'ARRAY') {
  990:         @keys = @$keys;
  991:     } else {
  992: 	@keys = sort(keys(%$defaults));
  993:     }
  994:     foreach my $attr (@keys) {
  995: 	# append a ' ' to the description if it doesn't have one already.
  996: 	my $description = $defaults->{$attr}->{'description'};
  997: 	$description .= ' ' if ($description !~ / $/);
  998: 	if ($defaults->{$attr}->{'edit_type'} eq 'entry') {
  999: 	    $result .= &Apache::edit::text_arg
 1000: 		($description,$attr,$token,
 1001: 		 $defaults->{$attr}->{'size'});
 1002: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'choice') {
 1003: 	    $result .= &Apache::edit::select_arg
 1004: 		($description,$attr,$defaults->{$attr}->{'choices'},$token);
 1005: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'onoff') {
 1006: 	    $result .= &Apache::edit::select_arg
 1007: 		($description,$attr,['on','off'],$token);
 1008: 	}
 1009: 	$result .= '<br />';
 1010:     }
 1011:     return $result;
 1012: }
 1013: 
 1014: 
 1015: ###################################################################
 1016: ##                                                               ##
 1017: ##           Insertion functions for editing plots               ##
 1018: ##                                                               ##
 1019: ###################################################################
 1020: 
 1021: #------------------------------------------------ insert_xxxxxxx
 1022: sub insert_plot {
 1023:     my $result = '';
 1024:     #  plot attributes
 1025:     $result .= "<plot \n";
 1026:     foreach my $attr (keys(%plot_defaults)) {
 1027: 	$result .= "     $attr=\"$plot_defaults{$attr}->{'default'}\"\n";
 1028:     }
 1029:     $result .= ">\n";
 1030:     # Add the components
 1031:     # $result .= &insert_key();
 1032:     # $result .= &insert_axis();
 1033:     # $result .= &insert_title();    
 1034:     # $result .= &insert_xlabel();    
 1035:     # $result .= &insert_ylabel();    
 1036:     $result .= &insert_curve();
 1037:     # close up the <plot>
 1038:     $result .= "</plot>\n";
 1039:     return $result;
 1040: }
 1041: 
 1042: sub insert_tics {
 1043:     my $result;
 1044:     $result .= &insert_xtics() . &insert_ytics;
 1045:     return $result;
 1046: }
 1047: 
 1048: sub insert_xtics {
 1049:     my $result;
 1050:     $result .= "\n    <xtics ";
 1051:     foreach my $attr (keys(%tic_defaults)) {
 1052: 	$result .= "$attr=\"$tic_defaults{$attr}->{'default'}\" ";
 1053:     }
 1054:     $result .= "/>\n";
 1055:     return $result;
 1056: }
 1057: 
 1058: sub insert_ytics {
 1059:     my $result;
 1060:     $result .= "\n    <ytics ";
 1061:     foreach my $attr (keys(%tic_defaults)) {
 1062: 	$result .= "$attr=\"$tic_defaults{$attr}->{'default'}\" ";
 1063:     }
 1064:     $result .= "/>\n";
 1065:     return $result;
 1066: }
 1067: 
 1068: sub insert_key {
 1069:     my $result;
 1070:     $result .= "\n    <key \n";
 1071:     foreach my $attr (keys(%key_defaults)) {
 1072: 	$result .= "         $attr=\"$key_defaults{$attr}->{'default'}\"\n";
 1073:     }
 1074:     $result .= "   />\n";
 1075:     return $result;
 1076: }
 1077: 
 1078: sub insert_axis{
 1079:     my $result;
 1080:     $result .= "\n    <axis ";
 1081:    foreach my $attr (keys(%axis_defaults)) {
 1082: 	$result .= "         $attr=\"$axis_defaults{$attr}->{'default'}\"\n";
 1083:     }
 1084:     $result .= "   />\n";
 1085:     return $result;
 1086: }
 1087: 
 1088: sub insert_title { return "\n    <title></title>\n"; }
 1089: sub insert_xlabel { return "\n    <xlabel></xlabel>\n"; }
 1090: sub insert_ylabel { return "\n    <ylabel></ylabel>\n"; }
 1091: 
 1092: sub insert_label {
 1093:     my $result;
 1094:     $result .= "\n    <label ";
 1095:     foreach my $attr (keys(%label_defaults)) {
 1096: 	$result .= '         '.$attr.'="'.
 1097: 	    $label_defaults{$attr}->{'default'}."\"\n";
 1098:     }
 1099:     $result .= "   ></label>\n";
 1100:     return $result;
 1101: }
 1102: 
 1103: sub insert_curve {
 1104:     my $result;
 1105:     $result .= "\n    <curve ";
 1106:     foreach my $attr (keys(%curve_defaults)) {
 1107: 	$result .= '         '.$attr.'="'.
 1108: 	    $curve_defaults{$attr}->{'default'}."\"\n";
 1109:     }
 1110:     $result .= "    >\n";
 1111:     $result .= &insert_data().&insert_data()."</curve>\n";
 1112: }
 1113: 
 1114: sub insert_function {
 1115:     my $result;
 1116:     $result .= "<function></function>\n";
 1117:     return $result;
 1118: }
 1119: 
 1120: sub insert_data {
 1121:     my $result;
 1122:     $result .= "     <data></data>\n";
 1123:     return $result;
 1124: }
 1125: 
 1126: ##----------------------------------------------------------------------
 1127: 1;
 1128: __END__
 1129: 
 1130: 

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