File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.112: download - view: text, annotated - select for diffs
Thu Dec 1 18:46:17 2005 UTC (18 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: version_2_1_X, version_2_1_3, version_2_1_2, version_2_1_1, version_2_1_0, version_2_0_99_1, HEAD
- finish off the conversion to allowing style tags get_all_text across tags
- BUG#4428

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

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