File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.161: download - view: text, annotated - select for diffs
Tue Jul 17 09:54:48 2012 UTC (11 years, 9 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Accidently killed off the utf-8 output file specification :-(

    1: # The LearningOnline Network with CAPA
    2: # Dynamic plot
    3: #
    4: # $Id: lonplot.pm,v 1.161 2012/07/17 09:54:48 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: 
   30: 
   31: 
   32: package Apache::lonplot;
   33: 
   34: use strict;
   35: use warnings FATAL=>'all';
   36: no warnings 'uninitialized';
   37: use Apache::File;
   38: use Apache::response;
   39: use Apache::lonxml;
   40: use Apache::edit;
   41: use Apache::lonnet;
   42: use LONCAPA;
   43:  
   44: 
   45: use vars qw/$weboutputformat $version/;
   46: 
   47: 
   48: 
   49: BEGIN {
   50:     &Apache::lonxml::register('Apache::lonplot',('gnuplot'));
   51:     #
   52:     # Determine the version of GNUPLOT
   53:     $weboutputformat = 'gif';
   54:     my $versionstring = `gnuplot --version 2>/dev/null`;
   55:     ($version) = ($versionstring =~ /^gnuplot ([\d.]+)/);
   56:     if ($version >= 4) {
   57:         $weboutputformat = 'png';
   58:     }
   59:     
   60: }
   61: 
   62: 
   63: =pod
   64: 
   65: ## 
   66: ## Description of data structures:
   67: ##
   68: ##  %plot       %key    %axis
   69: ## --------------------------
   70: ##  height      title   color
   71: ##  width       box     xmin
   72: ##  bgcolor     pos     xmax
   73: ##  fgcolor             ymin
   74: ##  transparent         ymax
   75: ##  grid
   76: ##  border
   77: ##  font
   78: ##  align
   79: ##
   80: ##  @labels: $labels[$i] = \%label
   81: ##           %label: text, xpos, ypos, justify
   82: ##
   83: ##  @curves: $curves[$i] = \%curve
   84: ##           %curve: name, linestyle, ( function | data )
   85: ##
   86: ##  $curves[$i]->{'data'} = [ [x1,x2,x3,x4],
   87: ##                            [y1,y2,y3,y4] ]
   88: ##
   89: 
   90: ###################################################################
   91: ##                                                               ##
   92: ##        Tests used in checking the validitity of input         ##
   93: ##                                                               ##
   94: ###################################################################
   95: 
   96: =cut
   97: 
   98: my $max_str_len = 50;    # if a label, title, xlabel, or ylabel text
   99:                          # is longer than this, it will be truncated.
  100: 
  101: my %linetypes =			# For png use these linetypes.
  102:     (
  103:      solid          => 1,
  104:      dashed         => 0
  105:     );
  106: my %ps_linetypes = 		# For ps the line types are different!
  107:    (
  108:     solid          => 0,
  109:     dashed         => 7
  110:    );
  111: 
  112: my %linestyles = 
  113:     (
  114:      lines          => 2,     # Maybe this will be used in the future
  115:      linespoints    => 2,     # to check on whether or not they have 
  116:      dots	    => 2,     # supplied enough <data></data> fields
  117:      points         => 2,     # to use the given line style.  But for
  118:      steps	    => 2,     # now there are more important things 
  119:      fsteps	    => 2,     # for me to deal with.
  120:      histeps        => 2,
  121:      errorbars	    => 3,
  122:      xerrorbars	    => [3,4],
  123:      yerrorbars	    => [3,4],
  124:      xyerrorbars    => [4,6],
  125:      boxes          => 3,
  126:      filledcurves   => 2,
  127:      vector	    => 4
  128:     );		    
  129: 
  130: my $int_test       = sub {$_[0]=~s/\s+//g;$_[0]=~/^\d+$/};
  131: my $real_test      = 
  132:     sub {$_[0]=~s/\s+//g;$_[0]=~/^[+-]?\d*\.?\d*([eE][+-]\d+)?$/};
  133: my $pos_real_test  =
  134:     sub {$_[0]=~s/\s+//g;$_[0]=~/^[+]?\d*\.?\d*([eE][+-]\d+)?$/};
  135: my $color_test     = sub {$_[0]=~s/\s+//g;$_[0]=~/^x[\da-fA-F]{6}$/};
  136: my $onoff_test     = sub {$_[0]=~/^(on|off)$/};
  137: my $key_pos_test   = sub {$_[0]=~/^(top|bottom|right|left|outside|below| )+$/};
  138: my $sml_test       = sub {$_[0]=~/^(\d+|small|medium|large)$/};
  139: my $linestyle_test = sub {exists($linestyles{$_[0]})};
  140: my $words_test     = sub {$_[0]=~s/\s+/ /g;$_[0]=~/^([\w~!\@\#\$\%^&\*\(\)-=_\+\[\]\{\}:\;\'<>,\.\/\?\\]+ ?)+$/};
  141: 
  142: my $arrowhead_test = sub{$_[0]=~/^(nohead|head|heads| )+$/};
  143: my $arrowstyle_test= sub{$_[0]=~/^(filled|empty|nofilled)+$/};
  144: my $degree_test  = sub{&$pos_real_test($_[0]) && ($_[0] <= 360.0)};
  145: 
  146: ###################################################################
  147: ##                                                               ##
  148: ##                      Attribute metadata                       ##
  149: ##                                                               ##
  150: ###################################################################
  151: my @gnuplot_edit_order = 
  152:     qw/alttag bgcolor fgcolor height width texwidth fontface font texfont
  153:     transparent grid samples 
  154:     border align plotcolor plottype gridtype lmargin rmargin
  155:     tmargin bmargin major_ticscale minor_ticscale boxwidth gridlayer fillstyle
  156:     pattern solid/;
  157: 
  158: my $margin_choices = ['default',0..20];
  159: 
  160: my %gnuplot_defaults = 
  161:     (
  162:      alttag       => {
  163: 	 default     => 'dynamically generated plot',
  164: 	 test        => $words_test,
  165: 	 description => 'Brief description of the plot',
  166:       	 edit_type   => 'entry',
  167: 	 size        => '40'
  168: 	 },
  169:      height       => {
  170: 	 default     => 300,
  171: 	 test        => $int_test,
  172: 	 description => 'Height of image (pixels)',
  173:       	 edit_type   => 'entry',
  174: 	 size        => '10'
  175: 	 },
  176:      width        => {
  177: 	 default     => 400,
  178: 	 test        => $int_test,
  179: 	 description => 'Width of image (pixels)',
  180: 	 edit_type   => 'entry',
  181: 	 size        => '10'
  182: 	 },
  183:      bgcolor      => {
  184: 	 default     => 'xffffff',
  185: 	 test        => $color_test, 
  186: 	 description => 'Background color of image (xffffff)',
  187: 	 edit_type   => 'entry',
  188: 	 size        => '10',
  189:          class       => 'colorchooser'
  190: 	 },
  191:      fgcolor      => {
  192: 	 default     => 'x000000',
  193: 	 test        => $color_test,
  194: 	 description => 'Foreground color of image (x000000)',
  195: 	 edit_type   => 'entry',
  196: 	 size        => '10',
  197:          class       => 'colorchooser'
  198: 	 },
  199:      transparent  => {
  200: 	 default     => 'off',
  201: 	 test        => $onoff_test, 
  202: 	 description => 'Transparent image',
  203: 	 edit_type   => 'onoff'
  204: 	 },
  205:      grid         => {
  206: 	 default     => 'on',
  207: 	 test        => $onoff_test, 
  208: 	 description => 'Display grid',
  209: 	 edit_type   => 'onoff'
  210: 	 },
  211:      gridlayer    => {
  212: 	 default     => 'off',
  213: 	 test        => $onoff_test, 
  214: 	 description => 'Display grid front layer over filled boxes or filled curves',
  215: 	 edit_type   => 'onoff'
  216: 	 },
  217:      box_border   => {
  218: 	 default     => 'noborder',
  219: 	 test        => sub {$_[0]=~/^(noborder|border)$/},
  220: 	 description => 'Draw border for boxes',
  221: 	 edit_type   => 'choice',
  222: 	 choices     => ['border','noborder']
  223: 	 },
  224:      border       => {
  225: 	 default     => 'on',
  226: 	 test        => $onoff_test, 
  227: 	 description => 'Draw border around plot',
  228: 	 edit_type   => 'onoff'
  229: 	 },
  230:      font         => {
  231: 	 default     => '9',
  232: 	 test        => $sml_test,
  233: 	 description => 'Font size to use in web output (pts)',
  234: 	 edit_type   => 'choice',
  235: 	 choices     => [['5','5 (small)'],'6','7','8',['9','9 (medium)'],'10',['11','11 (large)'],'12','15']
  236: 	 },
  237:      fontface     => {
  238:         default     => 'sans-serif',
  239:         test        => sub {$_[0]=~/^(sans-serif|serif|classic)$/},
  240:         description => 'Type of font to use',
  241:         edit_type   => 'choice',
  242:         choices     => ['sans-serif','serif', 'classic']
  243:         },
  244:      samples      => {
  245: 	 default     => '100',
  246: 	 test        => $int_test,
  247: 	 description => 'Number of samples for non-data plots',
  248: 	 edit_type   => 'choice',
  249: 	 choices     => ['100','200','500','1000','2000','5000']
  250: 	 },
  251:      align        => {
  252: 	 default     => 'middle',
  253: 	 test        => sub {$_[0]=~/^(left|right|middle|center)$/},
  254: 	 description => 'Alignment for image in HTML',
  255: 	 edit_type   => 'choice',
  256: 	 choices     => ['left','right','middle']
  257: 	 },
  258:      texwidth     => {
  259:          default     => '93',
  260:          test        => $int_test,
  261:          description => 'Width of plot when printed (mm)',
  262:          edit_type   => 'entry',
  263:          size        => '5'
  264:          },
  265:      texfont      => {
  266:          default     => '22',
  267:          test        => $int_test,
  268:          description => 'Font size to use in TeX output (pts):',
  269:          edit_type   => 'choice',
  270:          choices     => [qw/8 10 12 14 16 18 20 22 24 26 28 30 32 34 36/],
  271:          },
  272:      plotcolor    => {
  273:          default     => 'monochrome',
  274:          test        => sub {$_[0]=~/^(monochrome|color|colour)$/},
  275:          description => 'Color setting for printing:',
  276:          edit_type   => 'choice',
  277:          choices     => [qw/monochrome color colour/],
  278:          },
  279:      pattern      => {
  280: 	 default     => '',
  281: 	 test        => $int_test,
  282: 	 description => 'Pattern value for boxes:',
  283: 	 edit_type   => 'choice',
  284:          choices     => [0,1,2,3,4,5,6]
  285:          },
  286:      solid        => {
  287:          default     => 0,
  288:          test        => $real_test,
  289:          description => 'The density of fill style for boxes',
  290:          edit_type   => 'entry',
  291:          size        => '5'
  292:          },
  293:      fillstyle    => {
  294: 	 default     => 'empty',
  295: 	 test        => sub {$_[0]=~/^(empty|solid|pattern)$/},
  296: 	 description => 'Filled style for boxes:',
  297: 	 edit_type   => 'choice',
  298:          choices     => ['empty','solid','pattern']
  299:          },
  300:      plottype     => {
  301: 	 default     => 'Cartesian',
  302: 	 test        => sub {$_[0]=~/^(Polar|Cartesian)$/},
  303: 	 description => 'Plot type:',
  304: 	 edit_type   => 'choice',
  305:          choices     => ['Cartesian','Polar']
  306:          },
  307:      gridtype     => {
  308: 	 default     => 'Cartesian',
  309: 	 test        => sub {$_[0]=~/^(Polar|Cartesian|Linear-Log|Log-Linear|Log-Log)$/},
  310: 	 description => 'Grid type:',
  311: 	 edit_type   => 'choice',
  312:          choices     => ['Cartesian','Polar','Linear-Log','Log-Linear','Log-Log']
  313:          },
  314:      lmargin      => {
  315: 	 default     => 'default',
  316: 	 test        => sub {$_[0]=~/^(default|\d+)$/},
  317: 	 description => 'Left margin width (pts):',
  318: 	 edit_type   => 'choice',
  319:          choices     => $margin_choices,
  320:          },
  321:      rmargin      => {
  322: 	 default     => 'default',
  323: 	 test        => sub {$_[0]=~/^(default|\d+)$/},
  324: 	 description => 'Right margin width (pts):',
  325: 	 edit_type   => 'choice',
  326:          choices     => $margin_choices,
  327:          },
  328:      tmargin      => {
  329: 	 default     => 'default',
  330: 	 test        => sub {$_[0]=~/^(default|\d+)$/},
  331: 	 description => 'Top margin width (pts):',
  332: 	 edit_type   => 'choice',
  333:          choices     => $margin_choices,
  334:          },
  335:      bmargin      => {
  336: 	 default     => 'default',
  337: 	 test        => sub {$_[0]=~/^(default|\d+)$/},
  338: 	 description => 'Bottom margin width (pts):',
  339: 	 edit_type   => 'choice',
  340:          choices     => $margin_choices,
  341:          },
  342:      boxwidth     => {
  343: 	 default     => '',
  344: 	 test        => $real_test, 
  345: 	 description => 'Width of boxes, default is auto',
  346: 	 edit_type   => 'entry',
  347:          size        => '5'
  348:          },
  349:      major_ticscale  => {
  350:          default     => '1',
  351:          test        => $real_test,
  352:          description => 'Size of major tic marks (plot coordinates)',
  353:          edit_type   => 'entry',
  354:          size        => '5'
  355:          },
  356:      minor_ticscale  => {
  357:          default     => '0.5',
  358:          test        => $real_test,
  359:          description => 'Size of minor tic mark (plot coordinates)',
  360:          edit_type   => 'entry',
  361:          size        => '5'
  362:          },
  363:      );
  364: 
  365: my %key_defaults = 
  366:     (
  367:      title => { 
  368: 	 default => '',
  369: 	 test => $words_test,
  370: 	 description => 'Title of key',
  371: 	 edit_type   => 'entry',
  372: 	 size        => '40'
  373: 	 },
  374:      box   => { 
  375: 	 default => 'off',
  376: 	 test => $onoff_test,
  377: 	 description => 'Draw a box around the key?',
  378: 	 edit_type   => 'onoff'
  379: 	 },
  380:      pos   => { 
  381: 	 default => 'top right', 
  382: 	 test => $key_pos_test, 
  383: 	 description => 'Position of the key on the plot',
  384: 	 edit_type   => 'choice',
  385: 	 choices     => ['top left','top right','bottom left','bottom right',
  386: 			 'outside','below']
  387: 	 }
  388:      );
  389: 
  390: my %label_defaults = 
  391:     (
  392:      xpos    => {
  393: 	 default => 0,
  394: 	 test => $real_test,
  395: 	 description => 'X position of label (graph coordinates)',
  396: 	 edit_type   => 'entry',
  397: 	 size        => '10'
  398: 	 },
  399:      ypos    => {
  400: 	 default => 0, 
  401: 	 test => $real_test,
  402: 	 description => 'Y position of label (graph coordinates)',
  403: 	 edit_type   => 'entry',
  404: 	 size        => '10'
  405: 	 },
  406:      justify => {
  407: 	 default => 'left',    
  408: 	 test => sub {$_[0]=~/^(left|right|center)$/},
  409: 	 description => 'justification of the label text on the plot',
  410: 	 edit_type   => 'choice',
  411: 	 choices     => ['left','right','center']
  412:      },
  413:      rotate => {
  414:          default => 0,
  415:          test => $real_test,
  416:          description => 'Rotation of label (degrees)',
  417:          edit_type   => 'entry',
  418:          size        => '10',
  419:      }
  420:      );
  421: 
  422: my @tic_edit_order = ('location','mirror','start','increment','end',
  423:                       'minorfreq');
  424: my %tic_defaults =
  425:     (
  426:      location => {
  427: 	 default => 'border', 
  428: 	 test => sub {$_[0]=~/^(border|axis)$/},
  429: 	 description => 'Location of major tic marks',
  430: 	 edit_type   => 'choice',
  431: 	 choices     => ['border','axis']
  432: 	 },
  433:      mirror => {
  434: 	 default => 'on', 
  435: 	 test => $onoff_test,
  436: 	 description => 'Mirror tics on opposite axis?',
  437: 	 edit_type   => 'onoff'
  438: 	 },
  439:      start => {
  440: 	 default => '-10.0',
  441: 	 test => $real_test,
  442: 	 description => 'Start major tics at',
  443: 	 edit_type   => 'entry',
  444: 	 size        => '10'
  445: 	 },
  446:      increment => {
  447: 	 default => '1.0',
  448: 	 test => $real_test,
  449: 	 description => 'Place a major tic every',
  450: 	 edit_type   => 'entry',
  451: 	 size        => '10'
  452: 	 },
  453:      end => {
  454: 	 default => ' 10.0',
  455: 	 test => $real_test,
  456: 	 description => 'Stop major tics at ',
  457: 	 edit_type   => 'entry',
  458: 	 size        => '10'
  459: 	 },
  460:      minorfreq => {
  461: 	 default => '0',
  462: 	 test => $int_test,
  463: 	 description => 'Number of minor tics per major tic mark',
  464: 	 edit_type   => 'entry',
  465: 	 size        => '10'
  466: 	 },         
  467:      );
  468: 
  469: my @axis_edit_order = ('color','xmin','xmax','ymin','ymax','xformat', 'yformat', 'xzero', 'yzero');
  470: my %axis_defaults = 
  471:     (
  472:      color   => {
  473: 	 default => 'x000000', 
  474: 	 test => $color_test,
  475: 	 description => 'Color of grid lines (x000000)',
  476: 	 edit_type   => 'entry',
  477: 	 size        => '10',
  478:          class       => 'colorchooser'
  479: 	 },
  480:      xmin      => {
  481: 	 default => '-10.0',
  482: 	 test => $real_test,
  483: 	 description => 'Minimum x-value shown in plot',
  484: 	 edit_type   => 'entry',
  485: 	 size        => '10'
  486: 	 },
  487:      xmax      => {
  488: 	 default => ' 10.0',
  489: 	 test => $real_test,
  490: 	 description => 'Maximum x-value shown in plot',	 
  491: 	 edit_type   => 'entry',
  492: 	 size        => '10'
  493: 	 },
  494:      ymin      => {
  495: 	 default => '-10.0',
  496: 	 test => $real_test,
  497: 	 description => 'Minimum y-value shown in plot',	 
  498: 	 edit_type   => 'entry',
  499: 	 size        => '10'
  500: 	 },
  501:      ymax      => {
  502: 	 default => ' 10.0',
  503: 	 test => $real_test,
  504: 	 description => 'Maximum y-value shown in plot',	 
  505: 	 edit_type   => 'entry',
  506: 	 size        => '10'
  507:         },
  508:      xformat      => {
  509:          default     => 'on',
  510:          test        => sub {$_[0]=~/^(on|off|\d+(f|F|e|E))$/},
  511:          description => 'X-axis number formatting',
  512:          edit_type   => 'choice',
  513:          choices     => ['on', 'off', '2e', '2f'],
  514:          },
  515:      yformat      => {
  516:          default     => 'on',
  517:          test        => sub {$_[0]=~/^(on|off|\d+(f|F|e|E))$/},
  518:          description => 'Y-axis number formatting',
  519:          edit_type   => 'choice',
  520:          choices     => ['on', 'off', '2e', '2f'],
  521:          },
  522:      
  523:      xzero => {
  524:      	default => 'off',
  525:      	test	=> sub {$_[0]=~/^(off|line|thick-line|dotted)$/},
  526:      	description => 'Show x-zero (y=0) axis',
  527:      	edit_type  => 'choice',
  528:      	choices	=> ['off', 'line', 'thick-line', 'dotted'],
  529:      	},
  530:      
  531:      yzero => {
  532:      	default => 'off',
  533:      	test	=> sub {$_[0]=~/^(off|line|thick-line|dotted)$/},
  534:      	description => 'Show y-zero (x=0) axis',
  535:      	edit_type  => 'choice',
  536:      	choices	=> ['off', 'line', 'thick-line', 'dotted'],
  537:      	},
  538:      );
  539: 
  540: my @curve_edit_order = ('color','name','linestyle','linewidth','linetype',
  541: 			'pointtype','pointsize','limit', 'arrowhead', 'arrowstyle', 
  542: 			'arrowlength', 'arrowangle', 'arrowbackangle'
  543:     );
  544: 
  545: my %curve_defaults = 
  546:     (
  547:      color     => {
  548: 	 default => 'x000000',
  549: 	 test => $color_test,
  550: 	 description => 'Color of curve (x000000)',
  551: 	 edit_type   => 'entry',
  552: 	 size        => '10',
  553: 	 class       => 'colorchooser'
  554: 	 },
  555:      name      => {
  556: 	 default => '',
  557: 	 test => $words_test,
  558: 	 description => 'Name of curve to appear in key',
  559: 	 edit_type   => 'entry',
  560: 	 size        => '20'
  561: 	 },
  562:      linestyle => {
  563: 	 default => 'lines',
  564: 	 test => $linestyle_test,
  565: 	 description => 'Plot with:',
  566: 	 edit_type   => 'choice',
  567: 	 choices     => [keys(%linestyles)]
  568: 	 },
  569:      linewidth => {
  570:          default     => 1,
  571:          test        => $int_test,
  572:          description => 'Line width (may not apply to all plot styles)',
  573:          edit_type   => 'choice',
  574:          choices     => [1,2,3,4,5,6,7,8,9,10]
  575:          },
  576:      linetype => {
  577:          default     => 'solid',
  578:          test        => sub {$_[0]=~/^(solid|dashed)$/},
  579:          description => 'Line type (may not apply to all plot styles)',
  580:          edit_type   => 'choice',
  581:          choices     => ['solid', 'dashed']
  582:          }, 
  583:      pointsize => {
  584:          default     => 1,
  585:          test        => $pos_real_test,
  586:          description => 'Point size (may not apply to all plot styles)',
  587:          edit_type   => 'entry',
  588:          size        => '5'
  589:          },
  590:      pointtype => {
  591:          default     => 1,
  592:          test        => $int_test,
  593:          description => 'Point type (may not apply to all plot styles)',
  594:          edit_type   => 'choice',
  595:          choices     => [0,1,2,3,4,5,6]
  596:          },
  597:      limit     => {
  598:          default     => 'closed',
  599: 	 test        => sub {$_[0]=~/^(above|below|closed|x1|x2|y1|y2)$/},
  600:          description => 'Point to fill -- for filledcurves',
  601:          edit_type   => 'choice',
  602:          choices     => ['above', 'below', 'closed','x1','x2','y1','y2']
  603:          },
  604:      arrowhead => {
  605:          default     => 'head',
  606: 	 test        => $arrowhead_test,
  607: 	 description => 'Vector arrow head type',
  608: 	 edit_type   => 'choice',
  609: 	 choices     => ['nohead', 'head', 'heads']
  610:      },
  611:      arrowstyle => {
  612: 	 default     => 'filled',
  613: 	 test        => $arrowstyle_test,
  614: 	 description => 'Vector arrow head style',
  615: 	 edit_type   => 'choice',
  616: 	 choices     => ['filled', 'empty', 'nofilled']
  617:      },
  618:      arrowlength => {
  619: 	 default     => 0.02,
  620: 	 test        => $pos_real_test,
  621: 	 description => "Length of vector arrow (only applies to vector plots)",
  622: 	 edit_type   => 'entry',
  623: 	 size        => '5'
  624:      },
  625:      arrowangle  => {
  626: 	default      => 10.0,
  627: 	test         => $degree_test,
  628: 	description  => 'Angle of arrow branches to arrow body (only applies to vector plots)',
  629: 	edit_type    => 'entry',
  630: 	size         => '5'
  631:      },
  632: 
  633:      arrowbackangle => {
  634: 	 default    => 90.0,
  635: 	 test       => $degree_test,
  636: 	 descripton => 'Angle of arrow back lines to branches.',
  637: 	 edit_type  => 'entry',
  638: 	 size       => '5'
  639:      }
  640: 
  641:      );
  642: 
  643: ###################################################################
  644: ##                                                               ##
  645: ##                    parsing and edit rendering                 ##
  646: ##                                                               ##
  647: ###################################################################
  648: 
  649: undef %Apache::lonplot::plot;
  650: my (%key,%axis,$title,$xlabel,$ylabel,@labels,@curves,%xtics,%ytics);
  651: 
  652: sub start_gnuplot {
  653:     undef(%Apache::lonplot::plot);   undef(%key);    undef(%axis);
  654:     undef($title);  undef($xlabel); undef($ylabel);
  655:     undef(@labels); undef(@curves);
  656:     undef(%xtics);  undef(%ytics);
  657:     #
  658:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  659:     my $result='';
  660:     &Apache::lonxml::register('Apache::lonplot',
  661: 	     ('title','xlabel','ylabel','key','axis','label','curve',
  662: 	      'xtics','ytics'));
  663:     push (@Apache::lonxml::namespace,'lonplot');
  664:     if ($target eq 'web' || $target eq 'tex') {
  665: 	&get_attributes(\%Apache::lonplot::plot,\%gnuplot_defaults,$parstack,$safeeval,
  666: 			$tagstack->[-1]);
  667:     } elsif ($target eq 'edit') {
  668: 	$result .= &Apache::edit::tag_start($target,$token,'GnuPlot');
  669: 	$result .= &edit_attributes($target,$token,\%gnuplot_defaults,
  670: 				    \@gnuplot_edit_order)
  671: 	    .&Apache::edit::end_row()
  672: 	    .&Apache::edit::start_spanning_row();
  673:     } elsif ($target eq 'modified') {
  674: 	my $constructtag=&Apache::edit::get_new_args
  675: 	    ($token,$parstack,$safeeval,keys(%gnuplot_defaults));
  676: 
  677: 	if ($constructtag) {
  678: 	    #
  679: 	    # The color chooser does not prepent x to the color values
  680: 	    # Do that here:
  681: 	    #
  682: 	    foreach my $attribute ('bgcolor', 'fgcolor') {
  683: 		my $value = $token->[2]{$attribute};
  684: 		if (defined $value && !($value =~ /^x/)) {
  685: 		    $token->[2]{$attribute} = 'x' . $value;
  686: 		}
  687: 	    }
  688: 	    $result = &Apache::edit::rebuild_tag($token);
  689: 	}
  690:     }
  691:     return $result;
  692: }
  693: 
  694: sub end_gnuplot {
  695:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  696:     pop @Apache::lonxml::namespace;
  697:     &Apache::lonxml::deregister('Apache::lonplot',
  698: 	('title','xlabel','ylabel','key','axis','label','curve'));
  699:     my $result = '';
  700:     my $randnumber;
  701:     my $tmpdir =LONCAPA::tempdir(); # Where temporary files live:
  702: 
  703:     # need to call rand everytime start_script would evaluate, as the
  704:     # safe space rand number generator and the global rand generator 
  705:     # are not separate
  706:     if ($target eq 'web' || $target eq 'tex' || $target eq 'grade' ||
  707: 	$target eq 'answer') {
  708:       $randnumber=int(rand(1000));
  709:     }
  710:     if ($target eq 'web' || $target eq 'tex') {
  711: 	&check_inputs(); # Make sure we have all the data we need
  712: 	##
  713: 	## Determine filename
  714: 	my $filename = $env{'user.name'}.'_'.$env{'user.domain'}.
  715: 	    '_'.time.'_'.$$.$randnumber.'_plot';
  716: 	## Write the plot description to the file
  717: 	&write_gnuplot_file($tmpdir,$filename,$target);
  718: 	$filename = &escape($filename);
  719: 	## return image tag for the plot
  720: 	if ($target eq 'web') {
  721: 	    $result .= <<"ENDIMAGE";
  722: <img src    = "/cgi-bin/plot.$weboutputformat?file=$filename.data" 
  723:      width  = "$Apache::lonplot::plot{'width'}"
  724:      height = "$Apache::lonplot::plot{'height'}"
  725:      align  = "$Apache::lonplot::plot{'align'}"
  726:      alt    = "$Apache::lonplot::plot{'alttag'}" />
  727: ENDIMAGE
  728:         } elsif ($target eq 'tex') {
  729: 	    &Apache::lonxml::debug(" gnuplot wid = $Apache::lonplot::plot{'width'}");
  730: 	    &Apache::lonxml::debug(" gnuplot ht  = $Apache::lonplot::plot{'height'}");
  731: 	    #might be inside the safe space, register the URL for later
  732: 	    &Apache::lonxml::register_ssi("/cgi-bin/plot.gif?file=$filename.data&output=eps");
  733: 	    $result  = "%DYNAMICIMAGE:$Apache::lonplot::plot{'width'}:$Apache::lonplot::plot{'height'}:$Apache::lonplot::plot{'texwidth'}\n";
  734: 	    $result .= '\graphicspath{{'.$tmpdir.'}}'."\n";
  735: 	    $result .= '\includegraphics[width='.$Apache::lonplot::plot{'texwidth'}.' mm]{'.&unescape($filename).'.eps}';
  736: 	}
  737:     } elsif ($target eq 'edit') {
  738: 	$result.=&Apache::edit::tag_end($target,$token);
  739:     }
  740:     return $result;
  741: }
  742: 
  743: 
  744: ##--------------------------------------------------------------- xtics
  745: sub start_xtics {
  746:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  747:     my $result='';
  748:     if ($target eq 'web' || $target eq 'tex') {
  749: 	&get_attributes(\%xtics,\%tic_defaults,$parstack,$safeeval,
  750: 		    $tagstack->[-1]);
  751:     } elsif ($target eq 'edit') {
  752: 	$result .= &Apache::edit::tag_start($target,$token,'xtics');
  753: 	$result .= &edit_attributes($target,$token,\%tic_defaults,
  754: 				    \@tic_edit_order);
  755:     } elsif ($target eq 'modified') {
  756: 	my $constructtag=&Apache::edit::get_new_args
  757: 	    ($token,$parstack,$safeeval,keys(%tic_defaults));
  758: 	if ($constructtag) {
  759: 	    $result = &Apache::edit::rebuild_tag($token);
  760: 	}
  761:     }
  762:     return $result;
  763: }
  764: 
  765: sub end_xtics {
  766:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  767:     my $result = '';
  768:     if ($target eq 'web' || $target eq 'tex') {
  769:     } elsif ($target eq 'edit') {
  770: 	$result.=&Apache::edit::tag_end($target,$token);
  771:     }
  772:     return $result;
  773: }
  774: 
  775: ##--------------------------------------------------------------- ytics
  776: sub start_ytics {
  777:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  778:     my $result='';
  779:     if ($target eq 'web' || $target eq 'tex') {
  780: 	&get_attributes(\%ytics,\%tic_defaults,$parstack,$safeeval,
  781: 		    $tagstack->[-1]);
  782:     } elsif ($target eq 'edit') {
  783: 	$result .= &Apache::edit::tag_start($target,$token,'ytics');
  784: 	$result .= &edit_attributes($target,$token,\%tic_defaults,
  785: 				    \@tic_edit_order);
  786:     } elsif ($target eq 'modified') {
  787: 	my $constructtag=&Apache::edit::get_new_args
  788: 	    ($token,$parstack,$safeeval,keys(%tic_defaults));
  789: 	if ($constructtag) {
  790: 	    $result = &Apache::edit::rebuild_tag($token);
  791: 	}
  792:     }
  793:     return $result;
  794: }
  795: 
  796: sub end_ytics {
  797:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  798:     my $result = '';
  799:     if ($target eq 'web' || $target eq 'tex') {
  800:     } elsif ($target eq 'edit') {
  801: 	$result.=&Apache::edit::tag_end($target,$token);
  802:     }
  803:     return $result;
  804: }
  805: 
  806: ##-----------------------------------------------------------------font
  807: my %font_properties =
  808:     (
  809:      'classic'    => {
  810: 	 face       => 'classic',
  811: 	 file       => 'DejaVuSansMono-Bold',
  812: 	 printname  => 'Helvetica',
  813: 	 tex_no_file => 1,
  814:      },
  815:      'sans-serif' => {
  816: 	 face       => 'sans-serif',
  817: 	 file       => 'DejaVuSans',
  818: 	 printname  => 'DejaVuSans',
  819:      },
  820:      'serif'      => {
  821: 	 face       => 'serif',
  822: 	 file       => 'DejaVuSerif',
  823: 	 printname  => 'DejaVuSerif',
  824:      },
  825:      );
  826: 
  827: sub get_font {
  828:     my ($target) = @_;
  829:     my ($size, $selected_font);
  830: 
  831:     if ( $Apache::lonplot::plot{'font'} =~ /^(small|medium|large)/) {
  832: 	$selected_font = $font_properties{'classic'};
  833: 	if ( $Apache::lonplot::plot{'font'} eq 'small') {
  834: 	    $size = '5';
  835: 	} elsif ( $Apache::lonplot::plot{'font'} eq 'medium') {
  836: 	    $size = '9';
  837: 	} elsif ( $Apache::lonplot::plot{'font'} eq 'large') {
  838: 	    $size = '11';
  839: 	} else {
  840: 	    $size = '9';
  841: 	}
  842:     } else {
  843: 	$size = $Apache::lonplot::plot{'font'};
  844: 	$selected_font = $font_properties{$Apache::lonplot::plot{'fontface'}};
  845:     }
  846:     if ($target eq 'tex' && defined($Apache::lonplot::plot{'texfont'})) {
  847: #	$selected_font = $font_properties{'classic'};
  848: 	$size = $Apache::lonplot::plot{'texfont'};
  849:     }
  850:     return ($size, $selected_font);
  851: }
  852: 
  853: ##----------------------------------------------------------------- key
  854: sub start_key {
  855:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  856:     my $result='';
  857:     if ($target eq 'web' || $target eq 'tex') {
  858: 	&get_attributes(\%key,\%key_defaults,$parstack,$safeeval,
  859: 		    $tagstack->[-1]);
  860:     } elsif ($target eq 'edit') {
  861: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Key');
  862: 	$result .= &edit_attributes($target,$token,\%key_defaults);
  863:     } elsif ($target eq 'modified') {
  864: 	my $constructtag=&Apache::edit::get_new_args
  865: 	    ($token,$parstack,$safeeval,keys(%key_defaults));
  866: 	if ($constructtag) {
  867: 	    $result = &Apache::edit::rebuild_tag($token);
  868: 	}
  869:     }
  870:     return $result;
  871: }
  872: 
  873: sub end_key {
  874:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  875:     my $result = '';
  876:     if ($target eq 'web' || $target eq 'tex') {
  877:     } elsif ($target eq 'edit') {
  878: 	$result.=&Apache::edit::tag_end($target,$token);
  879:     }
  880:     return $result;
  881: }
  882: 
  883: sub parse_label {
  884:     my ($target,$text) = @_;
  885:     my $parser=HTML::LCParser->new(\$text);
  886:     my $result;
  887:     while (my $token=$parser->get_token) {
  888: 	if ($token->[0] eq 'S') {
  889: 	    if ($token->[1] eq 'sub') {
  890: 		$result .= '_{';
  891: 	    } elsif ($token->[1] eq 'sup') {
  892: 		$result .= '^{';
  893: 	    } else {
  894: 		$result .= $token->[4];
  895: 	    }
  896: 	} elsif ($token->[0] eq 'E') {
  897: 	    if ($token->[1] eq 'sub'
  898: 		|| $token->[1] eq 'sup') {
  899: 		$result .= '}';
  900: 	    } else {
  901: 		$result .= $token->[2];
  902: 	    }
  903: 	} elsif ($token->[0] eq 'T') {
  904: 	    $result .= &replace_entities($target,$token->[1]);
  905: 	}
  906:     }
  907:     return $result;
  908: }
  909: 
  910: #
  911: #  Note that there are severe restrictions on font selection in the
  912: # ps driver now.  later in life Gnuplot is supposed to support
  913: # utf-8 fonts in the posts script driver.  When this happens,
  914: # the tex entries with comments that include the word <FIX>
  915: # should be changed to print the correct glyphs rather than some
  916: # approximation or fallback of what is intended.
  917: 
  918: my %lookup = 
  919:    (  # Greek alphabet:
  920:       
  921:       '(Alpha|#913)'    => {'tex' => '{/Symbol A}', 'web' => "\x{391}"},
  922:       '(Beta|#914)'    => {'tex' => '{/Symbol B}', 'web' => "\x{392}"},
  923:       '(Chi|#935)'     => {'tex' => '{/Symbol C}', 'web' => "\x{3A7}"},
  924:       '(Delta|#916)'   => {'tex' => '{/Symbol D}', 'web' => "\x{394}"},
  925:       '(Epsilon|#917)' => {'tex' => '{/Symbol E}', 'web' => "\x{395}"},
  926:       '(Phi|#934)'     => {'tex' => '{/Symbol F}', 'web' => "\x{3A6}"},
  927:       '(Gamma|#915)'   => {'tex' => '{/Symbol G}', 'web' => "\x{393}"},
  928:       '(Eta|#919)'     => {'tex' => '{/Symbol H}', 'web' => "\x{397}"},
  929:       '(Iota|#921)'    => {'tex' => '{/Symbol I}', 'web' => "\x{399}"},
  930:       '(Kappa|#922)'   => {'tex' => '{/Symbol K}', 'web' => "\x{39A}"},
  931:       '(Lambda|#923)'  => {'tex' => '{/Symbol L}', 'web' => "\x{39B}"},
  932:       '(Mu|#924)'      => {'tex' => '{/Symbol M}', 'web' => "\x{39C}"},
  933:       '(Nu|#925)'      => {'tex' => '{/Symbol N}', 'web' => "\x{39D}"},
  934:       '(Omicron|#927)' => {'tex' => '{/Symbol O}', 'web' => "\x{39F}"},
  935:       '(Pi|#928)'      => {'tex' => '{/Symbol P}', 'web' => "\x{3A0}"},
  936:       '(Theta|#920)'   => {'tex' => '{/Symbol Q}', 'web' => "\x{398}"},
  937:       '(Rho|#929)'     => {'tex' => '{/Symbol R}', 'web' => "\x{3A1}"},
  938:       '(Sigma|#931)'   => {'tex' => '{/Symbol S}', 'web' => "\x{3A3}"},
  939:       '(Tau|#932)'     => {'tex' => '{/Symbol T}', 'web' => "\x{3A4}"},
  940:       '(Upsilon|#933)' => {'tex' => '{/Symbol U}', 'web' => "\x{3A5}"},
  941:       '(Omega|#937)'   => {'tex' => '{/Symbol W}', 'web' => "\x{3A9}"},
  942:       '(Xi|#926)'      => {'tex' => '{/Symbol X}', 'web' => "\x{39E}"},
  943:       '(Psi|#936)'     => {'tex' => '{/Symbol Y}', 'web' => "\x{3A8}"},
  944:       '(Zeta|#918)'    => {'tex' => '{/Symbol Z}', 'web' => "\x{396}"},
  945:       '(alpha|#945)'   => {'tex' => '{/Symbol a}', 'web' => "\x{3B1}"},
  946:       '(beta|#946)'    => {'tex' => '{/Symbol b}', 'web' => "\x{3B2}"},
  947:       '(chi|#967)'     => {'tex' => '{/Symbol c}', 'web' => "\x{3C7}"},
  948:       '(delta|#948)'   => {'tex' => '{/Symbol d}', 'web' => "\x{3B4}"},
  949:       '(epsilon|#949)' => {'tex' => '{/Symbol e}', 'web' => "\x{3B5}"},
  950:       '(phi|#966)'     => {'tex' => '{/Symbol f}', 'web' => "\x{3C6}"},
  951:       '(gamma|#947)'   => {'tex' => '{/Symbol g}', 'web' => "\x{3B3}"},
  952:       '(eta|#951)'     => {'tex' => '{/Symbol h}', 'web' => "\x{3B7}"},
  953:       '(iota|#953)'    => {'tex' => '{/Symbol i}', 'web' => "\x{3B9}"},
  954:       '(kappa|#954)'   => {'tex' => '{/Symbol k}', 'web' => "\x{3BA}"},
  955:       '(lambda|#955)'  => {'tex' => '{/Symbol k}', 'web' => "\x{3BB}"},
  956:       '(mu|#956)'      => {'tex' => '{/Symbol m}', 'web' => "\x{3BC}"},
  957:       '(nu|#957)'      => {'tex' => '{/Symbol n}', 'web' => "\x{3BD}"},
  958:       '(omicron|#959)' => {'tex' => '{/Symbol o}', 'web' => "\x{3BF}"},
  959:       '(pi|#960)'      => {'tex' => '{/Symbol p}', 'web' => "\x{3C0}"},
  960:       '(theta|#952)'   => {'tex' => '{/Symbol q}', 'web' => "\x{3B8}"},
  961:       '(rho|#961)'     => {'tex' => '{/Symbol r}', 'web' => "\x{3C1}"},
  962:       '(sigma|#963)'   => {'tex' => '{/Symbol s}', 'web' => "\x{3C3}"},
  963:       '(tau|#964)'     => {'tex' => '{/Symbol t}', 'web' => "\x{3C4}"},
  964:       '(upsilon|#965)' => {'tex' => '{/Symbol u}', 'web' => "\x{3C5}"},
  965:       '(omega|#969)'   => {'tex' => '{/Symbol w}', 'web' => "\x{3C9}"},
  966:       '(xi|#958)'      => {'tex' => '{/Symbol x}', 'web' => "\x{3BE}"},
  967:       '(psi|#968)'     => {'tex' => '{/Symbol y}', 'web' => "\x{3C8}"},
  968:       '(zeta|#950)'    => {'tex' => '{/Symbol z}', 'web' => "\x{3B6}"},
  969:       '(thetasym|#977)' => {'tex' => '{/Symbol \165}', 'web' => "\x{3d1}"},
  970:       '(upsih|#978)'   => {'tex' => '{/Symbol \241}', 'web' => "\x{3d2}"},
  971:       '(piv|#982)'     => {'tex' => '{/Symbol \166}', 'web' => "\x{3d6}"},
  972: 
  973: 
  974:       # Punctuation:
  975:       
  976:       '(quot|#034)'   => {'tex' =>  '\42',            'web' => '\42'},
  977:       '(amp|#038)'    => {'tex' =>  '\46',            'web' => '\46'},
  978:       '(lt|#060)'     => {'tex' =>  '\74',            'web' => '\74'},
  979:       '(gt|#062)'     => {'tex' =>  '\76',            'web' => '\76'},
  980:       '#131'          => {'tex' =>  '{/Symbol \246}', 'web' => "\x{192}"},
  981:       '#132'          => {'tex' => '{/Text \271}',    'web' => "\x{201e}"},
  982:       '#133'          => {'tex' => '{/Symbol \274}',  'web'=> "\x{2026}"},
  983:       '#134'          => {'tex' => '{/Text \262}',    'web' => "\x{2020}"},
  984:       '#135'          => {'tex' => '{/Text \263}',    'web' => "\x{2021}"},
  985:       '#136'          => {'tex' => '\\\\^',           'web' => '\\\\^'},
  986:       '#137'          => {'tex' => '%o',              'web' => "\x{2030}"}, # Per Mille <FIX>
  987:       '#138'          => {'tex' => 'S',               'web' => "\x{160}"}, # S-Caron <FIX>
  988:       '#139'          => {'tex' => '<',               'web' => '<'},
  989:       '#140'          => {'tex' => 'AE',              'web' => "\x{152}"}, # AE ligature <FIX>
  990:       '#145'          => {'tex' => '\140',            'web' => "\x{2018}"},
  991:       '#146'          => {'tex' => '\47',             'web' => "\x{2019}"},
  992:       '#147'          => {'tex' => '\140\140',        'web' => "\x{201c}"}, # Left " <FIX>
  993:       '#148'          => {'tex' => '\47\47',          'web' => '\\"'},      # Right " <FIX>
  994:       '#149'          => {'tex' => '{/Symbol \267}',  'web' => "\x{2022}"},
  995:       '#150'          => {'tex' => '{/Text \55}',     'web' => "\x{2013}"},  # en dash
  996:       '#151'          => {'tex' => '{/Symbol \55}',   'web' => "\x{2014}"},  # em dash
  997:       '#152'          => {'tex' => '\\\\~',           'web' => '\\\\~'},
  998:       '#153'          => {'tex' => '{/Symbol \324}',  'web' => "\x{2122}"}, # trademark
  999: 
 1000:       # Accented letters, and other furreign language glyphs.
 1001: 
 1002:       '#154'          => {'tex' => 's',               'web' => "\x{161}"}, # small s-caron no ps.
 1003:       '#155'          => {'tex' => '>',               'web' => '\76'},     # >
 1004:       '#156'          => {'tex' => '{/Text \366}',    'web' => "\x{153}"}, # oe ligature.<FIX>
 1005:       '#159',         => {'tex' => 'Y',               'web' => "\x{178}"}, # Y-umlaut - can't print <FIX>
 1006:       '(nbsp|#160)'   => {'tex' => ' ',               'web' => ' '},       # non breaking space.
 1007:       '(iexcl|#161)'  => {'tex' => '{/Text \241}',    'web' => "\x{a1}"},  # inverted !
 1008:       '(cent|#162)'   => {'tex' => '{/Text \242}',    'web' => "\x{a2}"},  # Cent currency.
 1009:       '(pound|#163)'  => {'tex' => '{/Text \243}',    'web' => "\x{a3}"},  # GB Pound currency.
 1010:       '(curren|#164)' => {'tex' => '{/ZapfDingbats \161}','web' => "\x{a4}"},  # Generic currency symb. <FIX>
 1011:       '(yen|#165)'    => {'tex' => '{/Text \245}',    'web' => "\x{a5}"},  # Yen currency.
 1012:       '(brvbar|#166)' => {'tex' => '{/Symbol \174}',  'web' => "\x{a6}"},  # Broken vert bar no print.
 1013:       '(sect|#167)'   => {'tex' => '{\247}',          'web' => "\x{a7}"},  # Section symbol.
 1014:       '(uml|#168)'    => {'tex' => '{\250}',          'web' => "\x{a8}"},  # 'naked' umlaut.
 1015:       '(copy|#169)'   => {'tex' => '{/Symbol \343}',  'web' => "\x{a9}"},  # Copyright symbol.
 1016:       '(ordf|#170)'   => {'tex' => '{/Text \343}',    'web' => "\x{aa}"},  # Feminine ordinal.
 1017:       '(laquo|#171)'  => {'tex' => '{/Text \253}',    'web' => "\x{ab}"},  # << quotes.
 1018:       '(not|#172)'    => {'tex' => '\254',            'web' => "\x{ac}"},  # Logical not.
 1019:       '(shy|#173)'    => {'tex' => '\255',               'web' => "\x{ad}"},  # soft hyphen.
 1020:       '(reg|#174)'    => {'tex' => '{/Symbol \342}',  'web' => "\x{ae}"},  # Registered tm.
 1021:       '(macr|#175)'   => {'tex' => '^{\255}',            'web' => "\x{af}"},  # 'naked' macron (overbar).
 1022:       '(deg|#176)'    => {'tex' => '{/Text \260}',    'web' => "\x{b0}"},  # Degree symbo..`
 1023:       '(plusmn|#177)' => {'tex' => '{/Symbol \261}',  'web' => "\x{b1}"},  # +/- symbol.
 1024:       '(sup2|#178)'   => {'tex' => '^2',              'web' => "\x{b2}"},  # Superscript 2.
 1025:       '(sup3|#179)'   => {'tex' => '^3',              'web' => "\x{b3}"},  # Superscript 3.
 1026:       '(acute|#180)'  => {'tex' => '{/Text \222}',    'web' => "\x{b4}"},  # 'naked' acute accent.
 1027:       '(micro|#181)'  => {'tex' => '{/Symbol \155}',  'web' => "\x{b5}"},  # Micro (small mu).
 1028:       '(para|#182)'   => {'tex' => '{/Text \266}',    'web' => "\x{b6}"},  # Paragraph symbol.
 1029:       '(middot|#183)' => {'tex' => '\267',            'web' => "\x{b7}"},  # middle dot
 1030:       '(cedil|#184)'  => {'tex' => '\233',            'web' => "\x{b8}"},  # 'naked' cedilla.
 1031:       '(sup1|#185)'   => {'tex' => '^1',              'web' => "\x{b9}"},  # superscript 1.
 1032:       '(ordm|#186)'   => {'tex' => '{\260}',          'web' => "\x{ba}"},  # masculine ordinal.
 1033:       '(raquo|#187)', => {'tex' => '\273',            'web' => "\x{bb}"},  # Right angle quotes.
 1034:       '(frac14|#188)' => {'tex' => '\274',            'web' => "\x{bc}"},  # 1/4.
 1035:       '(frac12|#189)' => {'tex' => '\275',            'web' => "\x{bd}"},  # 1/2.
 1036:       '(frac34|#190)' => {'tex' => '\276',            'web' => "\x{be}"},  # 3/4
 1037:       '(iquest|#191)' => {'tex' => '{/Text \277}',    'web' => "\x{bf}"},  # Inverted ?
 1038:       '(Agrave|#192)' => {'tex' => '\300',            'web' => "\x{c0}"},  # A Grave.
 1039:       '(Aacute|#193)' => {'tex' => '\301',            'web' => "\x{c1}"},  # A Acute.
 1040:       '(Acirc|#194)'  => {'tex' => '\302',            'web' => "\x{c2}"},  # A Circumflex.
 1041:       '(Atilde|#195)' => {'tex' => '\303',            'web' => "\x{c3}"},  # A tilde.
 1042:       '(Auml|#196)'   => {'tex' => '\304',            'web' => "\x{c4}"},  # A umlaut.
 1043:       '(Aring|#197)'  => {'tex' => '\305',            'web' => "\x{c5}"},  # A ring.
 1044:       '(AElig|#198)'  => {'tex' => '\306',            'web' => "\x{c6}"},  # AE ligature.
 1045:       '(Ccedil|#199)' => {'tex' => '\307',            'web' => "\x{c7}"},  # C cedilla
 1046:       '(Egrave|#200)' => {'tex' => '\310',            'web' => "\x{c8}"},  # E Accent grave.
 1047:       '(Eacute|#201)' => {'tex' => '\311',            'web' => "\x{c9}"},  # E acute accent.
 1048:       '(Ecirc|#202)'  => {'tex' => '\312',            'web' => "\x{ca}"},  # E Circumflex.
 1049:       '(Euml|#203)'   => {'tex' => '\313',            'web' => "\x{cb}"},  # E umlaut.
 1050:       '(Igrave|#204)' => {'tex' => '\314',            'web' => "\x{cc}"},  # I grave accent.
 1051:       '(Iacute|#205)' => {'tex' => '\315',            'web' => "\x{cd}"},  # I acute accent.
 1052:       '(Icirc|#206)'  => {'tex' => '\316',            'web' => "\x{ce}"},  # I circumflex.
 1053:       '(Iuml|#207)'   => {'tex' => '\317',            'web' => "\x{cf}"},  # I umlaut.
 1054:       '(ETH|#208)'    => {'tex' => '\320',            'web' => "\x{d0}"},  # Icelandic Cap eth.
 1055:       '(Ntilde|#209)' => {'tex' => '\321',            'web' => "\x{d1}"},  # Ntilde (enyan).
 1056:       '(Ograve|#210)' => {'tex' => '\322',            'web' => "\x{d2}"},  # O accent grave.
 1057:       '(Oacute|#211)' => {'tex' => '\323',            'web' => "\x{d3}"},  # O accent acute.
 1058:       '(Ocirc|#212)'  => {'tex' => '\324',            'web' => "\x{d4}"},  # O circumflex.
 1059:       '(Otilde|#213)' => {'tex' => '\325',            'web' => "\x{d5}"},  # O tilde.
 1060:       '(Ouml|#214)'   => {'tex' => '\326',            'web' => "\x{d6}"},  # O umlaut.
 1061:       '(times|#215)'  => {'tex' => '\327',            'web' => "\x{d7}"},  # Times symbol.
 1062:       '(Oslash|#216)' => {'tex' => '\330',            'web' => "\x{d8}"},  # O slash.
 1063:       '(Ugrave|#217)' => {'tex' => '\331',            'web' => "\x{d9}"},  # U accent grave.
 1064:       '(Uacute|#218)' => {'tex' => '\332',            'web' => "\x{da}"},  # U accent acute.
 1065:       '(Ucirc|#219)'  => {'tex' => '\333',            'web' => "\x{db}"},  # U circumflex.
 1066:       '(Uuml|#220)'   => {'tex' => '\334',            'web' => "\x{dc}"},  # U umlaut.
 1067:       '(Yacute|#221)' => {'tex' => '\335',            'web' => "\x{dd}"},  # Y accent acute.
 1068:       '(THORN|#222)'  => {'tex' => '\336',            'web' => "\x{de}"},  # Icelandic thorn.
 1069:       '(szlig|#223)'  => {'tex' => '\337',            'web' => "\x{df}"},  # German sharfes s.
 1070:       '(agrave|#224)' => {'tex' => '\340',            'web' => "\x{e0}"},  # a accent grave.
 1071:       '(aacute|#225)' => {'tex' => '\341',            'web' => "\x{e1}"},  # a grave.
 1072:       '(acirc|#226)'  => {'tex' => '\342',            'web' => "\x{e2}"},  # a circumflex.
 1073:       '(atilde|#227)' => {'tex' => '\343',            'web' => "\x{e3}"},  # a tilde.
 1074:       '(auml|#228)'   => {'tex' => '\344',            'web' => "\x{e4}"},  # a umlaut
 1075:       '(aring|#229)'  => {'tex' => '\345',            'web' => "\x{e5}"},  # a ring on top.
 1076:       '(aelig|#230)'  => {'tex' => '\346',            'web' => "\x{e6}"},  # ae ligature.
 1077:       '(ccedil|#231)' => {'tex' => '\347',            'web' => "\x{e7}"},  # C cedilla
 1078:       '(egrave|#232)' => {'tex' => '\350',            'web' => "\x{e8}"},  # e accent grave.
 1079:       '(eacute|#233)' => {'tex' => '\351',            'web' => "\x{e9}"},  # e accent acute.
 1080:       '(ecirc|#234)'  => {'tex' => '\352',            'web' => "\x{ea}" }, # e circumflex.
 1081:       '(euml|#235)'   => {'tex' => '\353',            'web' => "\x{eb}"},  # e umlaut.
 1082:       '(igrave|#236)' => {'tex' => '\354',            'web' => "\x{ec}"},  # i grave.
 1083:       '(iacute|#237)' => {'tex' => '\355',            'web' => "\x{ed}"},  # i acute.
 1084:       '(icirc|#238)'  => {'tex' => '\356',            'web' => "\x{ee}"},  # i circumflex.
 1085:       '(iuml|#239)'   => {'tex' => '\357',            'web' => "\x{ef}"},  # i umlaut.
 1086:       '(eth|#240)'    => {'tex' => '\360',            'web' => "\x{f0}"},  # Icelandic eth.
 1087:       '(ntilde|#241)' => {'tex' => '\361',            'web' => "\x{f1}"},  # n tilde.
 1088:       '(ograve|#242)' => {'tex' => '\362',            'web' => "\x{f2}"},  # o grave.
 1089:       '(oacute|#243)' => {'tex' => '\363',            'web' => "\x{f3}"},  # o acute.
 1090:       '(ocirc|#244)'  => {'tex' => '\364',            'web' => "\x{f4}"},  # o circumflex.
 1091:       '(otilde|#245)' => {'tex' => '\365',            'web' => "\x{f5}"},  # o tilde.
 1092:       '(ouml|#246)'   => {'tex' => '\366',            'web' => "\x{f6}"},  # o umlaut.
 1093:       '(divide|#247)' => {'tex' => '\367',            'web' => "\x{f7}"},  # division symbol
 1094:       '(oslash|#248)' => {'tex' => '\370',            'web' => "\x{f8}"},  # o slashed.
 1095:       '(ugrave|#249)' => {'tex' => '\371',            'web' => "\x{f9}"},  # u accent grave.
 1096:       '(uacute|#250)' => {'tex' => '\372',            'web' => "\x{fa}"},  # u acute.
 1097:       '(ucirc|#251)'  => {'tex' => '\373',            'web' => "\x{fb}"},  # u circumflex.
 1098:       '(uuml|#252)'   => {'tex' => '\374',            'web' => "\x{fc}"},  # u umlaut.
 1099:       '(yacute|#253)' => {'tex' => '\375',            'web' => "\x{fd}"},  # y acute accent.
 1100:       '(thorn|#254)'  => {'tex' => '\376',            'web' => "\x{fe}"},  # small thorn (icelandic).
 1101:       '(yuml|#255)'   => {'tex' => '\377',            'web' => "\x{ff}"},  # y umlaut.
 1102:       
 1103:       # Latin extended A entities:
 1104: 
 1105:       '(OElig|#338)'  => {'tex' => '{/Text \326}',   'web' => "\x{152}"},  # OE ligature.
 1106:       '(oelig|#339)'  => {'tex' => '{/Text \366}',   'web' => "\x{153}"},  # oe ligature.
 1107:       '(Scaron|#352)' => {'tex' => 'S',              'web' => "\x{160}"},  # S caron no printable.
 1108:       '(scaron|#353)' => {'tex' => 's',              'web' => "\x{161}"},  # s caron no printable.
 1109:       '(Yuml|#376)'   => {'tex' => 'Y',              'web' => "\x{178}"},  # Y umlaut - no printable.
 1110: 
 1111:       # Latin extended B.
 1112: 
 1113:       '(fnof|#402)'  => {'tex' =>'{/Symbol \246}',    'web' => "\x{192}"},  # f with little hook.
 1114: 
 1115:       # Standalone accents:
 1116: 
 1117:       '(circ|#710)'  => {'tex' => '^',               'web' => '^'},        # circumflex.
 1118:       '(tilde|#732)' => {'tex' => '~',               'web' => '~'},        # tilde.
 1119: 
 1120:       # General punctuation.  We're not able to make a distinction between
 1121:       # the various length spacings in the print version. (e.g. en/em/thin).
 1122:       # the various joiners will be empty strings in the print version too.
 1123: 
 1124: 
 1125:       '(ensp|#8194)'   => {'tex' => ' ',              'web' => "\x{2002}"}, # en space.
 1126:       '(emsp|#8195)'   => {'tex' => ' ',              'web' => "\x{2003}"}, # em space.
 1127:       '(thinsp|#8201)' => {'tex' => ' ',              'web' => "\x{2009}"}, # thin space.
 1128:       '(zwnj|#8204)'   => {'tex' => ' ',               'web' => "\x{200c}"}, # Zero width non joiner.
 1129:       '(zwj|#8205)'    => {'tex' => ' ',               'web' => "\x{200d}"}, # Zero width joiner.
 1130:       '(lrm|#8206)'    => {'tex' => ' ',               'web' => "\x{200e}"}, # Left to right mark
 1131:       '(rlm|#8207)'    => {'tex' => ' ',               'web' => "\x{200f}"}, # right to left mark.
 1132:       '(ndash|#8211)'  => {'tex' => '{/Text \55}',    'web' => "\x{2013}"}, # en dash.
 1133:       '(mdash|#8212)'  => {'tex' => '{/Symbol \55}',  'web' => "\x{2014}"}, # em dash.
 1134:       '(lsquo|#8216)'  => {'tex' => '{/Text \140}',   'web' => "\x{2018}"}, # Left single quote.
 1135:       '(rsquo|#8217)'  => {'tex' => '\47',            'web' => "\x{2019}"}, # Right single quote.
 1136:       '(sbquo|#8218)'  => {'tex' => '\54',             'web' => "\x{201a}"}, # Single low-9 quote.
 1137:       '(ldquo|#8220)'  => {'tex' => '\42',   'web' => "\x{201c}"}, # Left double quote.
 1138:       '(rdquo|#8221)'  => {'tex' => '\42',   'web' => "\x{201d}"}, # Right double quote.
 1139:       '(bdquo|#8222)'  => {'tex' => ',',              'web' => "\x{201e}"}, # Double low-9 quote.
 1140:       '(dagger|#8224)' => {'tex' => '+',   'web' => "\x{2020}"}, # Is this a dagger I see before me now?
 1141:       '(Dagger|#8225)' => {'tex' => '\261',   'web' => "\x{2021}"}, # it's handle pointing towards my heart?
 1142:       '(bull|#8226)'   => {'tex' => '\267',           'web' => "\x{2022}"}, # Bullet.
 1143:       '(hellep|#8230)' => {'tex' => '{/Symbol \274}',   'web' => "\x{2026}"}, # Ellipses.
 1144:       '(permil|#8240)' => {'tex' => '%_o',            'web' => "\x{2031}"}, # Per mille.
 1145:       '(prime|#8242)'  => {'tex' => '\264',           'web' => "\x{2032}"}, # Prime.
 1146:       '(Prime|#8243)'  => {'tex' => '{/Symbol \262}', 'web' => "\x{2033}"}, # double prime.
 1147:       '(lsaquo|#8249)' => {'tex' => '<',              'web' => "\x{2039}"}, # < quote.
 1148:       '(rsaquo|#8250)' => {'tex' => '\74',              'web' => "\x{203a}"}, # > quote.
 1149:       '(oline|#8254)'  => {'tex' => '{/Symbol \140}', 'web' => "\x{203e}"}, # Overline.
 1150:       '(frasl|#8260)'  => {'tex' => '/',              'web' => "\x{2044}"}, # Fraction slash.
 1151:       '(euro|#8364)'   => {'tex' => '{/Symbol \240}', 'web' => "\x{20ac}"}, # Euro currency.
 1152:       
 1153:       # Letter like symbols.
 1154: 
 1155:       '(weierp|#8472)'  => {'tex' => '{/Symbol \303}', 'web' => "\x{2118}"}, # Power set symbol
 1156:       '(image|#8465)'   => {'tex' => '{/Symbol \301}', 'web' => "\x{2111}"}, # Imaginary part
 1157:       '(real|#8476)'    => {'tex' => '{/Symbol \302}', 'web' => "\x{211c}"}, # Real part.
 1158:       '(trade|#8482)'   => {'tex' => '{/Symbol \344}', 'web' => "\x{2122}"}, # trademark symbol.
 1159:       '(alefsym|#8501)' => {'tex' => '{/Symbol \300}', 'web' => "\x{2135}"}, # Hebrew alef.
 1160: 
 1161:       # Arrows  of various types and directions.
 1162:       '(larr|#8592)'    => {'tex' => '{/Symbol \254}', 'web' => "\x{2190}"}, # <--
 1163:       '(uarr|#8593)'    => {'tex' => '{/Symbol \255}', 'web' => "\x{2191}"}, # up arrow.
 1164:       '(rarr|#8594)'    => {'tex' => '{/Symbol \256}', 'web' => "\x{2192}"}, # -->
 1165:       '(darr|#8595)'    => {'tex' => '{/Symbol \257}', 'web' => "\x{2193}"}, # down arrow.
 1166:       '(harr|#8596)'    => {'tex' => '{/Symbol \253}', 'web' => "\x{2194}"}, # <-->
 1167:       '(crarr|#8629)'   => {'tex' => '{/Symbol \277}', 'web' => "\x{21b5}"}, # corner arrow down and right.
 1168:       '(lArr|#8656)'    => {'tex' => '{/Symbol \334}', 'web' => "\x{21d0}"}, # <==
 1169:       '(uArr|#8657)'    => {'tex' => '{/Symbol \335}', 'web' => "\x{21d1}"}, # Up double arrow.
 1170:       '(rArr|#8658)'    => {'tex' => '{/Symbol \336}', 'web' => "\x{21d2}"}, # ==>
 1171:       '(dArr|#8659)'    => {'tex' => '{/Symbol \337}', 'web' => "\x{21d3}"}, # Down double arrow.
 1172:       '(hArr|#8660)'    => {'tex' => '{/Symbol \333}', 'web' => "\x{21d4}"}, # <==>
 1173: 
 1174:       # Mathematical operators. For some of these we do the best we can in printing.
 1175: 
 1176:       '(forall|#8704)'  => {'tex' => '{/Symbol \42}',   'web' => "\x{2200}"}, # For all.
 1177:       '(part|#8706)'    => {'tex' => '{/Symbol d}',     'web' => "\x{2202}"}, # partial derivative
 1178:       '(exist|#8707)'   => {'tex' => '{/Symbol \44}',   'web' => "\x{2203}"}, # There exists.
 1179:       '(empty|#8709)'   => {'tex' => '{/Symbol \306}',  'web' => "\x{2205}"}, # Null set.
 1180:       '(nabla|#8711)'   => {'tex' => '{/Symbol \321}',  'web' => "\x{2207}"}, # Gradient e.g.
 1181:       '(isin|#8712)'    => {'tex' => '{/Symbol \316}',  'web' => "\x{2208}"}, # Element of the set.
 1182:       '(notin|#8713)'   => {'tex' => '{/Symbol \317}',  'web' => "\x{2209}"}, # Not an element of
 1183:       '(ni|#8715)'      => {'tex' => '{/Symbol \47}',   'web' => "\x{220b}"}, # Contains as a member
 1184:       '(prod|#8719)'    => {'tex' => '{/Symbol \325}',  'web' => "\x{220f}"}, # Product 
 1185:       '(sum|#8721)'     => {'tex' => '{/Symbol \345}',  'web' => "\x{2211}"}, # Sum of.
 1186:       '(minus|#8722)'   => {'tex' => '{/Symbol \55}',   'web' => "\x{2212}"}, # - sign.
 1187:       '(lowast|#8727)'  => {'tex' => '*',               'web' => "\x{2217}"}, # * 
 1188:       '(radic|#8730)'   => {'tex' => '{/Symbol \326}',  'web' => "\x{221a}"}, # Square root. 
 1189:       '(prop|#8733)'    => {'tex' => '{/Symbol \265}',  'web' => "\x{221d}"}, # Proportional to.
 1190:       '(infin|#8734)'   => {'tex' => '{/Symbol \245}',  'web' => "\x{221e}"}, # Infinity.
 1191:       '(ang|#8736)'     => {'tex' => '{/Symbol \320}',  'web' => "\x{2220}"}, # Angle .
 1192:       '(and|#8743)'     => {'tex' => '{/Symbol \331}',  'web' => "\x{2227}"}, # Logical and.
 1193:       '(or|#8744)'      => {'tex' => '{/Symbol \332}',  'web' => "\x{2228}"}, # Logical or.
 1194:       '(cap|#8745)'     => {'tex' => '{/Symbol \307}',  'web' => "\x{2229}"}, # Set intersection.
 1195:       '(cup|#8746)'     => {'tex' => '{/Symbol \310}',  'web' => "\x{222a}"}, # Set union.
 1196:       '(int|8747)'      => {'tex' => '{/Symbol \362}',  'web' => "\x{222b}"}, # Integral.
 1197: 
 1198:       # Some gnuplot guru will have to explain to me why the next three
 1199:       # require the extra slashes... else they print very funkily.
 1200: 
 1201:       '(there4|#8756)'  => {'tex' => '{/Symbol \\\134}',  'web' => "\x{2234}"}, # Therefore triple dots.
 1202:       '(sim|#8764)'     => {'tex' => '\\\176',               'web' => "\x{223c}"}, # Simlar to.
 1203:       '(cong|#8773)'    => {'tex' => '{/Symbol \\\100}','web' => "\x{2245}"}, # Congruent to/with.
 1204: 
 1205:       '(asymp|#8776)'   => {'tex' => '{/Symbol \273}',  'web' => "\x{2248}"}, # Asymptotic to.
 1206:       '(ne|#8800)'      => {'tex' => '{/Symbol \271}',  'web' => "\x{2260}"}, # not equal to.
 1207:       '(equiv|#8801)'   => {'tex' => '{/Symbol \272}',  'web' => "\x{2261}"}, # Equivalent to.
 1208:       '(le|8804)'       => {'tex' => '{/Symbol \243}',  'web' => "\x{2264}"}, # Less than or equal to.
 1209:       '(ge|8805)'       => {'tex' => '{/Symbol \263}',  'web' => "\x{2265}"}, # Greater than or equal to
 1210:       '(sub|8834)'      => {'tex' => '{/Symbol \314}',  'web' => "\x{2282}"}, # Subset of.
 1211:       '(sup|8835)'      => {'tex' => '{/Symbol \311}',  'web' => "\x{2283}"}, # Super set of.
 1212:       '(nsub|8836)'     => {'tex' => '{/Symbol \313}',  'web' => "\x{2284}"}, # not subset of.
 1213:       '(sube|8838)'     => {'tex' => '{/Symbol \315}',  'web' => "\x{2286}"}, # Subset or equal.
 1214:       '(supe|8839)'     => {'tex' => '{/Symbol \312}',  'web' => "\x{2287}"}, # Superset or equal
 1215:       '(oplus|8853)'    => {'tex' => '{/Symbol \305}',  'web' => "\x{2295}"}, # O with plus inside
 1216:       '(otimes|8855)'   => {'tex' => '{/Symbol \304}',  'web' => "\x{2297}"}, # O with times.
 1217:       '(perp|8869)'     => {'tex' => '{/Symbol \136}',  'web' => "\x{22a5}"}, # Perpendicular.
 1218:       '(sdot|8901)'     => {'tex' => '{/Symbol \227}',  'web' => "\x{22c5}"}, # Dot operator.
 1219: 
 1220:       # Misc. technical symbols:
 1221: 
 1222:       '(lceil|8698)'    => {'tex' => '{/Symbol \351}',  'web' => "\x{2308}"}, # Left ceiling.
 1223:       '(rceil|8969)'    => {'tex' => '{/Symbol \371}',  'web' => "\x{2309}"}, # Right ceiling.
 1224:       '(lfloor|8970)'   => {'tex' => '{/Symbol \353}',  'web' => "\x{230a}"}, # Left floor.
 1225:       '(rfloor|8971)'   => {'tex' => '{/Symbol \373}',  'web' => "\x{230b}"}, # Right floor.
 1226: 
 1227:       # The gnuplot png font evidently does not have the big angle brackets at
 1228:       # positions 0x2329, 0x232a so use ordinary brackets.
 1229: 
 1230:       '(lang|9001)'     => {'tex' => '{/Symbol \341}',  'web' => '<'}, # Left angle bracket.
 1231:       '(rang|9002)'     => {'tex' => '{/Symbol \361}',  'web' => '>'}, # Right angle bracket.
 1232: 
 1233:       # Gemoetric shapes.
 1234: 
 1235:       '(loz|9674)'      => {'tex' => '{/Symbol \340}',  'web' => "\x{25ca}"}, # Lozenge.
 1236: 
 1237:       # Misc. symbols
 1238: 
 1239:       '(spades|9824)'   => {'tex' => '{/Symbol \252}', 'web' => "\x{2660}"}, 
 1240:       '(clubs|9827)'    => {'tex' => '{/Symbol \247}', 'web' => "\x{2663}"}, 
 1241:       '(hearts|9829)'   => {'tex' => '{/Symbol \251}', 'web' => "\x{2665}"}, 
 1242:       '(diams|9830)'    => {'tex' => '{/Symbol \250}', 'web' => "\x{2666}"}
 1243: 
 1244:     );
 1245: 
 1246: 
 1247: sub replace_entities {
 1248:     my ($target,$text) = @_;
 1249:     $text =~ s{([_^~\{\}]|\\\\)}{\\\\$1}g;
 1250:     while (my ($re, $replace) = each(%lookup)) {
 1251: 	my $repl = $replace->{$target};
 1252: 	$text =~ s/&$re;/$replace->{$target}/g;
 1253:     }
 1254:     $text =~ s{(&)}{\\\\$1}g;
 1255:     return $text;
 1256: }
 1257: 
 1258: ##------------------------------------------------------------------- title
 1259: sub start_title {
 1260:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1261:     my $result='';
 1262:     if ($target eq 'web' || $target eq 'tex') {
 1263: 	$title = &Apache::lonxml::get_all_text("/title",$parser,$style);
 1264: 	$title=&Apache::run::evaluate($title,$safeeval,$$parstack[-1]);
 1265: 	$title =~ s/\n/ /g;
 1266: 	if (length($title) > $max_str_len) {
 1267: 	    $title = substr($title,0,$max_str_len);
 1268: 	}
 1269: 	$title = &parse_label($target,$title);
 1270:     } elsif ($target eq 'edit') {
 1271: 	$result.=&Apache::edit::tag_start($target,$token,'Plot Title');
 1272: 	my $text=&Apache::lonxml::get_all_text("/title",$parser,$style);
 1273: 	$result.=&Apache::edit::editline('',$text,'',60);
 1274:     } elsif ($target eq 'modified') {
 1275: 	$result.=&Apache::edit::rebuild_tag($token);
 1276: 	$result.=&Apache::edit::modifiedfield("/title",$parser);
 1277:     }
 1278:     return $result;
 1279: }
 1280: 
 1281: sub end_title {
 1282:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1283:     my $result = '';
 1284:     if ($target eq 'web' || $target eq 'tex') {
 1285:     } elsif ($target eq 'edit') {
 1286: 	$result.=&Apache::edit::tag_end($target,$token);
 1287:     }
 1288:     return $result;
 1289: }
 1290: ##------------------------------------------------------------------- xlabel
 1291: sub start_xlabel {
 1292:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1293:     my $result='';
 1294:     if ($target eq 'web' || $target eq 'tex') {
 1295: 	$xlabel = &Apache::lonxml::get_all_text("/xlabel",$parser,$style);
 1296: 	$xlabel=&Apache::run::evaluate($xlabel,$safeeval,$$parstack[-1]);
 1297: 	$xlabel =~ s/\n/ /g;
 1298: 	if (length($xlabel) > $max_str_len) {
 1299: 	    $xlabel = substr($xlabel,0,$max_str_len);
 1300: 	}
 1301: 	$xlabel = &parse_label($target,$xlabel);
 1302:     } elsif ($target eq 'edit') {
 1303: 	$result.=&Apache::edit::tag_start($target,$token,'Plot Xlabel');
 1304: 	my $text=&Apache::lonxml::get_all_text("/xlabel",$parser,$style);
 1305: 	$result.=&Apache::edit::editline('',$text,'',60);
 1306:     } elsif ($target eq 'modified') {
 1307: 	$result.=&Apache::edit::rebuild_tag($token);	
 1308: 	$result.=&Apache::edit::modifiedfield("/xlabel",$parser);
 1309:     }
 1310:     return $result;
 1311: }
 1312: 
 1313: sub end_xlabel {
 1314:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1315:     my $result = '';
 1316:     if ($target eq 'web' || $target eq 'tex') {
 1317:     } elsif ($target eq 'edit') {
 1318: 	$result.=&Apache::edit::tag_end($target,$token);
 1319:     }
 1320:     return $result;
 1321: }
 1322: 
 1323: ##------------------------------------------------------------------- ylabel
 1324: sub start_ylabel {
 1325:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1326:     my $result='';
 1327:     if ($target eq 'web' || $target eq 'tex') {
 1328: 	$ylabel = &Apache::lonxml::get_all_text("/ylabel",$parser,$style);
 1329: 	$ylabel = &Apache::run::evaluate($ylabel,$safeeval,$$parstack[-1]);
 1330: 	$ylabel =~ s/\n/ /g;
 1331: 	if (length($ylabel) > $max_str_len) {
 1332: 	    $ylabel = substr($ylabel,0,$max_str_len);
 1333: 	}
 1334: 	$ylabel = &parse_label($target,$ylabel);
 1335:     } elsif ($target eq 'edit') {
 1336: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Ylabel');
 1337: 	my $text = &Apache::lonxml::get_all_text("/ylabel",$parser,$style);
 1338: 	$result .= &Apache::edit::editline('',$text,'',60);
 1339:     } elsif ($target eq 'modified') {
 1340: 	$result.=&Apache::edit::rebuild_tag($token);
 1341: 	$result.=&Apache::edit::modifiedfield("/ylabel",$parser);
 1342:     }
 1343:     return $result;
 1344: }
 1345: 
 1346: sub end_ylabel {
 1347:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1348:     my $result = '';
 1349:     if ($target eq 'web' || $target eq 'tex') {
 1350:     } elsif ($target eq 'edit') {
 1351: 	$result.=&Apache::edit::tag_end($target,$token);
 1352:     }
 1353:     return $result;
 1354: }
 1355: 
 1356: ##------------------------------------------------------------------- label
 1357: sub start_label {
 1358:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1359:     my $result='';
 1360:     if ($target eq 'web' || $target eq 'tex') {
 1361: 	my %label;
 1362: 	&get_attributes(\%label,\%label_defaults,$parstack,$safeeval,
 1363: 		    $tagstack->[-1]);
 1364: 	my $text = &Apache::lonxml::get_all_text("/label",$parser,$style);
 1365: 	$text = &Apache::run::evaluate($text,$safeeval,$$parstack[-1]);
 1366: 	$text =~ s/\n/ /g;
 1367: 	$text = substr($text,0,$max_str_len) if (length($text) > $max_str_len);
 1368: 	$label{'text'} = &parse_label($target,$text);
 1369: 	push(@labels,\%label);
 1370:     } elsif ($target eq 'edit') {
 1371: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Label');
 1372: 	$result .= &edit_attributes($target,$token,\%label_defaults);
 1373: 	my $text = &Apache::lonxml::get_all_text("/label",$parser,$style);
 1374: 	$result .= &Apache::edit::end_row().
 1375: 	    &Apache::edit::start_spanning_row().
 1376: 	    &Apache::edit::editline('',$text,'',60);
 1377:     } elsif ($target eq 'modified') {
 1378: 	&Apache::edit::get_new_args
 1379: 	    ($token,$parstack,$safeeval,keys(%label_defaults));
 1380: 	$result.=&Apache::edit::rebuild_tag($token);
 1381: 	$result.=&Apache::edit::modifiedfield("/label",$parser);
 1382:     }
 1383:     return $result;
 1384: }
 1385: 
 1386: sub end_label {
 1387:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1388:     my $result = '';
 1389:     if ($target eq 'web' || $target eq 'tex') {
 1390:     } elsif ($target eq 'edit') {
 1391: 	$result.=&Apache::edit::tag_end($target,$token);
 1392:     }
 1393:     return $result;
 1394: }
 1395: 
 1396: ##------------------------------------------------------------------- curve
 1397: sub start_curve {
 1398:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1399:     my $result='';
 1400:     &Apache::lonxml::register('Apache::lonplot',('function','data'));
 1401:     push (@Apache::lonxml::namespace,'curve');
 1402:     if ($target eq 'web' || $target eq 'tex') {
 1403: 	my %curve;
 1404: 	&get_attributes(\%curve,\%curve_defaults,$parstack,$safeeval,
 1405: 		    $tagstack->[-1]);
 1406: 	push (@curves,\%curve);
 1407:     } elsif ($target eq 'edit') {
 1408: 	$result .= &Apache::edit::tag_start($target,$token,'Curve');
 1409: 	$result .= &edit_attributes($target,$token,\%curve_defaults,
 1410:                                     \@curve_edit_order)
 1411: 	    .&Apache::edit::end_row()
 1412: 	    .&Apache::edit::start_spanning_row();
 1413: 
 1414:     } elsif ($target eq 'modified') {
 1415: 	my $constructtag=&Apache::edit::get_new_args
 1416: 	    ($token,$parstack,$safeeval,keys(%curve_defaults));
 1417: 	if ($constructtag) {
 1418: 	    #
 1419: 	    # Fix up the color attribute as jcolor does not prepend an x
 1420: 	    #
 1421: 	    my $value = $token->[2]{'color'};
 1422: 	    if (defined $value && !($value =~ /^x/)) {
 1423: 		$token->[2]{'color'} = 'x' . $value;
 1424: 	    }
 1425: 	    $result = &Apache::edit::rebuild_tag($token);
 1426: 	}
 1427:     }
 1428:     return $result;
 1429: }
 1430: 
 1431: sub end_curve {
 1432:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1433:     my $result = '';
 1434:     pop @Apache::lonxml::namespace;
 1435:     &Apache::lonxml::deregister('Apache::lonplot',('function','data'));
 1436:     if ($target eq 'web' || $target eq 'tex') {
 1437:     } elsif ($target eq 'edit') {
 1438: 	$result.=&Apache::edit::tag_end($target,$token);
 1439:     }
 1440:     return $result;
 1441: }
 1442: 
 1443: ##------------------------------------------------------------ curve function
 1444: sub start_function {
 1445:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1446:     my $result='';
 1447:     if ($target eq 'web' || $target eq 'tex') {
 1448: 	if (exists($curves[-1]->{'data'})) {
 1449: 	    &Apache::lonxml::warning
 1450:                 ('Use of the <b>curve function</b> tag precludes use of '.
 1451:                  ' the <b>curve data</b> tag.  '.
 1452:                  'The curve data tag will be omitted in favor of the '.
 1453:                  'curve function declaration.');
 1454: 	    delete $curves[-1]->{'data'} ;
 1455: 	}
 1456:         my $function = &Apache::lonxml::get_all_text("/function",$parser,
 1457: 						     $style);
 1458: 	$function = &Apache::run::evaluate($function,$safeeval,$$parstack[-1]);
 1459:         $function=~s/\^/\*\*/gs;
 1460: 	$curves[-1]->{'function'} = $function; 
 1461:     } elsif ($target eq 'edit') {
 1462: 	$result .= &Apache::edit::tag_start($target,$token,'Gnuplot compatible curve function');
 1463: 	my $text = &Apache::lonxml::get_all_text("/function",$parser,$style);
 1464: 	$result .= &Apache::edit::editline('',$text,'',60);
 1465:     } elsif ($target eq 'modified') {
 1466: 	$result.=&Apache::edit::rebuild_tag($token);
 1467: 	$result.=&Apache::edit::modifiedfield("/function",$parser);
 1468:     }
 1469:     return $result;
 1470: }
 1471: 
 1472: sub end_function {
 1473:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1474:     my $result = '';
 1475:     if ($target eq 'web' || $target eq 'tex') {
 1476:     } elsif ($target eq 'edit') {
 1477: 	$result .= &Apache::edit::end_table();
 1478:     }
 1479:     return $result;
 1480: }
 1481: 
 1482: ##------------------------------------------------------------ curve  data
 1483: sub start_data {
 1484:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1485:     my $result='';
 1486:     if ($target eq 'web' || $target eq 'tex') {
 1487: 	if (exists($curves[-1]->{'function'})) {
 1488: 	    &Apache::lonxml::warning
 1489:                 ('Use of the <b>curve function</b> tag precludes use of '.
 1490:                  ' the <b>curve data</b> tag.  '.
 1491:                  'The curve function tag will be omitted in favor of the '.
 1492:                  'curve data declaration.');
 1493: 	    delete($curves[-1]->{'function'});
 1494: 	}
 1495: 	my $datatext = &Apache::lonxml::get_all_text("/data",$parser,$style);
 1496: 	$datatext=&Apache::run::evaluate($datatext,$safeeval,$$parstack[-1]);
 1497: 	# Deal with cases where we're given an array...
 1498: 	if ($datatext =~ /^\@/) {
 1499: 	    $datatext = &Apache::run::run('return "'.$datatext.'"',
 1500: 					  $safeeval,1);
 1501: 	}
 1502: 	$datatext =~ s/\s+/ /g;
 1503: 	# Need to do some error checking on the @data array - 
 1504: 	# make sure it's all numbers and make sure each array 
 1505: 	# is of the same length.
 1506: 	my @data;
 1507: 	if ($datatext =~ /,/) { # comma deliminated
 1508: 	    @data = split /,/,$datatext;
 1509: 	} else { # Assume it's space separated.
 1510: 	    @data = split / /,$datatext;
 1511: 	}
 1512: 	for (my $i=0;$i<=$#data;$i++) {
 1513: 	    # Check that it's non-empty
 1514: 	    if (! defined($data[$i])) {
 1515: 		&Apache::lonxml::warning(
 1516: 		    'undefined curve data value.  Replacing with '.
 1517: 		    ' pi/e = 1.15572734979092');
 1518: 		$data[$i] = 1.15572734979092;
 1519: 	    }
 1520: 	    # Check that it's a number
 1521: 	    if (! &$real_test($data[$i]) & ! &$int_test($data[$i])) {
 1522: 		&Apache::lonxml::warning(
 1523: 		    'Bad curve data value of '.$data[$i].'  Replacing with '.
 1524: 		    ' pi/e = 1.15572734979092');
 1525: 		$data[$i] = 1.15572734979092;
 1526: 	    }
 1527: 	}
 1528: 	# complain if the number of data points is not the same as
 1529: 	# in previous sets of data.
 1530: 	if (($curves[-1]->{'data'}) && ($#data != $#{$curves[-1]->{'data'}->[0]})){
 1531: 	    &Apache::lonxml::warning
 1532: 		('Number of data points is not consistent with previous '.
 1533: 		 'number of data points');
 1534: 	}
 1535: 	push  @{$curves[-1]->{'data'}},\@data;
 1536:     } elsif ($target eq 'edit') {
 1537: 	$result .= &Apache::edit::tag_start($target,$token,'Comma or space deliminated curve data');
 1538: 	my $text = &Apache::lonxml::get_all_text("/data",$parser,$style);
 1539: 	$result .= &Apache::edit::editline('',$text,'',60);
 1540:     } elsif ($target eq 'modified') {
 1541: 	$result.=&Apache::edit::rebuild_tag($token);
 1542: 	$result.=&Apache::edit::modifiedfield("/data",$parser);
 1543:     }
 1544:     return $result;
 1545: }
 1546: 
 1547: sub end_data {
 1548:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1549:     my $result = '';
 1550:     if ($target eq 'web' || $target eq 'tex') {
 1551:     } elsif ($target eq 'edit') {
 1552: 	$result .= &Apache::edit::end_table();
 1553:     }
 1554:     return $result;
 1555: }
 1556: 
 1557: ##------------------------------------------------------------------- axis
 1558: sub start_axis {
 1559:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1560:     my $result='';
 1561:     if ($target eq 'web' || $target eq 'tex') {
 1562: 	&get_attributes(\%axis,\%axis_defaults,$parstack,$safeeval,
 1563: 			$tagstack->[-1]);
 1564:     } elsif ($target eq 'edit') {
 1565: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Axes');
 1566: 	$result .= &edit_attributes($target,$token,\%axis_defaults,
 1567: 				    \@axis_edit_order);
 1568:     } elsif ($target eq 'modified') {
 1569: 	my $constructtag=&Apache::edit::get_new_args
 1570: 	    ($token,$parstack,$safeeval,keys(%axis_defaults));
 1571: 
 1572: 	if ($constructtag) {
 1573: 	    #
 1574: 	    #  Fix up the color attribute since jchooser does not
 1575: 	    #  prepend an x to the color:
 1576: 	    #
 1577: 	    my $value = $token->[2]{'color'};
 1578: 	    if (defined $value && !($value =~ /^x/)) {
 1579: 		$token->[2]{'color'} = 'x' . $value;
 1580: 	    }
 1581: 
 1582: 	    $result = &Apache::edit::rebuild_tag($token);
 1583: 	}
 1584:     }
 1585:     return $result;
 1586: }
 1587: 
 1588: sub end_axis {
 1589:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1590:     my $result = '';
 1591:     if ($target eq 'web' || $target eq 'tex') {
 1592:     } elsif ($target eq 'edit') {
 1593: 	$result.=&Apache::edit::tag_end($target,$token);
 1594:     } elsif ($target eq 'modified') {
 1595:     }
 1596:     return $result;
 1597: }
 1598: 
 1599: ###################################################################
 1600: ##                                                               ##
 1601: ##        Utility Functions                                      ##
 1602: ##                                                               ##
 1603: ###################################################################
 1604: 
 1605: ##----------------------------------------------------------- set_defaults
 1606: sub set_defaults {
 1607:     my ($var,$defaults) = @_;
 1608:     my $key;
 1609:     foreach $key (keys(%$defaults)) {
 1610: 	$var->{$key} = $defaults->{$key}->{'default'};
 1611:     }
 1612: }
 1613: 
 1614: ##------------------------------------------------------------------- misc
 1615: sub get_attributes{
 1616:     my ($values,$defaults,$parstack,$safeeval,$tag) = @_;
 1617:     foreach my $attr (keys(%{$defaults})) {
 1618: 	if ($attr eq 'texwidth' || $attr eq 'texfont') {
 1619: 	    $values->{$attr} = 
 1620: 		&Apache::lonxml::get_param($attr,$parstack,$safeeval,undef,1);
 1621: 	} else {
 1622: 	    $values->{$attr} = 
 1623: 		&Apache::lonxml::get_param($attr,$parstack,$safeeval);
 1624: 	}
 1625: 	if ($values->{$attr} eq '' | !defined($values->{$attr})) {
 1626: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
 1627: 	    next;
 1628: 	}
 1629: 	my $test = $defaults->{$attr}->{'test'};
 1630: 	if (! &$test($values->{$attr})) {
 1631: 	    &Apache::lonxml::warning
 1632: 		($tag.':'.$attr.': Bad value.'.'Replacing your value with : '
 1633: 		 .$defaults->{$attr}->{'default'} );
 1634: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
 1635: 	}
 1636:     }
 1637:     return ;
 1638: }
 1639: 
 1640: ##------------------------------------------------------- write_gnuplot_file
 1641: sub write_gnuplot_file {
 1642:     my ($tmpdir,$filename,$target)= @_;
 1643:     my ($fontsize, $font_properties) =  &get_font($target);
 1644:     my $gnuplot_input = '';
 1645:     my $curve;
 1646:     #
 1647:     # Check to be sure we do not have any empty curves
 1648:     my @curvescopy;
 1649:     foreach my $curve (@curves) {
 1650:         if (exists($curve->{'function'})) {
 1651:             if ($curve->{'function'} !~ /^\s*$/) {
 1652:                 push(@curvescopy,$curve);
 1653:             }
 1654:         } elsif (exists($curve->{'data'})) {
 1655:             foreach my $data (@{$curve->{'data'}}) {
 1656:                 if (scalar(@$data) > 0) {
 1657:                     push(@curvescopy,$curve);
 1658:                     last;
 1659:                 }
 1660:             }
 1661:         }
 1662:     }
 1663:     @curves = @curvescopy;
 1664:     # Collect all the colors
 1665:     my @Colors;
 1666:     push @Colors, $Apache::lonplot::plot{'bgcolor'};
 1667:     push @Colors, $Apache::lonplot::plot{'fgcolor'}; 
 1668:     push @Colors, (defined($axis{'color'})?$axis{'color'}:$Apache::lonplot::plot{'fgcolor'});
 1669:     foreach $curve (@curves) {
 1670: 	push @Colors, ($curve->{'color'} ne '' ? 
 1671: 		       $curve->{'color'}       : 
 1672: 		       $Apache::lonplot::plot{'fgcolor'}        );
 1673:     }
 1674:     
 1675:     # set term
 1676:     if ($target eq 'web') {
 1677: 	$gnuplot_input .= 'set terminal png enhanced nocrop ';
 1678: 	$gnuplot_input .= 'transparent ' if ($Apache::lonplot::plot{'transparent'} eq 'on');
 1679: 	$gnuplot_input .= 'font "'.$Apache::lonnet::perlvar{'lonFontsDir'}.
 1680: 	    '/'.$font_properties->{'file'}.'.ttf" ';
 1681: 	$gnuplot_input .= $fontsize;
 1682: 	$gnuplot_input .= ' size '.$Apache::lonplot::plot{'width'}.','.$Apache::lonplot::plot{'height'}.' ';
 1683: 	$gnuplot_input .= "@Colors\n";
 1684: 	# set output
 1685: 	$gnuplot_input .= "set output\n";
 1686:     } elsif ($target eq 'tex') {
 1687: 	$gnuplot_input .= "set term postscript eps enhanced $Apache::lonplot::plot{'plotcolor'} dash ";
 1688: 	if (!$font_properties->{'tex_no_file'}) {
 1689: 	    $gnuplot_input .=
 1690: 		'fontfile "'.$Apache::lonnet::perlvar{'lonFontsDir'}.
 1691: 		'/'.$font_properties->{'file'}.'.pfb" ';
 1692: 	}
 1693: 	$gnuplot_input .= ' "'.$font_properties->{'printname'}.'" ';
 1694: 	$gnuplot_input .= $fontsize;
 1695: 	$gnuplot_input .= "\nset output \"".$tmpdir.
 1696: 	    &unescape($filename).".eps\"\n";
 1697: 	$gnuplot_input .= "set encoding iso_8859_1\n"; # Get access to extended font.
 1698: 
 1699:     }
 1700:     $gnuplot_input .= "set encoding utf8\n";
 1701:     # cartesian or polar plot?
 1702:     if (lc($Apache::lonplot::plot{'plottype'}) eq 'polar') {
 1703:         $gnuplot_input .= 'set polar'.$/;
 1704:     } else {
 1705:         # Assume Cartesian
 1706:     }
 1707:     # cartesian or polar grid?
 1708:     if (lc($Apache::lonplot::plot{'gridtype'}) eq 'polar') {
 1709:         $gnuplot_input .= 'set grid polar'.$/;
 1710:     } elsif (lc($Apache::lonplot::plot{'gridtype'}) eq 'linear-log') {
 1711:         $gnuplot_input .= 'set logscale x'.$/;
 1712:     } elsif (lc($Apache::lonplot::plot{'gridtype'}) eq 'log-linear') {
 1713:         $gnuplot_input .= 'set logscale y'.$/;
 1714:     } elsif (lc($Apache::lonplot::plot{'gridtype'}) eq 'log-log') {
 1715:         $gnuplot_input .= 'set logscale x'.$/;
 1716:         $gnuplot_input .= 'set logscale y'.$/;
 1717:     } else {
 1718:         # Assume Cartesian
 1719:     }
 1720:     # solid or pattern for boxes?
 1721:     if (lc($Apache::lonplot::plot{'fillstyle'}) eq 'solid') {
 1722:         $gnuplot_input .= 'set style fill solid '.
 1723: 	    $Apache::lonplot::plot{'solid'}.$Apache::lonplot::plot{'box_border'}.$/;
 1724:     } elsif (lc($Apache::lonplot::plot{'fillstyle'}) eq 'pattern') {
 1725:         $gnuplot_input .= 'set style fill pattern '.$Apache::lonplot::plot{'pattern'}.$Apache::lonplot::plot{'box_border'}.$/;
 1726:     } elsif (lc($Apache::lonplot::plot{'fillstyle'}) eq 'empty') {
 1727:     }
 1728:     # margin
 1729:     if (lc($Apache::lonplot::plot{'lmargin'}) ne 'default') {
 1730:         $gnuplot_input .= 'set lmargin '.$Apache::lonplot::plot{'lmargin'}.$/;
 1731:     }
 1732:     if (lc($Apache::lonplot::plot{'rmargin'}) ne 'default') {
 1733:         $gnuplot_input .= 'set rmargin '.$Apache::lonplot::plot{'rmargin'}.$/;
 1734:     }
 1735:     if (lc($Apache::lonplot::plot{'tmargin'}) ne 'default') {
 1736:         $gnuplot_input .= 'set tmargin '.$Apache::lonplot::plot{'tmargin'}.$/;
 1737:     }
 1738:     if (lc($Apache::lonplot::plot{'bmargin'}) ne 'default') {
 1739:         $gnuplot_input .= 'set bmargin '.$Apache::lonplot::plot{'bmargin'}.$/;
 1740:     }
 1741: 
 1742:     # tic scales
 1743:     if ($version > 4) {
 1744: 	$gnuplot_input .= 'set tics scale '.
 1745: 	    $Apache::lonplot::plot{'major_ticscale'}.', '.$Apache::lonplot::plot{'minor_ticscale'}.$/;
 1746:     } else {
 1747:     	$gnuplot_input .= 'set ticscale '.
 1748: 	    $Apache::lonplot::plot{'major_ticscale'}.' '.$Apache::lonplot::plot{'minor_ticscale'}.$/;
 1749:     }
 1750:     #boxwidth
 1751:     if (lc($Apache::lonplot::plot{'boxwidth'}) ne '') {
 1752: 	$gnuplot_input .= 'set boxwidth '.$Apache::lonplot::plot{'boxwidth'}.$/;
 1753:     }
 1754:     # gridlayer
 1755:     $gnuplot_input .= 'set grid noxtics noytics front '.$/ 
 1756: 	if ($Apache::lonplot::plot{'gridlayer'} eq 'on');
 1757: 
 1758:     # grid
 1759:     $gnuplot_input .= 'set grid'.$/ if ($Apache::lonplot::plot{'grid'} eq 'on');
 1760:     # border
 1761:     $gnuplot_input .= ($Apache::lonplot::plot{'border'} eq 'on'?
 1762: 		       'set border'.$/           :
 1763: 		       'set noborder'.$/         );
 1764:     # sampling rate for non-data curves
 1765:     $gnuplot_input .= "set samples $Apache::lonplot::plot{'samples'}\n";
 1766:     # title, xlabel, ylabel
 1767:     # titles
 1768:     my $extra_space_x = ($xtics{'location'} eq 'axis') ? ' 0, -0.5 ' : '';
 1769:     my $extra_space_y = ($ytics{'location'} eq 'axis') ? ' -0.5, 0 ' : '';
 1770: 
 1771:     if ($target eq 'tex') {
 1772: 	$gnuplot_input .= "set title  \"$title\"          font \"".$font_properties->{'printname'}.",".$fontsize."pt\"\n" if (defined($title)) ;
 1773: 	$gnuplot_input .= "set xlabel \"$xlabel\" $extra_space_x font \"".$font_properties->{'printname'}.",".$fontsize."pt\"\n" if (defined($xlabel));
 1774: 	$gnuplot_input .= "set ylabel \"$ylabel\" $extra_space_y font \"".$font_properties->{'printname'}.",".$fontsize."pt\"\n" if (defined($ylabel));
 1775:     } else {
 1776:         $gnuplot_input .= "set title  \"$title\"          \n" if (defined($title)) ;
 1777:         $gnuplot_input .= "set xlabel \"$xlabel\" $extra_space_x \n" if (defined($xlabel));
 1778:         $gnuplot_input .= "set ylabel \"$ylabel\" $extra_space_y \n" if (defined($ylabel));
 1779:     }
 1780:     # tics
 1781:     if (%xtics) {    
 1782: 	$gnuplot_input .= "set xtics $xtics{'location'} ";
 1783: 	$gnuplot_input .= ( $xtics{'mirror'} eq 'on'?"mirror ":"nomirror ");
 1784: 	$gnuplot_input .= "$xtics{'start'}, ";
 1785: 	$gnuplot_input .= "$xtics{'increment'}, ";
 1786: 	$gnuplot_input .= "$xtics{'end'} ";
 1787: 	if ($target eq 'tex') {
 1788: 	    $gnuplot_input .= 'font "Helvetica,22"';     # Needed in iso 8859-1 enc.
 1789: 	}
 1790: 	$gnuplot_input .= "\n";
 1791:         if ($xtics{'minorfreq'} != 0) {
 1792:             $gnuplot_input .= "set mxtics ".$xtics{'minorfreq'}."\n";
 1793:         } 
 1794:     } else {
 1795: 	if ($target eq 'tex') {
 1796: 	    $gnuplot_input .= 'set xtics font "Helvetica,22"'."\n"; # needed in iso 8859-1 enc
 1797: 	}
 1798:     }
 1799:     if (%ytics) {    
 1800: 	$gnuplot_input .= "set ytics $ytics{'location'} ";
 1801: 	$gnuplot_input .= ( $ytics{'mirror'} eq 'on'?"mirror ":"nomirror ");
 1802: 	$gnuplot_input .= "$ytics{'start'}, ";
 1803: 	$gnuplot_input .= "$ytics{'increment'}, ";
 1804:         $gnuplot_input .= "$ytics{'end'} ";
 1805:         if ($target eq 'tex') {
 1806:             $gnuplot_input .= 'font "Helvetica,22"'; # Needed in iso-8859-1 encoding.
 1807:         }
 1808:         $gnuplot_input .= "\n";
 1809:         if ($ytics{'minorfreq'} != 0) {
 1810:             $gnuplot_input .= "set mytics ".$ytics{'minorfreq'}."\n";
 1811:         } 
 1812:     } else {
 1813: 	if ($target eq 'tex') {
 1814: 	    $gnuplot_input .= 'set ytics font "Helvetica,22"'."\n"; # Needed for iso 8859-1 enc.
 1815: 	}
 1816:     }
 1817:     # axis
 1818:     if (%axis) {
 1819:         if ($axis{'xformat'} ne 'on') {
 1820:             $gnuplot_input .= "set format x ";
 1821:             if ($axis{'xformat'} eq 'off') {
 1822:                 $gnuplot_input .= "\"\"\n";
 1823:             } else {
 1824:                 $gnuplot_input .= "\"\%.".$axis{'xformat'}."\"\n";
 1825:             }
 1826:         }
 1827:         if ($axis{'yformat'} ne 'on') {
 1828:             $gnuplot_input .= "set format y ";
 1829:             if ($axis{'yformat'} eq 'off') {
 1830:                 $gnuplot_input .= "\"\"\n";
 1831:             } else {
 1832:                 $gnuplot_input .= "\"\%.".$axis{'yformat'}."\"\n";
 1833:             }
 1834:         }
 1835: 	$gnuplot_input .= "set xrange \[$axis{'xmin'}:$axis{'xmax'}\]\n";
 1836: 	$gnuplot_input .= "set yrange \[$axis{'ymin'}:$axis{'ymax'}\]\n";
 1837: 		if ($axis{'xzero'} ne 'off') {
 1838: 			$gnuplot_input .= "set xzeroaxis ";
 1839: 			if ($axis{'xzero'} eq 'line' || $axis{'xzero'} eq 'thick-line') {
 1840: 				$gnuplot_input .= "lt -1 ";
 1841: 				if ($axis{'xzero'} eq 'thick-line') {
 1842: 					$gnuplot_input .= "lw 3 ";
 1843: 				}
 1844: 			}
 1845: 			$gnuplot_input .= "\n";
 1846: 		}
 1847: 		if ($axis{'yzero'} ne 'off') {
 1848: 			$gnuplot_input .= "set yzeroaxis ";
 1849: 			if ($axis{'yzero'} eq 'line' || $axis{'yzero'} eq 'thick-line') {
 1850: 				$gnuplot_input .= "lt -1 ";
 1851: 				if ($axis{'yzero'} eq 'thick-line') {
 1852: 					$gnuplot_input .= "lw 3 ";
 1853: 				}
 1854: 			}
 1855: 			$gnuplot_input .= "\n";
 1856: 		}
 1857:     }
 1858:     # Key
 1859:     if (%key) {
 1860: 	$gnuplot_input .= 'set key '.$key{'pos'}.' ';
 1861: 	if ($key{'title'} ne '') {
 1862: 	    $gnuplot_input .= 'title "'.$key{'title'}.'" ';
 1863: 	} 
 1864: 	$gnuplot_input .= ($key{'box'} eq 'on' ? 'box ' : 'nobox ').$/;
 1865:     } else {
 1866: 	$gnuplot_input .= 'set nokey'.$/;
 1867:     }
 1868:     # labels
 1869:     my $label;
 1870:     foreach $label (@labels) {
 1871: 	$gnuplot_input .= 'set label "'.$label->{'text'}.'" at '.
 1872:                           $label->{'xpos'}.','.$label->{'ypos'};
 1873:         if ($label->{'rotate'} ne '') {
 1874:             $gnuplot_input .= ' rotate by '.$label->{'rotate'};
 1875:         }
 1876:         $gnuplot_input .= ' '.$label->{'justify'};
 1877: 
 1878:         if ($target eq 'tex') {
 1879: 	    $gnuplot_input .=' font "'.$font_properties->{'printname'}.','.$fontsize.'pt"' ;
 1880:         }
 1881:         $gnuplot_input .= $/;
 1882:     }
 1883:     if ($target eq 'tex') {
 1884:         $gnuplot_input .="set size 1,".$Apache::lonplot::plot{'height'}/$Apache::lonplot::plot{'width'}*1.38;
 1885:         $gnuplot_input .="\n";
 1886:     }
 1887:     # curves
 1888:     #
 1889:     # Each curve will have its very own linestyle.
 1890:     # (This should work just fine in web rendition I think).
 1891:     #  The line_xxx variables will hold the elements of the line style.
 1892:     #  type (solid/dashed), color, width
 1893:     #
 1894:     my $linestyle_index = 50;
 1895:     my $line_width   = '';
 1896: 
 1897:     # If arrows are needed there will be an arrow style for each as well:
 1898:     #
 1899: 
 1900:     my $arrow_style_index = 50;
 1901: 
 1902:     my $plot_command;
 1903:     my $plot_type;
 1904: 
 1905:     for (my $i = 0;$i<=$#curves;$i++) {
 1906: 	$curve = $curves[$i];
 1907: 	$plot_command.= ', ' if ($i > 0);
 1908: 	if ($target eq 'tex') {
 1909: 	    $curve->{'linewidth'} *= 2;
 1910: 	}
 1911: 	$line_width = $curve->{'linewidth'};
 1912: 	if (exists($curve->{'function'})) {
 1913: 	    $plot_type    = 
 1914: 		$curve->{'function'}.' title "'.
 1915: 		$curve->{'name'}.'" with '.
 1916:                 $curve->{'linestyle'};
 1917: 	} elsif (exists($curve->{'data'})) {
 1918: 	    # Store data values in $datatext
 1919: 	    my $datatext = '';
 1920: 	    #   get new filename
 1921: 	    my $datafilename = "$tmpdir/$filename.data.$i";
 1922: 	    my $fh=Apache::File->new(">$datafilename");
 1923: 	    # Compile data
 1924: 	    my @Data = @{$curve->{'data'}};
 1925: 	    my @Data0 = @{$Data[0]};
 1926: 	    for (my $i =0; $i<=$#Data0; $i++) {
 1927: 		my $dataset;
 1928: 		foreach $dataset (@Data) {
 1929: 		    $datatext .= $dataset->[$i] . ' ';
 1930: 		}
 1931: 		$datatext .= $/;
 1932: 	    }
 1933: 	    #   write file
 1934: 	    print $fh $datatext;
 1935: 	    close($fh);
 1936: 	    #   generate gnuplot text
 1937: 	    $plot_type = '"'.$datafilename.'" title "'.
 1938: 		$curve->{'name'}.'" with '.
 1939: 		$curve->{'linestyle'};
 1940: 	}
 1941: 	my $pointtype = '';
 1942: 	my $pointsize = '';
 1943: 
 1944: 	# Figure out the linestyle:
 1945: 
 1946: 	my $lt = $curve->{'linetype'} ne '' ? $curve->{'linetype'} 
 1947: 	                : 'solid';	# Line type defaults to solid.
 1948: 	# The mapping of lt -> the actual gnuplot line type depends on the target:
 1949: 
 1950: 	if ($target eq 'tex') {
 1951: 	    $lt = $ps_linetypes{$lt};
 1952: 	} else {
 1953: 	    $lt = $linetypes{$lt}
 1954: 	}
 1955: 
 1956: 	my $color = $curve->{'color'};
 1957: 	$color =~ s/^x/#/;	        # Convert xhex color -> #hex color.   
 1958: 
 1959: 	my $style_command = "set style line $linestyle_index $pointtype $pointsize linetype $lt linewidth $line_width lc rgb '$color'\n";
 1960: 	$gnuplot_input .= $style_command;
 1961: 
 1962: 
 1963: 
 1964: 	if (($curve->{'linestyle'} eq 'points')      ||
 1965: 	    ($curve->{'linestyle'} eq 'linespoints') ||
 1966: 	    ($curve->{'linestyle'} eq 'errorbars')   ||
 1967: 	    ($curve->{'linestyle'} eq 'xerrorbars')  ||
 1968: 	    ($curve->{'linestyle'} eq 'yerrorbars')  ||
 1969: 	    ($curve->{'linestyle'} eq 'xyerrorbars')) {
 1970: 	    
 1971: 	    $pointtype =' pointtype '.$curve->{'pointtype'};
 1972: 	    $pointsize =' pointsize '.$curve->{'pointsize'};
 1973: 	} elsif ($curve->{'linestyle'} eq 'filledcurves') { 
 1974: 	    $plot_command.= ' '.$curve->{'limit'};
 1975: 	} elsif ($curve->{'linestyle'} eq 'vector') {
 1976: 
 1977: 	    # Create the arrow head style add it to 
 1978: 	    # $gnuplot_input..and ensure it gets
 1979: 	    # Selected in the plot command.
 1980: 
 1981: 	    $gnuplot_input .= "set style arrow $arrow_style_index ";
 1982: 	    $gnuplot_input .= ' ' . $curve->{'arrowhead'};
 1983: 	    $gnuplot_input .= ' size ' . $curve->{'arrowlength'};
 1984: 	    $gnuplot_input .= ','.$curve->{'arrowangle'};
 1985: 	    $gnuplot_input .= ',' . $curve->{'arrowbackangle'}; 
 1986: 	    $gnuplot_input .=  ' ' . $curve->{'arrowstyle'} . " ls $linestyle_index\n";
 1987: 
 1988: 
 1989: 	    $plot_command  .= "  arrowstyle $arrow_style_index ";
 1990: 	    $arrow_style_index++;
 1991: 	}
 1992: 
 1993: 
 1994: 
 1995: 
 1996: 	# The condition below is because gnuplot lumps the linestyle in with the 
 1997: 	# arrowstyle _sigh_.
 1998: 
 1999: 	if ($curve->{'linestyle'} ne 'vector') {
 2000: 	    $plot_command.= " ls $linestyle_index";
 2001: 	}
 2002: 
 2003: 	$gnuplot_input .= 'plot ' . $plot_type . ' ' . $plot_command . "\n";
 2004: 	$linestyle_index++;	# Each curve get a unique linestyle.
 2005:     }
 2006:     # Write the output to a file.
 2007:     open (my $fh, "> $tmpdir$filename.data");
 2008:     binmode($fh, ':utf8');
 2009:     print $fh $gnuplot_input;
 2010:     close($fh);
 2011:     # That's all folks.
 2012:     return ;
 2013: }
 2014: 
 2015: #---------------------------------------------- check_inputs
 2016: sub check_inputs {
 2017:     ## Note: no inputs, no outputs - this acts only on global variables.
 2018:     ## Make sure we have all the input we need:
 2019:     if (! %Apache::lonplot::plot) { &set_defaults(\%Apache::lonplot::plot,\%gnuplot_defaults); }
 2020:     if (! %key ) {} # No key for this plot, thats okay
 2021: #    if (! %axis) { &set_defaults(\%axis,\%axis_defaults); }
 2022:     if (! defined($title )) {} # No title for this plot, thats okay
 2023:     if (! defined($xlabel)) {} # No xlabel for this plot, thats okay
 2024:     if (! defined($ylabel)) {} # No ylabel for this plot, thats okay
 2025:     if ($#labels < 0) { }      # No labels for this plot, thats okay
 2026:     if ($#curves < 0) { 
 2027: 	&Apache::lonxml::warning("No curves specified for plot!!!!");
 2028: 	return '';
 2029:     }
 2030:     my $curve;
 2031:     foreach $curve (@curves) {
 2032: 	if (!defined($curve->{'function'})&&!defined($curve->{'data'})){
 2033: 	    &Apache::lonxml::warning("One of the curves specified did not contain any curve data or curve function declarations\n");
 2034: 	    return '';
 2035: 	}
 2036:     }
 2037: }
 2038: 
 2039: #------------------------------------------------ make_edit
 2040: sub edit_attributes {
 2041:     my ($target,$token,$defaults,$keys) = @_;
 2042:     my ($result,@keys);
 2043:     if ($keys && ref($keys) eq 'ARRAY') {
 2044:         @keys = @$keys;
 2045:     } else {
 2046: 	@keys = sort(keys(%$defaults));
 2047:     }
 2048:     foreach my $attr (@keys) {
 2049: 	# append a ' ' to the description if it doesn't have one already.
 2050: 	my $description = $defaults->{$attr}->{'description'};
 2051: 	$description .= ' ' if ($description !~ / $/);
 2052: 	if ($defaults->{$attr}->{'edit_type'} eq 'entry') {
 2053: 	    $result .= &Apache::edit::text_arg
 2054: 		($description,$attr,$token,
 2055: 		 $defaults->{$attr}->{'size'},
 2056: 		$defaults->{$attr}->{'class'});
 2057: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'choice') {
 2058: 	    $result .= &Apache::edit::select_or_text_arg
 2059: 		($description,$attr,$defaults->{$attr}->{'choices'},$token);
 2060: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'onoff') {
 2061: 	    $result .= &Apache::edit::select_or_text_arg
 2062: 		($description,$attr,['on','off'],$token);
 2063: 	}
 2064: 	$result .= '<br />';
 2065:     }
 2066:     return $result;
 2067: }
 2068: 
 2069: 
 2070: ###################################################################
 2071: ##                                                               ##
 2072: ##           Insertion functions for editing plots               ##
 2073: ##                                                               ##
 2074: ###################################################################
 2075: 
 2076: sub insert_gnuplot {
 2077:     my $result = '';
 2078:     #  plot attributes
 2079:     $result .= "\n<gnuplot ";
 2080:     foreach my $attr (keys(%gnuplot_defaults)) {
 2081: 	$result .= "\n     $attr=\"$gnuplot_defaults{$attr}->{'default'}\"";
 2082:     }
 2083:     $result .= ">";
 2084:     # Add the components (most are commented out for simplicity)
 2085:     # $result .= &insert_key();
 2086:     # $result .= &insert_axis();
 2087:     # $result .= &insert_title();    
 2088:     # $result .= &insert_xlabel();    
 2089:     # $result .= &insert_ylabel();    
 2090:     $result .= &insert_curve();
 2091:     # close up the <gnuplot>
 2092:     $result .= "\n</gnuplot>";
 2093:     return $result;
 2094: }
 2095: 
 2096: sub insert_tics {
 2097:     my $result;
 2098:     $result .= &insert_xtics() . &insert_ytics;
 2099:     return $result;
 2100: }
 2101: 
 2102: sub insert_xtics {
 2103:     my $result;
 2104:     $result .= "\n    <xtics ";
 2105:     foreach my $attr (keys(%tic_defaults)) {
 2106: 	$result .= "\n        $attr=\"$tic_defaults{$attr}->{'default'}\" ";
 2107:     }
 2108:     $result .= "/>";
 2109:     return $result;
 2110: }
 2111: 
 2112: sub insert_ytics {
 2113:     my $result;
 2114:     $result .= "\n    <ytics ";
 2115:     foreach my $attr (keys(%tic_defaults)) {
 2116: 	$result .= "\n        $attr=\"$tic_defaults{$attr}->{'default'}\" ";
 2117:     }
 2118:     $result .= "/>";
 2119:     return $result;
 2120: }
 2121: 
 2122: sub insert_key {
 2123:     my $result;
 2124:     $result .= "\n    <key ";
 2125:     foreach my $attr (keys(%key_defaults)) {
 2126: 	$result .= "\n         $attr=\"$key_defaults{$attr}->{'default'}\"";
 2127:     }
 2128:     $result .= " />";
 2129:     return $result;
 2130: }
 2131: 
 2132: sub insert_axis{
 2133:     my $result;
 2134:     $result .= "\n    <axis ";
 2135:    foreach my $attr (keys(%axis_defaults)) {
 2136: 	$result .= "\n         $attr=\"$axis_defaults{$attr}->{'default'}\"";
 2137:     }
 2138:     $result .= " />";
 2139:     return $result;
 2140: }
 2141: 
 2142: sub insert_title  { return "\n    <title></title>"; }
 2143: sub insert_xlabel { return "\n    <xlabel></xlabel>"; }
 2144: sub insert_ylabel { return "\n    <ylabel></ylabel>"; }
 2145: 
 2146: sub insert_label {
 2147:     my $result;
 2148:     $result .= "\n    <label ";
 2149:     foreach my $attr (keys(%label_defaults)) {
 2150: 	$result .= "\n         $attr=\"".
 2151:             $label_defaults{$attr}->{'default'}."\"";
 2152:     }
 2153:     $result .= "></label>";
 2154:     return $result;
 2155: }
 2156: 
 2157: sub insert_curve {
 2158:     my $result;
 2159:     $result .= "\n    <curve ";
 2160:     foreach my $attr (keys(%curve_defaults)) {
 2161: 	$result .= "\n         $attr=\"".
 2162: 	    $curve_defaults{$attr}->{'default'}."\"";
 2163:     }
 2164:     $result .= " >";
 2165:     $result .= &insert_data().&insert_data()."\n    </curve>";
 2166: }
 2167: 
 2168: sub insert_function {
 2169:     my $result;
 2170:     $result .= "\n        <function></function>";
 2171:     return $result;
 2172: }
 2173: 
 2174: sub insert_data {
 2175:     my $result;
 2176:     $result .= "\n        <data></data>";
 2177:     return $result;
 2178: }
 2179: 
 2180: ##----------------------------------------------------------------------
 2181: 1;
 2182: __END__
 2183: 
 2184: 
 2185: =head1 NAME
 2186: 
 2187: Apache::lonplot.pm
 2188: 
 2189: =head1 SYNOPSIS
 2190: 
 2191: XML-based plotter of graphs
 2192: 
 2193: This is part of the LearningOnline Network with CAPA project
 2194: described at http://www.lon-capa.org.
 2195: 
 2196: 
 2197: =head1 SUBROUTINES (parsing and edit rendering)
 2198: 
 2199: =over
 2200: 
 2201: =item start_gnuplot()
 2202: 
 2203: =item end_gnuplot()
 2204: 
 2205: =item start_xtics()
 2206: 
 2207: =item end_xtics()
 2208: 
 2209: =item start_ytics()
 2210: 
 2211: =item end_ytics()
 2212: 
 2213: =item get_font()
 2214: 
 2215: =item start_key()
 2216: 
 2217: =item end_key()
 2218: 
 2219: =item parse_label()
 2220: 
 2221: =item replace_entities()
 2222: 
 2223: =item start_title()
 2224: 
 2225: =item end_title()
 2226: 
 2227: =item start_xlabel()
 2228: 
 2229: =item end_xlabel()
 2230: 
 2231: =item start_ylabel()
 2232: 
 2233: =item end_label()
 2234: 
 2235: =item start_curve()
 2236: 
 2237: =item end_curve()
 2238: 
 2239: =item start_function()
 2240: 
 2241: =item end_function()
 2242: 
 2243: =item start_data()
 2244: 
 2245: =item end_data()
 2246: 
 2247: =item start_axis()
 2248: 
 2249: =item end_axis
 2250: 
 2251: =back
 2252: 
 2253: =head1 SUBROUTINES (Utility)
 2254: 
 2255: =over
 2256: 
 2257: =item set_defaults()
 2258: 
 2259: =item get_attributes()
 2260: 
 2261: =item write_gnuplot_file()
 2262: 
 2263: =item check_inputs()
 2264: 
 2265: =item edit_attributes()
 2266: 
 2267: =back
 2268: 
 2269: =head1 SUBROUTINES (Insertion functions for editing plots)
 2270: 
 2271: =over
 2272: 
 2273: =item insert_gnuplot()
 2274: 
 2275: =item insert_tics()
 2276: 
 2277: =item insert_xtics()
 2278: 
 2279: =item insert_key()
 2280: 
 2281: =item insert_axis()
 2282: 
 2283: =item insert_title()
 2284: 
 2285: =item insert_xlabel()
 2286: 
 2287: =item insert_ylabel()
 2288: 
 2289: =item insert_label()
 2290: 
 2291: =item insert_curve()
 2292: 
 2293: =item insert_function()
 2294: 
 2295: =item insert_data()
 2296: 
 2297: =back
 2298: 
 2299: =cut

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