File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.119: download - view: text, annotated - select for diffs
Tue Jun 19 01:15:24 2007 UTC (16 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- reenable line width setting,
- add code for font point sizes, not actually working yet until ttf fonts are specified

    1: # The LearningOnline Network with CAPA
    2: # Dynamic plot
    3: #
    4: # $Id: lonplot.pm,v 1.119 2007/06/19 01:15:24 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]=~/^(\d+|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     => '9',
  207: 	 test        => $sml_test,
  208: 	 description => 'Size of font to use',
  209: 	 edit_type   => 'choice',
  210: 	 choices     => [['5','5 (small)'],'7',['9','9 (medium)'],'10','12',['15','15 (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     => 4,
  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: ##-----------------------------------------------------------------font
  677: sub get_font {
  678:     my ($size);
  679:     if ( $Apache::lonplot::plot{'font'} =~ /^(small|medium|large)/) {
  680: 	if ( $Apache::lonplot::plot{'font'} eq 'small') {
  681: 	    $size = '5';
  682: 	} elsif ( $Apache::lonplot::plot{'font'} eq 'medium') {
  683: 	    $size = '9';
  684: 	} elsif ( $Apache::lonplot::plot{'font'} eq 'large') {
  685: 	    $size = '15';
  686: 	} else {
  687: 	    $size = '9';
  688: 	}
  689:     } else {
  690: 	$size = $Apache::lonplot::plot{'font'};
  691:     }
  692:     return ($size);
  693: }
  694: 
  695: ##----------------------------------------------------------------- key
  696: sub start_key {
  697:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  698:     my $result='';
  699:     if ($target eq 'web' || $target eq 'tex') {
  700: 	&get_attributes(\%key,\%key_defaults,$parstack,$safeeval,
  701: 		    $tagstack->[-1]);
  702:     } elsif ($target eq 'edit') {
  703: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Key');
  704: 	$result .= &edit_attributes($target,$token,\%key_defaults);
  705:     } elsif ($target eq 'modified') {
  706: 	my $constructtag=&Apache::edit::get_new_args
  707: 	    ($token,$parstack,$safeeval,keys(%key_defaults));
  708: 	if ($constructtag) {
  709: 	    $result = &Apache::edit::rebuild_tag($token);
  710: 	}
  711:     }
  712:     return $result;
  713: }
  714: 
  715: sub end_key {
  716:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  717:     my $result = '';
  718:     if ($target eq 'web' || $target eq 'tex') {
  719:     } elsif ($target eq 'edit') {
  720: 	$result.=&Apache::edit::tag_end($target,$token);
  721:     }
  722:     return $result;
  723: }
  724: 
  725: ##------------------------------------------------------------------- title
  726: sub start_title {
  727:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  728:     my $result='';
  729:     if ($target eq 'web' || $target eq 'tex') {
  730: 	$title = &Apache::lonxml::get_all_text("/title",$parser,$style);
  731: 	$title=&Apache::run::evaluate($title,$safeeval,$$parstack[-1]);
  732: 	$title =~ s/\n/ /g;
  733: 	if (length($title) > $max_str_len) {
  734: 	    $title = substr($title,0,$max_str_len);
  735: 	}
  736:     } elsif ($target eq 'edit') {
  737: 	$result.=&Apache::edit::tag_start($target,$token,'Plot Title');
  738: 	my $text=&Apache::lonxml::get_all_text("/title",$parser,$style);
  739: 	$result.=&Apache::edit::editline('',$text,'',60);
  740:     } elsif ($target eq 'modified') {
  741: 	$result.=&Apache::edit::rebuild_tag($token);
  742: 	$result.=&Apache::edit::modifiedfield("/title",$parser);
  743:     }
  744:     return $result;
  745: }
  746: 
  747: sub end_title {
  748:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  749:     my $result = '';
  750:     if ($target eq 'web' || $target eq 'tex') {
  751:     } elsif ($target eq 'edit') {
  752: 	$result.=&Apache::edit::tag_end($target,$token);
  753:     }
  754:     return $result;
  755: }
  756: ##------------------------------------------------------------------- xlabel
  757: sub start_xlabel {
  758:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  759:     my $result='';
  760:     if ($target eq 'web' || $target eq 'tex') {
  761: 	$xlabel = &Apache::lonxml::get_all_text("/xlabel",$parser,$style);
  762: 	$xlabel=&Apache::run::evaluate($xlabel,$safeeval,$$parstack[-1]);
  763: 	$xlabel =~ s/\n/ /g;
  764: 	if (length($xlabel) > $max_str_len) {
  765: 	    $xlabel = substr($xlabel,0,$max_str_len);
  766: 	}
  767:     } elsif ($target eq 'edit') {
  768: 	$result.=&Apache::edit::tag_start($target,$token,'Plot Xlabel');
  769: 	my $text=&Apache::lonxml::get_all_text("/xlabel",$parser,$style);
  770: 	$result.=&Apache::edit::editline('',$text,'',60);
  771:     } elsif ($target eq 'modified') {
  772: 	$result.=&Apache::edit::rebuild_tag($token);	
  773: 	$result.=&Apache::edit::modifiedfield("/xlabel",$parser);
  774:     }
  775:     return $result;
  776: }
  777: 
  778: sub end_xlabel {
  779:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  780:     my $result = '';
  781:     if ($target eq 'web' || $target eq 'tex') {
  782:     } elsif ($target eq 'edit') {
  783: 	$result.=&Apache::edit::tag_end($target,$token);
  784:     }
  785:     return $result;
  786: }
  787: 
  788: ##------------------------------------------------------------------- ylabel
  789: sub start_ylabel {
  790:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  791:     my $result='';
  792:     if ($target eq 'web' || $target eq 'tex') {
  793: 	$ylabel = &Apache::lonxml::get_all_text("/ylabel",$parser,$style);
  794: 	$ylabel = &Apache::run::evaluate($ylabel,$safeeval,$$parstack[-1]);
  795: 	$ylabel =~ s/\n/ /g;
  796: 	if (length($ylabel) > $max_str_len) {
  797: 	    $ylabel = substr($ylabel,0,$max_str_len);
  798: 	}
  799:     } elsif ($target eq 'edit') {
  800: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Ylabel');
  801: 	my $text = &Apache::lonxml::get_all_text("/ylabel",$parser,$style);
  802: 	$result .= &Apache::edit::editline('',$text,'',60);
  803:     } elsif ($target eq 'modified') {
  804: 	$result.=&Apache::edit::rebuild_tag($token);
  805: 	$result.=&Apache::edit::modifiedfield("/ylabel",$parser);
  806:     }
  807:     return $result;
  808: }
  809: 
  810: sub end_ylabel {
  811:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  812:     my $result = '';
  813:     if ($target eq 'web' || $target eq 'tex') {
  814:     } elsif ($target eq 'edit') {
  815: 	$result.=&Apache::edit::tag_end($target,$token);
  816:     }
  817:     return $result;
  818: }
  819: 
  820: ##------------------------------------------------------------------- label
  821: sub start_label {
  822:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  823:     my $result='';
  824:     if ($target eq 'web' || $target eq 'tex') {
  825: 	my %label;
  826: 	&get_attributes(\%label,\%label_defaults,$parstack,$safeeval,
  827: 		    $tagstack->[-1]);
  828: 	my $text = &Apache::lonxml::get_all_text("/label",$parser,$style);
  829: 	$text = &Apache::run::evaluate($text,$safeeval,$$parstack[-1]);
  830: 	$text =~ s/\n/ /g;
  831: 	$text = substr($text,0,$max_str_len) if (length($text) > $max_str_len);
  832: 	$label{'text'} = $text;
  833: 	push(@labels,\%label);
  834:     } elsif ($target eq 'edit') {
  835: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Label');
  836: 	$result .= &edit_attributes($target,$token,\%label_defaults);
  837: 	my $text = &Apache::lonxml::get_all_text("/label",$parser,$style);
  838: 	$result .= &Apache::edit::end_row().
  839: 	    &Apache::edit::start_spanning_row().
  840: 	    &Apache::edit::editline('',$text,'',60);
  841:     } elsif ($target eq 'modified') {
  842: 	&Apache::edit::get_new_args
  843: 	    ($token,$parstack,$safeeval,keys(%label_defaults));
  844: 	$result.=&Apache::edit::rebuild_tag($token);
  845: 	$result.=&Apache::edit::modifiedfield("/label",$parser);
  846:     }
  847:     return $result;
  848: }
  849: 
  850: sub end_label {
  851:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  852:     my $result = '';
  853:     if ($target eq 'web' || $target eq 'tex') {
  854:     } elsif ($target eq 'edit') {
  855: 	$result.=&Apache::edit::tag_end($target,$token);
  856:     }
  857:     return $result;
  858: }
  859: 
  860: ##------------------------------------------------------------------- curve
  861: sub start_curve {
  862:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  863:     my $result='';
  864:     &Apache::lonxml::register('Apache::lonplot',('function','data'));
  865:     push (@Apache::lonxml::namespace,'curve');
  866:     if ($target eq 'web' || $target eq 'tex') {
  867: 	my %curve;
  868: 	&get_attributes(\%curve,\%curve_defaults,$parstack,$safeeval,
  869: 		    $tagstack->[-1]);
  870: 	push (@curves,\%curve);
  871:     } elsif ($target eq 'edit') {
  872: 	$result .= &Apache::edit::tag_start($target,$token,'Curve');
  873: 	$result .= &edit_attributes($target,$token,\%curve_defaults,
  874:                                     \@curve_edit_order)
  875: 	    .&Apache::edit::end_row()
  876: 	    .&Apache::edit::start_spanning_row();
  877: 
  878:     } elsif ($target eq 'modified') {
  879: 	my $constructtag=&Apache::edit::get_new_args
  880: 	    ($token,$parstack,$safeeval,keys(%curve_defaults));
  881: 	if ($constructtag) {
  882: 	    $result = &Apache::edit::rebuild_tag($token);
  883: 	}
  884:     }
  885:     return $result;
  886: }
  887: 
  888: sub end_curve {
  889:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  890:     my $result = '';
  891:     pop @Apache::lonxml::namespace;
  892:     &Apache::lonxml::deregister('Apache::lonplot',('function','data'));
  893:     if ($target eq 'web' || $target eq 'tex') {
  894:     } elsif ($target eq 'edit') {
  895: 	$result.=&Apache::edit::tag_end($target,$token);
  896:     }
  897:     return $result;
  898: }
  899: 
  900: ##------------------------------------------------------------ curve function
  901: sub start_function {
  902:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  903:     my $result='';
  904:     if ($target eq 'web' || $target eq 'tex') {
  905: 	if (exists($curves[-1]->{'data'})) {
  906: 	    &Apache::lonxml::warning
  907:                 ('Use of the <b>curve function</b> tag precludes use of '.
  908:                  ' the <b>curve data</b> tag.  '.
  909:                  'The curve data tag will be omitted in favor of the '.
  910:                  'curve function declaration.');
  911: 	    delete $curves[-1]->{'data'} ;
  912: 	}
  913:         my $function = &Apache::lonxml::get_all_text("/function",$parser,
  914: 						     $style);
  915: 	$function = &Apache::run::evaluate($function,$safeeval,$$parstack[-1]);
  916: 	$curves[-1]->{'function'} = $function; 
  917:     } elsif ($target eq 'edit') {
  918: 	$result .= &Apache::edit::tag_start($target,$token,'Gnuplot compatible curve function');
  919: 	my $text = &Apache::lonxml::get_all_text("/function",$parser,$style);
  920: 	$result .= &Apache::edit::editline('',$text,'',60);
  921:     } elsif ($target eq 'modified') {
  922: 	$result.=&Apache::edit::rebuild_tag($token);
  923: 	$result.=&Apache::edit::modifiedfield("/function",$parser);
  924:     }
  925:     return $result;
  926: }
  927: 
  928: sub end_function {
  929:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  930:     my $result = '';
  931:     if ($target eq 'web' || $target eq 'tex') {
  932:     } elsif ($target eq 'edit') {
  933: 	$result .= &Apache::edit::end_table();
  934:     }
  935:     return $result;
  936: }
  937: 
  938: ##------------------------------------------------------------ curve  data
  939: sub start_data {
  940:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  941:     my $result='';
  942:     if ($target eq 'web' || $target eq 'tex') {
  943: 	if (exists($curves[-1]->{'function'})) {
  944: 	    &Apache::lonxml::warning
  945:                 ('Use of the <b>curve function</b> tag precludes use of '.
  946:                  ' the <b>curve data</b> tag.  '.
  947:                  'The curve function tag will be omitted in favor of the '.
  948:                  'curve data declaration.');
  949: 	    delete($curves[-1]->{'function'});
  950: 	}
  951: 	my $datatext = &Apache::lonxml::get_all_text("/data",$parser,$style);
  952: 	$datatext=&Apache::run::evaluate($datatext,$safeeval,$$parstack[-1]);
  953: 	# Deal with cases where we're given an array...
  954: 	if ($datatext =~ /^\@/) {
  955: 	    $datatext = &Apache::run::run('return "'.$datatext.'"',
  956: 					  $safeeval,1);
  957: 	}
  958: 	$datatext =~ s/\s+/ /g;
  959: 	# Need to do some error checking on the @data array - 
  960: 	# make sure it's all numbers and make sure each array 
  961: 	# is of the same length.
  962: 	my @data;
  963: 	if ($datatext =~ /,/) { # comma deliminated
  964: 	    @data = split /,/,$datatext;
  965: 	} else { # Assume it's space separated.
  966: 	    @data = split / /,$datatext;
  967: 	}
  968: 	for (my $i=0;$i<=$#data;$i++) {
  969: 	    # Check that it's non-empty
  970: 	    if (! defined($data[$i])) {
  971: 		&Apache::lonxml::warning(
  972: 		    'undefined curve data value.  Replacing with '.
  973: 		    ' pi/e = 1.15572734979092');
  974: 		$data[$i] = 1.15572734979092;
  975: 	    }
  976: 	    # Check that it's a number
  977: 	    if (! &$real_test($data[$i]) & ! &$int_test($data[$i])) {
  978: 		&Apache::lonxml::warning(
  979: 		    'Bad curve data value of '.$data[$i].'  Replacing with '.
  980: 		    ' pi/e = 1.15572734979092');
  981: 		$data[$i] = 1.15572734979092;
  982: 	    }
  983: 	}
  984: 	# complain if the number of data points is not the same as
  985: 	# in previous sets of data.
  986: 	if (($curves[-1]->{'data'}) && ($#data != $#{@{$curves[-1]->{'data'}->[0]}})){
  987: 	    &Apache::lonxml::warning
  988: 		('Number of data points is not consistent with previous '.
  989: 		 'number of data points');
  990: 	}
  991: 	push  @{$curves[-1]->{'data'}},\@data;
  992:     } elsif ($target eq 'edit') {
  993: 	$result .= &Apache::edit::tag_start($target,$token,'Comma or space deliminated curve data');
  994: 	my $text = &Apache::lonxml::get_all_text("/data",$parser,$style);
  995: 	$result .= &Apache::edit::editline('',$text,'',60);
  996:     } elsif ($target eq 'modified') {
  997: 	$result.=&Apache::edit::rebuild_tag($token);
  998: 	$result.=&Apache::edit::modifiedfield("/data",$parser);
  999:     }
 1000:     return $result;
 1001: }
 1002: 
 1003: sub end_data {
 1004:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1005:     my $result = '';
 1006:     if ($target eq 'web' || $target eq 'tex') {
 1007:     } elsif ($target eq 'edit') {
 1008: 	$result .= &Apache::edit::end_table();
 1009:     }
 1010:     return $result;
 1011: }
 1012: 
 1013: ##------------------------------------------------------------------- axis
 1014: sub start_axis {
 1015:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1016:     my $result='';
 1017:     if ($target eq 'web' || $target eq 'tex') {
 1018: 	&get_attributes(\%axis,\%axis_defaults,$parstack,$safeeval,
 1019: 			$tagstack->[-1]);
 1020:     } elsif ($target eq 'edit') {
 1021: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Axes');
 1022: 	$result .= &edit_attributes($target,$token,\%axis_defaults,
 1023: 				    \@axis_edit_order);
 1024:     } elsif ($target eq 'modified') {
 1025: 	my $constructtag=&Apache::edit::get_new_args
 1026: 	    ($token,$parstack,$safeeval,keys(%axis_defaults));
 1027: 	if ($constructtag) {
 1028: 	    $result = &Apache::edit::rebuild_tag($token);
 1029: 	}
 1030:     }
 1031:     return $result;
 1032: }
 1033: 
 1034: sub end_axis {
 1035:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1036:     my $result = '';
 1037:     if ($target eq 'web' || $target eq 'tex') {
 1038:     } elsif ($target eq 'edit') {
 1039: 	$result.=&Apache::edit::tag_end($target,$token);
 1040:     } elsif ($target eq 'modified') {
 1041:     }
 1042:     return $result;
 1043: }
 1044: 
 1045: ###################################################################
 1046: ##                                                               ##
 1047: ##        Utility Functions                                      ##
 1048: ##                                                               ##
 1049: ###################################################################
 1050: 
 1051: ##----------------------------------------------------------- set_defaults
 1052: sub set_defaults {
 1053:     my ($var,$defaults) = @_;
 1054:     my $key;
 1055:     foreach $key (keys(%$defaults)) {
 1056: 	$var->{$key} = $defaults->{$key}->{'default'};
 1057:     }
 1058: }
 1059: 
 1060: ##------------------------------------------------------------------- misc
 1061: sub get_attributes{
 1062:     my ($values,$defaults,$parstack,$safeeval,$tag) = @_;
 1063:     foreach my $attr (keys(%{$defaults})) {
 1064: 	if ($attr eq 'texwidth' || $attr eq 'texfont') {
 1065: 	    $values->{$attr} = 
 1066: 		&Apache::lonxml::get_param($attr,$parstack,$safeeval,undef,1);
 1067: 	} else {
 1068: 	    $values->{$attr} = 
 1069: 		&Apache::lonxml::get_param($attr,$parstack,$safeeval);
 1070: 	}
 1071: 	if ($values->{$attr} eq '' | !defined($values->{$attr})) {
 1072: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
 1073: 	    next;
 1074: 	}
 1075: 	my $test = $defaults->{$attr}->{'test'};
 1076: 	if (! &$test($values->{$attr})) {
 1077: 	    &Apache::lonxml::warning
 1078: 		($tag.':'.$attr.': Bad value.'.'Replacing your value with : '
 1079: 		 .$defaults->{$attr}->{'default'} );
 1080: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
 1081: 	}
 1082:     }
 1083:     return ;
 1084: }
 1085: 
 1086: ##------------------------------------------------------- write_gnuplot_file
 1087: sub write_gnuplot_file {
 1088:     my ($tmpdir,$filename,$target)= @_;
 1089:     my $gnuplot_input = '';
 1090:     my $curve;
 1091:     my $pt = $Apache::lonplot::plot{'texfont'};
 1092:     #
 1093:     # Check to be sure we do not have any empty curves
 1094:     my @curvescopy;
 1095:     foreach my $curve (@curves) {
 1096:         if (exists($curve->{'function'})) {
 1097:             if ($curve->{'function'} !~ /^\s*$/) {
 1098:                 push(@curvescopy,$curve);
 1099:             }
 1100:         } elsif (exists($curve->{'data'})) {
 1101:             foreach my $data (@{$curve->{'data'}}) {
 1102:                 if (scalar(@$data) > 0) {
 1103:                     push(@curvescopy,$curve);
 1104:                     last;
 1105:                 }
 1106:             }
 1107:         }
 1108:     }
 1109:     @curves = @curvescopy;
 1110:     # Collect all the colors
 1111:     my @Colors;
 1112:     push @Colors, $Apache::lonplot::plot{'bgcolor'};
 1113:     push @Colors, $Apache::lonplot::plot{'fgcolor'}; 
 1114:     push @Colors, (defined($axis{'color'})?$axis{'color'}:$Apache::lonplot::plot{'fgcolor'});
 1115:     foreach $curve (@curves) {
 1116: 	push @Colors, ($curve->{'color'} ne '' ? 
 1117: 		       $curve->{'color'}       : 
 1118: 		       $Apache::lonplot::plot{'fgcolor'}        );
 1119:     }
 1120:     # set term
 1121:     if ($target eq 'web') {
 1122: 	$gnuplot_input .= 'set term '.$weboutputformat .' enhanced ';
 1123: 	$gnuplot_input .= 'transparent ' if ($Apache::lonplot::plot{'transparent'} eq 'on');
 1124: 	$gnuplot_input .= $Apache::lonplot::plot{'font'} . ' ';
 1125: 	$gnuplot_input .= 'size '.$Apache::lonplot::plot{'width'}.','.$Apache::lonplot::plot{'height'}.' ';
 1126: 	$gnuplot_input .= "@Colors\n";
 1127: 	# set output
 1128: 	$gnuplot_input .= "set output\n";
 1129:     } elsif ($target eq 'tex') {
 1130: 	$gnuplot_input .= "set term postscript eps enhanced $Apache::lonplot::plot{'plotcolor'} solid \"Helvetica\" $pt \n";
 1131: 	$gnuplot_input .= "set output \"/home/httpd/perl/tmp/".
 1132: 	    &unescape($filename).".eps\"\n";
 1133:     }
 1134:     # cartesian or polar plot?
 1135:     if (lc($Apache::lonplot::plot{'plottype'}) eq 'polar') {
 1136:         $gnuplot_input .= 'set polar'.$/;
 1137:     } else {
 1138:         # Assume Cartesian
 1139:     }
 1140:     # cartesian or polar grid?
 1141:     if (lc($Apache::lonplot::plot{'gridtype'}) eq 'polar') {
 1142:         $gnuplot_input .= 'set grid polar'.$/;
 1143:     } elsif (lc($Apache::lonplot::plot{'gridtype'}) eq 'linear-log') {
 1144:         $gnuplot_input .= 'set logscale x'.$/;
 1145:     } elsif (lc($Apache::lonplot::plot{'gridtype'}) eq 'log-linear') {
 1146:         $gnuplot_input .= 'set logscale y'.$/;
 1147:     } elsif (lc($Apache::lonplot::plot{'gridtype'}) eq 'log-log') {
 1148:         $gnuplot_input .= 'set logscale x'.$/;
 1149:         $gnuplot_input .= 'set logscale y'.$/;
 1150:     } else {
 1151:         # Assume Cartesian
 1152:     }
 1153:     # solid or pattern for boxes?
 1154:     if (lc($Apache::lonplot::plot{'fillstyle'}) eq 'solid') {
 1155:         $gnuplot_input .= 'set style fill solid '.
 1156: 	    $Apache::lonplot::plot{'solid'}.$Apache::lonplot::plot{'box_border'}.$/;
 1157:     } elsif (lc($Apache::lonplot::plot{'fillstyle'}) eq 'pattern') {
 1158:         $gnuplot_input .= 'set style fill pattern '.$Apache::lonplot::plot{'pattern'}.$Apache::lonplot::plot{'box_border'}.$/;
 1159:     } elsif (lc($Apache::lonplot::plot{'fillstyle'}) eq 'empty') {
 1160:     }
 1161:     # margin
 1162:     if (lc($Apache::lonplot::plot{'lmargin'}) ne 'default') {
 1163:         $gnuplot_input .= 'set lmargin '.$Apache::lonplot::plot{'lmargin'}.$/;
 1164:     }
 1165:     if (lc($Apache::lonplot::plot{'rmargin'}) ne 'default') {
 1166:         $gnuplot_input .= 'set rmargin '.$Apache::lonplot::plot{'rmargin'}.$/;
 1167:     }
 1168:     if (lc($Apache::lonplot::plot{'tmargin'}) ne 'default') {
 1169:         $gnuplot_input .= 'set tmargin '.$Apache::lonplot::plot{'tmargin'}.$/;
 1170:     }
 1171:     if (lc($Apache::lonplot::plot{'bmargin'}) ne 'default') {
 1172:         $gnuplot_input .= 'set bmargin '.$Apache::lonplot::plot{'bmargin'}.$/;
 1173:     }
 1174:     # tic scales
 1175:     $gnuplot_input .= 'set ticscale '.
 1176:         $Apache::lonplot::plot{'major_ticscale'}.' '.$Apache::lonplot::plot{'minor_ticscale'}.$/;
 1177:     #boxwidth
 1178:     if (lc($Apache::lonplot::plot{'boxwidth'}) ne '') {
 1179: 	$gnuplot_input .= 'set boxwidth '.$Apache::lonplot::plot{'boxwidth'}.$/;
 1180:     }
 1181:     # gridlayer
 1182:     $gnuplot_input .= 'set grid noxtics noytics front '.$/ 
 1183: 	if ($Apache::lonplot::plot{'gridlayer'} eq 'on');
 1184: 
 1185:     # grid
 1186:     $gnuplot_input .= 'set grid'.$/ if ($Apache::lonplot::plot{'grid'} eq 'on');
 1187:     # border
 1188:     $gnuplot_input .= ($Apache::lonplot::plot{'border'} eq 'on'?
 1189: 		       'set border'.$/           :
 1190: 		       'set noborder'.$/         );
 1191:     # sampling rate for non-data curves
 1192:     $gnuplot_input .= "set samples $Apache::lonplot::plot{'samples'}\n";
 1193:     # title, xlabel, ylabel
 1194:     # titles
 1195:     if ($target eq 'tex') {
 1196:         $gnuplot_input .= "set title  \"$title\" font \"Helvetica,".$pt."pt\"\n"  if (defined($title)) ;
 1197:         $gnuplot_input .= "set xlabel \"$xlabel\" font \"Helvetica,".$pt."pt\" \n" if (defined($xlabel));
 1198:         $gnuplot_input .= "set ylabel \"$ylabel\" font \"Helvetica,".$pt."pt\"\n" if (defined($ylabel));
 1199:     } else {
 1200:         $gnuplot_input .= "set title  \"$title\"  \n"  if (defined($title)) ;
 1201:         $gnuplot_input .= "set xlabel \"$xlabel\" \n" if (defined($xlabel));
 1202:         $gnuplot_input .= "set ylabel \"$ylabel\" \n" if (defined($ylabel));
 1203:     }
 1204:     # tics
 1205:     if (%xtics) {    
 1206: 	$gnuplot_input .= "set xtics $xtics{'location'} ";
 1207: 	$gnuplot_input .= ( $xtics{'mirror'} eq 'on'?"mirror ":"nomirror ");
 1208: 	$gnuplot_input .= "$xtics{'start'}, ";
 1209: 	$gnuplot_input .= "$xtics{'increment'}, ";
 1210: 	$gnuplot_input .= "$xtics{'end'}\n";
 1211:         if ($xtics{'minorfreq'} != 0) {
 1212:             $gnuplot_input .= "set mxtics ".$xtics{'minorfreq'}."\n";
 1213:         } 
 1214:     }
 1215:     if (%ytics) {    
 1216: 	$gnuplot_input .= "set ytics $ytics{'location'} ";
 1217: 	$gnuplot_input .= ( $ytics{'mirror'} eq 'on'?"mirror ":"nomirror ");
 1218: 	$gnuplot_input .= "$ytics{'start'}, ";
 1219: 	$gnuplot_input .= "$ytics{'increment'}, ";
 1220:         $gnuplot_input .= "$ytics{'end'}\n";
 1221:         if ($ytics{'minorfreq'} != 0) {
 1222:             $gnuplot_input .= "set mytics ".$ytics{'minorfreq'}."\n";
 1223:         } 
 1224:     }
 1225:     # axis
 1226:     if (%axis) {
 1227: 	$gnuplot_input .= "set xrange \[$axis{'xmin'}:$axis{'xmax'}\]\n";
 1228: 	$gnuplot_input .= "set yrange \[$axis{'ymin'}:$axis{'ymax'}\]\n";
 1229:     }
 1230:     # Key
 1231:     if (%key) {
 1232: 	$gnuplot_input .= 'set key '.$key{'pos'}.' ';
 1233: 	if ($key{'title'} ne '') {
 1234: 	    $gnuplot_input .= 'title "'.$key{'title'}.'" ';
 1235: 	} 
 1236: 	$gnuplot_input .= ($key{'box'} eq 'on' ? 'box ' : 'nobox ').$/;
 1237:     } else {
 1238: 	$gnuplot_input .= 'set nokey'.$/;
 1239:     }
 1240:     # labels
 1241:     my $label;
 1242:     foreach $label (@labels) {
 1243: 	$gnuplot_input .= 'set label "'.$label->{'text'}.'" at '.
 1244: 	    $label->{'xpos'}.','.$label->{'ypos'}.' '.$label->{'justify'};
 1245:         if ($target eq 'tex') {
 1246:             $gnuplot_input .=' font "Helvetica,'.$pt.'pt"' ;
 1247:         }
 1248:         $gnuplot_input .= $/;
 1249:     }
 1250:     if ($target eq 'tex') {
 1251:         $gnuplot_input .="set size 1,".$Apache::lonplot::plot{'height'}/$Apache::lonplot::plot{'width'}*1.38;
 1252:         $gnuplot_input .="\n";
 1253:         }
 1254:     # curves
 1255:     $gnuplot_input .= 'plot ';
 1256:     for (my $i = 0;$i<=$#curves;$i++) {
 1257: 	$curve = $curves[$i];
 1258: 	$gnuplot_input.= ', ' if ($i > 0);
 1259: 	if ($target eq 'tex') {
 1260: 	    $curve->{'linewidth'} *= 2;
 1261: 	}
 1262: 	if (exists($curve->{'function'})) {
 1263: 	    $gnuplot_input.= 
 1264: 		$curve->{'function'}.' title "'.
 1265: 		$curve->{'name'}.'" with '.
 1266:                 $curve->{'linestyle'};
 1267:             $gnuplot_input.= ' linewidth '.$curve->{'linewidth'};
 1268: 
 1269:             if (($curve->{'linestyle'} eq 'points')      ||
 1270:                 ($curve->{'linestyle'} eq 'linespoints') ||
 1271:                 ($curve->{'linestyle'} eq 'errorbars')   ||
 1272:                 ($curve->{'linestyle'} eq 'xerrorbars')  ||
 1273:                 ($curve->{'linestyle'} eq 'yerrorbars')  ||
 1274:                 ($curve->{'linestyle'} eq 'xyerrorbars')) {
 1275:                 $gnuplot_input.=' pointtype '.$curve->{'pointtype'};
 1276:                 $gnuplot_input.=' pointsize '.$curve->{'pointsize'};
 1277:             } elsif ($curve->{'linestyle'} eq 'filledcurves') { 
 1278:                 $gnuplot_input.= ' '.$curve->{'limit'};
 1279:             }
 1280: 	} elsif (exists($curve->{'data'})) {
 1281: 	    # Store data values in $datatext
 1282: 	    my $datatext = '';
 1283: 	    #   get new filename
 1284: 	    my $datafilename = "$tmpdir/$filename.data.$i";
 1285: 	    my $fh=Apache::File->new(">$datafilename");
 1286: 	    # Compile data
 1287: 	    my @Data = @{$curve->{'data'}};
 1288: 	    my @Data0 = @{$Data[0]};
 1289: 	    for (my $i =0; $i<=$#Data0; $i++) {
 1290: 		my $dataset;
 1291: 		foreach $dataset (@Data) {
 1292: 		    $datatext .= $dataset->[$i] . ' ';
 1293: 		}
 1294: 		$datatext .= $/;
 1295: 	    }
 1296: 	    #   write file
 1297: 	    print $fh $datatext;
 1298: 	    close($fh);
 1299: 	    #   generate gnuplot text
 1300: 	    $gnuplot_input.= '"'.$datafilename.'" title "'.
 1301: 		$curve->{'name'}.'" with '.
 1302: 		$curve->{'linestyle'};
 1303:             $gnuplot_input.= ' linewidth '.$curve->{'linewidth'};
 1304:             if (($curve->{'linestyle'} eq 'points')      ||
 1305:                 ($curve->{'linestyle'} eq 'linespoints') ||
 1306:                 ($curve->{'linestyle'} eq 'errorbars')   ||
 1307:                 ($curve->{'linestyle'} eq 'xerrorbars')  ||
 1308:                 ($curve->{'linestyle'} eq 'yerrorbars')  ||
 1309:                 ($curve->{'linestyle'} eq 'xyerrorbars')) {
 1310:                 $gnuplot_input.=' pointtype '.$curve->{'pointtype'};
 1311:                 $gnuplot_input.=' pointsize '.$curve->{'pointsize'};
 1312:             } elsif ($curve->{'linestyle'} eq 'filledcurves') { 
 1313:                 $gnuplot_input.= ' '.$curve->{'limit'};
 1314:             }
 1315: 	}
 1316:     }
 1317:     # Write the output to a file.
 1318:     my $fh=Apache::File->new(">$tmpdir$filename.data");
 1319:     print $fh $gnuplot_input;
 1320:     close($fh);
 1321:     # That's all folks.
 1322:     return ;
 1323: }
 1324: 
 1325: #---------------------------------------------- check_inputs
 1326: sub check_inputs {
 1327:     ## Note: no inputs, no outputs - this acts only on global variables.
 1328:     ## Make sure we have all the input we need:
 1329:     if (! %Apache::lonplot::plot) { &set_defaults(\%Apache::lonplot::plot,\%gnuplot_defaults); }
 1330:     if (! %key ) {} # No key for this plot, thats okay
 1331: #    if (! %axis) { &set_defaults(\%axis,\%axis_defaults); }
 1332:     if (! defined($title )) {} # No title for this plot, thats okay
 1333:     if (! defined($xlabel)) {} # No xlabel for this plot, thats okay
 1334:     if (! defined($ylabel)) {} # No ylabel for this plot, thats okay
 1335:     if ($#labels < 0) { }      # No labels for this plot, thats okay
 1336:     if ($#curves < 0) { 
 1337: 	&Apache::lonxml::warning("No curves specified for plot!!!!");
 1338: 	return '';
 1339:     }
 1340:     my $curve;
 1341:     foreach $curve (@curves) {
 1342: 	if (!defined($curve->{'function'})&&!defined($curve->{'data'})){
 1343: 	    &Apache::lonxml::warning("One of the curves specified did not contain any curve data or curve function declarations\n");
 1344: 	    return '';
 1345: 	}
 1346:     }
 1347: }
 1348: 
 1349: #------------------------------------------------ make_edit
 1350: sub edit_attributes {
 1351:     my ($target,$token,$defaults,$keys) = @_;
 1352:     my ($result,@keys);
 1353:     if ($keys && ref($keys) eq 'ARRAY') {
 1354:         @keys = @$keys;
 1355:     } else {
 1356: 	@keys = sort(keys(%$defaults));
 1357:     }
 1358:     foreach my $attr (@keys) {
 1359: 	# append a ' ' to the description if it doesn't have one already.
 1360: 	my $description = $defaults->{$attr}->{'description'};
 1361: 	$description .= ' ' if ($description !~ / $/);
 1362: 	if ($defaults->{$attr}->{'edit_type'} eq 'entry') {
 1363: 	    $result .= &Apache::edit::text_arg
 1364: 		($description,$attr,$token,
 1365: 		 $defaults->{$attr}->{'size'});
 1366: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'choice') {
 1367: 	    $result .= &Apache::edit::select_or_text_arg
 1368: 		($description,$attr,$defaults->{$attr}->{'choices'},$token);
 1369: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'onoff') {
 1370: 	    $result .= &Apache::edit::select_or_text_arg
 1371: 		($description,$attr,['on','off'],$token);
 1372: 	}
 1373: 	$result .= '<br />';
 1374:     }
 1375:     return $result;
 1376: }
 1377: 
 1378: 
 1379: ###################################################################
 1380: ##                                                               ##
 1381: ##           Insertion functions for editing plots               ##
 1382: ##                                                               ##
 1383: ###################################################################
 1384: 
 1385: sub insert_gnuplot {
 1386:     my $result = '';
 1387:     #  plot attributes
 1388:     $result .= "\n<gnuplot ";
 1389:     foreach my $attr (keys(%gnuplot_defaults)) {
 1390: 	$result .= "\n     $attr=\"$gnuplot_defaults{$attr}->{'default'}\"";
 1391:     }
 1392:     $result .= ">";
 1393:     # Add the components (most are commented out for simplicity)
 1394:     # $result .= &insert_key();
 1395:     # $result .= &insert_axis();
 1396:     # $result .= &insert_title();    
 1397:     # $result .= &insert_xlabel();    
 1398:     # $result .= &insert_ylabel();    
 1399:     $result .= &insert_curve();
 1400:     # close up the <gnuplot>
 1401:     $result .= "\n</gnuplot>";
 1402:     return $result;
 1403: }
 1404: 
 1405: sub insert_tics {
 1406:     my $result;
 1407:     $result .= &insert_xtics() . &insert_ytics;
 1408:     return $result;
 1409: }
 1410: 
 1411: sub insert_xtics {
 1412:     my $result;
 1413:     $result .= "\n    <xtics ";
 1414:     foreach my $attr (keys(%tic_defaults)) {
 1415: 	$result .= "\n        $attr=\"$tic_defaults{$attr}->{'default'}\" ";
 1416:     }
 1417:     $result .= "/>";
 1418:     return $result;
 1419: }
 1420: 
 1421: sub insert_ytics {
 1422:     my $result;
 1423:     $result .= "\n    <ytics ";
 1424:     foreach my $attr (keys(%tic_defaults)) {
 1425: 	$result .= "\n        $attr=\"$tic_defaults{$attr}->{'default'}\" ";
 1426:     }
 1427:     $result .= "/>";
 1428:     return $result;
 1429: }
 1430: 
 1431: sub insert_key {
 1432:     my $result;
 1433:     $result .= "\n    <key ";
 1434:     foreach my $attr (keys(%key_defaults)) {
 1435: 	$result .= "\n         $attr=\"$key_defaults{$attr}->{'default'}\"";
 1436:     }
 1437:     $result .= " />";
 1438:     return $result;
 1439: }
 1440: 
 1441: sub insert_axis{
 1442:     my $result;
 1443:     $result .= "\n    <axis ";
 1444:    foreach my $attr (keys(%axis_defaults)) {
 1445: 	$result .= "\n         $attr=\"$axis_defaults{$attr}->{'default'}\"";
 1446:     }
 1447:     $result .= " />";
 1448:     return $result;
 1449: }
 1450: 
 1451: sub insert_title  { return "\n    <title></title>"; }
 1452: sub insert_xlabel { return "\n    <xlabel></xlabel>"; }
 1453: sub insert_ylabel { return "\n    <ylabel></ylabel>"; }
 1454: 
 1455: sub insert_label {
 1456:     my $result;
 1457:     $result .= "\n    <label ";
 1458:     foreach my $attr (keys(%label_defaults)) {
 1459: 	$result .= "\n         $attr=\"".
 1460:             $label_defaults{$attr}->{'default'}."\"";
 1461:     }
 1462:     $result .= "></label>";
 1463:     return $result;
 1464: }
 1465: 
 1466: sub insert_curve {
 1467:     my $result;
 1468:     $result .= "\n    <curve ";
 1469:     foreach my $attr (keys(%curve_defaults)) {
 1470: 	$result .= "\n         $attr=\"".
 1471: 	    $curve_defaults{$attr}->{'default'}."\"";
 1472:     }
 1473:     $result .= " >";
 1474:     $result .= &insert_data().&insert_data()."\n    </curve>";
 1475: }
 1476: 
 1477: sub insert_function {
 1478:     my $result;
 1479:     $result .= "\n        <function></function>";
 1480:     return $result;
 1481: }
 1482: 
 1483: sub insert_data {
 1484:     my $result;
 1485:     $result .= "\n        <data></data>";
 1486:     return $result;
 1487: }
 1488: 
 1489: ##----------------------------------------------------------------------
 1490: 1;
 1491: __END__
 1492: 
 1493: 

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