File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.109: download - view: text, annotated - select for diffs
Tue Jun 7 22:30:42 2005 UTC (18 years, 11 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
In 'tex' target prefix the plot with a tex comment that tells
outer tags that this is a dynamic image and what the size is.

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

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