File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.93: download - view: text, annotated - select for diffs
Thu Oct 30 20:52:54 2003 UTC (20 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: version_1_1_0, version_1_0_99_3, version_1_0_99_2, version_1_0_99_1, version_1_0_99, HEAD
- BUG#1974, <textarea>s delete the initial linefeeds if they exist, now checks old value and preserves the \n from the old value if it had been there.

    1: # The LearningOnline Network with CAPA
    2: # Dynamic plot
    3: #
    4: # $Id: lonplot.pm,v 1.93 2003/10/30 20:52:54 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: # 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: 	$result.=&Apache::edit::rebuild_tag($token);
  663: 	$result.=&Apache::edit::modifiedfield("/title",$parser);
  664:     }
  665:     return $result;
  666: }
  667: 
  668: sub end_title {
  669:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  670:     my $result = '';
  671:     if ($target eq 'web' || $target eq 'tex') {
  672:     } elsif ($target eq 'edit') {
  673: 	$result.=&Apache::edit::tag_end($target,$token);
  674:     }
  675:     return $result;
  676: }
  677: ##------------------------------------------------------------------- xlabel
  678: sub start_xlabel {
  679:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  680:     my $result='';
  681:     if ($target eq 'web' || $target eq 'tex') {
  682: 	$xlabel = &Apache::lonxml::get_all_text("/xlabel",$parser);
  683: 	$xlabel=&Apache::run::evaluate($xlabel,$safeeval,$$parstack[-1]);
  684: 	$xlabel =~ s/\n/ /g;
  685: 	if (length($xlabel) > $max_str_len) {
  686: 	    $xlabel = substr($xlabel,0,$max_str_len);
  687: 	}
  688:     } elsif ($target eq 'edit') {
  689: 	$result.=&Apache::edit::tag_start($target,$token,'Plot Xlabel');
  690: 	my $text=&Apache::lonxml::get_all_text("/xlabel",$parser);
  691: 	$result.=&Apache::edit::end_row().
  692: 	    &Apache::edit::start_spanning_row().
  693: 	    &Apache::edit::editline('',$text,'',60);
  694:     } elsif ($target eq 'modified') {
  695: 	$result.=&Apache::edit::rebuild_tag($token);	
  696: 	$result.=&Apache::edit::modifiedfield("/xlabel",$parser);
  697:     }
  698:     return $result;
  699: }
  700: 
  701: sub end_xlabel {
  702:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  703:     my $result = '';
  704:     if ($target eq 'web' || $target eq 'tex') {
  705:     } elsif ($target eq 'edit') {
  706: 	$result.=&Apache::edit::tag_end($target,$token);
  707:     }
  708:     return $result;
  709: }
  710: 
  711: ##------------------------------------------------------------------- ylabel
  712: sub start_ylabel {
  713:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  714:     my $result='';
  715:     if ($target eq 'web' || $target eq 'tex') {
  716: 	$ylabel = &Apache::lonxml::get_all_text("/ylabel",$parser);
  717: 	$ylabel = &Apache::run::evaluate($ylabel,$safeeval,$$parstack[-1]);
  718: 	$ylabel =~ s/\n/ /g;
  719: 	if (length($ylabel) > $max_str_len) {
  720: 	    $ylabel = substr($ylabel,0,$max_str_len);
  721: 	}
  722:     } elsif ($target eq 'edit') {
  723: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Ylabel');
  724: 	my $text = &Apache::lonxml::get_all_text("/ylabel",$parser);
  725: 	$result .= &Apache::edit::end_row().
  726: 	    &Apache::edit::start_spanning_row().
  727: 	    &Apache::edit::editline('',$text,'',60);
  728:     } elsif ($target eq 'modified') {
  729: 	$result.=&Apache::edit::rebuild_tag($token);
  730: 	$result.=&Apache::edit::modifiedfield("/ylabel",$parser);
  731:     }
  732:     return $result;
  733: }
  734: 
  735: sub end_ylabel {
  736:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  737:     my $result = '';
  738:     if ($target eq 'web' || $target eq 'tex') {
  739:     } elsif ($target eq 'edit') {
  740: 	$result.=&Apache::edit::tag_end($target,$token);
  741:     }
  742:     return $result;
  743: }
  744: 
  745: ##------------------------------------------------------------------- label
  746: sub start_label {
  747:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  748:     my $result='';
  749:     if ($target eq 'web' || $target eq 'tex') {
  750: 	my %label;
  751: 	&get_attributes(\%label,\%label_defaults,$parstack,$safeeval,
  752: 		    $tagstack->[-1]);
  753: 	my $text = &Apache::lonxml::get_all_text("/label",$parser);
  754: 	$text = &Apache::run::evaluate($text,$safeeval,$$parstack[-1]);
  755: 	$text =~ s/\n/ /g;
  756: 	$text = substr($text,0,$max_str_len) if (length($text) > $max_str_len);
  757: 	$label{'text'} = $text;
  758: 	push(@labels,\%label);
  759:     } elsif ($target eq 'edit') {
  760: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Label');
  761: 	$result .= &edit_attributes($target,$token,\%label_defaults);
  762: 	my $text = &Apache::lonxml::get_all_text("/label",$parser);
  763: 	$result .= &Apache::edit::end_row().
  764: 	    &Apache::edit::start_spanning_row().
  765: 	    &Apache::edit::editline('',$text,'',60);
  766:     } elsif ($target eq 'modified') {
  767: 	&Apache::edit::get_new_args
  768: 	    ($token,$parstack,$safeeval,keys(%label_defaults));
  769: 	$result.=&Apache::edit::rebuild_tag($token);
  770: 	$result.=&Apache::edit::modifiedfield("/label",$parser);
  771:     }
  772:     return $result;
  773: }
  774: 
  775: sub end_label {
  776:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  777:     my $result = '';
  778:     if ($target eq 'web' || $target eq 'tex') {
  779:     } elsif ($target eq 'edit') {
  780: 	$result.=&Apache::edit::tag_end($target,$token);
  781:     }
  782:     return $result;
  783: }
  784: 
  785: ##------------------------------------------------------------------- curve
  786: sub start_curve {
  787:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  788:     my $result='';
  789:     &Apache::lonxml::register('Apache::lonplot',('function','data'));
  790:     push (@Apache::lonxml::namespace,'curve');
  791:     if ($target eq 'web' || $target eq 'tex') {
  792: 	my %curve;
  793: 	&get_attributes(\%curve,\%curve_defaults,$parstack,$safeeval,
  794: 		    $tagstack->[-1]);
  795: 	push (@curves,\%curve);
  796:     } elsif ($target eq 'edit') {
  797: 	$result .= &Apache::edit::tag_start($target,$token,'Curve');
  798: 	$result .= &help_win($curve_help_text);
  799: 	$result .= &edit_attributes($target,$token,\%curve_defaults,
  800:                                     \@curve_edit_order);
  801:     } elsif ($target eq 'modified') {
  802: 	my $constructtag=&Apache::edit::get_new_args
  803: 	    ($token,$parstack,$safeeval,keys(%curve_defaults));
  804: 	if ($constructtag) {
  805: 	    $result = &Apache::edit::rebuild_tag($token);
  806: 	    $result.= &Apache::edit::handle_insert();
  807: 	}
  808:     }
  809:     return $result;
  810: }
  811: 
  812: sub end_curve {
  813:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  814:     my $result = '';
  815:     pop @Apache::lonxml::namespace;
  816:     &Apache::lonxml::deregister('Apache::lonplot',('function','data'));
  817:     if ($target eq 'web' || $target eq 'tex') {
  818:     } elsif ($target eq 'edit') {
  819: 	$result.=&Apache::edit::tag_end($target,$token);
  820:     }
  821:     return $result;
  822: }
  823: 
  824: ##------------------------------------------------------------ curve function
  825: sub start_function {
  826:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  827:     my $result='';
  828:     if ($target eq 'web' || $target eq 'tex') {
  829: 	if (exists($curves[-1]->{'data'})) {
  830: 	    &Apache::lonxml::warning
  831:                 ('Use of the <b>curve function</b> tag precludes use of '.
  832:                  ' the <b>curve data</b> tag.  '.
  833:                  'The curve data tag will be omitted in favor of the '.
  834:                  'curve function declaration.');
  835: 	    delete $curves[-1]->{'data'} ;
  836: 	}
  837:         my $function = &Apache::lonxml::get_all_text("/function",$parser);
  838: 	$function = &Apache::run::evaluate($function,$safeeval,$$parstack[-1]);
  839: 	$curves[-1]->{'function'} = $function; 
  840:     } elsif ($target eq 'edit') {
  841: 	$result .= &Apache::edit::tag_start($target,$token,'Gnuplot compatible curve function');
  842: 	my $text = &Apache::lonxml::get_all_text("/function",$parser);
  843: 	$result .= &Apache::edit::end_row().
  844: 	    &Apache::edit::start_spanning_row().
  845: 	    &Apache::edit::editline('',$text,'',60);
  846:     } elsif ($target eq 'modified') {
  847: 	$result.=&Apache::edit::rebuild_tag($token);
  848: 	$result.=&Apache::edit::modifiedfield("/function",$parser);
  849:     }
  850:     return $result;
  851: }
  852: 
  853: sub end_function {
  854:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  855:     my $result = '';
  856:     if ($target eq 'web' || $target eq 'tex') {
  857:     } elsif ($target eq 'edit') {
  858: 	$result .= &Apache::edit::end_table();
  859:     }
  860:     return $result;
  861: }
  862: 
  863: ##------------------------------------------------------------ curve  data
  864: sub start_data {
  865:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  866:     my $result='';
  867:     if ($target eq 'web' || $target eq 'tex') {
  868: 	if (exists($curves[-1]->{'function'})) {
  869: 	    &Apache::lonxml::warning
  870:                 ('Use of the <b>curve function</b> tag precludes use of '.
  871:                  ' the <b>curve data</b> tag.  '.
  872:                  'The curve function tag will be omitted in favor of the '.
  873:                  'curve data declaration.');
  874: 	    delete($curves[-1]->{'function'});
  875: 	}
  876: 	my $datatext = &Apache::lonxml::get_all_text("/data",$parser);
  877: 	$datatext=&Apache::run::evaluate($datatext,$safeeval,$$parstack[-1]);
  878: 	# Deal with cases where we're given an array...
  879: 	if ($datatext =~ /^\@/) {
  880: 	    $datatext = &Apache::run::run('return "'.$datatext.'"',
  881: 					  $safeeval,1);
  882: 	}
  883: 	$datatext =~ s/\s+/ /g;
  884: 	# Need to do some error checking on the @data array - 
  885: 	# make sure it's all numbers and make sure each array 
  886: 	# is of the same length.
  887: 	my @data;
  888: 	if ($datatext =~ /,/) { # comma deliminated
  889: 	    @data = split /,/,$datatext;
  890: 	} else { # Assume it's space seperated.
  891: 	    @data = split / /,$datatext;
  892: 	}
  893: 	for (my $i=0;$i<=$#data;$i++) {
  894: 	    # Check that it's non-empty
  895: 	    if (! defined($data[$i])) {
  896: 		&Apache::lonxml::warning(
  897: 		    'undefined curve data value.  Replacing with '.
  898: 		    ' pi/e = 1.15572734979092');
  899: 		$data[$i] = 1.15572734979092;
  900: 	    }
  901: 	    # Check that it's a number
  902: 	    if (! &$real_test($data[$i]) & ! &$int_test($data[$i])) {
  903: 		&Apache::lonxml::warning(
  904: 		    'Bad curve data value of '.$data[$i].'  Replacing with '.
  905: 		    ' pi/e = 1.15572734979092');
  906: 		$data[$i] = 1.15572734979092;
  907: 	    }
  908: 	}
  909: 	# complain if the number of data points is not the same as
  910: 	# in previous sets of data.
  911: 	if (($curves[-1]->{'data'}) && ($#data != $#{@{$curves[-1]->{'data'}->[0]}})){
  912: 	    &Apache::lonxml::warning
  913: 		('Number of data points is not consistent with previous '.
  914: 		 'number of data points');
  915: 	}
  916: 	push  @{$curves[-1]->{'data'}},\@data;
  917:     } elsif ($target eq 'edit') {
  918: 	$result .= &Apache::edit::tag_start($target,$token,'Comma or space deliminated curve data');
  919: 	my $text = &Apache::lonxml::get_all_text("/data",$parser);
  920: 	$result .= &Apache::edit::end_row().
  921: 	    &Apache::edit::start_spanning_row().
  922: 	    &Apache::edit::editline('',$text,'',60);
  923:     } elsif ($target eq 'modified') {
  924: 	$result.=&Apache::edit::rebuild_tag($token);
  925: 	$result.=&Apache::edit::modifiedfield("/data",$parser);
  926:     }
  927:     return $result;
  928: }
  929: 
  930: sub end_data {
  931:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  932:     my $result = '';
  933:     if ($target eq 'web' || $target eq 'tex') {
  934:     } elsif ($target eq 'edit') {
  935: 	$result .= &Apache::edit::end_table();
  936:     }
  937:     return $result;
  938: }
  939: 
  940: ##------------------------------------------------------------------- axis
  941: sub start_axis {
  942:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  943:     my $result='';
  944:     if ($target eq 'web' || $target eq 'tex') {
  945: 	&get_attributes(\%axis,\%axis_defaults,$parstack,$safeeval,
  946: 			$tagstack->[-1]);
  947:     } elsif ($target eq 'edit') {
  948: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Axes');
  949: 	$result .= &edit_attributes($target,$token,\%axis_defaults,
  950: 				    \@axis_edit_order);
  951:     } elsif ($target eq 'modified') {
  952: 	my $constructtag=&Apache::edit::get_new_args
  953: 	    ($token,$parstack,$safeeval,keys(%axis_defaults));
  954: 	if ($constructtag) {
  955: 	    $result = &Apache::edit::rebuild_tag($token);
  956: 	}
  957:     }
  958:     return $result;
  959: }
  960: 
  961: sub end_axis {
  962:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  963:     my $result = '';
  964:     if ($target eq 'web' || $target eq 'tex') {
  965:     } elsif ($target eq 'edit') {
  966: 	$result.=&Apache::edit::tag_end($target,$token);
  967:     } elsif ($target eq 'modified') {
  968:     }
  969:     return $result;
  970: }
  971: 
  972: ###################################################################
  973: ##                                                               ##
  974: ##        Utility Functions                                      ##
  975: ##                                                               ##
  976: ###################################################################
  977: 
  978: ##----------------------------------------------------------- set_defaults
  979: sub set_defaults {
  980:     my ($var,$defaults) = @_;
  981:     my $key;
  982:     foreach $key (keys(%$defaults)) {
  983: 	$var->{$key} = $defaults->{$key}->{'default'};
  984:     }
  985: }
  986: 
  987: ##------------------------------------------------------------------- misc
  988: sub get_attributes{
  989:     my ($values,$defaults,$parstack,$safeeval,$tag) = @_;
  990:     foreach my $attr (keys(%{$defaults})) {
  991: 	if ($attr eq 'texwidth' || $attr eq 'texfont') {
  992: 	    $values->{$attr} = 
  993: 		&Apache::lonxml::get_param($attr,$parstack,$safeeval,undef,1);
  994: 	} else {
  995: 	    $values->{$attr} = 
  996: 		&Apache::lonxml::get_param($attr,$parstack,$safeeval);
  997: 	}
  998: 	if ($values->{$attr} eq '' | !defined($values->{$attr})) {
  999: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
 1000: 	    next;
 1001: 	}
 1002: 	my $test = $defaults->{$attr}->{'test'};
 1003: 	if (! &$test($values->{$attr})) {
 1004: 	    &Apache::lonxml::warning
 1005: 		($tag.':'.$attr.': Bad value.'.'Replacing your value with : '
 1006: 		 .$defaults->{$attr}->{'default'} );
 1007: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
 1008: 	}
 1009:     }
 1010:     return ;
 1011: }
 1012: 
 1013: ##------------------------------------------------------- write_gnuplot_file
 1014: sub write_gnuplot_file {
 1015:     my ($tmpdir,$filename,$target)= @_;
 1016:     my $gnuplot_input = '';
 1017:     my $curve;
 1018:     my $pt = $plot{'texfont'};
 1019:     # Collect all the colors
 1020:     my @Colors;
 1021:     push @Colors, $plot{'bgcolor'};
 1022:     push @Colors, $plot{'fgcolor'}; 
 1023:     push @Colors, (defined($axis{'color'})?$axis{'color'}:$plot{'fgcolor'});
 1024:     foreach $curve (@curves) {
 1025: 	push @Colors, ($curve->{'color'} ne '' ? 
 1026: 		       $curve->{'color'}       : 
 1027: 		       $plot{'fgcolor'}        );
 1028:     }
 1029:     # set term
 1030:     if ($target eq 'web') {
 1031: 	$gnuplot_input .= 'set term gif ';
 1032: 	$gnuplot_input .= 'transparent ' if ($plot{'transparent'} eq 'on');
 1033: 	$gnuplot_input .= $plot{'font'} . ' ';
 1034: 	$gnuplot_input .= 'size '.$plot{'width'}.','.$plot{'height'}.' ';
 1035: 	$gnuplot_input .= "@Colors\n";
 1036: 	# set output
 1037: 	$gnuplot_input .= "set output\n";
 1038:     } elsif ($target eq 'tex') {
 1039: 	$gnuplot_input .= "set term postscript eps monochrome solid \"Helvetica\" $pt \n";
 1040: 	$gnuplot_input .= "set output \"/home/httpd/perl/tmp/".
 1041: 	    &Apache::lonnet::unescape($filename).".eps\"\n";
 1042:     }
 1043:     # cartesian or polar?
 1044:     if (lc($plot{'plottype'}) eq 'polar') {
 1045:         $gnuplot_input .= 'set polar'.$/;
 1046:     } else {
 1047:         # Assume Cartesian
 1048:     }
 1049:     # grid
 1050:     $gnuplot_input .= 'set grid'.$/ if ($plot{'grid'} eq 'on');
 1051:     # border
 1052:     $gnuplot_input .= ($plot{'border'} eq 'on'?
 1053: 		       'set border'.$/           :
 1054: 		       'set noborder'.$/         );
 1055:     # sampling rate for non-data curves
 1056:     $gnuplot_input .= "set samples $plot{'samples'}\n";
 1057:     # title, xlabel, ylabel
 1058:     # titles
 1059:     if ($target eq 'tex') {
 1060:         $gnuplot_input .= "set title  \"$title\" font \"Helvetica,".$pt."pt\"\n"  if (defined($title)) ;
 1061:         $gnuplot_input .= "set xlabel \"$xlabel\" font \"Helvetica,".$pt."pt\" \n" if (defined($xlabel));
 1062:         $gnuplot_input .= "set ylabel \"$ylabel\" font \"Helvetica,".$pt."pt\"\n" if (defined($ylabel));
 1063:     } else {
 1064:         $gnuplot_input .= "set title  \"$title\"  \n"  if (defined($title)) ;
 1065:         $gnuplot_input .= "set xlabel \"$xlabel\" \n" if (defined($xlabel));
 1066:         $gnuplot_input .= "set ylabel \"$ylabel\" \n" if (defined($ylabel));
 1067:     }
 1068:     # tics
 1069:     if (%xtics) {    
 1070: 	$gnuplot_input .= "set xtics $xtics{'location'} ";
 1071: 	$gnuplot_input .= ( $xtics{'mirror'} eq 'on'?"mirror ":"nomirror ");
 1072: 	$gnuplot_input .= "$xtics{'start'}, ";
 1073: 	$gnuplot_input .= "$xtics{'increment'}, ";
 1074: 	$gnuplot_input .= "$xtics{'end'}\n";
 1075:         if ($xtics{'minorfreq'} != 0) {
 1076:             $gnuplot_input .= "set mxtics ".$xtics{'minorfreq'}."\n";
 1077:         } 
 1078:     }
 1079:     if (%ytics) {    
 1080: 	$gnuplot_input .= "set ytics $ytics{'location'} ";
 1081: 	$gnuplot_input .= ( $ytics{'mirror'} eq 'on'?"mirror ":"nomirror ");
 1082: 	$gnuplot_input .= "$ytics{'start'}, ";
 1083: 	$gnuplot_input .= "$ytics{'increment'}, ";
 1084:         $gnuplot_input .= "$ytics{'end'}\n";
 1085:         if ($ytics{'minorfreq'} != 0) {
 1086:             $gnuplot_input .= "set mytics ".$ytics{'minorfreq'}."\n";
 1087:         } 
 1088:     }
 1089:     # axis
 1090:     if (%axis) {
 1091: 	$gnuplot_input .= "set xrange \[$axis{'xmin'}:$axis{'xmax'}\]\n";
 1092: 	$gnuplot_input .= "set yrange \[$axis{'ymin'}:$axis{'ymax'}\]\n";
 1093:     }
 1094:     # Key
 1095:     if (%key) {
 1096: 	$gnuplot_input .= 'set key '.$key{'pos'}.' ';
 1097: 	if ($key{'title'} ne '') {
 1098: 	    $gnuplot_input .= 'title "'.$key{'title'}.'" ';
 1099: 	} 
 1100: 	$gnuplot_input .= ($key{'box'} eq 'on' ? 'box ' : 'nobox ').$/;
 1101:     } else {
 1102: 	$gnuplot_input .= 'set nokey'.$/;
 1103:     }
 1104:     # labels
 1105:     my $label;
 1106:     foreach $label (@labels) {
 1107: 	$gnuplot_input .= 'set label "'.$label->{'text'}.'" at '.
 1108: 	    $label->{'xpos'}.','.$label->{'ypos'}.' '.$label->{'justify'}.' font "Helvetica,'.$pt.'pt"'.$/ ;
 1109:     }
 1110:     if ($target eq 'tex') {
 1111:         $gnuplot_input .="set size 1,".$plot{'height'}/$plot{'width'}*1.38;
 1112:         $gnuplot_input .="\n";
 1113:         }
 1114:     # curves
 1115:     $gnuplot_input .= 'plot ';
 1116:     for (my $i = 0;$i<=$#curves;$i++) {
 1117: 	$curve = $curves[$i];
 1118: 	$gnuplot_input.= ', ' if ($i > 0);
 1119: 	if (exists($curve->{'function'})) {
 1120: 	    $gnuplot_input.= 
 1121: 		$curve->{'function'}.' title "'.
 1122: 		$curve->{'name'}.'" with '.
 1123:                 $curve->{'linestyle'};
 1124:             $gnuplot_input.= ' linewidth 4 ' if ($target eq 'tex');
 1125:             if (($curve->{'linestyle'} eq 'points')      ||
 1126:                 ($curve->{'linestyle'} eq 'linespoints') ||
 1127:                 ($curve->{'linestyle'} eq 'errorbars')   ||
 1128:                 ($curve->{'linestyle'} eq 'xerrorbars')  ||
 1129:                 ($curve->{'linestyle'} eq 'yerrorbars')  ||
 1130:                 ($curve->{'linestyle'} eq 'xyerrorbars')) {
 1131:                 $gnuplot_input.=' pointtype '.$curve->{'pointtype'};
 1132:                 $gnuplot_input.=' pointsize '.$curve->{'pointsize'};
 1133:             }
 1134: 	} elsif (exists($curve->{'data'})) {
 1135: 	    # Store data values in $datatext
 1136: 	    my $datatext = '';
 1137: 	    #   get new filename
 1138: 	    my $datafilename = "$tmpdir/$filename.data.$i";
 1139: 	    my $fh=Apache::File->new(">$datafilename");
 1140: 	    # Compile data
 1141: 	    my @Data = @{$curve->{'data'}};
 1142: 	    my @Data0 = @{$Data[0]};
 1143: 	    for (my $i =0; $i<=$#Data0; $i++) {
 1144: 		my $dataset;
 1145: 		foreach $dataset (@Data) {
 1146: 		    $datatext .= $dataset->[$i] . ' ';
 1147: 		}
 1148: 		$datatext .= $/;
 1149: 	    }
 1150: 	    #   write file
 1151: 	    print $fh $datatext;
 1152: 	    close ($fh);
 1153: 	    #   generate gnuplot text
 1154: 	    $gnuplot_input.= '"'.$datafilename.'" title "'.
 1155: 		$curve->{'name'}.'" with '.
 1156: 		$curve->{'linestyle'};
 1157:             $gnuplot_input.= ' linewidth 4 ' if ($target eq 'tex');
 1158:             if (($curve->{'linestyle'} eq 'points')      ||
 1159:                 ($curve->{'linestyle'} eq 'linespoints') ||
 1160:                 ($curve->{'linestyle'} eq 'errorbars')   ||
 1161:                 ($curve->{'linestyle'} eq 'xerrorbars')  ||
 1162:                 ($curve->{'linestyle'} eq 'yerrorbars')  ||
 1163:                 ($curve->{'linestyle'} eq 'xyerrorbars')) {
 1164:                 $gnuplot_input.=' pointtype '.$curve->{'pointtype'};
 1165:                 $gnuplot_input.=' pointsize '.$curve->{'pointsize'};
 1166:             }
 1167: 	}
 1168:     }
 1169:     # Write the output to a file.
 1170:     my $fh=Apache::File->new(">$tmpdir$filename.data");
 1171:     print $fh $gnuplot_input;
 1172:     close($fh);
 1173:     # That's all folks.
 1174:     return ;
 1175: }
 1176: 
 1177: #---------------------------------------------- check_inputs
 1178: sub check_inputs {
 1179:     ## Note: no inputs, no outputs - this acts only on global variables.
 1180:     ## Make sure we have all the input we need:
 1181:     if (! %plot) { &set_defaults(\%plot,\%gnuplot_defaults); }
 1182:     if (! %key ) {} # No key for this plot, thats okay
 1183: #    if (! %axis) { &set_defaults(\%axis,\%axis_defaults); }
 1184:     if (! defined($title )) {} # No title for this plot, thats okay
 1185:     if (! defined($xlabel)) {} # No xlabel for this plot, thats okay
 1186:     if (! defined($ylabel)) {} # No ylabel for this plot, thats okay
 1187:     if ($#labels < 0) { }      # No labels for this plot, thats okay
 1188:     if ($#curves < 0) { 
 1189: 	&Apache::lonxml::warning("No curves specified for plot!!!!");
 1190: 	return '';
 1191:     }
 1192:     my $curve;
 1193:     foreach $curve (@curves) {
 1194: 	if (!defined($curve->{'function'})&&!defined($curve->{'data'})){
 1195: 	    &Apache::lonxml::warning("One of the curves specified did not contain any curve data or curve function declarations\n");
 1196: 	    return '';
 1197: 	}
 1198:     }
 1199: }
 1200: 
 1201: #------------------------------------------------ make_edit
 1202: sub edit_attributes {
 1203:     my ($target,$token,$defaults,$keys) = @_;
 1204:     my ($result,@keys);
 1205:     if ($keys && ref($keys) eq 'ARRAY') {
 1206:         @keys = @$keys;
 1207:     } else {
 1208: 	@keys = sort(keys(%$defaults));
 1209:     }
 1210:     foreach my $attr (@keys) {
 1211: 	# append a ' ' to the description if it doesn't have one already.
 1212: 	my $description = $defaults->{$attr}->{'description'};
 1213: 	$description .= ' ' if ($description !~ / $/);
 1214: 	if ($defaults->{$attr}->{'edit_type'} eq 'entry') {
 1215: 	    $result .= &Apache::edit::text_arg
 1216: 		($description,$attr,$token,
 1217: 		 $defaults->{$attr}->{'size'});
 1218: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'choice') {
 1219: 	    $result .= &Apache::edit::select_arg
 1220: 		($description,$attr,$defaults->{$attr}->{'choices'},$token);
 1221: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'onoff') {
 1222: 	    $result .= &Apache::edit::select_arg
 1223: 		($description,$attr,['on','off'],$token);
 1224: 	}
 1225: 	$result .= '<br />';
 1226:     }
 1227:     return $result;
 1228: }
 1229: 
 1230: 
 1231: ###################################################################
 1232: ##                                                               ##
 1233: ##           Insertion functions for editing plots               ##
 1234: ##                                                               ##
 1235: ###################################################################
 1236: 
 1237: sub insert_gnuplot {
 1238:     my $result = '';
 1239:     #  plot attributes
 1240:     $result .= "\n<gnuplot ";
 1241:     foreach my $attr (keys(%gnuplot_defaults)) {
 1242: 	$result .= "\n     $attr=\"$gnuplot_defaults{$attr}->{'default'}\"";
 1243:     }
 1244:     $result .= ">";
 1245:     # Add the components (most are commented out for simplicity)
 1246:     # $result .= &insert_key();
 1247:     # $result .= &insert_axis();
 1248:     # $result .= &insert_title();    
 1249:     # $result .= &insert_xlabel();    
 1250:     # $result .= &insert_ylabel();    
 1251:     $result .= &insert_curve();
 1252:     # close up the <gnuplot>
 1253:     $result .= "\n</gnuplot>";
 1254:     return $result;
 1255: }
 1256: 
 1257: sub insert_tics {
 1258:     my $result;
 1259:     $result .= &insert_xtics() . &insert_ytics;
 1260:     return $result;
 1261: }
 1262: 
 1263: sub insert_xtics {
 1264:     my $result;
 1265:     $result .= "\n    <xtics ";
 1266:     foreach my $attr (keys(%tic_defaults)) {
 1267: 	$result .= "\n        $attr=\"$tic_defaults{$attr}->{'default'}\" ";
 1268:     }
 1269:     $result .= "/>";
 1270:     return $result;
 1271: }
 1272: 
 1273: sub insert_ytics {
 1274:     my $result;
 1275:     $result .= "\n    <ytics ";
 1276:     foreach my $attr (keys(%tic_defaults)) {
 1277: 	$result .= "\n        $attr=\"$tic_defaults{$attr}->{'default'}\" ";
 1278:     }
 1279:     $result .= "/>";
 1280:     return $result;
 1281: }
 1282: 
 1283: sub insert_key {
 1284:     my $result;
 1285:     $result .= "\n    <key ";
 1286:     foreach my $attr (keys(%key_defaults)) {
 1287: 	$result .= "\n         $attr=\"$key_defaults{$attr}->{'default'}\"";
 1288:     }
 1289:     $result .= " />";
 1290:     return $result;
 1291: }
 1292: 
 1293: sub insert_axis{
 1294:     my $result;
 1295:     $result .= "\n    <axis ";
 1296:    foreach my $attr (keys(%axis_defaults)) {
 1297: 	$result .= "\n         $attr=\"$axis_defaults{$attr}->{'default'}\"";
 1298:     }
 1299:     $result .= " />";
 1300:     return $result;
 1301: }
 1302: 
 1303: sub insert_title  { return "\n    <title></title>"; }
 1304: sub insert_xlabel { return "\n    <xlabel></xlabel>"; }
 1305: sub insert_ylabel { return "\n    <ylabel></ylabel>"; }
 1306: 
 1307: sub insert_label {
 1308:     my $result;
 1309:     $result .= "\n    <label ";
 1310:     foreach my $attr (keys(%label_defaults)) {
 1311: 	$result .= "\n         $attr=\"".
 1312:             $label_defaults{$attr}->{'default'}."\"";
 1313:     }
 1314:     $result .= "></label>";
 1315:     return $result;
 1316: }
 1317: 
 1318: sub insert_curve {
 1319:     my $result;
 1320:     $result .= "\n    <curve ";
 1321:     foreach my $attr (keys(%curve_defaults)) {
 1322: 	$result .= "\n         $attr=\"".
 1323: 	    $curve_defaults{$attr}->{'default'}."\"";
 1324:     }
 1325:     $result .= " >";
 1326:     $result .= &insert_data().&insert_data()."\n    </curve>";
 1327: }
 1328: 
 1329: sub insert_function {
 1330:     my $result;
 1331:     $result .= "\n        <function></function>";
 1332:     return $result;
 1333: }
 1334: 
 1335: sub insert_data {
 1336:     my $result;
 1337:     $result .= "\n        <data></data>";
 1338:     return $result;
 1339: }
 1340: 
 1341: ##----------------------------------------------------------------------
 1342: # Javascript functions to display help for tags
 1343: 
 1344: sub make_javascript {
 1345:     my $helpwindowwidth  = 400;
 1346:     my $helpwindowheight = 400;
 1347:     my $result = '';
 1348:     $result.=<<"ENDFUNCTION";
 1349: <script language="JavaScript">
 1350: function openWin(text)
 1351: {
 1352:   newWin = open("", "new_W", "width=$helpwindowwidth,height=$helpwindowheight,resizable=1,scrollbars=1");
 1353:   newWin.document.open("text/html", "replace");
 1354:   newWin.document.writeln(text);
 1355:   newWin.document.writeln('<center><a href=\"javascript:window.close()\">close this window</a></center>');
 1356:   newWin.document.close();
 1357: }
 1358: </script>
 1359: ENDFUNCTION
 1360:     return $result;
 1361: }
 1362: 
 1363: sub help_win {
 1364:     my ($helptext)=@_;
 1365:     $helptext =~ s/\n/ /g;
 1366:     $helptext =~ s/\'/\\\'/g;
 1367:     my $result = '';
 1368:     $result.=<<"ENDWIN";
 1369: <table width="100%"><tr><td align="right">
 1370: <a href="javascript:openWin('$helptext')">help</a>
 1371: </td></tr></table><hr />
 1372: ENDWIN
 1373:     return $result;
 1374: }
 1375: ##----------------------------------------------------------------------
 1376: 1;
 1377: __END__
 1378: 
 1379: 

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