File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.108: download - view: text, annotated - select for diffs
Tue May 31 22:15:32 2005 UTC (18 years, 11 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Support registration of a callback by upper level tags to take tag dependent
action when a gnuplot image is created.  Note that callback nesting is not
supported at this time.

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

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