File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.107: download - view: text, annotated - select for diffs
Mon May 16 21:58:41 2005 UTC (19 years ago) by foxr
Branches: MAIN
CVS tags: version_1_99_1_tmcc, HEAD
Export the %plot hash so that clients can figure out the image size e.g.

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

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