File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.85: download - view: text, annotated - select for diffs
Tue Jun 10 18:46:02 2003 UTC (20 years, 11 months ago) by matthew
Branches: MAIN
CVS tags: version_1_0_2, version_1_0_1, version_1_0_0, version_0_99_5, version_0_99_4, version_0_99_3, version_0_99_2, HEAD
Putting <tag> in html output supresses the display the thing in "<",">"'s.
Who knew?

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

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