File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.129: download - view: text, annotated - select for diffs
Tue Aug 28 23:48:39 2007 UTC (16 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- support gnuplot 4.2

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

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