File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.89: download - view: text, annotated - select for diffs
Fri Sep 19 17:53:03 2003 UTC (20 years, 7 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Bug 2201: Added support for minor tick marks.
Modified font code from Alex to only be used if we are printing.

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

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