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