File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.127: download - view: text, annotated - select for diffs
Sat Aug 4 00:01:52 2007 UTC (16 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- escape inadvertent attempt to access the enhanced label commands

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

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