File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.92: download - view: text, annotated - select for diffs
Fri Oct 24 17:35:32 2003 UTC (20 years, 6 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Better TeX font support - allow users to specify the size of the font
used when the eps file is generated.  Ought to be case insensitive.

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

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