File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.105: download - view: text, annotated - select for diffs
Thu Feb 24 22:01:40 2005 UTC (19 years, 2 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Added "plotcolor" attribute on the <gnuplot> tag.  Choices are "monochrome",
"color", and "colour".  Defaults to "monochrome".

    1: # The LearningOnline Network with CAPA
    2: # Dynamic plot
    3: #
    4: # $Id: lonplot.pm,v 1.105 2005/02/24 22:01:40 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: 
   29: package Apache::lonplot;
   30: 
   31: use strict;
   32: use warnings FATAL=>'all';
   33: no warnings 'uninitialized';
   34: use Apache::File;
   35: use Apache::response;
   36: use Apache::lonxml;
   37: use Apache::edit;
   38: 
   39: use vars qw/$weboutputformat $versionstring/;
   40: 
   41: BEGIN {
   42:     &Apache::lonxml::register('Apache::lonplot',('gnuplot'));
   43:     #
   44:     # Determine the version of GNUPLOT
   45:     $weboutputformat = 'gif';
   46:     $versionstring = `gnuplot --version 2>/dev/null`;
   47:     if ($versionstring =~ /^gnuplot 4/) {
   48:         $weboutputformat = 'png';
   49:     }
   50: }
   51: 
   52: ## 
   53: ## Description of data structures:
   54: ##
   55: ##  %plot       %key    %axis
   56: ## --------------------------
   57: ##  height      title   color
   58: ##  width       box     xmin
   59: ##  bgcolor     pos     xmax
   60: ##  fgcolor             ymin
   61: ##  transparent         ymax
   62: ##  grid
   63: ##  border
   64: ##  font
   65: ##  align
   66: ##
   67: ##  @labels: $labels[$i] = \%label
   68: ##           %label: text, xpos, ypos, justify
   69: ##
   70: ##  @curves: $curves[$i] = \%curve
   71: ##           %curve: name, linestyle, ( function | data )
   72: ##
   73: ##  $curves[$i]->{'data'} = [ [x1,x2,x3,x4],
   74: ##                            [y1,y2,y3,y4] ]
   75: ##
   76: 
   77: ###################################################################
   78: ##                                                               ##
   79: ##        Tests used in checking the validitity of input         ##
   80: ##                                                               ##
   81: ###################################################################
   82: 
   83: my $max_str_len = 50;    # if a label, title, xlabel, or ylabel text
   84:                          # is longer than this, it will be truncated.
   85: 
   86: my %linestyles = 
   87:     (
   88:      lines          => 2,     # Maybe this will be used in the future
   89:      linespoints    => 2,     # to check on whether or not they have 
   90:      dots	    => 2,     # supplied enough <data></data> fields
   91:      points         => 2,     # to use the given line style.  But for
   92:      steps	    => 2,     # now there are more important things 
   93:      fsteps	    => 2,     # for me to deal with.
   94:      histeps        => 2,
   95:      errorbars	    => 3,
   96:      xerrorbars	    => [3,4],
   97:      yerrorbars	    => [3,4],
   98:      xyerrorbars    => [4,6],
   99:      boxes          => 3,
  100:      vector	    => 4
  101:     );		    
  102: 
  103: my $int_test       = sub {$_[0]=~s/\s+//g;$_[0]=~/^\d+$/};
  104: my $real_test      = 
  105:     sub {$_[0]=~s/\s+//g;$_[0]=~/^[+-]?\d*\.?\d*([eE][+-]\d+)?$/};
  106: my $pos_real_test  =
  107:     sub {$_[0]=~s/\s+//g;$_[0]=~/^[+]?\d*\.?\d*([eE][+-]\d+)?$/};
  108: my $color_test     = sub {$_[0]=~s/\s+//g;$_[0]=~/^x[\da-fA-F]{6}$/};
  109: my $onoff_test     = sub {$_[0]=~/^(on|off)$/};
  110: my $key_pos_test   = sub {$_[0]=~/^(top|bottom|right|left|outside|below| )+$/};
  111: my $sml_test       = sub {$_[0]=~/^(small|medium|large)$/};
  112: my $linestyle_test = sub {exists($linestyles{$_[0]})};
  113: my $words_test     = sub {$_[0]=~s/\s+/ /g;$_[0]=~/^([\w~!\@\#\$\%^&\*\(\)-=_\+\[\]\{\}:\;\'<>,\.\/\?\\]+ ?)+$/};
  114: 
  115: ###################################################################
  116: ##                                                               ##
  117: ##                      Attribute metadata                       ##
  118: ##                                                               ##
  119: ###################################################################
  120: my @gnuplot_edit_order = 
  121:     qw/alttag bgcolor fgcolor height width font transparent grid samples 
  122:     border align texwidth texfont plotcolor plottype lmargin rmargin tmargin
  123:     bmargin major_ticscale minor_ticscale/;
  124: 
  125: my $margin_choices = ['default',0..20];
  126: 
  127: my %gnuplot_defaults = 
  128:     (
  129:      alttag       => {
  130: 	 default     => 'dynamically generated plot',
  131: 	 test        => $words_test,
  132: 	 description => 'brief description of the plot',
  133:       	 edit_type   => 'entry',
  134: 	 size        => '40'
  135: 	 },
  136:      height       => {
  137: 	 default     => 300,
  138: 	 test        => $int_test,
  139: 	 description => 'height of image (pixels)',
  140:       	 edit_type   => 'entry',
  141: 	 size        => '10'
  142: 	 },
  143:      width        => {
  144: 	 default     => 400,
  145: 	 test        => $int_test,
  146: 	 description => 'width of image (pixels)',
  147: 	 edit_type   => 'entry',
  148: 	 size        => '10'
  149: 	 },
  150:      bgcolor      => {
  151: 	 default     => 'xffffff',
  152: 	 test        => $color_test, 
  153: 	 description => 'background color of image (xffffff)',
  154: 	 edit_type   => 'entry',
  155: 	 size        => '10'
  156: 	 },
  157:      fgcolor      => {
  158: 	 default     => 'x000000',
  159: 	 test        => $color_test,
  160: 	 description => 'foreground color of image (x000000)',
  161: 	 edit_type   => 'entry',
  162: 	 size        => '10'
  163: 	 },
  164:      transparent  => {
  165: 	 default     => 'off',
  166: 	 test        => $onoff_test, 
  167: 	 description => 'Transparent image',
  168: 	 edit_type   => 'onoff'
  169: 	 },
  170:      grid         => {
  171: 	 default     => 'on',
  172: 	 test        => $onoff_test, 
  173: 	 description => 'Display grid',
  174: 	 edit_type   => 'onoff'
  175: 	 },
  176:      border       => {
  177: 	 default     => 'on',
  178: 	 test        => $onoff_test, 
  179: 	 description => 'Draw border around plot',
  180: 	 edit_type   => 'onoff'
  181: 	 },
  182:      font         => {
  183: 	 default     => 'medium',
  184: 	 test        => $sml_test,
  185: 	 description => 'Size of font to use',
  186: 	 edit_type   => 'choice',
  187: 	 choices     => ['small','medium','large']
  188: 	 },
  189:      samples         => {
  190: 	 default     => '100',
  191: 	 test        => $int_test,
  192: 	 description => 'Number of samples for non-data plots',
  193: 	 edit_type   => 'choice',
  194: 	 choices     => ['100','200','500','1000','2000','5000']
  195: 	 },
  196:      align        => {
  197: 	 default     => 'center',
  198: 	 test        => sub {$_[0]=~/^(left|right|center)$/},
  199: 	 description => 'alignment for image in html',
  200: 	 edit_type   => 'choice',
  201: 	 choices     => ['left','right','center']
  202: 	 },
  203:      texwidth     => {
  204:          default     => '93',
  205:          test        => $int_test,
  206:          description => 'Width of plot when printed (mm)',
  207:          edit_type   => 'entry',
  208:          size        => '5'
  209:          },
  210:      texfont     => {
  211:          default     => '22',
  212:          test        => $int_test,
  213:          description => 'Font size to use in TeX output (pts):',
  214:          edit_type   => 'choice',
  215:          choices     => [qw/8 10 12 14 16 18 20 22 24 26 28 30 32 34 36/],
  216:          },
  217:      plotcolor   => {
  218:          default     => 'monochrome',
  219:          test        => sub {$_[0]=~/^(monochrome|color|colour)$/},
  220:          description => 'Color setting for printing:',
  221:          edit_type   => 'choice',
  222:          choices     => [qw/monochrome color colour/],
  223:          },
  224:      plottype  => {
  225: 	 default     => 'Cartesian',
  226: 	 test        => sub {$_[0]=~/^(Polar|Cartesian)$/},
  227: 	 description => 'Plot type:',
  228: 	 edit_type   => 'choice',
  229:          choices     => ['Cartesian','Polar']
  230:          },
  231:      lmargin   => {
  232: 	 default     => 'default',
  233: 	 test        => sub {$_[0]=~/^(default|\d+)$/},
  234: 	 description => 'Left margin width (pts):',
  235: 	 edit_type   => 'choice',
  236:          choices     => $margin_choices,
  237:          },
  238:      rmargin   => {
  239: 	 default     => 'default',
  240: 	 test        => sub {$_[0]=~/^(default|\d+)$/},
  241: 	 description => 'Right margin width (pts):',
  242: 	 edit_type   => 'choice',
  243:          choices     => $margin_choices,
  244:          },
  245:      tmargin   => {
  246: 	 default     => 'default',
  247: 	 test        => sub {$_[0]=~/^(default|\d+)$/},
  248: 	 description => 'Top margin width (pts):',
  249: 	 edit_type   => 'choice',
  250:          choices     => $margin_choices,
  251:          },
  252:      bmargin   => {
  253: 	 default     => 'default',
  254: 	 test        => sub {$_[0]=~/^(default|\d+)$/},
  255: 	 description => 'Bottom margin width (pts):',
  256: 	 edit_type   => 'choice',
  257:          choices     => $margin_choices,
  258:          },
  259:      major_ticscale  => {
  260:          default     => '1',
  261:          test        => $real_test,
  262:          description => 'Size of major tic marks (plot coordinates)',
  263:          edit_type   => 'entry',
  264:          size        => '5'
  265:          },
  266:      minor_ticscale  => {
  267:          default     => '0.5',
  268:          test        => $real_test,
  269:          description => 'Size of minor tic mark (plot coordinates)',
  270:          edit_type   => 'entry',
  271:          size        => '5'
  272:          },
  273:      );
  274: 
  275: my %key_defaults = 
  276:     (
  277:      title => { 
  278: 	 default => '',
  279: 	 test => $words_test,
  280: 	 description => 'Title of key',
  281: 	 edit_type   => 'entry',
  282: 	 size        => '40'
  283: 	 },
  284:      box   => { 
  285: 	 default => 'off',
  286: 	 test => $onoff_test,
  287: 	 description => 'Draw a box around the key?',
  288: 	 edit_type   => 'onoff'
  289: 	 },
  290:      pos   => { 
  291: 	 default => 'top right', 
  292: 	 test => $key_pos_test, 
  293: 	 description => 'position of the key on the plot',
  294: 	 edit_type   => 'choice',
  295: 	 choices     => ['top left','top right','bottom left','bottom right',
  296: 			 'outside','below']
  297: 	 }
  298:      );
  299: 
  300: my %label_defaults = 
  301:     (
  302:      xpos    => {
  303: 	 default => 0,
  304: 	 test => $real_test,
  305: 	 description => 'x position of label (graph coordinates)',
  306: 	 edit_type   => 'entry',
  307: 	 size        => '10'
  308: 	 },
  309:      ypos    => {
  310: 	 default => 0, 
  311: 	 test => $real_test,
  312: 	 description => 'y position of label (graph coordinates)',
  313: 	 edit_type   => 'entry',
  314: 	 size        => '10'
  315: 	 },
  316:      justify => {
  317: 	 default => 'left',    
  318: 	 test => sub {$_[0]=~/^(left|right|center)$/},
  319: 	 description => 'justification of the label text on the plot',
  320: 	 edit_type   => 'choice',
  321: 	 choices     => ['left','right','center']
  322:      }
  323:      );
  324: 
  325: my @tic_edit_order = ('location','mirror','start','increment','end',
  326:                       'minorfreq');
  327: my %tic_defaults =
  328:     (
  329:      location => {
  330: 	 default => 'border', 
  331: 	 test => sub {$_[0]=~/^(border|axis)$/},
  332: 	 description => 'Location of major tic marks',
  333: 	 edit_type   => 'choice',
  334: 	 choices     => ['border','axis']
  335: 	 },
  336:      mirror => {
  337: 	 default => 'on', 
  338: 	 test => $onoff_test,
  339: 	 description => 'mirror tics on opposite axis?',
  340: 	 edit_type   => 'onoff'
  341: 	 },
  342:      start => {
  343: 	 default => '-10.0',
  344: 	 test => $real_test,
  345: 	 description => 'Start major tics at',
  346: 	 edit_type   => 'entry',
  347: 	 size        => '10'
  348: 	 },
  349:      increment => {
  350: 	 default => '1.0',
  351: 	 test => $real_test,
  352: 	 description => 'Place a major tic every',
  353: 	 edit_type   => 'entry',
  354: 	 size        => '10'
  355: 	 },
  356:      end => {
  357: 	 default => ' 10.0',
  358: 	 test => $real_test,
  359: 	 description => 'Stop major tics at ',
  360: 	 edit_type   => 'entry',
  361: 	 size        => '10'
  362: 	 },
  363:      minorfreq => {
  364: 	 default => '0',
  365: 	 test => $int_test,
  366: 	 description => 'Number of minor tics per major tic mark',
  367: 	 edit_type   => 'entry',
  368: 	 size        => '10'
  369: 	 },         
  370:      );
  371: 
  372: my @axis_edit_order = ('color','xmin','xmax','ymin','ymax');
  373: my %axis_defaults = 
  374:     (
  375:      color   => {
  376: 	 default => 'x000000', 
  377: 	 test => $color_test,
  378: 	 description => 'color of grid lines (x000000)',
  379: 	 edit_type   => 'entry',
  380: 	 size        => '10'
  381: 	 },
  382:      xmin      => {
  383: 	 default => '-10.0',
  384: 	 test => $real_test,
  385: 	 description => 'minimum x-value shown in plot',
  386: 	 edit_type   => 'entry',
  387: 	 size        => '10'
  388: 	 },
  389:      xmax      => {
  390: 	 default => ' 10.0',
  391: 	 test => $real_test,
  392: 	 description => 'maximum x-value shown in plot',	 
  393: 	 edit_type   => 'entry',
  394: 	 size        => '10'
  395: 	 },
  396:      ymin      => {
  397: 	 default => '-10.0',
  398: 	 test => $real_test,
  399: 	 description => 'minimum y-value shown in plot',	 
  400: 	 edit_type   => 'entry',
  401: 	 size        => '10'
  402: 	 },
  403:      ymax      => {
  404: 	 default => ' 10.0',
  405: 	 test => $real_test,
  406: 	 description => 'maximum y-value shown in plot',	 
  407: 	 edit_type   => 'entry',
  408: 	 size        => '10'
  409: 	 }
  410:      );
  411: 
  412: my @curve_edit_order = ('color','name','linestyle','pointtype','pointsize');
  413: 
  414: my %curve_defaults = 
  415:     (
  416:      color     => {
  417: 	 default => 'x000000',
  418: 	 test => $color_test,
  419: 	 description => 'color of curve (x000000)',
  420: 	 edit_type   => 'entry',
  421: 	 size        => '10'
  422: 	 },
  423:      name      => {
  424: 	 default => '',
  425: 	 test => $words_test,
  426: 	 description => 'name of curve to appear in key',
  427: 	 edit_type   => 'entry',
  428: 	 size        => '20'
  429: 	 },
  430:      linestyle => {
  431: 	 default => 'lines',
  432: 	 test => $linestyle_test,
  433: 	 description => 'Line style',
  434: 	 edit_type   => 'choice',
  435: 	 choices     => [keys(%linestyles)]
  436: 	 },
  437: # gnuplots term=gif driver does not handle linewidth :(
  438: #     linewidth => {
  439: #         default     => 1,
  440: #         test        => $int_test,
  441: #         description => 'Line width (may not apply to all line styles)',
  442: #         edit_type   => 'choice',
  443: #         choices     => [1,2,3,4,5,6,7,8,9,10]
  444: #         },
  445:      pointsize => {
  446:          default     => 1,
  447:          test        => $pos_real_test,
  448:          description => 'point size (may not apply to all line styles)',
  449:          edit_type   => 'entry',
  450:          size        => '5'
  451:          },
  452:      pointtype => {
  453:          default     => 1,
  454:          test        => $int_test,
  455:          description => 'point type (may not apply to all line styles)',
  456:          edit_type   => 'choice',
  457:          choices     => [0,1,2,3,4,5,6]
  458:          }
  459:      );
  460: 
  461: ###################################################################
  462: ##                                                               ##
  463: ##                    parsing and edit rendering                 ##
  464: ##                                                               ##
  465: ###################################################################
  466: my (%plot,%key,%axis,$title,$xlabel,$ylabel,@labels,@curves,%xtics,%ytics);
  467: 
  468: sub start_gnuplot {
  469:     undef(%plot);   undef(%key);    undef(%axis);
  470:     undef($title);  undef($xlabel); undef($ylabel);
  471:     undef(@labels); undef(@curves);
  472:     undef(%xtics);  undef(%ytics);
  473:     #
  474:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  475:     my $result='';
  476:     &Apache::lonxml::register('Apache::lonplot',
  477: 	     ('title','xlabel','ylabel','key','axis','label','curve',
  478: 	      'xtics','ytics'));
  479:     push (@Apache::lonxml::namespace,'lonplot');
  480:     if ($target eq 'web' || $target eq 'tex') {
  481: 	&get_attributes(\%plot,\%gnuplot_defaults,$parstack,$safeeval,
  482: 			$tagstack->[-1]);
  483:     } elsif ($target eq 'edit') {
  484: 	$result .= &Apache::edit::tag_start($target,$token,'GnuPlot');
  485: 	$result .= &edit_attributes($target,$token,\%gnuplot_defaults,
  486: 				    \@gnuplot_edit_order);
  487:     } elsif ($target eq 'modified') {
  488: 	my $constructtag=&Apache::edit::get_new_args
  489: 	    ($token,$parstack,$safeeval,keys(%gnuplot_defaults));
  490: 	if ($constructtag) {
  491: 	    $result = &Apache::edit::rebuild_tag($token);
  492: 	}
  493:     }
  494:     return $result;
  495: }
  496: 
  497: sub end_gnuplot {
  498:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  499:     pop @Apache::lonxml::namespace;
  500:     &Apache::lonxml::deregister('Apache::lonplot',
  501: 	('title','xlabel','ylabel','key','axis','label','curve'));
  502:     my $result = '';
  503:     my $randnumber;
  504:     # need to call rand everytime start_script would evaluate, as the
  505:     # safe space rand number generator and the global rand generator 
  506:     # are not separate
  507:     if ($target eq 'web' || $target eq 'tex' || $target eq 'grade' ||
  508: 	$target eq 'answer') {
  509:       $randnumber=int(rand(1000));
  510:     }
  511:     if ($target eq 'web' || $target eq 'tex') {
  512: 	&check_inputs(); # Make sure we have all the data we need
  513: 	##
  514: 	## Determine filename
  515: 	my $tmpdir = '/home/httpd/perl/tmp/';
  516: 	my $filename = $ENV{'user.name'}.'_'.$ENV{'user.domain'}.
  517: 	    '_'.time.'_'.$$.$randnumber.'_plot';
  518: 	## Write the plot description to the file
  519: 	&write_gnuplot_file($tmpdir,$filename,$target);
  520: 	$filename = &Apache::lonnet::escape($filename);
  521: 	## return image tag for the plot
  522: 	if ($target eq 'web') {
  523: 	    $result .= <<"ENDIMAGE";
  524: <img src    = "/cgi-bin/plot.gif?file=$filename.data&output=$weboutputformat" 
  525:      width  = "$plot{'width'}"
  526:      height = "$plot{'height'}"
  527:      align  = "$plot{'align'}"
  528:      alt    = "$plot{'alttag'}" />
  529: ENDIMAGE
  530:         } elsif ($target eq 'tex') {
  531: 	    #might be inside the safe space, register the URL for later
  532: 	    &Apache::lonxml::register_ssi("/cgi-bin/plot.gif?file=$filename.data&output=eps");
  533: 	    $result = '\graphicspath{{/home/httpd/perl/tmp/}}\includegraphics[width='.$plot{'texwidth'}.' mm]{'.&Apache::lonnet::unescape($filename).'.eps}';
  534: 	}
  535:     } elsif ($target eq 'edit') {
  536: 	$result.=&Apache::edit::tag_end($target,$token);
  537:     }
  538:     return $result;
  539: }
  540: 
  541: 
  542: ##--------------------------------------------------------------- xtics
  543: sub start_xtics {
  544:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  545:     my $result='';
  546:     if ($target eq 'web' || $target eq 'tex') {
  547: 	&get_attributes(\%xtics,\%tic_defaults,$parstack,$safeeval,
  548: 		    $tagstack->[-1]);
  549:     } elsif ($target eq 'edit') {
  550: 	$result .= &Apache::edit::tag_start($target,$token,'xtics');
  551: 	$result .= &edit_attributes($target,$token,\%tic_defaults,
  552: 				    \@tic_edit_order);
  553:     } elsif ($target eq 'modified') {
  554: 	my $constructtag=&Apache::edit::get_new_args
  555: 	    ($token,$parstack,$safeeval,keys(%tic_defaults));
  556: 	if ($constructtag) {
  557: 	    $result = &Apache::edit::rebuild_tag($token);
  558: 	}
  559:     }
  560:     return $result;
  561: }
  562: 
  563: sub end_xtics {
  564:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  565:     my $result = '';
  566:     if ($target eq 'web' || $target eq 'tex') {
  567:     } elsif ($target eq 'edit') {
  568: 	$result.=&Apache::edit::tag_end($target,$token);
  569:     }
  570:     return $result;
  571: }
  572: 
  573: ##--------------------------------------------------------------- ytics
  574: sub start_ytics {
  575:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  576:     my $result='';
  577:     if ($target eq 'web' || $target eq 'tex') {
  578: 	&get_attributes(\%ytics,\%tic_defaults,$parstack,$safeeval,
  579: 		    $tagstack->[-1]);
  580:     } elsif ($target eq 'edit') {
  581: 	$result .= &Apache::edit::tag_start($target,$token,'ytics');
  582: 	$result .= &edit_attributes($target,$token,\%tic_defaults,
  583: 				    \@tic_edit_order);
  584:     } elsif ($target eq 'modified') {
  585: 	my $constructtag=&Apache::edit::get_new_args
  586: 	    ($token,$parstack,$safeeval,keys(%tic_defaults));
  587: 	if ($constructtag) {
  588: 	    $result = &Apache::edit::rebuild_tag($token);
  589: 	}
  590:     }
  591:     return $result;
  592: }
  593: 
  594: sub end_ytics {
  595:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  596:     my $result = '';
  597:     if ($target eq 'web' || $target eq 'tex') {
  598:     } elsif ($target eq 'edit') {
  599: 	$result.=&Apache::edit::tag_end($target,$token);
  600:     }
  601:     return $result;
  602: }
  603: 
  604: 
  605: ##----------------------------------------------------------------- key
  606: sub start_key {
  607:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  608:     my $result='';
  609:     if ($target eq 'web' || $target eq 'tex') {
  610: 	&get_attributes(\%key,\%key_defaults,$parstack,$safeeval,
  611: 		    $tagstack->[-1]);
  612:     } elsif ($target eq 'edit') {
  613: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Key');
  614: 	$result .= &edit_attributes($target,$token,\%key_defaults);
  615:     } elsif ($target eq 'modified') {
  616: 	my $constructtag=&Apache::edit::get_new_args
  617: 	    ($token,$parstack,$safeeval,keys(%key_defaults));
  618: 	if ($constructtag) {
  619: 	    $result = &Apache::edit::rebuild_tag($token);
  620: 	}
  621:     }
  622:     return $result;
  623: }
  624: 
  625: sub end_key {
  626:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  627:     my $result = '';
  628:     if ($target eq 'web' || $target eq 'tex') {
  629:     } elsif ($target eq 'edit') {
  630: 	$result.=&Apache::edit::tag_end($target,$token);
  631:     }
  632:     return $result;
  633: }
  634: 
  635: ##------------------------------------------------------------------- title
  636: sub start_title {
  637:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  638:     my $result='';
  639:     if ($target eq 'web' || $target eq 'tex') {
  640: 	$title = &Apache::lonxml::get_all_text("/title",$parser);
  641: 	$title=&Apache::run::evaluate($title,$safeeval,$$parstack[-1]);
  642: 	$title =~ s/\n/ /g;
  643: 	if (length($title) > $max_str_len) {
  644: 	    $title = substr($title,0,$max_str_len);
  645: 	}
  646:     } elsif ($target eq 'edit') {
  647: 	$result.=&Apache::edit::tag_start($target,$token,'Plot Title');
  648: 	my $text=&Apache::lonxml::get_all_text("/title",$parser);
  649: 	$result.=&Apache::edit::end_row().
  650: 	    &Apache::edit::start_spanning_row().
  651: 	    &Apache::edit::editline('',$text,'',60);
  652:     } elsif ($target eq 'modified') {
  653: 	$result.=&Apache::edit::rebuild_tag($token);
  654: 	$result.=&Apache::edit::modifiedfield("/title",$parser);
  655:     }
  656:     return $result;
  657: }
  658: 
  659: sub end_title {
  660:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  661:     my $result = '';
  662:     if ($target eq 'web' || $target eq 'tex') {
  663:     } elsif ($target eq 'edit') {
  664: 	$result.=&Apache::edit::tag_end($target,$token);
  665:     }
  666:     return $result;
  667: }
  668: ##------------------------------------------------------------------- xlabel
  669: sub start_xlabel {
  670:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  671:     my $result='';
  672:     if ($target eq 'web' || $target eq 'tex') {
  673: 	$xlabel = &Apache::lonxml::get_all_text("/xlabel",$parser);
  674: 	$xlabel=&Apache::run::evaluate($xlabel,$safeeval,$$parstack[-1]);
  675: 	$xlabel =~ s/\n/ /g;
  676: 	if (length($xlabel) > $max_str_len) {
  677: 	    $xlabel = substr($xlabel,0,$max_str_len);
  678: 	}
  679:     } elsif ($target eq 'edit') {
  680: 	$result.=&Apache::edit::tag_start($target,$token,'Plot Xlabel');
  681: 	my $text=&Apache::lonxml::get_all_text("/xlabel",$parser);
  682: 	$result.=&Apache::edit::end_row().
  683: 	    &Apache::edit::start_spanning_row().
  684: 	    &Apache::edit::editline('',$text,'',60);
  685:     } elsif ($target eq 'modified') {
  686: 	$result.=&Apache::edit::rebuild_tag($token);	
  687: 	$result.=&Apache::edit::modifiedfield("/xlabel",$parser);
  688:     }
  689:     return $result;
  690: }
  691: 
  692: sub end_xlabel {
  693:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  694:     my $result = '';
  695:     if ($target eq 'web' || $target eq 'tex') {
  696:     } elsif ($target eq 'edit') {
  697: 	$result.=&Apache::edit::tag_end($target,$token);
  698:     }
  699:     return $result;
  700: }
  701: 
  702: ##------------------------------------------------------------------- ylabel
  703: sub start_ylabel {
  704:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  705:     my $result='';
  706:     if ($target eq 'web' || $target eq 'tex') {
  707: 	$ylabel = &Apache::lonxml::get_all_text("/ylabel",$parser);
  708: 	$ylabel = &Apache::run::evaluate($ylabel,$safeeval,$$parstack[-1]);
  709: 	$ylabel =~ s/\n/ /g;
  710: 	if (length($ylabel) > $max_str_len) {
  711: 	    $ylabel = substr($ylabel,0,$max_str_len);
  712: 	}
  713:     } elsif ($target eq 'edit') {
  714: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Ylabel');
  715: 	my $text = &Apache::lonxml::get_all_text("/ylabel",$parser);
  716: 	$result .= &Apache::edit::end_row().
  717: 	    &Apache::edit::start_spanning_row().
  718: 	    &Apache::edit::editline('',$text,'',60);
  719:     } elsif ($target eq 'modified') {
  720: 	$result.=&Apache::edit::rebuild_tag($token);
  721: 	$result.=&Apache::edit::modifiedfield("/ylabel",$parser);
  722:     }
  723:     return $result;
  724: }
  725: 
  726: sub end_ylabel {
  727:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  728:     my $result = '';
  729:     if ($target eq 'web' || $target eq 'tex') {
  730:     } elsif ($target eq 'edit') {
  731: 	$result.=&Apache::edit::tag_end($target,$token);
  732:     }
  733:     return $result;
  734: }
  735: 
  736: ##------------------------------------------------------------------- label
  737: sub start_label {
  738:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  739:     my $result='';
  740:     if ($target eq 'web' || $target eq 'tex') {
  741: 	my %label;
  742: 	&get_attributes(\%label,\%label_defaults,$parstack,$safeeval,
  743: 		    $tagstack->[-1]);
  744: 	my $text = &Apache::lonxml::get_all_text("/label",$parser);
  745: 	$text = &Apache::run::evaluate($text,$safeeval,$$parstack[-1]);
  746: 	$text =~ s/\n/ /g;
  747: 	$text = substr($text,0,$max_str_len) if (length($text) > $max_str_len);
  748: 	$label{'text'} = $text;
  749: 	push(@labels,\%label);
  750:     } elsif ($target eq 'edit') {
  751: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Label');
  752: 	$result .= &edit_attributes($target,$token,\%label_defaults);
  753: 	my $text = &Apache::lonxml::get_all_text("/label",$parser);
  754: 	$result .= &Apache::edit::end_row().
  755: 	    &Apache::edit::start_spanning_row().
  756: 	    &Apache::edit::editline('',$text,'',60);
  757:     } elsif ($target eq 'modified') {
  758: 	&Apache::edit::get_new_args
  759: 	    ($token,$parstack,$safeeval,keys(%label_defaults));
  760: 	$result.=&Apache::edit::rebuild_tag($token);
  761: 	$result.=&Apache::edit::modifiedfield("/label",$parser);
  762:     }
  763:     return $result;
  764: }
  765: 
  766: sub end_label {
  767:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  768:     my $result = '';
  769:     if ($target eq 'web' || $target eq 'tex') {
  770:     } elsif ($target eq 'edit') {
  771: 	$result.=&Apache::edit::tag_end($target,$token);
  772:     }
  773:     return $result;
  774: }
  775: 
  776: ##------------------------------------------------------------------- curve
  777: sub start_curve {
  778:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  779:     my $result='';
  780:     &Apache::lonxml::register('Apache::lonplot',('function','data'));
  781:     push (@Apache::lonxml::namespace,'curve');
  782:     if ($target eq 'web' || $target eq 'tex') {
  783: 	my %curve;
  784: 	&get_attributes(\%curve,\%curve_defaults,$parstack,$safeeval,
  785: 		    $tagstack->[-1]);
  786: 	push (@curves,\%curve);
  787:     } elsif ($target eq 'edit') {
  788: 	$result .= &Apache::edit::tag_start($target,$token,'Curve');
  789: 	$result .= &edit_attributes($target,$token,\%curve_defaults,
  790:                                     \@curve_edit_order);
  791:     } elsif ($target eq 'modified') {
  792: 	my $constructtag=&Apache::edit::get_new_args
  793: 	    ($token,$parstack,$safeeval,keys(%curve_defaults));
  794: 	if ($constructtag) {
  795: 	    $result = &Apache::edit::rebuild_tag($token);
  796: 	    $result.= &Apache::edit::handle_insert();
  797: 	}
  798:     }
  799:     return $result;
  800: }
  801: 
  802: sub end_curve {
  803:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  804:     my $result = '';
  805:     pop @Apache::lonxml::namespace;
  806:     &Apache::lonxml::deregister('Apache::lonplot',('function','data'));
  807:     if ($target eq 'web' || $target eq 'tex') {
  808:     } elsif ($target eq 'edit') {
  809: 	$result.=&Apache::edit::tag_end($target,$token);
  810:     }
  811:     return $result;
  812: }
  813: 
  814: ##------------------------------------------------------------ curve function
  815: sub start_function {
  816:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  817:     my $result='';
  818:     if ($target eq 'web' || $target eq 'tex') {
  819: 	if (exists($curves[-1]->{'data'})) {
  820: 	    &Apache::lonxml::warning
  821:                 ('Use of the <b>curve function</b> tag precludes use of '.
  822:                  ' the <b>curve data</b> tag.  '.
  823:                  'The curve data tag will be omitted in favor of the '.
  824:                  'curve function declaration.');
  825: 	    delete $curves[-1]->{'data'} ;
  826: 	}
  827:         my $function = &Apache::lonxml::get_all_text("/function",$parser);
  828: 	$function = &Apache::run::evaluate($function,$safeeval,$$parstack[-1]);
  829: 	$curves[-1]->{'function'} = $function; 
  830:     } elsif ($target eq 'edit') {
  831: 	$result .= &Apache::edit::tag_start($target,$token,'Gnuplot compatible curve function');
  832: 	my $text = &Apache::lonxml::get_all_text("/function",$parser);
  833: 	$result .= &Apache::edit::end_row().
  834: 	    &Apache::edit::start_spanning_row().
  835: 	    &Apache::edit::editline('',$text,'',60);
  836:     } elsif ($target eq 'modified') {
  837: 	$result.=&Apache::edit::rebuild_tag($token);
  838: 	$result.=&Apache::edit::modifiedfield("/function",$parser);
  839:     }
  840:     return $result;
  841: }
  842: 
  843: sub end_function {
  844:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  845:     my $result = '';
  846:     if ($target eq 'web' || $target eq 'tex') {
  847:     } elsif ($target eq 'edit') {
  848: 	$result .= &Apache::edit::end_table();
  849:     }
  850:     return $result;
  851: }
  852: 
  853: ##------------------------------------------------------------ curve  data
  854: sub start_data {
  855:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  856:     my $result='';
  857:     if ($target eq 'web' || $target eq 'tex') {
  858: 	if (exists($curves[-1]->{'function'})) {
  859: 	    &Apache::lonxml::warning
  860:                 ('Use of the <b>curve function</b> tag precludes use of '.
  861:                  ' the <b>curve data</b> tag.  '.
  862:                  'The curve function tag will be omitted in favor of the '.
  863:                  'curve data declaration.');
  864: 	    delete($curves[-1]->{'function'});
  865: 	}
  866: 	my $datatext = &Apache::lonxml::get_all_text("/data",$parser);
  867: 	$datatext=&Apache::run::evaluate($datatext,$safeeval,$$parstack[-1]);
  868: 	# Deal with cases where we're given an array...
  869: 	if ($datatext =~ /^\@/) {
  870: 	    $datatext = &Apache::run::run('return "'.$datatext.'"',
  871: 					  $safeeval,1);
  872: 	}
  873: 	$datatext =~ s/\s+/ /g;
  874: 	# Need to do some error checking on the @data array - 
  875: 	# make sure it's all numbers and make sure each array 
  876: 	# is of the same length.
  877: 	my @data;
  878: 	if ($datatext =~ /,/) { # comma deliminated
  879: 	    @data = split /,/,$datatext;
  880: 	} else { # Assume it's space separated.
  881: 	    @data = split / /,$datatext;
  882: 	}
  883: 	for (my $i=0;$i<=$#data;$i++) {
  884: 	    # Check that it's non-empty
  885: 	    if (! defined($data[$i])) {
  886: 		&Apache::lonxml::warning(
  887: 		    'undefined curve data value.  Replacing with '.
  888: 		    ' pi/e = 1.15572734979092');
  889: 		$data[$i] = 1.15572734979092;
  890: 	    }
  891: 	    # Check that it's a number
  892: 	    if (! &$real_test($data[$i]) & ! &$int_test($data[$i])) {
  893: 		&Apache::lonxml::warning(
  894: 		    'Bad curve data value of '.$data[$i].'  Replacing with '.
  895: 		    ' pi/e = 1.15572734979092');
  896: 		$data[$i] = 1.15572734979092;
  897: 	    }
  898: 	}
  899: 	# complain if the number of data points is not the same as
  900: 	# in previous sets of data.
  901: 	if (($curves[-1]->{'data'}) && ($#data != $#{@{$curves[-1]->{'data'}->[0]}})){
  902: 	    &Apache::lonxml::warning
  903: 		('Number of data points is not consistent with previous '.
  904: 		 'number of data points');
  905: 	}
  906: 	push  @{$curves[-1]->{'data'}},\@data;
  907:     } elsif ($target eq 'edit') {
  908: 	$result .= &Apache::edit::tag_start($target,$token,'Comma or space deliminated curve data');
  909: 	my $text = &Apache::lonxml::get_all_text("/data",$parser);
  910: 	$result .= &Apache::edit::end_row().
  911: 	    &Apache::edit::start_spanning_row().
  912: 	    &Apache::edit::editline('',$text,'',60);
  913:     } elsif ($target eq 'modified') {
  914: 	$result.=&Apache::edit::rebuild_tag($token);
  915: 	$result.=&Apache::edit::modifiedfield("/data",$parser);
  916:     }
  917:     return $result;
  918: }
  919: 
  920: sub end_data {
  921:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  922:     my $result = '';
  923:     if ($target eq 'web' || $target eq 'tex') {
  924:     } elsif ($target eq 'edit') {
  925: 	$result .= &Apache::edit::end_table();
  926:     }
  927:     return $result;
  928: }
  929: 
  930: ##------------------------------------------------------------------- axis
  931: sub start_axis {
  932:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  933:     my $result='';
  934:     if ($target eq 'web' || $target eq 'tex') {
  935: 	&get_attributes(\%axis,\%axis_defaults,$parstack,$safeeval,
  936: 			$tagstack->[-1]);
  937:     } elsif ($target eq 'edit') {
  938: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Axes');
  939: 	$result .= &edit_attributes($target,$token,\%axis_defaults,
  940: 				    \@axis_edit_order);
  941:     } elsif ($target eq 'modified') {
  942: 	my $constructtag=&Apache::edit::get_new_args
  943: 	    ($token,$parstack,$safeeval,keys(%axis_defaults));
  944: 	if ($constructtag) {
  945: 	    $result = &Apache::edit::rebuild_tag($token);
  946: 	}
  947:     }
  948:     return $result;
  949: }
  950: 
  951: sub end_axis {
  952:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  953:     my $result = '';
  954:     if ($target eq 'web' || $target eq 'tex') {
  955:     } elsif ($target eq 'edit') {
  956: 	$result.=&Apache::edit::tag_end($target,$token);
  957:     } elsif ($target eq 'modified') {
  958:     }
  959:     return $result;
  960: }
  961: 
  962: ###################################################################
  963: ##                                                               ##
  964: ##        Utility Functions                                      ##
  965: ##                                                               ##
  966: ###################################################################
  967: 
  968: ##----------------------------------------------------------- set_defaults
  969: sub set_defaults {
  970:     my ($var,$defaults) = @_;
  971:     my $key;
  972:     foreach $key (keys(%$defaults)) {
  973: 	$var->{$key} = $defaults->{$key}->{'default'};
  974:     }
  975: }
  976: 
  977: ##------------------------------------------------------------------- misc
  978: sub get_attributes{
  979:     my ($values,$defaults,$parstack,$safeeval,$tag) = @_;
  980:     foreach my $attr (keys(%{$defaults})) {
  981: 	if ($attr eq 'texwidth' || $attr eq 'texfont') {
  982: 	    $values->{$attr} = 
  983: 		&Apache::lonxml::get_param($attr,$parstack,$safeeval,undef,1);
  984: 	} else {
  985: 	    $values->{$attr} = 
  986: 		&Apache::lonxml::get_param($attr,$parstack,$safeeval);
  987: 	}
  988: 	if ($values->{$attr} eq '' | !defined($values->{$attr})) {
  989: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
  990: 	    next;
  991: 	}
  992: 	my $test = $defaults->{$attr}->{'test'};
  993: 	if (! &$test($values->{$attr})) {
  994: 	    &Apache::lonxml::warning
  995: 		($tag.':'.$attr.': Bad value.'.'Replacing your value with : '
  996: 		 .$defaults->{$attr}->{'default'} );
  997: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
  998: 	}
  999:     }
 1000:     return ;
 1001: }
 1002: 
 1003: ##------------------------------------------------------- write_gnuplot_file
 1004: sub write_gnuplot_file {
 1005:     my ($tmpdir,$filename,$target)= @_;
 1006:     my $gnuplot_input = '';
 1007:     my $curve;
 1008:     my $pt = $plot{'texfont'};
 1009:     #
 1010:     # Check to be sure we do not have any empty curves
 1011:     my @curvescopy;
 1012:     foreach my $curve (@curves) {
 1013:         if (exists($curve->{'function'})) {
 1014:             if ($curve->{'function'} !~ /^\s*$/) {
 1015:                 push(@curvescopy,$curve);
 1016:             }
 1017:         } elsif (exists($curve->{'data'})) {
 1018:             foreach my $data (@{$curve->{'data'}}) {
 1019:                 if (scalar(@$data) > 0) {
 1020:                     push(@curvescopy,$curve);
 1021:                     last;
 1022:                 }
 1023:             }
 1024:         }
 1025:     }
 1026:     @curves = @curvescopy;
 1027:     # Collect all the colors
 1028:     my @Colors;
 1029:     push @Colors, $plot{'bgcolor'};
 1030:     push @Colors, $plot{'fgcolor'}; 
 1031:     push @Colors, (defined($axis{'color'})?$axis{'color'}:$plot{'fgcolor'});
 1032:     foreach $curve (@curves) {
 1033: 	push @Colors, ($curve->{'color'} ne '' ? 
 1034: 		       $curve->{'color'}       : 
 1035: 		       $plot{'fgcolor'}        );
 1036:     }
 1037:     # set term
 1038:     if ($target eq 'web') {
 1039: 	$gnuplot_input .= 'set term '.$weboutputformat .' ';
 1040: 	$gnuplot_input .= 'transparent ' if ($plot{'transparent'} eq 'on');
 1041: 	$gnuplot_input .= $plot{'font'} . ' ';
 1042: 	$gnuplot_input .= 'size '.$plot{'width'}.','.$plot{'height'}.' ';
 1043: 	$gnuplot_input .= "@Colors\n";
 1044: 	# set output
 1045: 	$gnuplot_input .= "set output\n";
 1046:     } elsif ($target eq 'tex') {
 1047: 	$gnuplot_input .= "set term postscript eps $plot{'plotcolor'} solid \"Helvetica\" $pt \n";
 1048: 	$gnuplot_input .= "set output \"/home/httpd/perl/tmp/".
 1049: 	    &Apache::lonnet::unescape($filename).".eps\"\n";
 1050:     }
 1051:     # cartesian or polar?
 1052:     if (lc($plot{'plottype'}) eq 'polar') {
 1053:         $gnuplot_input .= 'set polar'.$/;
 1054:     } else {
 1055:         # Assume Cartesian
 1056:     }
 1057:     # margin
 1058:     if (lc($plot{'lmargin'}) ne 'default') {
 1059:         $gnuplot_input .= 'set lmargin '.$plot{'lmargin'}.$/;
 1060:     }
 1061:     if (lc($plot{'rmargin'}) ne 'default') {
 1062:         $gnuplot_input .= 'set rmargin '.$plot{'rmargin'}.$/;
 1063:     }
 1064:     if (lc($plot{'tmargin'}) ne 'default') {
 1065:         $gnuplot_input .= 'set tmargin '.$plot{'tmargin'}.$/;
 1066:     }
 1067:     if (lc($plot{'bmargin'}) ne 'default') {
 1068:         $gnuplot_input .= 'set bmargin '.$plot{'bmargin'}.$/;
 1069:     }
 1070:     # tic scales
 1071:     $gnuplot_input .= 'set ticscale '.
 1072:         $plot{'major_ticscale'}.' '.$plot{'minor_ticscale'}.$/;
 1073:     # grid
 1074:     $gnuplot_input .= 'set grid'.$/ if ($plot{'grid'} eq 'on');
 1075:     # border
 1076:     $gnuplot_input .= ($plot{'border'} eq 'on'?
 1077: 		       'set border'.$/           :
 1078: 		       'set noborder'.$/         );
 1079:     # sampling rate for non-data curves
 1080:     $gnuplot_input .= "set samples $plot{'samples'}\n";
 1081:     # title, xlabel, ylabel
 1082:     # titles
 1083:     if ($target eq 'tex') {
 1084:         $gnuplot_input .= "set title  \"$title\" font \"Helvetica,".$pt."pt\"\n"  if (defined($title)) ;
 1085:         $gnuplot_input .= "set xlabel \"$xlabel\" font \"Helvetica,".$pt."pt\" \n" if (defined($xlabel));
 1086:         $gnuplot_input .= "set ylabel \"$ylabel\" font \"Helvetica,".$pt."pt\"\n" if (defined($ylabel));
 1087:     } else {
 1088:         $gnuplot_input .= "set title  \"$title\"  \n"  if (defined($title)) ;
 1089:         $gnuplot_input .= "set xlabel \"$xlabel\" \n" if (defined($xlabel));
 1090:         $gnuplot_input .= "set ylabel \"$ylabel\" \n" if (defined($ylabel));
 1091:     }
 1092:     # tics
 1093:     if (%xtics) {    
 1094: 	$gnuplot_input .= "set xtics $xtics{'location'} ";
 1095: 	$gnuplot_input .= ( $xtics{'mirror'} eq 'on'?"mirror ":"nomirror ");
 1096: 	$gnuplot_input .= "$xtics{'start'}, ";
 1097: 	$gnuplot_input .= "$xtics{'increment'}, ";
 1098: 	$gnuplot_input .= "$xtics{'end'}\n";
 1099:         if ($xtics{'minorfreq'} != 0) {
 1100:             $gnuplot_input .= "set mxtics ".$xtics{'minorfreq'}."\n";
 1101:         } 
 1102:     }
 1103:     if (%ytics) {    
 1104: 	$gnuplot_input .= "set ytics $ytics{'location'} ";
 1105: 	$gnuplot_input .= ( $ytics{'mirror'} eq 'on'?"mirror ":"nomirror ");
 1106: 	$gnuplot_input .= "$ytics{'start'}, ";
 1107: 	$gnuplot_input .= "$ytics{'increment'}, ";
 1108:         $gnuplot_input .= "$ytics{'end'}\n";
 1109:         if ($ytics{'minorfreq'} != 0) {
 1110:             $gnuplot_input .= "set mytics ".$ytics{'minorfreq'}."\n";
 1111:         } 
 1112:     }
 1113:     # axis
 1114:     if (%axis) {
 1115: 	$gnuplot_input .= "set xrange \[$axis{'xmin'}:$axis{'xmax'}\]\n";
 1116: 	$gnuplot_input .= "set yrange \[$axis{'ymin'}:$axis{'ymax'}\]\n";
 1117:     }
 1118:     # Key
 1119:     if (%key) {
 1120: 	$gnuplot_input .= 'set key '.$key{'pos'}.' ';
 1121: 	if ($key{'title'} ne '') {
 1122: 	    $gnuplot_input .= 'title "'.$key{'title'}.'" ';
 1123: 	} 
 1124: 	$gnuplot_input .= ($key{'box'} eq 'on' ? 'box ' : 'nobox ').$/;
 1125:     } else {
 1126: 	$gnuplot_input .= 'set nokey'.$/;
 1127:     }
 1128:     # labels
 1129:     my $label;
 1130:     foreach $label (@labels) {
 1131: 	$gnuplot_input .= 'set label "'.$label->{'text'}.'" at '.
 1132: 	    $label->{'xpos'}.','.$label->{'ypos'}.' '.$label->{'justify'};
 1133:         if ($target eq 'tex') {
 1134:             $gnuplot_input .=' font "Helvetica,'.$pt.'pt"' ;
 1135:         }
 1136:         $gnuplot_input .= $/;
 1137:     }
 1138:     if ($target eq 'tex') {
 1139:         $gnuplot_input .="set size 1,".$plot{'height'}/$plot{'width'}*1.38;
 1140:         $gnuplot_input .="\n";
 1141:         }
 1142:     # curves
 1143:     $gnuplot_input .= 'plot ';
 1144:     for (my $i = 0;$i<=$#curves;$i++) {
 1145: 	$curve = $curves[$i];
 1146: 	$gnuplot_input.= ', ' if ($i > 0);
 1147: 	if (exists($curve->{'function'})) {
 1148: 	    $gnuplot_input.= 
 1149: 		$curve->{'function'}.' title "'.
 1150: 		$curve->{'name'}.'" with '.
 1151:                 $curve->{'linestyle'};
 1152:             $gnuplot_input.= ' linewidth 4 ' if ($target eq 'tex');
 1153:             if (($curve->{'linestyle'} eq 'points')      ||
 1154:                 ($curve->{'linestyle'} eq 'linespoints') ||
 1155:                 ($curve->{'linestyle'} eq 'errorbars')   ||
 1156:                 ($curve->{'linestyle'} eq 'xerrorbars')  ||
 1157:                 ($curve->{'linestyle'} eq 'yerrorbars')  ||
 1158:                 ($curve->{'linestyle'} eq 'xyerrorbars')) {
 1159:                 $gnuplot_input.=' pointtype '.$curve->{'pointtype'};
 1160:                 $gnuplot_input.=' pointsize '.$curve->{'pointsize'};
 1161:             }
 1162: 	} elsif (exists($curve->{'data'})) {
 1163: 	    # Store data values in $datatext
 1164: 	    my $datatext = '';
 1165: 	    #   get new filename
 1166: 	    my $datafilename = "$tmpdir/$filename.data.$i";
 1167: 	    my $fh=Apache::File->new(">$datafilename");
 1168: 	    # Compile data
 1169: 	    my @Data = @{$curve->{'data'}};
 1170: 	    my @Data0 = @{$Data[0]};
 1171: 	    for (my $i =0; $i<=$#Data0; $i++) {
 1172: 		my $dataset;
 1173: 		foreach $dataset (@Data) {
 1174: 		    $datatext .= $dataset->[$i] . ' ';
 1175: 		}
 1176: 		$datatext .= $/;
 1177: 	    }
 1178: 	    #   write file
 1179: 	    print $fh $datatext;
 1180: 	    close ($fh);
 1181: 	    #   generate gnuplot text
 1182: 	    $gnuplot_input.= '"'.$datafilename.'" title "'.
 1183: 		$curve->{'name'}.'" with '.
 1184: 		$curve->{'linestyle'};
 1185:             $gnuplot_input.= ' linewidth 4 ' if ($target eq 'tex');
 1186:             if (($curve->{'linestyle'} eq 'points')      ||
 1187:                 ($curve->{'linestyle'} eq 'linespoints') ||
 1188:                 ($curve->{'linestyle'} eq 'errorbars')   ||
 1189:                 ($curve->{'linestyle'} eq 'xerrorbars')  ||
 1190:                 ($curve->{'linestyle'} eq 'yerrorbars')  ||
 1191:                 ($curve->{'linestyle'} eq 'xyerrorbars')) {
 1192:                 $gnuplot_input.=' pointtype '.$curve->{'pointtype'};
 1193:                 $gnuplot_input.=' pointsize '.$curve->{'pointsize'};
 1194:             }
 1195: 	}
 1196:     }
 1197:     # Write the output to a file.
 1198:     my $fh=Apache::File->new(">$tmpdir$filename.data");
 1199:     print $fh $gnuplot_input;
 1200:     close($fh);
 1201:     # That's all folks.
 1202:     return ;
 1203: }
 1204: 
 1205: #---------------------------------------------- check_inputs
 1206: sub check_inputs {
 1207:     ## Note: no inputs, no outputs - this acts only on global variables.
 1208:     ## Make sure we have all the input we need:
 1209:     if (! %plot) { &set_defaults(\%plot,\%gnuplot_defaults); }
 1210:     if (! %key ) {} # No key for this plot, thats okay
 1211: #    if (! %axis) { &set_defaults(\%axis,\%axis_defaults); }
 1212:     if (! defined($title )) {} # No title for this plot, thats okay
 1213:     if (! defined($xlabel)) {} # No xlabel for this plot, thats okay
 1214:     if (! defined($ylabel)) {} # No ylabel for this plot, thats okay
 1215:     if ($#labels < 0) { }      # No labels for this plot, thats okay
 1216:     if ($#curves < 0) { 
 1217: 	&Apache::lonxml::warning("No curves specified for plot!!!!");
 1218: 	return '';
 1219:     }
 1220:     my $curve;
 1221:     foreach $curve (@curves) {
 1222: 	if (!defined($curve->{'function'})&&!defined($curve->{'data'})){
 1223: 	    &Apache::lonxml::warning("One of the curves specified did not contain any curve data or curve function declarations\n");
 1224: 	    return '';
 1225: 	}
 1226:     }
 1227: }
 1228: 
 1229: #------------------------------------------------ make_edit
 1230: sub edit_attributes {
 1231:     my ($target,$token,$defaults,$keys) = @_;
 1232:     my ($result,@keys);
 1233:     if ($keys && ref($keys) eq 'ARRAY') {
 1234:         @keys = @$keys;
 1235:     } else {
 1236: 	@keys = sort(keys(%$defaults));
 1237:     }
 1238:     foreach my $attr (@keys) {
 1239: 	# append a ' ' to the description if it doesn't have one already.
 1240: 	my $description = $defaults->{$attr}->{'description'};
 1241: 	$description .= ' ' if ($description !~ / $/);
 1242: 	if ($defaults->{$attr}->{'edit_type'} eq 'entry') {
 1243: 	    $result .= &Apache::edit::text_arg
 1244: 		($description,$attr,$token,
 1245: 		 $defaults->{$attr}->{'size'});
 1246: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'choice') {
 1247: 	    $result .= &Apache::edit::select_or_text_arg
 1248: 		($description,$attr,$defaults->{$attr}->{'choices'},$token);
 1249: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'onoff') {
 1250: 	    $result .= &Apache::edit::select_or_text_arg
 1251: 		($description,$attr,['on','off'],$token);
 1252: 	}
 1253: 	$result .= '<br />';
 1254:     }
 1255:     return $result;
 1256: }
 1257: 
 1258: 
 1259: ###################################################################
 1260: ##                                                               ##
 1261: ##           Insertion functions for editing plots               ##
 1262: ##                                                               ##
 1263: ###################################################################
 1264: 
 1265: sub insert_gnuplot {
 1266:     my $result = '';
 1267:     #  plot attributes
 1268:     $result .= "\n<gnuplot ";
 1269:     foreach my $attr (keys(%gnuplot_defaults)) {
 1270: 	$result .= "\n     $attr=\"$gnuplot_defaults{$attr}->{'default'}\"";
 1271:     }
 1272:     $result .= ">";
 1273:     # Add the components (most are commented out for simplicity)
 1274:     # $result .= &insert_key();
 1275:     # $result .= &insert_axis();
 1276:     # $result .= &insert_title();    
 1277:     # $result .= &insert_xlabel();    
 1278:     # $result .= &insert_ylabel();    
 1279:     $result .= &insert_curve();
 1280:     # close up the <gnuplot>
 1281:     $result .= "\n</gnuplot>";
 1282:     return $result;
 1283: }
 1284: 
 1285: sub insert_tics {
 1286:     my $result;
 1287:     $result .= &insert_xtics() . &insert_ytics;
 1288:     return $result;
 1289: }
 1290: 
 1291: sub insert_xtics {
 1292:     my $result;
 1293:     $result .= "\n    <xtics ";
 1294:     foreach my $attr (keys(%tic_defaults)) {
 1295: 	$result .= "\n        $attr=\"$tic_defaults{$attr}->{'default'}\" ";
 1296:     }
 1297:     $result .= "/>";
 1298:     return $result;
 1299: }
 1300: 
 1301: sub insert_ytics {
 1302:     my $result;
 1303:     $result .= "\n    <ytics ";
 1304:     foreach my $attr (keys(%tic_defaults)) {
 1305: 	$result .= "\n        $attr=\"$tic_defaults{$attr}->{'default'}\" ";
 1306:     }
 1307:     $result .= "/>";
 1308:     return $result;
 1309: }
 1310: 
 1311: sub insert_key {
 1312:     my $result;
 1313:     $result .= "\n    <key ";
 1314:     foreach my $attr (keys(%key_defaults)) {
 1315: 	$result .= "\n         $attr=\"$key_defaults{$attr}->{'default'}\"";
 1316:     }
 1317:     $result .= " />";
 1318:     return $result;
 1319: }
 1320: 
 1321: sub insert_axis{
 1322:     my $result;
 1323:     $result .= "\n    <axis ";
 1324:    foreach my $attr (keys(%axis_defaults)) {
 1325: 	$result .= "\n         $attr=\"$axis_defaults{$attr}->{'default'}\"";
 1326:     }
 1327:     $result .= " />";
 1328:     return $result;
 1329: }
 1330: 
 1331: sub insert_title  { return "\n    <title></title>"; }
 1332: sub insert_xlabel { return "\n    <xlabel></xlabel>"; }
 1333: sub insert_ylabel { return "\n    <ylabel></ylabel>"; }
 1334: 
 1335: sub insert_label {
 1336:     my $result;
 1337:     $result .= "\n    <label ";
 1338:     foreach my $attr (keys(%label_defaults)) {
 1339: 	$result .= "\n         $attr=\"".
 1340:             $label_defaults{$attr}->{'default'}."\"";
 1341:     }
 1342:     $result .= "></label>";
 1343:     return $result;
 1344: }
 1345: 
 1346: sub insert_curve {
 1347:     my $result;
 1348:     $result .= "\n    <curve ";
 1349:     foreach my $attr (keys(%curve_defaults)) {
 1350: 	$result .= "\n         $attr=\"".
 1351: 	    $curve_defaults{$attr}->{'default'}."\"";
 1352:     }
 1353:     $result .= " >";
 1354:     $result .= &insert_data().&insert_data()."\n    </curve>";
 1355: }
 1356: 
 1357: sub insert_function {
 1358:     my $result;
 1359:     $result .= "\n        <function></function>";
 1360:     return $result;
 1361: }
 1362: 
 1363: sub insert_data {
 1364:     my $result;
 1365:     $result .= "\n        <data></data>";
 1366:     return $result;
 1367: }
 1368: 
 1369: ##----------------------------------------------------------------------
 1370: 1;
 1371: __END__
 1372: 
 1373: 

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