File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.137: download - view: text, annotated - select for diffs
Mon May 12 11:13:28 2008 UTC (16 years, 1 month ago) by foxr
Branches: MAIN
CVS tags: HEAD
Add more entities.

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

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