File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.82: download - view: text, annotated - select for diffs
Tue Apr 22 19:47:47 2003 UTC (21 years ago) by matthew
Branches: MAIN
CVS tags: HEAD
Added 'texwidth' attribute.  The attribute is not implemented but can be
entered and has a default value.

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

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