File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.118.2.2: download - view: text, annotated - select for diffs
Tue Sep 18 23:30:25 2007 UTC (16 years, 7 months ago) by albertel
Branches: version_2_5_X
Diff to branchpoint 1.118: preferred, unified
- backport 1.130

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

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