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