File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.146: download - view: text, annotated - select for diffs
Mon Jun 9 10:07:01 2008 UTC (15 years, 11 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Unconditionally hard-wire the tic fonts for printing to Helvetica.
This is done since the DejaVu sans seems to have a problem with the
mius sign in tick labelling, while helvetica does not.

    1: # The LearningOnline Network with CAPA
    2: # Dynamic plot
    3: #
    4: # $Id: lonplot.pm,v 1.146 2008/06/09 10:07:01 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: #	$selected_font = $font_properties{'classic'};
  761: 	$size = $Apache::lonplot::plot{'texfont'};
  762:     }
  763:     return ($size, $selected_font);
  764: }
  765: 
  766: ##----------------------------------------------------------------- key
  767: sub start_key {
  768:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  769:     my $result='';
  770:     if ($target eq 'web' || $target eq 'tex') {
  771: 	&get_attributes(\%key,\%key_defaults,$parstack,$safeeval,
  772: 		    $tagstack->[-1]);
  773:     } elsif ($target eq 'edit') {
  774: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Key');
  775: 	$result .= &edit_attributes($target,$token,\%key_defaults);
  776:     } elsif ($target eq 'modified') {
  777: 	my $constructtag=&Apache::edit::get_new_args
  778: 	    ($token,$parstack,$safeeval,keys(%key_defaults));
  779: 	if ($constructtag) {
  780: 	    $result = &Apache::edit::rebuild_tag($token);
  781: 	}
  782:     }
  783:     return $result;
  784: }
  785: 
  786: sub end_key {
  787:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  788:     my $result = '';
  789:     if ($target eq 'web' || $target eq 'tex') {
  790:     } elsif ($target eq 'edit') {
  791: 	$result.=&Apache::edit::tag_end($target,$token);
  792:     }
  793:     return $result;
  794: }
  795: 
  796: sub parse_label {
  797:     my ($target,$text) = @_;
  798:     my $parser=HTML::LCParser->new(\$text);
  799:     my $result;
  800:     while (my $token=$parser->get_token) {
  801: 	if ($token->[0] eq 'S') {
  802: 	    if ($token->[1] eq 'sub') {
  803: 		$result .= '_{';
  804: 	    } elsif ($token->[1] eq 'sup') {
  805: 		$result .= '^{';
  806: 	    } else {
  807: 		$result .= $token->[4];
  808: 	    }
  809: 	} elsif ($token->[0] eq 'E') {
  810: 	    if ($token->[1] eq 'sub'
  811: 		|| $token->[1] eq 'sup') {
  812: 		$result .= '}';
  813: 	    } else {
  814: 		$result .= $token->[2];
  815: 	    }
  816: 	} elsif ($token->[0] eq 'T') {
  817: 	    $result .= &replace_entities($target,$token->[1]);
  818: 	}
  819:     }
  820:     return $result;
  821: }
  822: 
  823: #
  824: #  Note that there are severe restrictions on font selection in the
  825: # ps driver now.  later in life Gnuplot is supposed to support
  826: # utf-8 fonts in the posts script driver.  When this happens,
  827: # the tex entries with comments that include the word <FIX>
  828: # should be changed to print the correct glyphs rather than some
  829: # approximation or fallback of what is intended.
  830: 
  831: my %lookup = 
  832:    (  # Greek alphabet:
  833:       
  834:       '(Alpha|#913)'    => {'tex' => '{/Symbol A}', 'web' => "\x{391}"},
  835:       '(Beta|#914)'    => {'tex' => '{/Symbol B}', 'web' => "\x{392}"},
  836:       '(Chi|#935)'     => {'tex' => '{/Symbol C}', 'web' => "\x{3A7}"},
  837:       '(Delta|#916)'   => {'tex' => '{/Symbol D}', 'web' => "\x{394}"},
  838:       '(Epsilon|#917)' => {'tex' => '{/Symbol E}', 'web' => "\x{395}"},
  839:       '(Phi|#934)'     => {'tex' => '{/Symbol F}', 'web' => "\x{3A6}"},
  840:       '(Gamma|#915)'   => {'tex' => '{/Symbol G}', 'web' => "\x{393}"},
  841:       '(Eta|#919)'     => {'tex' => '{/Symbol H}', 'web' => "\x{397}"},
  842:       '(Iota|#921)'    => {'tex' => '{/Symbol I}', 'web' => "\x{399}"},
  843:       '(Kappa|#922)'   => {'tex' => '{/Symbol K}', 'web' => "\x{39A}"},
  844:       '(Lambda|#923)'  => {'tex' => '{/Symbol L}', 'web' => "\x{39B}"},
  845:       '(Mu|#924)'      => {'tex' => '{/Symbol M}', 'web' => "\x{39C}"},
  846:       '(Nu|#925)'      => {'tex' => '{/Symbol N}', 'web' => "\x{39D}"},
  847:       '(Omicron|#927)' => {'tex' => '{/Symbol O}', 'web' => "\x{39F}"},
  848:       '(Pi|#928)'      => {'tex' => '{/Symbol P}', 'web' => "\x{3A0}"},
  849:       '(Theta|#920)'   => {'tex' => '{/Symbol Q}', 'web' => "\x{398}"},
  850:       '(Rho|#929)'     => {'tex' => '{/Symbol R}', 'web' => "\x{3A1}"},
  851:       '(Sigma|#931)'   => {'tex' => '{/Symbol S}', 'web' => "\x{3A3}"},
  852:       '(Tau|#932)'     => {'tex' => '{/Symbol T}', 'web' => "\x{3A4}"},
  853:       '(Upsilon|#933)' => {'tex' => '{/Symbol U}', 'web' => "\x{3A5}"},
  854:       '(Omega|#937)'   => {'tex' => '{/Symbol W}', 'web' => "\x{3A9}"},
  855:       '(Xi|#926)'      => {'tex' => '{/Symbol X}', 'web' => "\x{39E}"},
  856:       '(Psi|#936)'     => {'tex' => '{/Symbol Y}', 'web' => "\x{3A8}"},
  857:       '(Zeta|#918)'    => {'tex' => '{/Symbol Z}', 'web' => "\x{396}"},
  858:       '(alpha|#945)'   => {'tex' => '{/Symbol a}', 'web' => "\x{3B1}"},
  859:       '(beta|#946)'    => {'tex' => '{/Symbol b}', 'web' => "\x{3B2}"},
  860:       '(chi|#967)'     => {'tex' => '{/Symbol c}', 'web' => "\x{3C7}"},
  861:       '(delta|#948)'   => {'tex' => '{/Symbol d}', 'web' => "\x{3B4}"},
  862:       '(epsilon|#949)' => {'tex' => '{/Symbol e}', 'web' => "\x{3B5}"},
  863:       '(phi|#966)'     => {'tex' => '{/Symbol f}', 'web' => "\x{3C6}"},
  864:       '(gamma|#947)'   => {'tex' => '{/Symbol g}', 'web' => "\x{3B3}"},
  865:       '(eta|#951)'     => {'tex' => '{/Symbol h}', 'web' => "\x{3B7}"},
  866:       '(iota|#953)'    => {'tex' => '{/Symbol i}', 'web' => "\x{3B9}"},
  867:       '(kappa|#954)'   => {'tex' => '{/Symbol k}', 'web' => "\x{3BA}"},
  868:       '(lambda|#955)'  => {'tex' => '{/Symbol k}', 'web' => "\x{3BB}"},
  869:       '(mu|#956)'      => {'tex' => '{/Symbol m}', 'web' => "\x{3BC}"},
  870:       '(nu|#957)'      => {'tex' => '{/Symbol n}', 'web' => "\x{3BD}"},
  871:       '(omicron|#959)' => {'tex' => '{/Symbol o}', 'web' => "\x{3BF}"},
  872:       '(pi|#960)'      => {'tex' => '{/Symbol p}', 'web' => "\x{3C0}"},
  873:       '(theta|#952)'   => {'tex' => '{/Symbol q}', 'web' => "\x{3B8}"},
  874:       '(rho|#961)'     => {'tex' => '{/Symbol r}', 'web' => "\x{3C1}"},
  875:       '(sigma|#963)'   => {'tex' => '{/Symbol s}', 'web' => "\x{3C3}"},
  876:       '(tau|#964)'     => {'tex' => '{/Symbol t}', 'web' => "\x{3C4}"},
  877:       '(upsilon|#965)' => {'tex' => '{/Symbol u}', 'web' => "\x{3C5}"},
  878:       '(omega|#969)'   => {'tex' => '{/Symbol w}', 'web' => "\x{3C9}"},
  879:       '(xi|#958)'      => {'tex' => '{/Symbol x}', 'web' => "\x{3BE}"},
  880:       '(psi|#968)'     => {'tex' => '{/Symbol y}', 'web' => "\x{3C8}"},
  881:       '(zeta|#950)'    => {'tex' => '{/Symbol z}', 'web' => "\x{3B6}"},
  882:       '(thetasym|#977)' => {'tex' => '{/Symbol \165}', 'web' => "\x{3d1}"},
  883:       '(upsih|#978)'   => {'tex' => '{/Symbol \241}', 'web' => "\x{3d2}"},
  884:       '(piv|#982)'     => {'tex' => '{/Symbol \166}', 'web' => "\x{3d6}"},
  885: 
  886: 
  887:       # Punctuation:
  888:       
  889:       '(quot|#034)'   => {'tex' =>  '\42',            'web' => '\42'},
  890:       '(amp|#038)'    => {'tex' =>  '\46',            'web' => '\46'},
  891:       '(lt|#060)'     => {'tex' =>  '\74',            'web' => '\74'},
  892:       '(gt|#062)'     => {'tex' =>  '\76',            'web' => '\76'},
  893:       '#131'          => {'tex' =>  '{/Symbol \246}', 'web' => "\x{192}"},
  894:       '#132'          => {'tex' => '{/Text \271}',    'web' => "\x{201e}"},
  895:       '#133'          => {'tex' => '{/Symbol \274}',  'web'=> "\x{2026}"},
  896:       '#134'          => {'tex' => '{/Text \262}',    'web' => "\x{2020}"},
  897:       '#135'          => {'tex' => '{/Text \263}',    'web' => "\x{2021}"},
  898:       '#136'          => {'tex' => '\\\\^',           'web' => '\\\\^'},
  899:       '#137'          => {'tex' => '%o',              'web' => "\x{2030}"}, # Per Mille <FIX>
  900:       '#138'          => {'tex' => 'S',               'web' => "\x{160}"}, # S-Caron <FIX>
  901:       '#139'          => {'tex' => '<',               'web' => '<'},
  902:       '#140'          => {'tex' => 'AE',              'web' => "\x{152}"}, # AE ligature <FIX>
  903:       '#145'          => {'tex' => '\140',            'web' => "\x{2018}"},
  904:       '#146'          => {'tex' => '\47',             'web' => "\x{2019}"},
  905:       '#147'          => {'tex' => '\140\140',        'web' => "\x{201c}"}, # Left " <FIX>
  906:       '#148'          => {'tex' => '\47\47',          'web' => '\\"'},      # Right " <FIX>
  907:       '#149'          => {'tex' => '{/Symbol \267}',  'web' => "\x{2022}"},
  908:       '#150'          => {'tex' => '{/Text \55}',     'web' => "\x{2013}"},  # en dash
  909:       '#151'          => {'tex' => '{/Symbol \55}',   'web' => "\x{2014}"},  # em dash
  910:       '#152'          => {'tex' => '\\\\~',           'web' => '\\\\~'},
  911:       '#153'          => {'tex' => '{/Symbol \324}',  'web' => "\x{2122}"}, # trademark
  912: 
  913:       # Accented letters, and other furreign language glyphs.
  914: 
  915:       '#154'          => {'tex' => 's',               'web' => "\x{161}"}, # small s-caron no ps.
  916:       '#155'          => {'tex' => '>',               'web' => '\76'},     # >
  917:       '#156'          => {'tex' => '{/Text \366}',    'web' => "\x{153}"}, # oe ligature.<FIX>
  918:       '#159',         => {'tex' => 'Y',               'web' => "\x{178}"}, # Y-umlaut - can't print <FIX>
  919:       '(nbsp|#160)'   => {'tex' => ' ',               'web' => ' '},       # non breaking space.
  920:       '(iexcl|#161)'  => {'tex' => '{/Text \241}',    'web' => "\x{a1}"},  # inverted !
  921:       '(cent|#162)'   => {'tex' => '{/Text \242}',    'web' => "\x{a2}"},  # Cent currency.
  922:       '(pound|#163)'  => {'tex' => '{/Text \243}',    'web' => "\x{a3}"},  # GB Pound currency.
  923:       '(curren|#164)' => {'tex' => '{/ZapfDingbats \161}','web' => "\x{a4}"},  # Generic currency symb. <FIX>
  924:       '(yen|#165)'    => {'tex' => '{/Text \245}',    'web' => "\x{a5}"},  # Yen currency.
  925:       '(brvbar|#166)' => {'tex' => '{/Symbol \174}',  'web' => "\x{a6}"},  # Broken vert bar no print.
  926:       '(sect|#167)'   => {'tex' => '{\247}',          'web' => "\x{a7}"},  # Section symbol.
  927:       '(uml|#168)'    => {'tex' => '{\250}',          'web' => "\x{a8}"},  # 'naked' umlaut.
  928:       '(copy|#169)'   => {'tex' => '{/Symbol \343}',  'web' => "\x{a9}"},  # Copyright symbol.
  929:       '(ordf|#170)'   => {'tex' => '{/Text \343}',    'web' => "\x{aa}"},  # Feminine ordinal.
  930:       '(laquo|#171)'  => {'tex' => '{/Text \253}',    'web' => "\x{ab}"},  # << quotes.
  931:       '(not|#172)'    => {'tex' => '\254',            'web' => "\x{ac}"},  # Logical not.
  932:       '(shy|#173)'    => {'tex' => '\255',               'web' => "\x{ad}"},  # soft hyphen.
  933:       '(reg|#174)'    => {'tex' => '{/Symbol \342}',  'web' => "\x{ae}"},  # Registered tm.
  934:       '(macr|#175)'   => {'tex' => '^{\255}',            'web' => "\x{af}"},  # 'naked' macron (overbar).
  935:       '(deg|#176)'    => {'tex' => '{/Text \260}',    'web' => "\x{b0}"},  # Degree symbo..`
  936:       '(plusmn|#177)' => {'tex' => '{/Symbol \261}',  'web' => "\x{b1}"},  # +/- symbol.
  937:       '(sup2|#178)'   => {'tex' => '^2',              'web' => "\x{b2}"},  # Superscript 2.
  938:       '(sup3|#179)'   => {'tex' => '^3',              'web' => "\x{b3}"},  # Superscript 3.
  939:       '(acute|#180)'  => {'tex' => '{/Text \222}',    'web' => "\x{b4}"},  # 'naked' acute accent.
  940:       '(micro|#181)'  => {'tex' => '{/Symbol \155}',  'web' => "\x{b5}"},  # Micro (small mu).
  941:       '(para|#182)'   => {'tex' => '{/Text \266}',    'web' => "\x{b6}"},  # Paragraph symbol.
  942:       '(middot|#183)' => {'tex' => '\267',            'web' => "\x{b7}"},  # middle dot
  943:       '(cedil|#184)'  => {'tex' => '\233',            'web' => "\x{b8}"},  # 'naked' cedilla.
  944:       '(sup1|#185)'   => {'tex' => '^1',              'web' => "\x{b9}"},  # superscript 1.
  945:       '(ordm|#186)'   => {'tex' => '{\260}',          'web' => "\x{ba}"},  # masculine ordinal.
  946:       '(raquo|#187)', => {'tex' => '\273',            'web' => "\x{bb}"},  # Right angle quotes.
  947:       '(frac14|#188)' => {'tex' => '\274',            'web' => "\x{bc}"},  # 1/4.
  948:       '(frac12|#189)' => {'tex' => '\275',            'web' => "\x{bd}"},  # 1/2.
  949:       '(frac34|#190)' => {'tex' => '\276',            'web' => "\x{be}"},  # 3/4
  950:       '(iquest|#191)' => {'tex' => '{/Text \277}',    'web' => "\x{bf}"},  # Inverted ?
  951:       '(Agrave|#192)' => {'tex' => '\300',            'web' => "\x{c0}"},  # A Grave.
  952:       '(Aacute|#193)' => {'tex' => '\301',            'web' => "\x{c1}"},  # A Acute.
  953:       '(Acirc|#194)'  => {'tex' => '\302',            'web' => "\x{c2}"},  # A Circumflex.
  954:       '(Atilde|#195)' => {'tex' => '\303',            'web' => "\x{c3}"},  # A tilde.
  955:       '(Auml|#196)'   => {'tex' => '\304',            'web' => "\x{c4}"},  # A umlaut.
  956:       '(Aring|#197)'  => {'tex' => '\305',            'web' => "\x{c5}"},  # A ring.
  957:       '(AElig|#198)'  => {'tex' => '\306',            'web' => "\x{c6}"},  # AE ligature.
  958:       '(Ccedil|#199)' => {'tex' => '\307',            'web' => "\x{c7}"},  # C cedilla
  959:       '(Egrave|#200)' => {'tex' => '\310',            'web' => "\x{c8}"},  # E Accent grave.
  960:       '(Eacute|#201)' => {'tex' => '\311',            'web' => "\x{c9}"},  # E acute accent.
  961:       '(Ecirc|#202)'  => {'tex' => '\312',            'web' => "\x{ca}"},  # E Circumflex.
  962:       '(Euml|#203)'   => {'tex' => '\313',            'web' => "\x{cb}"},  # E umlaut.
  963:       '(Igrave|#204)' => {'tex' => '\314',            'web' => "\x{cc}"},  # I grave accent.
  964:       '(Iacute|#205)' => {'tex' => '\315',            'web' => "\x{cd}"},  # I acute accent.
  965:       '(Icirc|#206)'  => {'tex' => '\316',            'web' => "\x{ce}"},  # I circumflex.
  966:       '(Iuml|#207)'   => {'tex' => '\317',            'web' => "\x{cf}"},  # I umlaut.
  967:       '(ETH|#208)'    => {'tex' => '\320',            'web' => "\x{d0}"},  # Icelandic Cap eth.
  968:       '(Ntilde|#209)' => {'tex' => '\321',            'web' => "\x{d1}"},  # Ntilde (enyan).
  969:       '(Ograve|#210)' => {'tex' => '\322',            'web' => "\x{d2}"},  # O accent grave.
  970:       '(Oacute|#211)' => {'tex' => '\323',            'web' => "\x{d3}"},  # O accent acute.
  971:       '(Ocirc|#212)'  => {'tex' => '\324',            'web' => "\x{d4}"},  # O circumflex.
  972:       '(Otilde|#213)' => {'tex' => '\325',            'web' => "\x{d5}"},  # O tilde.
  973:       '(Ouml|#214)'   => {'tex' => '\326',            'web' => "\x{d6}"},  # O umlaut.
  974:       '(times|#215)'  => {'tex' => '\327',            'web' => "\x{d7}"},  # Times symbol.
  975:       '(Oslash|#216)' => {'tex' => '\330',            'web' => "\x{d8}"},  # O slash.
  976:       '(Ugrave|#217)' => {'tex' => '\331',            'web' => "\x{d9}"},  # U accent grave.
  977:       '(Uacute|#218)' => {'tex' => '\332',            'web' => "\x{da}"},  # U accent acute.
  978:       '(Ucirc|#219)'  => {'tex' => '\333',            'web' => "\x{db}"},  # U circumflex.
  979:       '(Uuml|#220)'   => {'tex' => '\334',            'web' => "\x{dc}"},  # U umlaut.
  980:       '(Yacute|#221)' => {'tex' => '\335',            'web' => "\x{dd}"},  # Y accent acute.
  981:       '(THORN|#222)'  => {'tex' => '\336',            'web' => "\x{de}"},  # Icelandic thorn.
  982:       '(szlig|#223)'  => {'tex' => '\337',            'web' => "\x{df}"},  # German sharfes s.
  983:       '(agrave|#224)' => {'tex' => '\340',            'web' => "\x{e0}"},  # a accent grave.
  984:       '(aacute|#225)' => {'tex' => '\341',            'web' => "\x{e1}"},  # a grave.
  985:       '(acirc|#226)'  => {'tex' => '\342',            'web' => "\x{e2}"},  # a circumflex.
  986:       '(atilde|#227)' => {'tex' => '\343',            'web' => "\x{e3}"},  # a tilde.
  987:       '(auml|#228)'   => {'tex' => '\344',            'web' => "\x{e4}"},  # a umlaut
  988:       '(aring|#229)'  => {'tex' => '\345',            'web' => "\x{e5}"},  # a ring on top.
  989:       '(aelig|#230)'  => {'tex' => '\346',            'web' => "\x{e6}"},  # ae ligature.
  990:       '(ccedil|#231)' => {'tex' => '\347',            'web' => "\x{e7}"},  # C cedilla
  991:       '(egrave|#232)' => {'tex' => '\350',            'web' => "\x{e8}"},  # e accent grave.
  992:       '(eacute|#233)' => {'tex' => '\351',            'web' => "\x{e9}"},  # e accent acute.
  993:       '(ecirc|#234)'  => {'tex' => '\352',            'web' => "\x{ea}" }, # e circumflex.
  994:       '(euml|#235)'   => {'tex' => '\353',            'web' => "\x{eb}"},  # e umlaut.
  995:       '(igrave|#236)' => {'tex' => '\354',            'web' => "\x{ec}"},  # i grave.
  996:       '(iacute|#237)' => {'tex' => '\355',            'web' => "\x{ed}"},  # i acute.
  997:       '(icirc|#238)'  => {'tex' => '\356',            'web' => "\x{ee}"},  # i circumflex.
  998:       '(iuml|#239)'   => {'tex' => '\357',            'web' => "\x{ef}"},  # i umlaut.
  999:       '(eth|#240)'    => {'tex' => '\360',            'web' => "\x{f0}"},  # Icelandic eth.
 1000:       '(ntilde|#241)' => {'tex' => '\361',            'web' => "\x{f1}"},  # n tilde.
 1001:       '(ograve|#242)' => {'tex' => '\362',            'web' => "\x{f2}"},  # o grave.
 1002:       '(oacute|#243)' => {'tex' => '\363',            'web' => "\x{f3}"},  # o acute.
 1003:       '(ocirc|#244)'  => {'tex' => '\364',            'web' => "\x{f4}"},  # o circumflex.
 1004:       '(otilde|#245)' => {'tex' => '\365',            'web' => "\x{f5}"},  # o tilde.
 1005:       '(ouml|#246)'   => {'tex' => '\366',            'web' => "\x{f6}"},  # o umlaut.
 1006:       '(divide|#247)' => {'tex' => '\367',            'web' => "\x{f7}"},  # division symbol
 1007:       '(oslash|#248)' => {'tex' => '\370',            'web' => "\x{f8}"},  # o slashed.
 1008:       '(ugrave|#249)' => {'tex' => '\371',            'web' => "\x{f9}"},  # u accent grave.
 1009:       '(uacute|#250)' => {'tex' => '\372',            'web' => "\x{fa}"},  # u acute.
 1010:       '(ucirc|#251)'  => {'tex' => '\373',            'web' => "\x{fb}"},  # u circumflex.
 1011:       '(uuml|#252)'   => {'tex' => '\374',            'web' => "\x{fc}"},  # u umlaut.
 1012:       '(yacute|#253)' => {'tex' => '\375',            'web' => "\x{fd}"},  # y acute accent.
 1013:       '(thorn|#254)'  => {'tex' => '\376',            'web' => "\x{fe}"},  # small thorn (icelandic).
 1014:       '(yuml|#255)'   => {'tex' => '\377',            'web' => "\x{ff}"},  # y umlaut.
 1015:       
 1016:       # Latin extended A entities:
 1017: 
 1018:       '(OElig|#338)'  => {'tex' => '{/Text \326}',   'web' => "\x{152}"},  # OE ligature.
 1019:       '(oelig|#339)'  => {'tex' => '{/Text \366}',   'web' => "\x{153}"},  # oe ligature.
 1020:       '(Scaron|#352)' => {'tex' => 'S',              'web' => "\x{160}"},  # S caron no printable.
 1021:       '(scaron|#353)' => {'tex' => 's',              'web' => "\x{161}"},  # s caron no printable.
 1022:       '(Yuml|#376)'   => {'tex' => 'Y',              'web' => "\x{178}"},  # Y umlaut - no printable.
 1023: 
 1024:       # Latin extended B.
 1025: 
 1026:       '(fnof|#402)'  => {'tex' =>'{/Symbol \246}',    'web' => "\x{192}"},  # f with little hook.
 1027: 
 1028:       # Standalone accents:
 1029: 
 1030:       '(circ|#710)'  => {'tex' => '^',               'web' => '^'},        # circumflex.
 1031:       '(tilde|#732)' => {'tex' => '~',               'web' => '~'},        # tilde.
 1032: 
 1033:       # General punctuation.  We're not able to make a distinction between
 1034:       # the various length spacings in the print version. (e.g. en/em/thin).
 1035:       # the various joiners will be empty strings in the print version too.
 1036: 
 1037: 
 1038:       '(ensp|#8194)'   => {'tex' => ' ',              'web' => "\x{2002}"}, # en space.
 1039:       '(emsp|#8195)'   => {'tex' => ' ',              'web' => "\x{2003}"}, # em space.
 1040:       '(thinsp|#8201)' => {'tex' => ' ',              'web' => "\x{2009}"}, # thin space.
 1041:       '(zwnj|#8204)'   => {'tex' => ' ',               'web' => "\x{200c}"}, # Zero width non joiner.
 1042:       '(zwj|#8205)'    => {'tex' => ' ',               'web' => "\x{200d}"}, # Zero width joiner.
 1043:       '(lrm|#8206)'    => {'tex' => ' ',               'web' => "\x{200e}"}, # Left to right mark
 1044:       '(rlm|#8207)'    => {'tex' => ' ',               'web' => "\x{200f}"}, # right to left mark.
 1045:       '(ndash|#8211)'  => {'tex' => '{/Text \55}',    'web' => "\x{2013}"}, # en dash.
 1046:       '(mdash|#8212)'  => {'tex' => '{/Symbol \55}',  'web' => "\x{2014}"}, # em dash.
 1047:       '(lsquo|#8216)'  => {'tex' => '{/Text \140}',   'web' => "\x{2018}"}, # Left single quote.
 1048:       '(rsquo|#8217)'  => {'tex' => '\47',            'web' => "\x{2019}"}, # Right single quote.
 1049:       '(sbquo|#8218)'  => {'tex' => '\54',             'web' => "\x{201a}"}, # Single low-9 quote.
 1050:       '(ldquo|#8220)'  => {'tex' => '\42',   'web' => "\x{201c}"}, # Left double quote.
 1051:       '(rdquo|#8221)'  => {'tex' => '\42',   'web' => "\x{201d}"}, # Right double quote.
 1052:       '(bdquo|#8222)'  => {'tex' => ',',              'web' => "\x{201e}"}, # Double low-9 quote.
 1053:       '(dagger|#8224)' => {'tex' => '+',   'web' => "\x{2020}"}, # Is this a dagger I see before me now?
 1054:       '(Dagger|#8225)' => {'tex' => '\261',   'web' => "\x{2021}"}, # it's handle pointing towards my heart?
 1055:       '(bull|#8226)'   => {'tex' => '\267',           'web' => "\x{2022}"}, # Bullet.
 1056:       '(hellep|#8230)' => {'tex' => '{/Symbol \274}',   'web' => "\x{2026}"}, # Ellipses.
 1057:       '(permil|#8240)' => {'tex' => '%_o',            'web' => "\x{2031}"}, # Per mille.
 1058:       '(prime|#8242)'  => {'tex' => '\264',           'web' => "\x{2032}"}, # Prime.
 1059:       '(Prime|#8243)'  => {'tex' => '{/Symbol \262}', 'web' => "\x{2033}"}, # double prime.
 1060:       '(lsaquo|#8249)' => {'tex' => '<',              'web' => "\x{2039}"}, # < quote.
 1061:       '(rsaquo|#8250)' => {'tex' => '\74',              'web' => "\x{203a}"}, # > quote.
 1062:       '(oline|#8254)'  => {'tex' => '{/Symbol \140}', 'web' => "\x{203e}"}, # Overline.
 1063:       '(frasl|#8260)'  => {'tex' => '/',              'web' => "\x{2044}"}, # Fraction slash.
 1064:       '(euro|#8364)'   => {'tex' => '{/Symbol \240}', 'web' => "\x{20ac}"}, # Euro currency.
 1065:       
 1066:       # Letter like symbols.
 1067: 
 1068:       '(weierp|#8472)'  => {'tex' => '{/Symbol \303}', 'web' => "\x{2118}"}, # Power set symbol
 1069:       '(image|#8465)'   => {'tex' => '{/Symbol \301}', 'web' => "\x{2111}"}, # Imaginary part
 1070:       '(real|#8476)'    => {'tex' => '{/Symbol \302}', 'web' => "\x{211c}"}, # Real part.
 1071:       '(trade|#8482)'   => {'tex' => '{/Symbol \344}', 'web' => "\x{2122}"}, # trademark symbol.
 1072:       '(alefsym|#8501)' => {'tex' => '{/Symbol \300}', 'web' => "\x{2135}"}, # Hebrew alef.
 1073: 
 1074:       # Arrows  of various types and directions.
 1075:       '(larr|#8592)'    => {'tex' => '{/Symbol \254}', 'web' => "\x{2190}"}, # <--
 1076:       '(uarr|#8593)'    => {'tex' => '{/Symbol \255}', 'web' => "\x{2191}"}, # up arrow.
 1077:       '(rarr|#8594)'    => {'tex' => '{/Symbol \256}', 'web' => "\x{2192}"}, # -->
 1078:       '(darr|#8595)'    => {'tex' => '{/Symbol \257}', 'web' => "\x{2193}"}, # down arrow.
 1079:       '(harr|#8596)'    => {'tex' => '{/Symbol \253}', 'web' => "\x{2194}"}, # <-->
 1080:       '(crarr|#8629)'   => {'tex' => '{/Symbol \277}', 'web' => "\x{21b5}"}, # corner arrow down and right.
 1081:       '(lArr|#8656)'    => {'tex' => '{/Symbol \334}', 'web' => "\x{21d0}"}, # <==
 1082:       '(uArr|#8657)'    => {'tex' => '{/Symbol \335}', 'web' => "\x{21d1}"}, # Up double arrow.
 1083:       '(rArr|#8658)'    => {'tex' => '{/Symbol \336}', 'web' => "\x{21d2}"}, # ==>
 1084:       '(dArr|#8659)'    => {'tex' => '{/Symbol \337}', 'web' => "\x{21d3}"}, # Down double arrow.
 1085:       '(hArr|#8660)'    => {'tex' => '{/Symbol \333}', 'web' => "\x{21d4}"}, # <==>
 1086: 
 1087:       # Mathematical operators. For some of these we do the best we can in printing.
 1088: 
 1089:       '(forall|#8704)'  => {'tex' => '{/Symbol \42}',   'web' => "\x{2200}"}, # For all.
 1090:       '(part|#8706)'    => {'tex' => '{/Symbol d}',     'web' => "\x{2202}"}, # partial derivative
 1091:       '(exist|#8707)'   => {'tex' => '{/Symbol \44}',   'web' => "\x{2203}"}, # There exists.
 1092:       '(empty|#8709)'   => {'tex' => '{/Symbol \306}',  'web' => "\x{2205}"}, # Null set.
 1093:       '(nabla|#8711)'   => {'tex' => '{/Symbol \321}',  'web' => "\x{2207}"}, # Gradient e.g.
 1094:       '(isin|#8712)'    => {'tex' => '{/Symbol \316}',  'web' => "\x{2208}"}, # Element of the set.
 1095:       '(notin|#8713)'   => {'tex' => '{/Symbol \317}',  'web' => "\x{2209}"}, # Not an element of
 1096:       '(ni|#8715)'      => {'tex' => '{/Symbol \47}',   'web' => "\x{220b}"}, # Contains as a member
 1097:       '(prod|#8719)'    => {'tex' => '{/Symbol \325}',  'web' => "\x{220f}"}, # Product 
 1098:       '(sum|#8721)'     => {'tex' => '{/Symbol \345}',  'web' => "\x{2211}"}, # Sum of.
 1099:       '(minus|#8722)'   => {'tex' => '{/Symbol \55}',   'web' => "\x{2212}"}, # - sign.
 1100:       '(lowast|#8727)'  => {'tex' => '*',               'web' => "\x{2217}"}, # * 
 1101:       '(radic|#8730)'   => {'tex' => '{/Symbol \326}',  'web' => "\x{221a}"}, # Square root. 
 1102:       '(prop|#8733)'    => {'tex' => '{/Symbol \265}',  'web' => "\x{221d}"}, # Proportional to.
 1103:       '(infin|#8734)'   => {'tex' => '{/Symbol \245}',  'web' => "\x{221e}"}, # Infinity.
 1104:       '(ang|#8736)'     => {'tex' => '{/Symbol \320}',  'web' => "\x{2220}"}, # Angle .
 1105:       '(and|#8743)'     => {'tex' => '{/Symbol \331}',  'web' => "\x{2227}"}, # Logical and.
 1106:       '(or|#8744)'      => {'tex' => '{/Symbol \332}',  'web' => "\x{2228}"}, # Logical or.
 1107:       '(cap|#8745)'     => {'tex' => '{/Symbol \307}',  'web' => "\x{2229}"}, # Set intersection.
 1108:       '(cup|#8746)'     => {'tex' => '{/Symbol \310}',  'web' => "\x{222a}"}, # Set union.
 1109:       '(int|8747)'      => {'tex' => '{/Symbol \362}',  'web' => "\x{222b}"}, # Integral.
 1110: 
 1111:       # Some gnuplot guru will have to explain to me why the next three
 1112:       # require the extra slashes... else they print very funkily.
 1113: 
 1114:       '(there4|#8756)'  => {'tex' => '{/Symbol \\\134}',  'web' => "\x{2234}"}, # Therefore triple dots.
 1115:       '(sim|#8764)'     => {'tex' => '\\\176',               'web' => "\x{223c}"}, # Simlar to.
 1116:       '(cong|#8773)'    => {'tex' => '{/Symbol \\\100}','web' => "\x{2245}"}, # Congruent to/with.
 1117: 
 1118:       '(asymp|#8776)'   => {'tex' => '{/Symbol \273}',  'web' => "\x{2248}"}, # Asymptotic to.
 1119:       '(ne|#8800)'      => {'tex' => '{/Symbol \271}',  'web' => "\x{2260}"}, # not equal to.
 1120:       '(equiv|#8801)'   => {'tex' => '{/Symbol \272}',  'web' => "\x{2261}"}, # Equivalent to.
 1121:       '(le|8804)'       => {'tex' => '{/Symbol \243}',  'web' => "\x{2264}"}, # Less than or equal to.
 1122:       '(ge|8805)'       => {'tex' => '{/Symbol \263}',  'web' => "\x{2265}"}, # Greater than or equal to
 1123:       '(sub|8834)'      => {'tex' => '{/Symbol \314}',  'web' => "\x{2282}"}, # Subset of.
 1124:       '(sup|8835)'      => {'tex' => '{/Symbol \311}',  'web' => "\x{2283}"}, # Super set of.
 1125:       '(nsub|8836)'     => {'tex' => '{/Symbol \313}',  'web' => "\x{2284}"}, # not subset of.
 1126:       '(sube|8838)'     => {'tex' => '{/Symbol \315}',  'web' => "\x{2286}"}, # Subset or equal.
 1127:       '(supe|8839)'     => {'tex' => '{/Symbol \312}',  'web' => "\x{2287}"}, # Superset or equal
 1128:       '(oplus|8853)'    => {'tex' => '{/Symbol \305}',  'web' => "\x{2295}"}, # O with plus inside
 1129:       '(otimes|8855)'   => {'tex' => '{/Symbol \304}',  'web' => "\x{2297}"}, # O with times.
 1130:       '(perp|8869)'     => {'tex' => '{/Symbol \136}',  'web' => "\x{22a5}"}, # Perpendicular.
 1131:       '(sdot|8901)'     => {'tex' => '{/Symbol \227}',  'web' => "\x{22c5}"}, # Dot operator.
 1132: 
 1133:       # Misc. technical symbols:
 1134: 
 1135:       '(lceil|8698)'    => {'tex' => '{/Symbol \351}',  'web' => "\x{2308}"}, # Left ceiling.
 1136:       '(rceil|8969)'    => {'tex' => '{/Symbol \371}',  'web' => "\x{2309}"}, # Right ceiling.
 1137:       '(lfloor|8970)'   => {'tex' => '{/Symbol \353}',  'web' => "\x{230a}"}, # Left floor.
 1138:       '(rfloor|8971)'   => {'tex' => '{/Symbol \373}',  'web' => "\x{230b}"}, # Right floor.
 1139: 
 1140:       # The gnuplot png font evidently does not have the big angle brackets at
 1141:       # positions 0x2329, 0x232a so use ordinary brackets.
 1142: 
 1143:       '(lang|9001)'     => {'tex' => '{/Symbol \341}',  'web' => '<'}, # Left angle bracket.
 1144:       '(rang|9002)'     => {'tex' => '{/Symbol \361}',  'web' => '>'}, # Right angle bracket.
 1145: 
 1146:       # Gemoetric shapes.
 1147: 
 1148:       '(loz|9674)'      => {'tex' => '{/Symbol \340}',  'web' => "\x{25ca}"}, # Lozenge.
 1149: 
 1150:       # Misc. symbols
 1151: 
 1152:       '(spades|9824)'   => {'tex' => '{/Symbol \252}', 'web' => "\x{2660}"}, 
 1153:       '(clubs|9827)'    => {'tex' => '{/Symbol \247}', 'web' => "\x{2663}"}, 
 1154:       '(hearts|9829)'   => {'tex' => '{/Symbol \251}', 'web' => "\x{2665}"}, 
 1155:       '(diams|9830)'    => {'tex' => '{/Symbol \250}', 'web' => "\x{2666}"}
 1156: 
 1157:     );
 1158: 
 1159: 
 1160: sub replace_entities {
 1161:     my ($target,$text) = @_;
 1162:     $text =~ s{([_^~\{\}]|\\\\)}{\\\\$1}g;
 1163:     while (my ($re, $replace) = each(%lookup)) {
 1164: 	my $repl = $replace->{$target};
 1165: 	$text =~ s/&$re;/$replace->{$target}/g;
 1166:     }
 1167:     $text =~ s{(&)}{\\\\$1}g;
 1168:     return $text;
 1169: }
 1170: 
 1171: ##------------------------------------------------------------------- title
 1172: sub start_title {
 1173:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1174:     my $result='';
 1175:     if ($target eq 'web' || $target eq 'tex') {
 1176: 	$title = &Apache::lonxml::get_all_text("/title",$parser,$style);
 1177: 	$title=&Apache::run::evaluate($title,$safeeval,$$parstack[-1]);
 1178: 	$title =~ s/\n/ /g;
 1179: 	if (length($title) > $max_str_len) {
 1180: 	    $title = substr($title,0,$max_str_len);
 1181: 	}
 1182: 	$title = &parse_label($target,$title);
 1183:     } elsif ($target eq 'edit') {
 1184: 	$result.=&Apache::edit::tag_start($target,$token,'Plot Title');
 1185: 	my $text=&Apache::lonxml::get_all_text("/title",$parser,$style);
 1186: 	$result.=&Apache::edit::editline('',$text,'',60);
 1187:     } elsif ($target eq 'modified') {
 1188: 	$result.=&Apache::edit::rebuild_tag($token);
 1189: 	$result.=&Apache::edit::modifiedfield("/title",$parser);
 1190:     }
 1191:     return $result;
 1192: }
 1193: 
 1194: sub end_title {
 1195:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1196:     my $result = '';
 1197:     if ($target eq 'web' || $target eq 'tex') {
 1198:     } elsif ($target eq 'edit') {
 1199: 	$result.=&Apache::edit::tag_end($target,$token);
 1200:     }
 1201:     return $result;
 1202: }
 1203: ##------------------------------------------------------------------- xlabel
 1204: sub start_xlabel {
 1205:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1206:     my $result='';
 1207:     if ($target eq 'web' || $target eq 'tex') {
 1208: 	$xlabel = &Apache::lonxml::get_all_text("/xlabel",$parser,$style);
 1209: 	$xlabel=&Apache::run::evaluate($xlabel,$safeeval,$$parstack[-1]);
 1210: 	$xlabel =~ s/\n/ /g;
 1211: 	if (length($xlabel) > $max_str_len) {
 1212: 	    $xlabel = substr($xlabel,0,$max_str_len);
 1213: 	}
 1214: 	$xlabel = &parse_label($target,$xlabel);
 1215:     } elsif ($target eq 'edit') {
 1216: 	$result.=&Apache::edit::tag_start($target,$token,'Plot Xlabel');
 1217: 	my $text=&Apache::lonxml::get_all_text("/xlabel",$parser,$style);
 1218: 	$result.=&Apache::edit::editline('',$text,'',60);
 1219:     } elsif ($target eq 'modified') {
 1220: 	$result.=&Apache::edit::rebuild_tag($token);	
 1221: 	$result.=&Apache::edit::modifiedfield("/xlabel",$parser);
 1222:     }
 1223:     return $result;
 1224: }
 1225: 
 1226: sub end_xlabel {
 1227:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1228:     my $result = '';
 1229:     if ($target eq 'web' || $target eq 'tex') {
 1230:     } elsif ($target eq 'edit') {
 1231: 	$result.=&Apache::edit::tag_end($target,$token);
 1232:     }
 1233:     return $result;
 1234: }
 1235: 
 1236: ##------------------------------------------------------------------- ylabel
 1237: sub start_ylabel {
 1238:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1239:     my $result='';
 1240:     if ($target eq 'web' || $target eq 'tex') {
 1241: 	$ylabel = &Apache::lonxml::get_all_text("/ylabel",$parser,$style);
 1242: 	$ylabel = &Apache::run::evaluate($ylabel,$safeeval,$$parstack[-1]);
 1243: 	$ylabel =~ s/\n/ /g;
 1244: 	if (length($ylabel) > $max_str_len) {
 1245: 	    $ylabel = substr($ylabel,0,$max_str_len);
 1246: 	}
 1247: 	$ylabel = &parse_label($target,$ylabel);
 1248:     } elsif ($target eq 'edit') {
 1249: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Ylabel');
 1250: 	my $text = &Apache::lonxml::get_all_text("/ylabel",$parser,$style);
 1251: 	$result .= &Apache::edit::editline('',$text,'',60);
 1252:     } elsif ($target eq 'modified') {
 1253: 	$result.=&Apache::edit::rebuild_tag($token);
 1254: 	$result.=&Apache::edit::modifiedfield("/ylabel",$parser);
 1255:     }
 1256:     return $result;
 1257: }
 1258: 
 1259: sub end_ylabel {
 1260:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1261:     my $result = '';
 1262:     if ($target eq 'web' || $target eq 'tex') {
 1263:     } elsif ($target eq 'edit') {
 1264: 	$result.=&Apache::edit::tag_end($target,$token);
 1265:     }
 1266:     return $result;
 1267: }
 1268: 
 1269: ##------------------------------------------------------------------- label
 1270: sub start_label {
 1271:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1272:     my $result='';
 1273:     if ($target eq 'web' || $target eq 'tex') {
 1274: 	my %label;
 1275: 	&get_attributes(\%label,\%label_defaults,$parstack,$safeeval,
 1276: 		    $tagstack->[-1]);
 1277: 	my $text = &Apache::lonxml::get_all_text("/label",$parser,$style);
 1278: 	$text = &Apache::run::evaluate($text,$safeeval,$$parstack[-1]);
 1279: 	$text =~ s/\n/ /g;
 1280: 	$text = substr($text,0,$max_str_len) if (length($text) > $max_str_len);
 1281: 	$label{'text'} = &parse_label($target,$text);
 1282: 	push(@labels,\%label);
 1283:     } elsif ($target eq 'edit') {
 1284: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Label');
 1285: 	$result .= &edit_attributes($target,$token,\%label_defaults);
 1286: 	my $text = &Apache::lonxml::get_all_text("/label",$parser,$style);
 1287: 	$result .= &Apache::edit::end_row().
 1288: 	    &Apache::edit::start_spanning_row().
 1289: 	    &Apache::edit::editline('',$text,'',60);
 1290:     } elsif ($target eq 'modified') {
 1291: 	&Apache::edit::get_new_args
 1292: 	    ($token,$parstack,$safeeval,keys(%label_defaults));
 1293: 	$result.=&Apache::edit::rebuild_tag($token);
 1294: 	$result.=&Apache::edit::modifiedfield("/label",$parser);
 1295:     }
 1296:     return $result;
 1297: }
 1298: 
 1299: sub end_label {
 1300:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1301:     my $result = '';
 1302:     if ($target eq 'web' || $target eq 'tex') {
 1303:     } elsif ($target eq 'edit') {
 1304: 	$result.=&Apache::edit::tag_end($target,$token);
 1305:     }
 1306:     return $result;
 1307: }
 1308: 
 1309: ##------------------------------------------------------------------- curve
 1310: sub start_curve {
 1311:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1312:     my $result='';
 1313:     &Apache::lonxml::register('Apache::lonplot',('function','data'));
 1314:     push (@Apache::lonxml::namespace,'curve');
 1315:     if ($target eq 'web' || $target eq 'tex') {
 1316: 	my %curve;
 1317: 	&get_attributes(\%curve,\%curve_defaults,$parstack,$safeeval,
 1318: 		    $tagstack->[-1]);
 1319: 	push (@curves,\%curve);
 1320:     } elsif ($target eq 'edit') {
 1321: 	$result .= &Apache::edit::tag_start($target,$token,'Curve');
 1322: 	$result .= &edit_attributes($target,$token,\%curve_defaults,
 1323:                                     \@curve_edit_order)
 1324: 	    .&Apache::edit::end_row()
 1325: 	    .&Apache::edit::start_spanning_row();
 1326: 
 1327:     } elsif ($target eq 'modified') {
 1328: 	my $constructtag=&Apache::edit::get_new_args
 1329: 	    ($token,$parstack,$safeeval,keys(%curve_defaults));
 1330: 	if ($constructtag) {
 1331: 	    $result = &Apache::edit::rebuild_tag($token);
 1332: 	}
 1333:     }
 1334:     return $result;
 1335: }
 1336: 
 1337: sub end_curve {
 1338:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1339:     my $result = '';
 1340:     pop @Apache::lonxml::namespace;
 1341:     &Apache::lonxml::deregister('Apache::lonplot',('function','data'));
 1342:     if ($target eq 'web' || $target eq 'tex') {
 1343:     } elsif ($target eq 'edit') {
 1344: 	$result.=&Apache::edit::tag_end($target,$token);
 1345:     }
 1346:     return $result;
 1347: }
 1348: 
 1349: ##------------------------------------------------------------ curve function
 1350: sub start_function {
 1351:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1352:     my $result='';
 1353:     if ($target eq 'web' || $target eq 'tex') {
 1354: 	if (exists($curves[-1]->{'data'})) {
 1355: 	    &Apache::lonxml::warning
 1356:                 ('Use of the <b>curve function</b> tag precludes use of '.
 1357:                  ' the <b>curve data</b> tag.  '.
 1358:                  'The curve data tag will be omitted in favor of the '.
 1359:                  'curve function declaration.');
 1360: 	    delete $curves[-1]->{'data'} ;
 1361: 	}
 1362:         my $function = &Apache::lonxml::get_all_text("/function",$parser,
 1363: 						     $style);
 1364: 	$function = &Apache::run::evaluate($function,$safeeval,$$parstack[-1]);
 1365: 	$curves[-1]->{'function'} = $function; 
 1366:     } elsif ($target eq 'edit') {
 1367: 	$result .= &Apache::edit::tag_start($target,$token,'Gnuplot compatible curve function');
 1368: 	my $text = &Apache::lonxml::get_all_text("/function",$parser,$style);
 1369: 	$result .= &Apache::edit::editline('',$text,'',60);
 1370:     } elsif ($target eq 'modified') {
 1371: 	$result.=&Apache::edit::rebuild_tag($token);
 1372: 	$result.=&Apache::edit::modifiedfield("/function",$parser);
 1373:     }
 1374:     return $result;
 1375: }
 1376: 
 1377: sub end_function {
 1378:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1379:     my $result = '';
 1380:     if ($target eq 'web' || $target eq 'tex') {
 1381:     } elsif ($target eq 'edit') {
 1382: 	$result .= &Apache::edit::end_table();
 1383:     }
 1384:     return $result;
 1385: }
 1386: 
 1387: ##------------------------------------------------------------ curve  data
 1388: sub start_data {
 1389:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1390:     my $result='';
 1391:     if ($target eq 'web' || $target eq 'tex') {
 1392: 	if (exists($curves[-1]->{'function'})) {
 1393: 	    &Apache::lonxml::warning
 1394:                 ('Use of the <b>curve function</b> tag precludes use of '.
 1395:                  ' the <b>curve data</b> tag.  '.
 1396:                  'The curve function tag will be omitted in favor of the '.
 1397:                  'curve data declaration.');
 1398: 	    delete($curves[-1]->{'function'});
 1399: 	}
 1400: 	my $datatext = &Apache::lonxml::get_all_text("/data",$parser,$style);
 1401: 	$datatext=&Apache::run::evaluate($datatext,$safeeval,$$parstack[-1]);
 1402: 	# Deal with cases where we're given an array...
 1403: 	if ($datatext =~ /^\@/) {
 1404: 	    $datatext = &Apache::run::run('return "'.$datatext.'"',
 1405: 					  $safeeval,1);
 1406: 	}
 1407: 	$datatext =~ s/\s+/ /g;
 1408: 	# Need to do some error checking on the @data array - 
 1409: 	# make sure it's all numbers and make sure each array 
 1410: 	# is of the same length.
 1411: 	my @data;
 1412: 	if ($datatext =~ /,/) { # comma deliminated
 1413: 	    @data = split /,/,$datatext;
 1414: 	} else { # Assume it's space separated.
 1415: 	    @data = split / /,$datatext;
 1416: 	}
 1417: 	for (my $i=0;$i<=$#data;$i++) {
 1418: 	    # Check that it's non-empty
 1419: 	    if (! defined($data[$i])) {
 1420: 		&Apache::lonxml::warning(
 1421: 		    'undefined curve data value.  Replacing with '.
 1422: 		    ' pi/e = 1.15572734979092');
 1423: 		$data[$i] = 1.15572734979092;
 1424: 	    }
 1425: 	    # Check that it's a number
 1426: 	    if (! &$real_test($data[$i]) & ! &$int_test($data[$i])) {
 1427: 		&Apache::lonxml::warning(
 1428: 		    'Bad curve data value of '.$data[$i].'  Replacing with '.
 1429: 		    ' pi/e = 1.15572734979092');
 1430: 		$data[$i] = 1.15572734979092;
 1431: 	    }
 1432: 	}
 1433: 	# complain if the number of data points is not the same as
 1434: 	# in previous sets of data.
 1435: 	if (($curves[-1]->{'data'}) && ($#data != $#{@{$curves[-1]->{'data'}->[0]}})){
 1436: 	    &Apache::lonxml::warning
 1437: 		('Number of data points is not consistent with previous '.
 1438: 		 'number of data points');
 1439: 	}
 1440: 	push  @{$curves[-1]->{'data'}},\@data;
 1441:     } elsif ($target eq 'edit') {
 1442: 	$result .= &Apache::edit::tag_start($target,$token,'Comma or space deliminated curve data');
 1443: 	my $text = &Apache::lonxml::get_all_text("/data",$parser,$style);
 1444: 	$result .= &Apache::edit::editline('',$text,'',60);
 1445:     } elsif ($target eq 'modified') {
 1446: 	$result.=&Apache::edit::rebuild_tag($token);
 1447: 	$result.=&Apache::edit::modifiedfield("/data",$parser);
 1448:     }
 1449:     return $result;
 1450: }
 1451: 
 1452: sub end_data {
 1453:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1454:     my $result = '';
 1455:     if ($target eq 'web' || $target eq 'tex') {
 1456:     } elsif ($target eq 'edit') {
 1457: 	$result .= &Apache::edit::end_table();
 1458:     }
 1459:     return $result;
 1460: }
 1461: 
 1462: ##------------------------------------------------------------------- axis
 1463: sub start_axis {
 1464:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1465:     my $result='';
 1466:     if ($target eq 'web' || $target eq 'tex') {
 1467: 	&get_attributes(\%axis,\%axis_defaults,$parstack,$safeeval,
 1468: 			$tagstack->[-1]);
 1469:     } elsif ($target eq 'edit') {
 1470: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Axes');
 1471: 	$result .= &edit_attributes($target,$token,\%axis_defaults,
 1472: 				    \@axis_edit_order);
 1473:     } elsif ($target eq 'modified') {
 1474: 	my $constructtag=&Apache::edit::get_new_args
 1475: 	    ($token,$parstack,$safeeval,keys(%axis_defaults));
 1476: 	if ($constructtag) {
 1477: 	    $result = &Apache::edit::rebuild_tag($token);
 1478: 	}
 1479:     }
 1480:     return $result;
 1481: }
 1482: 
 1483: sub end_axis {
 1484:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1485:     my $result = '';
 1486:     if ($target eq 'web' || $target eq 'tex') {
 1487:     } elsif ($target eq 'edit') {
 1488: 	$result.=&Apache::edit::tag_end($target,$token);
 1489:     } elsif ($target eq 'modified') {
 1490:     }
 1491:     return $result;
 1492: }
 1493: 
 1494: ###################################################################
 1495: ##                                                               ##
 1496: ##        Utility Functions                                      ##
 1497: ##                                                               ##
 1498: ###################################################################
 1499: 
 1500: ##----------------------------------------------------------- set_defaults
 1501: sub set_defaults {
 1502:     my ($var,$defaults) = @_;
 1503:     my $key;
 1504:     foreach $key (keys(%$defaults)) {
 1505: 	$var->{$key} = $defaults->{$key}->{'default'};
 1506:     }
 1507: }
 1508: 
 1509: ##------------------------------------------------------------------- misc
 1510: sub get_attributes{
 1511:     my ($values,$defaults,$parstack,$safeeval,$tag) = @_;
 1512:     foreach my $attr (keys(%{$defaults})) {
 1513: 	if ($attr eq 'texwidth' || $attr eq 'texfont') {
 1514: 	    $values->{$attr} = 
 1515: 		&Apache::lonxml::get_param($attr,$parstack,$safeeval,undef,1);
 1516: 	} else {
 1517: 	    $values->{$attr} = 
 1518: 		&Apache::lonxml::get_param($attr,$parstack,$safeeval);
 1519: 	}
 1520: 	if ($values->{$attr} eq '' | !defined($values->{$attr})) {
 1521: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
 1522: 	    next;
 1523: 	}
 1524: 	my $test = $defaults->{$attr}->{'test'};
 1525: 	if (! &$test($values->{$attr})) {
 1526: 	    &Apache::lonxml::warning
 1527: 		($tag.':'.$attr.': Bad value.'.'Replacing your value with : '
 1528: 		 .$defaults->{$attr}->{'default'} );
 1529: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
 1530: 	}
 1531:     }
 1532:     return ;
 1533: }
 1534: 
 1535: ##------------------------------------------------------- write_gnuplot_file
 1536: sub write_gnuplot_file {
 1537:     my ($tmpdir,$filename,$target)= @_;
 1538:     my ($fontsize, $font_properties) =  &get_font($target);
 1539:     my $gnuplot_input = '';
 1540:     my $curve;
 1541:     #
 1542:     # Check to be sure we do not have any empty curves
 1543:     my @curvescopy;
 1544:     foreach my $curve (@curves) {
 1545:         if (exists($curve->{'function'})) {
 1546:             if ($curve->{'function'} !~ /^\s*$/) {
 1547:                 push(@curvescopy,$curve);
 1548:             }
 1549:         } elsif (exists($curve->{'data'})) {
 1550:             foreach my $data (@{$curve->{'data'}}) {
 1551:                 if (scalar(@$data) > 0) {
 1552:                     push(@curvescopy,$curve);
 1553:                     last;
 1554:                 }
 1555:             }
 1556:         }
 1557:     }
 1558:     @curves = @curvescopy;
 1559:     # Collect all the colors
 1560:     my @Colors;
 1561:     push @Colors, $Apache::lonplot::plot{'bgcolor'};
 1562:     push @Colors, $Apache::lonplot::plot{'fgcolor'}; 
 1563:     push @Colors, (defined($axis{'color'})?$axis{'color'}:$Apache::lonplot::plot{'fgcolor'});
 1564:     foreach $curve (@curves) {
 1565: 	push @Colors, ($curve->{'color'} ne '' ? 
 1566: 		       $curve->{'color'}       : 
 1567: 		       $Apache::lonplot::plot{'fgcolor'}        );
 1568:     }
 1569:     # set term
 1570:     if ($target eq 'web') {
 1571: 	$gnuplot_input .= 'set terminal png enhanced nocrop ';
 1572: 	$gnuplot_input .= 'transparent ' if ($Apache::lonplot::plot{'transparent'} eq 'on');
 1573: 	$gnuplot_input .= 'font "'.$Apache::lonnet::perlvar{'lonFontsDir'}.
 1574: 	    '/'.$font_properties->{'file'}.'.ttf" ';
 1575: 	$gnuplot_input .= $fontsize;
 1576: 	$gnuplot_input .= ' size '.$Apache::lonplot::plot{'width'}.','.$Apache::lonplot::plot{'height'}.' ';
 1577: 	$gnuplot_input .= "@Colors\n";
 1578: 	# set output
 1579: 	$gnuplot_input .= "set output\n";
 1580:     } elsif ($target eq 'tex') {
 1581: 	$gnuplot_input .= "set term postscript eps enhanced $Apache::lonplot::plot{'plotcolor'} solid ";
 1582: 	if (!$font_properties->{'tex_no_file'}) {
 1583: 	    $gnuplot_input .=
 1584: 		'fontfile "'.$Apache::lonnet::perlvar{'lonFontsDir'}.
 1585: 		'/'.$font_properties->{'file'}.'.pfb" ';
 1586: 	}
 1587: 	$gnuplot_input .= ' "'.$font_properties->{'printname'}.'" ';
 1588: 	$gnuplot_input .= $fontsize;
 1589: 	$gnuplot_input .= "\nset output \"/home/httpd/perl/tmp/".
 1590: 	    &unescape($filename).".eps\"\n";
 1591: 	$gnuplot_input .= "set encoding iso_8859_1\n"; # Get access to extended font.
 1592: 
 1593:     }
 1594:     # cartesian or polar plot?
 1595:     if (lc($Apache::lonplot::plot{'plottype'}) eq 'polar') {
 1596:         $gnuplot_input .= 'set polar'.$/;
 1597:     } else {
 1598:         # Assume Cartesian
 1599:     }
 1600:     # cartesian or polar grid?
 1601:     if (lc($Apache::lonplot::plot{'gridtype'}) eq 'polar') {
 1602:         $gnuplot_input .= 'set grid polar'.$/;
 1603:     } elsif (lc($Apache::lonplot::plot{'gridtype'}) eq 'linear-log') {
 1604:         $gnuplot_input .= 'set logscale x'.$/;
 1605:     } elsif (lc($Apache::lonplot::plot{'gridtype'}) eq 'log-linear') {
 1606:         $gnuplot_input .= 'set logscale y'.$/;
 1607:     } elsif (lc($Apache::lonplot::plot{'gridtype'}) eq 'log-log') {
 1608:         $gnuplot_input .= 'set logscale x'.$/;
 1609:         $gnuplot_input .= 'set logscale y'.$/;
 1610:     } else {
 1611:         # Assume Cartesian
 1612:     }
 1613:     # solid or pattern for boxes?
 1614:     if (lc($Apache::lonplot::plot{'fillstyle'}) eq 'solid') {
 1615:         $gnuplot_input .= 'set style fill solid '.
 1616: 	    $Apache::lonplot::plot{'solid'}.$Apache::lonplot::plot{'box_border'}.$/;
 1617:     } elsif (lc($Apache::lonplot::plot{'fillstyle'}) eq 'pattern') {
 1618:         $gnuplot_input .= 'set style fill pattern '.$Apache::lonplot::plot{'pattern'}.$Apache::lonplot::plot{'box_border'}.$/;
 1619:     } elsif (lc($Apache::lonplot::plot{'fillstyle'}) eq 'empty') {
 1620:     }
 1621:     # margin
 1622:     if (lc($Apache::lonplot::plot{'lmargin'}) ne 'default') {
 1623:         $gnuplot_input .= 'set lmargin '.$Apache::lonplot::plot{'lmargin'}.$/;
 1624:     }
 1625:     if (lc($Apache::lonplot::plot{'rmargin'}) ne 'default') {
 1626:         $gnuplot_input .= 'set rmargin '.$Apache::lonplot::plot{'rmargin'}.$/;
 1627:     }
 1628:     if (lc($Apache::lonplot::plot{'tmargin'}) ne 'default') {
 1629:         $gnuplot_input .= 'set tmargin '.$Apache::lonplot::plot{'tmargin'}.$/;
 1630:     }
 1631:     if (lc($Apache::lonplot::plot{'bmargin'}) ne 'default') {
 1632:         $gnuplot_input .= 'set bmargin '.$Apache::lonplot::plot{'bmargin'}.$/;
 1633:     }
 1634: 
 1635:     # tic scales
 1636:     if ($version > 4) {
 1637: 	$gnuplot_input .= 'set tics scale '.
 1638: 	    $Apache::lonplot::plot{'major_ticscale'}.', '.$Apache::lonplot::plot{'minor_ticscale'}.$/;
 1639:     } else {
 1640:     	$gnuplot_input .= 'set ticscale '.
 1641: 	    $Apache::lonplot::plot{'major_ticscale'}.' '.$Apache::lonplot::plot{'minor_ticscale'}.$/;
 1642:     }
 1643:     #boxwidth
 1644:     if (lc($Apache::lonplot::plot{'boxwidth'}) ne '') {
 1645: 	$gnuplot_input .= 'set boxwidth '.$Apache::lonplot::plot{'boxwidth'}.$/;
 1646:     }
 1647:     # gridlayer
 1648:     $gnuplot_input .= 'set grid noxtics noytics front '.$/ 
 1649: 	if ($Apache::lonplot::plot{'gridlayer'} eq 'on');
 1650: 
 1651:     # grid
 1652:     $gnuplot_input .= 'set grid'.$/ if ($Apache::lonplot::plot{'grid'} eq 'on');
 1653:     # border
 1654:     $gnuplot_input .= ($Apache::lonplot::plot{'border'} eq 'on'?
 1655: 		       'set border'.$/           :
 1656: 		       'set noborder'.$/         );
 1657:     # sampling rate for non-data curves
 1658:     $gnuplot_input .= "set samples $Apache::lonplot::plot{'samples'}\n";
 1659:     # title, xlabel, ylabel
 1660:     # titles
 1661:     my $extra_space_x = ($xtics{'location'} eq 'axis') ? ' 0, -0.5 ' : '';
 1662:     my $extra_space_y = ($ytics{'location'} eq 'axis') ? ' -0.5, 0 ' : '';
 1663: 
 1664:     if ($target eq 'tex') {
 1665: 	$gnuplot_input .= "set title  \"$title\"          font \"".$font_properties->{'printname'}.",".$fontsize."pt\"\n" if (defined($title)) ;
 1666: 	$gnuplot_input .= "set xlabel \"$xlabel\" $extra_space_x font \"".$font_properties->{'printname'}.",".$fontsize."pt\"\n" if (defined($xlabel));
 1667: 	$gnuplot_input .= "set ylabel \"$ylabel\" $extra_space_y font \"".$font_properties->{'printname'}.",".$fontsize."pt\"\n" if (defined($ylabel));
 1668:     } else {
 1669:         $gnuplot_input .= "set title  \"$title\"          \n" if (defined($title)) ;
 1670:         $gnuplot_input .= "set xlabel \"$xlabel\" $extra_space_x \n" if (defined($xlabel));
 1671:         $gnuplot_input .= "set ylabel \"$ylabel\" $extra_space_y \n" if (defined($ylabel));
 1672:     }
 1673:     # tics
 1674:     if (%xtics) {    
 1675: 	$gnuplot_input .= "set xtics $xtics{'location'} ";
 1676: 	$gnuplot_input .= ( $xtics{'mirror'} eq 'on'?"mirror ":"nomirror ");
 1677: 	$gnuplot_input .= "$xtics{'start'}, ";
 1678: 	$gnuplot_input .= "$xtics{'increment'}, ";
 1679: 	$gnuplot_input .= "$xtics{'end'} ";
 1680: 	if ($target eq 'tex') {
 1681: 	    $gnuplot_input .= 'font "Helvetica,22"';     # Needed in iso 8859-1 enc.
 1682: 	}
 1683: 	$gnuplot_input .= "\n";
 1684:         if ($xtics{'minorfreq'} != 0) {
 1685:             $gnuplot_input .= "set mxtics ".$xtics{'minorfreq'}."\n";
 1686:         } 
 1687:     } else {
 1688: 	if ($target eq 'tex') {
 1689: 	    $gnuplot_input .= 'set xtics font "Helvetica,22"'."\n"; # needed in iso 8859-1 enc
 1690: 	}
 1691:     }
 1692:     if (%ytics) {    
 1693: 	$gnuplot_input .= "set ytics $ytics{'location'} ";
 1694: 	$gnuplot_input .= ( $ytics{'mirror'} eq 'on'?"mirror ":"nomirror ");
 1695: 	$gnuplot_input .= "$ytics{'start'}, ";
 1696: 	$gnuplot_input .= "$ytics{'increment'}, ";
 1697:         $gnuplot_input .= "$ytics{'end'} ";
 1698:         if ($ytics{'minorfreq'} != 0) {
 1699:             $gnuplot_input .= "set mytics ".$ytics{'minorfreq'}."\n";
 1700:         } 
 1701: 	if ($target eq 'tex') {
 1702: 	    $gnuplot_input .= 'font "Helvetica,22"'; # Needed in iso-8859-1 encoding.
 1703: 	}
 1704: 	$gnuplot_input .= "\n";
 1705: 
 1706:     } else {
 1707: 	if ($target eq 'tex') {
 1708: 	    $gnuplot_input .= 'set ytics font "Helvetica,22"'."\n"; # Needed for iso 8859-1 enc.
 1709: 	}
 1710:     }
 1711:     # axis
 1712:     if (%axis) {
 1713:         if ($axis{'xformat'} ne 'on') {
 1714:             $gnuplot_input .= "set format x ";
 1715:             if ($axis{'xformat'} eq 'off') {
 1716:                 $gnuplot_input .= "\"\"\n";
 1717:             } else {
 1718:                 $gnuplot_input .= "\"\%.".$axis{'xformat'}."\"\n";
 1719:             }
 1720:         }
 1721:         if ($axis{'yformat'} ne 'on') {
 1722:             $gnuplot_input .= "set format y ";
 1723:             if ($axis{'yformat'} eq 'off') {
 1724:                 $gnuplot_input .= "\"\"\n";
 1725:             } else {
 1726:                 $gnuplot_input .= "\"\%.".$axis{'yformat'}."\"\n";
 1727:             }
 1728:         }
 1729: 	$gnuplot_input .= "set xrange \[$axis{'xmin'}:$axis{'xmax'}\]\n";
 1730: 	$gnuplot_input .= "set yrange \[$axis{'ymin'}:$axis{'ymax'}\]\n";
 1731:     }
 1732:     # Key
 1733:     if (%key) {
 1734: 	$gnuplot_input .= 'set key '.$key{'pos'}.' ';
 1735: 	if ($key{'title'} ne '') {
 1736: 	    $gnuplot_input .= 'title "'.$key{'title'}.'" ';
 1737: 	} 
 1738: 	$gnuplot_input .= ($key{'box'} eq 'on' ? 'box ' : 'nobox ').$/;
 1739:     } else {
 1740: 	$gnuplot_input .= 'set nokey'.$/;
 1741:     }
 1742:     # labels
 1743:     my $label;
 1744:     foreach $label (@labels) {
 1745: 	$gnuplot_input .= 'set label "'.$label->{'text'}.'" at '.
 1746:                           $label->{'xpos'}.','.$label->{'ypos'};
 1747:         if ($label->{'rotate'} ne '') {
 1748:             $gnuplot_input .= ' rotate by '.$label->{'rotate'};
 1749:         }
 1750:         $gnuplot_input .= ' '.$label->{'justify'};
 1751: 
 1752:         if ($target eq 'tex') {
 1753: 	    $gnuplot_input .=' font "'.$font_properties->{'printname'}.','.$fontsize.'pt"' ;
 1754:         }
 1755:         $gnuplot_input .= $/;
 1756:     }
 1757:     if ($target eq 'tex') {
 1758:         $gnuplot_input .="set size 1,".$Apache::lonplot::plot{'height'}/$Apache::lonplot::plot{'width'}*1.38;
 1759:         $gnuplot_input .="\n";
 1760:     }
 1761:     # curves
 1762:     $gnuplot_input .= 'plot ';
 1763:     for (my $i = 0;$i<=$#curves;$i++) {
 1764: 	$curve = $curves[$i];
 1765: 	$gnuplot_input.= ', ' if ($i > 0);
 1766: 	if ($target eq 'tex') {
 1767: 	    $curve->{'linewidth'} *= 2;
 1768: 	}
 1769: 	if (exists($curve->{'function'})) {
 1770: 	    $gnuplot_input.= 
 1771: 		$curve->{'function'}.' title "'.
 1772: 		$curve->{'name'}.'" with '.
 1773:                 $curve->{'linestyle'};
 1774: 
 1775:             if (($curve->{'linestyle'} eq 'points')      ||
 1776:                 ($curve->{'linestyle'} eq 'linespoints') ||
 1777:                 ($curve->{'linestyle'} eq 'errorbars')   ||
 1778:                 ($curve->{'linestyle'} eq 'xerrorbars')  ||
 1779:                 ($curve->{'linestyle'} eq 'yerrorbars')  ||
 1780:                 ($curve->{'linestyle'} eq 'xyerrorbars')) {
 1781:                 $gnuplot_input.=' pointtype '.$curve->{'pointtype'};
 1782:                 $gnuplot_input.=' pointsize '.$curve->{'pointsize'};
 1783:             } elsif ($curve->{'linestyle'} eq 'filledcurves') { 
 1784:                 $gnuplot_input.= ' '.$curve->{'limit'};
 1785:             } elsif ($curve->{'linetype'} ne '' &&
 1786:                      $curve->{'linestyle'} eq 'lines') {
 1787:                 $gnuplot_input.= ' linetype ';
 1788:                 $gnuplot_input.= $linetypes{$curve->{'linetype'}};
 1789:                 $gnuplot_input.= ' linecolor rgb "';
 1790:                 # convert color from xaaaaaa to #aaaaaa
 1791:                 $curve->{'color'} =~ s/^x/#/;
 1792:                 $gnuplot_input.= $curve->{'color'}.'"';
 1793:             }
 1794:             $gnuplot_input.= ' linewidth '.$curve->{'linewidth'};
 1795: 
 1796: 	} elsif (exists($curve->{'data'})) {
 1797: 	    # Store data values in $datatext
 1798: 	    my $datatext = '';
 1799: 	    #   get new filename
 1800: 	    my $datafilename = "$tmpdir/$filename.data.$i";
 1801: 	    my $fh=Apache::File->new(">$datafilename");
 1802: 	    # Compile data
 1803: 	    my @Data = @{$curve->{'data'}};
 1804: 	    my @Data0 = @{$Data[0]};
 1805: 	    for (my $i =0; $i<=$#Data0; $i++) {
 1806: 		my $dataset;
 1807: 		foreach $dataset (@Data) {
 1808: 		    $datatext .= $dataset->[$i] . ' ';
 1809: 		}
 1810: 		$datatext .= $/;
 1811: 	    }
 1812: 	    #   write file
 1813: 	    print $fh $datatext;
 1814: 	    close($fh);
 1815: 	    #   generate gnuplot text
 1816: 	    $gnuplot_input.= '"'.$datafilename.'" title "'.
 1817: 		$curve->{'name'}.'" with '.
 1818: 		$curve->{'linestyle'};
 1819:             if (($curve->{'linestyle'} eq 'points')      ||
 1820:                 ($curve->{'linestyle'} eq 'linespoints') ||
 1821:                 ($curve->{'linestyle'} eq 'errorbars')   ||
 1822:                 ($curve->{'linestyle'} eq 'xerrorbars')  ||
 1823:                 ($curve->{'linestyle'} eq 'yerrorbars')  ||
 1824:                 ($curve->{'linestyle'} eq 'xyerrorbars')) {
 1825:                 $gnuplot_input.=' pointtype '.$curve->{'pointtype'};
 1826:                 $gnuplot_input.=' pointsize '.$curve->{'pointsize'};
 1827:             } elsif ($curve->{'linestyle'} eq 'filledcurves') { 
 1828:                 $gnuplot_input.= ' '.$curve->{'limit'};
 1829:             } elsif ($curve->{'linetype'} ne '' &&
 1830:                      $curve->{'linestyle'} eq 'lines') {
 1831:                 $gnuplot_input.= ' linetype ';
 1832:                 $gnuplot_input.= $linetypes{$curve->{'linetype'}};
 1833:                 $gnuplot_input.= ' linecolor rgb "';
 1834:                 # convert color from xaaaaaa to #aaaaaa
 1835:                 $curve->{'color'} =~ s/^x/#/;
 1836:                 $gnuplot_input.= $curve->{'color'}.'"';
 1837:             }
 1838:                 $gnuplot_input.= ' linewidth '.$curve->{'linewidth'}; 
 1839: 	}
 1840:     }
 1841:     # Write the output to a file.
 1842:     open (my $fh,">$tmpdir$filename.data");
 1843:     binmode($fh, ":utf8");
 1844:     print $fh $gnuplot_input;
 1845:     close($fh);
 1846:     # That's all folks.
 1847:     return ;
 1848: }
 1849: 
 1850: #---------------------------------------------- check_inputs
 1851: sub check_inputs {
 1852:     ## Note: no inputs, no outputs - this acts only on global variables.
 1853:     ## Make sure we have all the input we need:
 1854:     if (! %Apache::lonplot::plot) { &set_defaults(\%Apache::lonplot::plot,\%gnuplot_defaults); }
 1855:     if (! %key ) {} # No key for this plot, thats okay
 1856: #    if (! %axis) { &set_defaults(\%axis,\%axis_defaults); }
 1857:     if (! defined($title )) {} # No title for this plot, thats okay
 1858:     if (! defined($xlabel)) {} # No xlabel for this plot, thats okay
 1859:     if (! defined($ylabel)) {} # No ylabel for this plot, thats okay
 1860:     if ($#labels < 0) { }      # No labels for this plot, thats okay
 1861:     if ($#curves < 0) { 
 1862: 	&Apache::lonxml::warning("No curves specified for plot!!!!");
 1863: 	return '';
 1864:     }
 1865:     my $curve;
 1866:     foreach $curve (@curves) {
 1867: 	if (!defined($curve->{'function'})&&!defined($curve->{'data'})){
 1868: 	    &Apache::lonxml::warning("One of the curves specified did not contain any curve data or curve function declarations\n");
 1869: 	    return '';
 1870: 	}
 1871:     }
 1872: }
 1873: 
 1874: #------------------------------------------------ make_edit
 1875: sub edit_attributes {
 1876:     my ($target,$token,$defaults,$keys) = @_;
 1877:     my ($result,@keys);
 1878:     if ($keys && ref($keys) eq 'ARRAY') {
 1879:         @keys = @$keys;
 1880:     } else {
 1881: 	@keys = sort(keys(%$defaults));
 1882:     }
 1883:     foreach my $attr (@keys) {
 1884: 	# append a ' ' to the description if it doesn't have one already.
 1885: 	my $description = $defaults->{$attr}->{'description'};
 1886: 	$description .= ' ' if ($description !~ / $/);
 1887: 	if ($defaults->{$attr}->{'edit_type'} eq 'entry') {
 1888: 	    $result .= &Apache::edit::text_arg
 1889: 		($description,$attr,$token,
 1890: 		 $defaults->{$attr}->{'size'});
 1891: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'choice') {
 1892: 	    $result .= &Apache::edit::select_or_text_arg
 1893: 		($description,$attr,$defaults->{$attr}->{'choices'},$token);
 1894: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'onoff') {
 1895: 	    $result .= &Apache::edit::select_or_text_arg
 1896: 		($description,$attr,['on','off'],$token);
 1897: 	}
 1898: 	$result .= '<br />';
 1899:     }
 1900:     return $result;
 1901: }
 1902: 
 1903: 
 1904: ###################################################################
 1905: ##                                                               ##
 1906: ##           Insertion functions for editing plots               ##
 1907: ##                                                               ##
 1908: ###################################################################
 1909: 
 1910: sub insert_gnuplot {
 1911:     my $result = '';
 1912:     #  plot attributes
 1913:     $result .= "\n<gnuplot ";
 1914:     foreach my $attr (keys(%gnuplot_defaults)) {
 1915: 	$result .= "\n     $attr=\"$gnuplot_defaults{$attr}->{'default'}\"";
 1916:     }
 1917:     $result .= ">";
 1918:     # Add the components (most are commented out for simplicity)
 1919:     # $result .= &insert_key();
 1920:     # $result .= &insert_axis();
 1921:     # $result .= &insert_title();    
 1922:     # $result .= &insert_xlabel();    
 1923:     # $result .= &insert_ylabel();    
 1924:     $result .= &insert_curve();
 1925:     # close up the <gnuplot>
 1926:     $result .= "\n</gnuplot>";
 1927:     return $result;
 1928: }
 1929: 
 1930: sub insert_tics {
 1931:     my $result;
 1932:     $result .= &insert_xtics() . &insert_ytics;
 1933:     return $result;
 1934: }
 1935: 
 1936: sub insert_xtics {
 1937:     my $result;
 1938:     $result .= "\n    <xtics ";
 1939:     foreach my $attr (keys(%tic_defaults)) {
 1940: 	$result .= "\n        $attr=\"$tic_defaults{$attr}->{'default'}\" ";
 1941:     }
 1942:     $result .= "/>";
 1943:     return $result;
 1944: }
 1945: 
 1946: sub insert_ytics {
 1947:     my $result;
 1948:     $result .= "\n    <ytics ";
 1949:     foreach my $attr (keys(%tic_defaults)) {
 1950: 	$result .= "\n        $attr=\"$tic_defaults{$attr}->{'default'}\" ";
 1951:     }
 1952:     $result .= "/>";
 1953:     return $result;
 1954: }
 1955: 
 1956: sub insert_key {
 1957:     my $result;
 1958:     $result .= "\n    <key ";
 1959:     foreach my $attr (keys(%key_defaults)) {
 1960: 	$result .= "\n         $attr=\"$key_defaults{$attr}->{'default'}\"";
 1961:     }
 1962:     $result .= " />";
 1963:     return $result;
 1964: }
 1965: 
 1966: sub insert_axis{
 1967:     my $result;
 1968:     $result .= "\n    <axis ";
 1969:    foreach my $attr (keys(%axis_defaults)) {
 1970: 	$result .= "\n         $attr=\"$axis_defaults{$attr}->{'default'}\"";
 1971:     }
 1972:     $result .= " />";
 1973:     return $result;
 1974: }
 1975: 
 1976: sub insert_title  { return "\n    <title></title>"; }
 1977: sub insert_xlabel { return "\n    <xlabel></xlabel>"; }
 1978: sub insert_ylabel { return "\n    <ylabel></ylabel>"; }
 1979: 
 1980: sub insert_label {
 1981:     my $result;
 1982:     $result .= "\n    <label ";
 1983:     foreach my $attr (keys(%label_defaults)) {
 1984: 	$result .= "\n         $attr=\"".
 1985:             $label_defaults{$attr}->{'default'}."\"";
 1986:     }
 1987:     $result .= "></label>";
 1988:     return $result;
 1989: }
 1990: 
 1991: sub insert_curve {
 1992:     my $result;
 1993:     $result .= "\n    <curve ";
 1994:     foreach my $attr (keys(%curve_defaults)) {
 1995: 	$result .= "\n         $attr=\"".
 1996: 	    $curve_defaults{$attr}->{'default'}."\"";
 1997:     }
 1998:     $result .= " >";
 1999:     $result .= &insert_data().&insert_data()."\n    </curve>";
 2000: }
 2001: 
 2002: sub insert_function {
 2003:     my $result;
 2004:     $result .= "\n        <function></function>";
 2005:     return $result;
 2006: }
 2007: 
 2008: sub insert_data {
 2009:     my $result;
 2010:     $result .= "\n        <data></data>";
 2011:     return $result;
 2012: }
 2013: 
 2014: ##----------------------------------------------------------------------
 2015: 1;
 2016: __END__
 2017: 
 2018: 

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