Annotation of loncom/homework/functionplotresponse.pm, revision 1.47

1.1       www         1: # LearningOnline Network with CAPA
                      2: # option list style responses
                      3: #
1.47    ! www         4: # $Id: functionplotresponse.pm,v 1.46 2010/11/23 23:55:01 www Exp $
1.1       www         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: 
                     29: package Apache::functionplotresponse;
                     30: use strict;
                     31: use Apache::response();
                     32: use Apache::lonlocal;
                     33: use Apache::lonnet;
1.36      www        34:  
1.1       www        35: BEGIN {
1.37      www        36:   &Apache::lonxml::register('Apache::functionplotresponse',('functionplotresponse','backgroundplot','spline',
                     37:                                                             'functionplotrule','functionplotruleset',
                     38:                                                             'functionplotelements'));
1.1       www        39: }
                     40: 
1.5       www        41: #
                     42: # There can be a number of applets on a page, each called ggbApplet_$id, 
                     43: # where $id is the "_"-concatenated part and responseid
                     44: #
                     45: 
1.1       www        46: sub geogebra_startcode {
1.3       www        47:     my ($id)=@_;
1.1       www        48:     return (<<ENDSTARTCODE);
1.3       www        49: <applet name="ggbApplet_$id" code="geogebra.GeoGebraApplet" archive="geogebra.jar"
1.40      www        50:          codebase="/adm/geogebra/"  width="722" height="447" MAYSCRIPT>
1.1       www        51:        <param name="java_arguments" value="-Xmx512m -Djnlp.packEnabled=true"/>
                     52: ENDSTARTCODE
                     53: }
                     54: 
                     55: sub geogebra_endcode {
1.2       www        56:     return &Apache::lonhtmlcommon::java_not_enabled()."</applet>\n";
                     57: }
                     58: 
1.5       www        59: #
                     60: # This is the internal GeoGebra bytecode which defines the spline functions
                     61: #
1.2       www        62: sub geogebra_spline_program {
                     63:     return (<<ENDSPLINEPROGRAM);
1.42      www        64: <param name="ggbBase64" value="UEsDBBQACAAIANOAcz0AAAAAAAAAAAAAAAASAAAAZ2VvZ2VicmFfbWFjcm8ueG1s7Vxtb6tGGv3c/grEh1Vuu4njlzje2/hW5b1Sb3ulu1qttGorYhPHrQ0WJomnv74zA9hxgGuGNfYYnw/JYDwM8ByYM545z7n7fjWfKc9euJwG/lBtX12riuePgvHUnwzVp+jhcqB+/+Hru4kXTLz70FUegnDuRkO1e9VVldVy+t4Pfnbn3nLhjrzPo0dv7v4UjNyIt/YYRYv3rdbLy8tVevxVEE5ak0l0tVqO6fHzmb8cqsnGe9rc1kEvXV69c33dbv33409x85dTfxm5/shTFXpdc3cUBspoPmYXMVQ/L2ZT3+uoShQEs5xdjjdbrHf971P7n8pn+vepQ8vOr6oyHQW+NZ157JKWj8HLj/6/6UGaGw7VKHzy1PSEP/qLp0hxr4fqD6ritmnh0rIzVDVadGnhqq207i9P0bryc1JbS2o/82r0pEva/IgFTYmmUXx+9yl6DEK2NXYjtofW9Gbe3PMjJSILumcRTP1IVWbuvTdjV/Lh66/u2FUrwf0f3ihKrjn9/sGdLT12vq/u6Pd6MAtChTZP8Z7w//f8vztbPLp0iz4HvOrMJV6oPLsz9m2yhzb3MRh7W3tdfzrnqCvLyFuwBto0hAvPGycPVXzJdGNBm+QP16sLGgVBOF4qq/jEChmqPVb+FR/Lq/Cb/Tz9Kzlt9/XeiMxeX81dK4nTjohpjYhY54ARo4/5/x2yzs2NPEHrH+Ixa0rQevsO2moRektGPGkk3PvfV5R/Vot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hZgv6l61TSuOhxn88oxcNPevR2Oxbo8K+zMrr59P+tFdv3ek9/Z16mn3Y/f3L1Dplr0P+MbffP0yooHXvH3aIe4IvgF+btNuNTTplGnDfZ5WTbf1dKo/qp6z5wxCgOoxUM5NGbk4IrtV8V19Un0qJTv/i124EENGo5lc8W9RrEHXPqDsZOVtsv+hk3B79Zi14uplzTui833OXcaz98wvtheLSclrA4atfXRMtLY/oK2D2Zv7f3Rfi3CfYnfnOaM31SlsceWwZzOvQON34y3fwFQSwcI3KfwzsQEAAClDgAAUEsBAhQAFAAIAAgA04BzPTOjqPpOCgAAU0wBABIAAAAAAAAAAAAAAAAAAAAAAGdlb2dlYnJhX21hY3JvLnhtbFBLAQIUABQACAAIANOAcz1FzN5dGgAAABgAAAAWAAAAAAAAAAAAAAAAAI4KAABnZW9nZWJyYV9qYXZhc2NyaXB0LmpzUEsBAhQAFAAIAAgA04BzPdyn8M7EBAAApQ4AAAwAAAAAAAAAAAAAAAAA7AoAAGdlb2dlYnJhLnhtbFBLBQYAAAAAAwADAL4AAADqDwAAAAA=" />
1.2       www        65: ENDSPLINEPROGRAM
                     66: }
                     67: 
1.5       www        68: #
                     69: # The standard set of parameters inside <applet>
                     70: #
1.2       www        71: sub geogebra_default_parameters {
1.3       www        72:    my ($id)=@_;
1.2       www        73:    return(<<ENDDEFAULTPARAMETERS);
                     74:         <param name="image" value="/adm/lonIcons/lonanim.gif"  />
                     75:         <param name="boxborder" value="false"  />
                     76:         <param name="centerimage" value="true"  />
1.39      www        77: 	<param name="cache_archive" value="geogebra.jar, geogebra_main.jar, geogebra_gui.jar, geogebra_cas.jar, geogebra_algos.jar, geogebra_export.jar, geogebra_javascript.jar, jlatexmath.jar, jlm_greek.jar, jlm_cyrillic.jar, geogebra_properties.jar" />
                     78: 	<param name="cache_version" value="3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0" />
1.2       www        79:         <param name="framePossible" value="false" />
                     80: 
                     81:         <param name="showResetIcon" value="false" />
                     82:         <param name="showAnimationButton" value="false" />
                     83:         <param name="enableRightClick" value="false" />
                     84:         <param name="errorDialogsActive" value="true" />
                     85:         <param name="enableLabelDrags" value="false" />
                     86:         <param name="showMenuBar" value="false" />
                     87:         <param name="showToolBar" value="false" />
                     88:         <param name="showToolBarHelp" value="false" />
                     89:         <param name="showAlgebraInput" value="false" />
                     90:         <param name="enableShiftDragZoom" value="false" />
                     91:         <param name="allowRescaling" value="false" />
                     92:         <param name="enableLabelDrags" value="false" />
1.3       www        93:         <param name="ggbOnInitParam" value="applet_$id" />
1.2       www        94: ENDDEFAULTPARAMETERS
1.1       www        95: }
                     96: 
1.5       www        97: #
                     98: # This subroutine is called by LON-CAPA at </problem>
                     99: # Each applet on the page will call function ggbOnInit when it is done loading
                    100: # This function in turn will call the respective function registered by start_init_script
                    101: # Which one of the registered functions is called is determined by ggbOnInitParam, which GeoGebra passes to ggbOnInit
                    102: #
                    103: 
1.3       www       104: sub init_script {
1.16      www       105:    if ($#Apache::functionplotresponse::callscripts>=0) {
                    106:       my $script='';
                    107:       foreach my $id (@Apache::functionplotresponse::callscripts) {
                    108:           $script.="if (param=='applet_$id') { loaded_$id=true; }\n";
                    109:       }
                    110:       $script.="if (".join(' && ',map { "loaded_$_" } (@Apache::functionplotresponse::callscripts)).
1.17      www       111:                ") { setTimeout('ggbInitAll()',20) }";
1.16      www       112:       my $calls=join("\n",map { "ggbInit_$_();" } (@Apache::functionplotresponse::callscripts)); 
1.3       www       113:       return (<<ENDGGBINIT);
                    114: <script type="text/javascript">
                    115: // <![CDATA[
1.16      www       116: // Function that each applet will call when loaded
                    117: // It will pass "its" parameter
                    118: // Set flags for when an applet is loaded, wait till all are loaded, and then some
1.3       www       119: function ggbOnInit(param) {
1.16      www       120: $script
                    121: }
                    122: function ggbInitAll() {
1.17      www       123: $calls
1.3       www       124: }
                    125: // ]]>
                    126: </script>
                    127: ENDGGBINIT
                    128:    }
                    129: }
                    130: 
1.5       www       131: #
                    132: # Each Geogebra applet is supposed to call this when parameters change
1.10      www       133: # Changes the hidden fields on the web page
1.5       www       134: #
                    135: sub update_script {
                    136:     my ($id)=@_;
                    137:     return (<<ENDUPDATESCRIPT);
                    138: <script type="text/javascript">
                    139: // <![CDATA[
                    140: function updatePointCoordinates_$id(coordinateName) {
                    141:             var x = document.ggbApplet_$id.getXcoord(coordinateName);
                    142:             var y = document.ggbApplet_$id.getYcoord(coordinateName);
1.9       www       143:             document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_x"].value = x;
                    144:             document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_y"].value = y;
1.5       www       145:         }
                    146: // ]]>
                    147: </script>
                    148: ENDUPDATESCRIPT
                    149: }
                    150: 
                    151: #
                    152: # Register the above update-handler for a variable
                    153: #
                    154: 
                    155: sub update_register {
                    156:    my ($id,$variable)=@_;
1.6       www       157:    return "document.ggbApplet_$id.registerObjectUpdateListener('$variable','updatePointCoordinates_$id');\n";
                    158: }
                    159: 
                    160: #
1.40      www       161: # Set a point coordinate variable
1.6       www       162: #
1.40      www       163: sub set_point_coordinate {
1.6       www       164:    my ($id,$variable,$x,$y)=@_;
                    165:    return (<<ENDSETVARIABLE);
1.9       www       166: document.ggbApplet_$id.evalCommand("$variable=($x,$y)");
1.40      www       167: document.ggbApplet_$id.setLabelVisible("$variable",false);
1.6       www       168: ENDSETVARIABLE
                    169: }
                    170: 
                    171: #
1.40      www       172: # Set a slope coordinate variable
                    173: #
                    174: sub set_slope_coordinate {
                    175:    my ($id,$variable,$xrel,$yrel,$xmin,$xmax,$ymin,$ymax,$pointname)=@_;
                    176:    my $xvariable=$variable.'x';
                    177:    my $yvariable=$variable.'y';
                    178:    my $domain=$xmax-$xmin;
                    179:    my $range=$ymax-$ymin;
                    180:    my $xinterval=$domain/100.;
                    181:    my $yinterval=$range/200.;
                    182:    return (<<ENDSETSVARIABLE);
                    183: document.ggbApplet_$id.evalCommand("$xvariable=Slider[0,$domain,$xinterval]");
                    184: document.ggbApplet_$id.setVisible("$xvariable", false);
                    185: document.ggbApplet_$id.evalCommand("$xvariable=$xrel");
                    186: document.ggbApplet_$id.evalCommand("$yvariable=Slider[-$range,$range,$yinterval]");
                    187: document.ggbApplet_$id.setVisible("$yvariable", false);
                    188: document.ggbApplet_$id.evalCommand("$yvariable=$yrel");
                    189: document.ggbApplet_$id.evalCommand("$variable=($xvariable+x($pointname),$yvariable+y($pointname))");
                    190: document.ggbApplet_$id.setLabelVisible("$variable", false);
                    191: ENDSETSVARIABLE
                    192: }
                    193: 
                    194: #
1.9       www       195: # Input field name for a coordinate variable
                    196: #
                    197: 
                    198: sub field_name {
                    199:     my ($id,$variable,$name)=@_;
                    200:     return "HWVAL_$id\_$variable\_$name";
                    201: }
                    202: 
                    203: #
                    204: # Generate an input field for a coordinate variable
                    205: #
                    206: 
                    207: sub generate_input_field {
                    208:     my ($id,$variable,$x,$y)=@_;
                    209:     $Apache::functionplotresponse::inputfields.=
                    210:        "<input type='hidden' name='".&field_name($id,$variable,'x')."' value='$x' />\n".
                    211:        "<input type='hidden' name='".&field_name($id,$variable,'y')."' value='$y' />\n";
                    212: }
                    213: 
                    214: #
1.40      www       215: # Initialize a new point coordinate variable at set a listener on it
1.6       www       216: #
1.40      www       217: sub new_point_coordinate {
1.6       www       218:     my ($id,$variable,$x,$y)=@_;
1.11      www       219:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
1.10      www       220:        $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
                    221:     }
1.11      www       222:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
1.10      www       223:        $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
                    224:     }
1.9       www       225:     &generate_input_field($id,$variable,$x,$y);
1.40      www       226:     return &set_point_coordinate($id,$variable,$x,$y).&update_register($id,$variable);
                    227: }
                    228: 
                    229: #
                    230: # Initialize a new slope coordinate variable at set a listener on it
                    231: #
                    232: sub new_slope_coordinate {
                    233:     my ($id,$variable,$x,$y,$pointname,$xp,$yp,$xmin,$xmax,$ymin,$ymax)=@_;
                    234: #
                    235: # $variable: name of the slope point
                    236: # $x, $y: coordinates of the slope point
                    237: # $pointname: name of the associated point point
                    238: # $xp $yp: coordinates of the point point
                    239: #
                    240:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
                    241:        $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
                    242:     }
                    243:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
                    244:        $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
                    245:     }
                    246:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$pointname,'x')})) {
                    247:        $xp=$Apache::functionplotresponse::previous{&field_name($id,$pointname,'x')};
                    248:     }
                    249:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$pointname,'y')})) {
                    250:        $yp=$Apache::functionplotresponse::previous{&field_name($id,$pointname,'y')};
                    251:     }
                    252: 
                    253:     &generate_input_field($id,$variable,$x,$y);
                    254:     my $xrel=$x-$xp;
                    255:     my $yrel=$y-$yp;
                    256:     return &set_slope_coordinate($id,$variable,$xrel,$yrel,$xmin,$xmax,$ymin,$ymax,$pointname).&update_register($id,$variable);
1.5       www       257: }
                    258: 
                    259: #
                    260: # This registers the init-function call for ggbOnInit, which LON-CAPA will place at </problem>
                    261: # It then starts the right headers
                    262: #
1.3       www       263: sub start_init_script {
                    264:     my ($id)=@_;
1.16      www       265: # Add id to the list of ggbInit_$id functions that need to be called
                    266:     push(@Apache::functionplotresponse::callscripts,$id);
1.5       www       267: # ... and open this function
1.3       www       268:     return (<<ENDSTARTINIT);
                    269: <script type="text/javascript">
                    270: // <![CDATA[
1.5       www       271: // variable that will eventually be passed back to the server
                    272: var coordinateMap_$id = [];
1.16      www       273: // flag for not loaded yet
                    274: var loaded_$id=false;
1.5       www       275: // Init-function for applet
1.3       www       276: function ggbInit_$id() {
                    277: ENDSTARTINIT
                    278: }
                    279: 
1.5       www       280: #
                    281: # This sets the axes inside ggbInit_$id
                    282: #
                    283: 
1.4       www       284: sub axes_script {
                    285:     my ($id,$xmin,$xmax,$ymin,$ymax,$xvisible,$yvisible,$gvisible)=@_;
                    286:     return (<<ENDAXESSCRIPT);
                    287:             // changes (xmin, xmax, ymin, ymax)
                    288:             document.ggbApplet_$id.setCoordSystem($xmin,$xmax,$ymin,$ymax);
                    289: 
                    290:             // makes the (x,y) axis (in)visible
                    291:             document.ggbApplet_$id.setAxesVisible($xvisible,$yvisible);
                    292:             // makes the grid (in)visible
                    293:             document.ggbApplet_$id.setGridVisible($gvisible);
                    294: ENDAXESSCRIPT
                    295: }
                    296: 
1.14      www       297: sub axes_label {
1.45      www       298:     my ($id,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel)=@_;
1.14      www       299:     unless ($xlabel || $ylabel) { return ''; }
                    300:     my $return='document.ggbApplet_'.$id.'.evalCommand("topRight=Corner[3]");';
                    301:     if ($xlabel) {
1.45      www       302:       if (($ymin<0) && ($ymax>0)) {
1.14      www       303:        $return.=(<<ENDXAXISLABELSCRIPT);
                    304: document.ggbApplet_$id.evalCommand("Xlabel=(x(topRight)-AxisStepX[],AxisStepY[]/6)");
                    305: document.ggbApplet_$id.setVisible("Xlabel",false);
                    306: document.ggbApplet_$id.evalCommand("Text[\\"$xlabel\\", Xlabel]");
                    307: ENDXAXISLABELSCRIPT
1.45      www       308:       } else {
                    309:        $return.=(<<ENDXOFFAXISLABEL);
                    310: document.ggbApplet_$id.evalCommand("LowerRight=Corner[2]");
                    311: document.ggbApplet_$id.evalCommand("Text[\\"$xlabel\\", (x(LowerRight) - AxisStepX[], y(LowerRight) + AxisStepY[] / 2)]");
                    312: ENDXOFFAXISLABEL
                    313:       }
1.14      www       314:     }
                    315:     if ($ylabel) {
1.45      www       316:       if (($xmin<0) && ($xmax>0)) {
1.14      www       317:        $return.=(<<ENDYAXISLABELSCRIPT);
                    318: document.ggbApplet_$id.evalCommand("Ylabel=(AxisStepX[]/6,y(topRight)-AxisStepY[]/3)");
                    319: document.ggbApplet_$id.setVisible("Ylabel",false);
                    320: document.ggbApplet_$id.evalCommand("Text[\\"$ylabel\\", Ylabel]");
                    321: ENDYAXISLABELSCRIPT
1.45      www       322:       } else {
                    323:        $return.=(<<ENDYOFFAXISLABEL);
                    324: document.ggbApplet_$id.evalCommand("UpperLeft=Corner[4]");
                    325: document.ggbApplet_$id.evalCommand("Text[\\"$ylabel\\", (x(UpperLeft) + AxisStepX[] / 5, y(UpperLeft) - AxisStepY[] / 1.8)]");
                    326: ENDYOFFAXISLABEL
                    327:       }
1.14      www       328:     }
                    329:     return $return;
                    330: }
                    331: 
1.4       www       332: sub plot_script {
1.47    ! www       333:    my ($id,$function,$fixed,$label,$color,$xmin,$xmax,$thickness)=@_;
1.41      www       334:    $label=~s/\W//g;
                    335:    if (($label) && ($label!~/^[A-Za-z]/)) {
                    336:       $label='C'.$label;
                    337:    }
                    338:    my $visible=0;
                    339:    if ($label) {
                    340:       $visible="1";
                    341:    } else {
                    342:       $Apache::functionplotresponse::counter++;
                    343:       $label='C'.$Apache::functionplotresponse::counter;
                    344:    }
1.46      www       345:    my $rc=0;
                    346:    my $gc=0;
                    347:    my $bc=0;
                    348:    if ($color) {
                    349:       my ($rh,$gh,$bh)=($color=~/(..)(..)(..)/);
                    350:       $rc=hex($rh);
                    351:       $gc=hex($gh);
                    352:       $bc=hex($bh);
                    353:    }
1.6       www       354:    if ($fixed) {
1.43      www       355:       return "document.ggbApplet_$id.evalCommand('$label=Function[$function,$xmin,$xmax]');\n".
1.46      www       356:              ($visible?'':"document.ggbApplet_$id.setLabelVisible('$label', false);\n").
1.47    ! www       357:              ($color?"document.ggbApplet_$id.setColor('$label',$rc,$gc,$bc);\n":'').
        !           358:              ($thickness?"document.ggbApplet_$id.setLineThickness('$label',$thickness);\n":'');
1.6       www       359:    } else {
1.46      www       360:        return "document.ggbApplet_$id.evalCommand('y=$function');\n";
1.6       www       361:    }
1.4       www       362: }
                    363: 
1.5       www       364: #
1.7       www       365: # Subroutine that generates code for spline $label based on stored information
1.6       www       366: #
                    367: 
                    368: sub generate_spline {
1.40      www       369:    my ($id,$label,$xmin,$xmax,$ymin,$ymax)=@_;
1.6       www       370:    my $result='';
1.7       www       371:    my $order=$Apache::functionplotresponse::splineorder{$label};
                    372:    my $x=$Apache::functionplotresponse::splineinitx{$label};
                    373:    my $y=$Apache::functionplotresponse::splineinity{$label};
                    374:    my $sx=$Apache::functionplotresponse::splinescalex{$label};
                    375:    my $sy=$Apache::functionplotresponse::splinescaley{$label};
                    376:    my @coords=();
                    377:    foreach my $i (1..$order) {
1.40      www       378:        $result.=&new_point_coordinate($id,$label.'P'.$i,$x,$y);
                    379:        my $xp=$x;
1.8       www       380:        $x+=$sx/(2.*($order-1));
1.7       www       381:        push(@coords,$label.'P'.$i);
1.40      www       382:        $result.=&new_slope_coordinate($id,$label.'S'.$i,$x,$y+$sy,$label.'P'.$i,$xp,$y,$xmin,$xmax,$ymin,$ymax);
1.8       www       383:        $x+=$sx/(2.*($order-1));
1.7       www       384:        push(@coords,$label.'S'.$i);
                    385:    }
                    386:    $result.='document.ggbApplet_'.$id.'.evalCommand("Spline'.$order.'['.join(',',@coords).']");'."\n";
1.6       www       387:    return $result;
                    388: }
                    389: #
                    390: # <backgroundplot function="..." fixed="yes/no" />
1.5       www       391: #
1.4       www       392: sub start_backgroundplot {
                    393:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    394:    my $result='';
                    395:    my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
                    396:    my $function=&Apache::lonxml::get_param('function',$parstack,$safeeval);
1.47    ! www       397:    my $xinitial=&Apache::lonxml::get_param('xinitial',$parstack,$safeeval);
        !           398:    my $xfinal=&Apache::lonxml::get_param('xfinal',$parstack,$safeeval);
1.41      www       399:    my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
1.46      www       400:    my $color=&Apache::lonxml::get_param('color',$parstack,$safeeval);
                    401:    $color=~s/[^a-fA-F0-9]//gs;
                    402:    unless (length($color)==6) { $color=''; }
1.6       www       403:    my $fixed=(&Apache::lonxml::get_param('fixed',$parstack,$safeeval)=~/on|true|yes|1/i?1:0);
                    404:  
1.4       www       405:    unless ($function) { $function="0"; }
                    406:    if ($target eq 'web') {
1.41      www       407:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
1.47    ! www       408:       unless (defined($xinitial)) { $xinitial=$xmin; }
        !           409:       unless (defined($xfinal)) { $xfinal=$xmax; }
        !           410:       $result.=&plot_script($internalid,$function,$fixed,$label,$color,$xinitial,$xfinal);
1.13      www       411:    } elsif ($target eq 'edit') {
                    412:         $result=&Apache::edit::tag_start($target,$token,'Background Function Plot').
                    413:              &Apache::edit::text_arg('Function:','function',
                    414:                                      $token,'16').
1.47    ! www       415:              &Apache::edit::text_arg('Initial x-value (optional):','xinitial',
        !           416:                                      $token,'8').
        !           417:              &Apache::edit::text_arg('Final x-value (optional):','xfinal',
        !           418:                                      $token,'8').
1.41      www       419:              &Apache::edit::text_arg('Label on Plot:','label',
                    420:                                      $token,'8').
1.46      www       421:              &Apache::edit::text_arg('Color (hex code):','color',
                    422:                                      $token,'8').
1.13      www       423:              &Apache::edit::select_arg('Fixed location:','fixed',
                    424:                                   ['yes','no'],$token).
                    425:              &Apache::edit::end_row();
                    426:   } elsif ($target eq 'modified') {
                    427:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.47    ! www       428:                                                  $safeeval,'function','label','xinitial','xfinal','color','fixed');
1.13      www       429:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    430:   }
                    431:   return $result;
1.4       www       432: }
                    433: 
                    434: sub end_backgroundplot {
1.13      www       435:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    436:    my $result='';
                    437:    if ($target eq 'edit') {
                    438:        $result=&Apache::edit::end_table();
                    439:    }
                    440:    return $result;
1.6       www       441: }
                    442: 
                    443: #
1.25      www       444: # <functionplotrule ... />
1.12      www       445: #
1.25      www       446: sub start_functionplotrule {
1.12      www       447:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    448:    my $result='';
1.24      www       449:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
                    450:    $Apache::functionplotresponse::counter++;
                    451:    if ($label=~/\W/) {
1.25      www       452:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
1.24      www       453:    }
                    454:    $label=~s/\W//gs;
                    455:    unless ($label) {
                    456:       $label='R'.$Apache::functionplotresponse::counter;
                    457:    } else {
                    458:       $label='R'.$label;
                    459:    }
                    460:    if ($Apache::functionplotresponse::splineorder{$label}) {
1.25      www       461:        &Apache::lonxml::error(&mt('Rule indices must be unique.'));
1.24      www       462:    }
                    463: 
                    464: 
                    465:    if ($target eq 'grade') {
                    466: # Simply remember - in order - for later
1.25      www       467:       my $beginninglabel=&Apache::lonxml::get_param('xinitiallabel',$parstack,$safeeval);
                    468:       my $endinglabel=&Apache::lonxml::get_param('xfinallabel',$parstack,$safeeval);
1.24      www       469:       if (($beginninglabel=~/\W/) || ($endinglabel=~/W/)) {
1.25      www       470:           &Apache::lonxml::warning(&mt('Rule labels must be alphanumeric.'));
1.24      www       471:       }
                    472:       $beginninglabel=~s/\W//gs;
                    473:       $endinglabel=~s/\W//gs;
                    474:       my $relationship=&Apache::lonxml::get_param('relationship',$parstack,$safeeval);
                    475:       $relationship=~s/\W//gs;
                    476:       $relationship=lc($relationship);
                    477:       unless ($relationship=~/^(eq|ge|gt|le|lt|ne)$/) {
1.25      www       478:           &Apache::lonxml::warning(&mt('Rule relationship not defined.'));
1.24      www       479:           $relationship='eq';
                    480:       }
1.35      www       481:       my $derivative=&Apache::lonxml::get_param('derivativeorder',$parstack,$safeeval);
1.42      www       482:       unless (($derivative==-1) || ($derivative==0) || ($derivative==1) || ($derivative==2)) {
1.25      www       483:          &Apache::lonxml::warning(&mt('Rule derivative not defined.'));
1.24      www       484:          $derivative=0;
                    485:       }
1.25      www       486:       push(@Apache::functionplotresponse::functionplotrules,join(':',(
1.24      www       487:            $label,
                    488:            $derivative,
1.25      www       489:            &Apache::lonxml::get_param('xinitial',$parstack,$safeeval),
1.24      www       490:            $beginninglabel,
1.25      www       491:            &Apache::lonxml::get_param('xfinal',$parstack,$safeeval),
1.24      www       492:            $endinglabel,
1.35      www       493:            &Apache::lonxml::get_param('minimumlength',$parstack,$safeeval),
                    494:            &Apache::lonxml::get_param('maximumlength',$parstack,$safeeval),
1.24      www       495:            $relationship,
1.33      www       496:            &Apache::lonxml::get_param('value',$parstack,$safeeval),
                    497:            &Apache::lonxml::get_param('percenterror',$parstack,$safeeval)
1.24      www       498:           )));
                    499:    } elsif ($target eq 'edit') {
1.29      www       500:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Evaluation Rule').
1.36      www       501:              &Apache::edit::text_arg('Index/Name:','index',
                    502:                                      $token,'10').'&nbsp;'.
1.35      www       503:              &Apache::edit::select_arg(&mt('Function:'),'derivativeorder',
1.29      www       504:                                   [['0','Function itself'],
                    505:                                    ['1','First derivative'],
1.42      www       506:                                    ['2','Second derivative'],
                    507:                                    ['-1','Integral']],$token).'<br />'.
1.44      www       508:              &Apache::edit::text_arg('Initial x-value:','xinitial',
1.35      www       509:                                       $token,'8').
1.44      www       510:              &Apache::edit::select_or_text_arg('Initial x-value label:','xinitiallabel',
                    511:                                                [['start','Start of Plot'],
                    512:                                                 ['end','End of Plot']],$token,'8').'<br />'.
1.30      www       513: 
1.44      www       514:              &Apache::edit::text_arg('Final x-value (optional):','xfinal',
1.35      www       515:                                       $token,'8').
1.44      www       516:              &Apache::edit::select_or_text_arg('Final x-value label (optional):','xfinallabel',
1.32      www       517:                                                [['end','End of Plot']],$token,'8').'<br />'.
1.44      www       518:              &Apache::edit::text_arg('Minimum length for range (optional):','minimumlength',
1.35      www       519:                                      $token,'8').
1.44      www       520:              &Apache::edit::text_arg('Maximum length for range (optional):','maximumlength',
1.35      www       521:                                      $token,'8').'<br />'.
1.38      www       522:              &Apache::edit::select_or_text_arg(&mt('Relationship:'),'relationship',
1.29      www       523:                                   [['eq','equal'],
                    524:                                    ['ne','not equal'],
                    525:                                    ['ge','greater than or equal'],
                    526:                                    ['gt','greater than'],
                    527:                                    ['lt','less than'],
                    528:                                    ['le','less than or equal']],$token).
                    529:              $result.= &Apache::edit::select_or_text_arg('Value:','value',
1.35      www       530:                                                [['undef','not defined']],$token,'8').
1.29      www       531:              &Apache::edit::text_arg('Percent error:','percenterror',
1.35      www       532:                                      $token,'8').
1.29      www       533:              &Apache::edit::end_row();
                    534:   } elsif ($target eq 'modified') {
                    535:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.35      www       536:                                                  $safeeval,'index','derivativeorder',
                    537:                                                            'xinitial','xinitiallabel','xfinal','xfinallabel',
                    538:                                                            'minimumlength','maximumlength',
                    539:                                                            'relationship','value','percenterror');
1.29      www       540:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
1.13      www       541:    }
1.12      www       542:    return $result;
                    543: }
                    544: 
1.25      www       545: sub end_functionplotrule {
1.13      www       546:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    547:    my $result='';
                    548:    if ($target eq 'edit') {
                    549:        $result=&Apache::edit::end_table();
                    550:    }
                    551:    return $result;
1.12      www       552: }
                    553: 
                    554: 
                    555: #
1.23      www       556: # <spline index="..." order="1,2,3,4" initx="..." inity="..." scalex="..." scaley="..." />
1.6       www       557: #
                    558: # Unfortunately, GeoGebra seems to want all splines after everything else, so we need to store them
                    559: #
                    560: sub start_spline {
                    561:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.13      www       562:    my $result='';
                    563:    if ($target eq 'web') {
1.23      www       564:       my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
1.13      www       565:       $Apache::functionplotresponse::counter++;
                    566:       if ($label=~/\W/) {
1.23      www       567:          &Apache::lonxml::warning(&mt('Spline indices should only contain alphanumeric characters.'));
1.13      www       568:       }
                    569:       $label=~s/\W//gs;
1.23      www       570:       unless ($label) { 
                    571:          $label='S'.$Apache::functionplotresponse::counter; 
                    572:       } else {
                    573:          $label='S'.$label;
                    574:       }
1.13      www       575:       if ($Apache::functionplotresponse::splineorder{$label}) {
1.23      www       576:          &Apache::lonxml::error(&mt('Spline indices must be unique.'));
1.13      www       577:       }
                    578: 
                    579:       my $order=&Apache::lonxml::get_param('order',$parstack,$safeeval);
                    580:       if ($order<2) { $order=2; }
                    581:       if ($order>8) { $order=8; }
                    582:       $Apache::functionplotresponse::splineorder{$label}=$order;
                    583: 
                    584:       my $x=&Apache::lonxml::get_param('initx',$parstack,$safeeval);
                    585:       unless ($x) { $x=0; }
                    586:       $Apache::functionplotresponse::splineinitx{$label}=$x;
                    587: 
                    588:       my $y=&Apache::lonxml::get_param('inity',$parstack,$safeeval);
                    589:       unless ($y) { $y=0; }
                    590:       $Apache::functionplotresponse::splineinity{$label}=$y;
                    591: 
                    592:       my $sx=&Apache::lonxml::get_param('scalex',$parstack,$safeeval);
                    593:       unless ($sx) { $sx=$order; }
                    594:       $Apache::functionplotresponse::splinescalex{$label}=$sx;
                    595: 
                    596:       my $sy=&Apache::lonxml::get_param('scaley',$parstack,$safeeval);
                    597:       unless ($sy) { $sy=2; }
                    598:       $Apache::functionplotresponse::splinescaley{$label}=$sy;
                    599:    } elsif ($target eq 'edit') {
                    600:         $result=&Apache::edit::tag_start($target,$token,'Spline').
1.23      www       601:              &Apache::edit::text_arg('Index:','index',
1.14      www       602:                                      $token,'4').'&nbsp;'.
1.13      www       603:              &Apache::edit::select_arg('Order:','order',
1.44      www       604:                                   ['2','3','4','5','6','7','8'],$token).'&nbsp;'.
1.13      www       605:              &Apache::edit::text_arg('Initial x-value:','initx',
1.14      www       606:                                      $token,'4').'&nbsp;'.
1.13      www       607:              &Apache::edit::text_arg('Initial y-value:','inity',
1.14      www       608:                                      $token,'4').'&nbsp;'.
1.13      www       609:              &Apache::edit::text_arg('Scale x:','scalex',
1.14      www       610:                                      $token,'4').'&nbsp;'.
1.13      www       611:              &Apache::edit::text_arg('Scale y:','scaley',
                    612:                                      $token,'4').
                    613:              &Apache::edit::end_row();
                    614:   } elsif ($target eq 'modified') {
                    615:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.23      www       616:                                                  $safeeval,'index','order','initx','inity',
1.13      www       617:                                                            'scalex','scaley');
                    618:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    619:   }
                    620:   return $result;
1.6       www       621: }
                    622: 
                    623: sub end_spline {
1.13      www       624:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    625:    my $result='';
                    626:    if ($target eq 'edit') {
                    627:        $result=&Apache::edit::end_table();
                    628:    }
                    629:    return $result;
1.4       www       630: }
                    631:  
1.3       www       632: sub end_init_script {
                    633:     return (<<ENDENDINIT);
                    634: }
                    635: // ]]>
                    636: </script>
                    637: ENDENDINIT
                    638: }
                    639: 
1.10      www       640: #
                    641: # Storing and restoring spline coordinates from part answers
                    642: #
                    643: sub decode_previous_answer {
                    644:    my ($answer)=@_;
                    645:    foreach my $coordinate (split(/\,/,$answer)) {
                    646:       my ($key,$value)=split(/\=/,$coordinate);
                    647:       $Apache::functionplotresponse::previous{$key}=$value;
                    648:    }
                    649: }
                    650: 
                    651: sub get_answer_from_form_fields {
                    652:    my ($id)=@_;
                    653:    my $answer='';
                    654:    my %coords=();
                    655:    foreach my $field (keys(%env)) {
                    656:       if ($field=~/^form\.HWVAL\_$id/) {
                    657:          $field=~/^form\.(.*)$/;
                    658:          $coords{$1}=$env{$field};
                    659:       }
                    660:    }
                    661:    $answer=join(',',map { $_.'='.$coords{$_} } (sort(keys(%coords))));
                    662:    return ($answer,%coords);
                    663: }
                    664: 
1.15      www       665: #
                    666: # The following functions calculate the cubic-hermite splines server-side
                    667: #
                    668: 
                    669: sub cubic_hermite {
                    670:    my ($t,$p1,$s1,$p2,$s2)=@_;
1.42      www       671:    return (2.*$t*$t*$t-3.*$t*$t+1.)*$p1 + 3.*($t*$t*$t-2.*$t*$t+$t)*($s1-$p1)+
                    672:           (-2.*$t*$t*$t+3.*$t*$t)  *$p2 + 3.*($t*$t*$t-$t*$t)      *($s2-$p2);
1.15      www       673: }
                    674: 
                    675: #
                    676: # d/dt(...)
                    677: # 
                    678: 
                    679: sub ddt_cubic_hermite {
                    680:    my ($t,$p1,$s1,$p2,$s2)=@_;
1.42      www       681:    return (6.*$t*$t-6.*$t) *$p1 + 3.*(3.*$t*$t-4.*$t+1.)*($s1-$p1)+
                    682:           (-6.*$t*$t+6.*$t)*$p2 + 3.*(3.*$t*$t-2.*$t)   *($s2-$p2);
1.15      www       683: }
                    684: 
                    685: #
                    686: # d^2/dt^2(...)
                    687: #
                    688: 
                    689: sub d2dt2_cubic_hermite {
                    690:    my ($t,$p1,$s1,$p2,$s2)=@_;
1.42      www       691:    return (12.*$t-6.) *$p1 + 3.*(6.*$t-4.)*($s1-$p1)+
                    692:           (-12.*$t+6.)*$p2 + 3.*(6.*$t-2.)*($s2-$p2);
1.15      www       693: }
                    694: 
                    695: #
1.18      www       696: # Array index calculation
                    697: #
                    698: sub array_index {
                    699:    my ($xmin,$xmax,$x)=@_;
1.38      www       700:    if ($x ne '') {
                    701:       return int(($x-$xmin)/($xmax-$xmin)*400.+0.5);
                    702:    } else {
                    703:       return undef;
                    704:    }
1.20      www       705: }
                    706: 
                    707: #
1.18      www       708: # Populate the arrays
                    709: #
                    710: 
                    711: sub populate_arrays {
                    712:     my ($id,$xmin,$xmax)=@_;
1.26      www       713:     for (my $i=0; $i<=400; $i++) {
1.35      www       714:        $Apache::functionplotresponse::actualxval[$i]=undef;
1.19      www       715:        $Apache::functionplotresponse::func[$i]=undef;
1.22      www       716:        $Apache::functionplotresponse::dfuncdx[$i]=undef;
1.19      www       717:        $Apache::functionplotresponse::d2funcd2x[$i]=undef;
1.18      www       718:     }
1.19      www       719:     unless ($xmax>$xmin) { return 'no_func'; }
1.18      www       720: # Run over all splines in response
                    721:     foreach my $label (split(/\,/,$env{"form.HWVAL_AllSplines_$id"})) {
1.19      www       722:         my $xiold=-1;
1.18      www       723: # Run over all points in spline
1.19      www       724:         for (my $i=1; $i<$env{"form.HWVAL_SplineOrder_".$id."_".$label}; $i++) {
1.18      www       725:             my $ni=$i+1;
                    726:             my @xparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_x'},
                    727:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_x'},
                    728:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_x'},
                    729:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_x'});
                    730:             my @yparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_y'},
                    731:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_y'},
                    732:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_y'},
                    733:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_y'});
                    734: # Run in small steps over spline parameter
1.26      www       735:             for (my $t=0; $t<=1; $t+=0.0001) {
1.35      www       736:                 my $xreal=&cubic_hermite($t,@xparms);
                    737:                 my $xi=&array_index($xmin,$xmax,$xreal);
1.19      www       738:                 if ($xi<$xiold) { return 'no_func'; }
1.26      www       739:                 if (($xi>$xiold) && ($xi>=0) && ($xi<=400)) {
1.19      www       740:                    if (defined($Apache::functionplotresponse::func[$xi])) { return 'no_func'; }
1.18      www       741:                    $xiold=$xi;
1.35      www       742:                    $Apache::functionplotresponse::actualxval[$xi]=$xreal;
1.22      www       743: # Function value
1.30      www       744:                    my $funcval=&cubic_hermite($t,@yparms);
                    745:                    $Apache::functionplotresponse::func[$xi]=$funcval;
                    746:                    if (defined($funcval)) {
                    747:                       if ($xi<$Apache::functionplotresponse::functionplotrulelabels{'start'}) {
                    748:                          $Apache::functionplotresponse::functionplotrulelabels{'start'}=$xi;
                    749:                       }
                    750:                       if ($xi>$Apache::functionplotresponse::functionplotrulelabels{'end'}) {
                    751:                          $Apache::functionplotresponse::functionplotrulelabels{'end'}=$xi;
                    752:                       }
                    753:                    }
1.28      www       754: # Chain rule
1.22      www       755: # dy/dx=dy/dt/(dx/dt)
                    756:                    my $dxdt=&ddt_cubic_hermite($t,@xparms);
                    757:                    if ($dxdt) {
                    758:                       $Apache::functionplotresponse::dfuncdx[$xi]=&ddt_cubic_hermite($t,@yparms)/$dxdt;
1.34      www       759: # Second derivative
1.28      www       760:                       $Apache::functionplotresponse::d2funcdx2[$xi]=
1.34      www       761:                          ($dxdt*&d2dt2_cubic_hermite($t,@yparms)-&ddt_cubic_hermite($t,@yparms)*&d2dt2_cubic_hermite($t,@xparms))/
                    762:                          ($dxdt*$dxdt*$dxdt);
1.22      www       763:                    }
1.18      www       764:                 }
                    765:             }
                    766:         }
                    767:     }
                    768: }
                    769: 
                    770: #
1.37      www       771: # Implementation of <functionplotresponse>
1.15      www       772: #
                    773: 
1.1       www       774: sub start_functionplotresponse {
                    775:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    776:   my $result='';
1.6       www       777: # To remember the splines - somehow, they need to come last
                    778:   undef %Apache::functionplotresponse::splineorder;
                    779:   undef %Apache::functionplotresponse::splineinitx;
                    780:   undef %Apache::functionplotresponse::splineinity;
                    781:   undef %Apache::functionplotresponse::splinescalex;
                    782:   undef %Apache::functionplotresponse::splinescaley;
1.10      www       783: # Remember input fields, etc
                    784:   undef %Apache::functionplotresponse::previous;
1.9       www       785:   $Apache::functionplotresponse::inputfields='';
1.6       www       786:   $Apache::functionplotresponse::counter=0;
1.24      www       787: # Remember rules
1.25      www       788:   undef @Apache::functionplotresponse::functionplotrules;
1.37      www       789: # Remember failed rules
                    790:   if ($target eq 'grade') {
                    791:      undef @Apache::functionplotresponse::failedrules;
                    792:   }
                    793: # Delete previous awards
                    794:   undef $Apache::functionplotresponse::awarddetail;
1.10      www       795: # Part and ID
                    796:   my $partid=$Apache::inputtags::part;
                    797:   my $id=&Apache::response::start_response($parstack,$safeeval);
1.6       www       798: # Internal ID to mark the applet and its coordinates
1.10      www       799:   my $internalid = $partid.'_'.$id;
                    800: # Previous answer
                    801:   &decode_previous_answer($Apache::lonhomework::history{"resource.$partid.$id.submission"});
                    802: 
1.6       www       803: # Parameters of <functionplotresponse>
1.41      www       804:   my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval);
1.6       www       805:   my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
                    806:   my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
                    807:   my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
1.14      www       808:   my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval);
                    809:   my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval);
1.12      www       810:   if ($target eq 'edit') {
                    811:     $result.=&Apache::edit::start_table($token)
                    812:        .'<tr><td><span class="LC_nobreak">'.&mt('Function Plot Question').'</span></td>'
                    813:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
1.37      www       814:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'
                    815:        .&Apache::edit::insertlist($target,$token)
1.12      www       816:        .'</span></td>'
                    817:        ."<td>&nbsp;"
                    818:        .&Apache::edit::end_row()
                    819:        .&Apache::edit::start_spanning_row()
                    820:        ."\n";
1.14      www       821:     $result.=&Apache::edit::text_arg('Label x-axis:','xlabel',
                    822:                                      $token,'6').'&nbsp;'.
                    823:              &Apache::edit::text_arg('Minimum x-value:','xmin',
                    824:                                      $token,'4').'&nbsp;'.
1.12      www       825:              &Apache::edit::text_arg('Maximum x-value:','xmax',
1.14      www       826:                                      $token,'4').'&nbsp;'.
1.12      www       827:              &Apache::edit::select_arg('x-axis visible:','xaxisvisible',
1.32      www       828:                                   ['yes','no'],$token).'<br />'.
1.14      www       829:              &Apache::edit::text_arg('Label y-axis:','ylabel',
                    830:                                      $token,'6').'&nbsp;'.
1.12      www       831:              &Apache::edit::text_arg('Minimum y-value:','ymin',
1.14      www       832:                                      $token,'4').'&nbsp;'.
1.12      www       833:              &Apache::edit::text_arg('Maximum y-value:','ymax',
1.14      www       834:                                      $token,'4').'&nbsp;'.
1.12      www       835:              &Apache::edit::select_arg('y-axis visible:','yaxisvisible',
1.32      www       836:                                   ['yes','no'],$token).'<br />'.
1.12      www       837:              &Apache::edit::select_arg('Grid visible:','gridvisible',
1.47    ! www       838:                                   ['yes','no'],$token).'<br />'.
        !           839:              &Apache::edit::text_arg('Background plot(s) for answer (function:xmin:xmax,function:xmin:xmax,...):',
        !           840:                                          'answerdisplay',$token,'50');
        !           841: 
1.12      www       842:              &Apache::edit::end_row().&Apache::edit::start_spanning_row();
                    843:   } elsif ($target eq 'modified') {
                    844:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.14      www       845:                                                  $safeeval,'xlabel','xmin','xmax','ylabel','ymin','ymax',
1.47    ! www       846:                                                            'xaxisvisible','yaxisvisible','gridvisible','answerdisplay');
1.12      www       847:     if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
1.3       www       848: 
1.12      www       849:   } elsif ($target eq 'meta') {
1.10      www       850:        $result=&Apache::response::meta_package_write('functionplotresponse');
1.35      www       851:   } elsif (($target eq 'answer') &&
                    852:             ($env{'form.answer_output_mode'} ne 'tex') &&
                    853:             ($Apache::lonhomework::viewgrades == 'F')) {
                    854:       my (undef,undef,$udom,$uname)=&Apache::lonnet::whichuser();
                    855:       my $windowopen=&Apache::lonhtmlcommon::javascript_docopen();
                    856:       my $start_page = &Apache::loncommon::start_page('Rules Log', undef,
                    857:                                                {'only_body' => 1,
                    858:                                                 'bgcolor'   => '#FFFFFF',
                    859:                                                 'js_ready'  => 1,});
                    860:       my $end_page = &Apache::loncommon::end_page({'js_ready' => 1,});
                    861:       $uname =~s/\W//g;
                    862:       $udom  =~s/\W//g;
                    863:       my $function_name =
                    864:                 join('_','LONCAPA_scriptvars',$uname,$udom,
                    865:                      $env{'form.counter'},$Apache::lonxml::curdepth);
                    866:       my $rules_var ="<script type=\"text/javascript\">
                    867: // <![CDATA[
                    868:     function $function_name() {newWindow=open('','new_W','width=500,height=500,scrollbars=1,resizable=yes');newWindow.$windowopen;newWindow.document.writeln('$start_page<pre>".
                    869:     $Apache::functionplotresponse::ruleslog.
                    870:     "<\\/pre>$end_page');newWindow.document.close();newWindow.focus()}
                    871: // ]]>
                    872: </script><a href=\"javascript:$function_name();void(0);\">".&mt('Rules Log')."</a><br />";
                    873:             &Apache::lonxml::add_script_result($rules_var);
                    874:         }
                    875: 
1.1       www       876:   return $result;
                    877: }
                    878: 
1.25      www       879: sub compare_rel {
1.26      www       880:    my ($relationship,$value,$realval,$tol)=@_;
1.36      www       881: # is the real value undefined?
1.26      www       882:    unless (defined($realval)) {
1.36      www       883: # the real value is not defined
1.26      www       884:       if ($relationship eq 'eq') {
                    885:          if ($value eq 'undef') {
                    886:             return 1;
                    887:          } else {
                    888:             return 0;
                    889:          }
                    890:       } elsif ($relationship eq 'ne') {
                    891:          if ($value eq 'undef') {
                    892:             return 0;
                    893:          } else {
                    894:             return 1;
                    895:          }
                    896:       } else {
                    897:          return 0;
                    898:       }
                    899:    }
                    900: 
1.36      www       901: # is the expected value undefined?
                    902:    if ($value eq 'undef') {
                    903: # but by now we know that the real value is defined
                    904:       return 0;
                    905:    }
                    906: 
                    907: # both are defined.
1.26      www       908:    if ($relationship eq 'gt') {
                    909:       return ($realval>$value);
                    910:    } elsif ($relationship eq 'ge') {
                    911:       return ($realval>$value-$tol);
                    912:    } elsif ($relationship eq 'lt') {
                    913:       return ($realval<$value);
                    914:    } elsif ($relationship eq 'le') {
                    915:       return ($realval<$value+$tol);
                    916:    } elsif ($relationship eq 'ne') {
                    917:       return (abs($value-$realval)>$tol);
                    918:    } else {
                    919:       return (abs($value-$realval)<$tol);
                    920:    }
1.25      www       921:    return 0;
                    922: }
                    923: 
1.35      www       924: sub addlog {
                    925:    my ($text)=@_;
                    926:    $Apache::functionplotresponse::ruleslog.=$text.'<br />';
                    927: }
                    928: 
                    929: sub actualval {
                    930:    my ($i,$xmin,$xmax)=@_;
                    931:    return $xmin+$i/400.*($xmax-$xmin);
                    932: }
                    933:  
1.25      www       934: sub functionplotrulecheck {
1.33      www       935:    my ($rule,$xmin,$xmax,$ymin,$ymax)=@_;
                    936: 
1.35      www       937:    my ($label,$derivative,$xinitial,$xinitiallabel,$xfinal,$xfinallabel,$minimumlength,$maximumlength,$relationship,$value,$percent)
1.25      www       938:       =split(/\:/,$rule);
1.33      www       939:    $percent=($percent>0?$percent:5);
1.35      www       940:    &addlog("=================");
1.42      www       941:    &addlog("Rule $label for ".($derivative<0?'integral':('function itself','first derivative','second derivative')[$derivative])." $relationship $value");
1.30      www       942:    my $li=0;
                    943:    my $lh=400;
                    944: 
1.31      www       945: # Special case: the upper boundary was not defined
                    946: # and needs to be set to the value where
                    947: # the condition is not true anymore => set flag
                    948: 
                    949:    my $findupper=0;
                    950:    if (($xfinal eq '')
                    951:     && (!defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}))
                    952:     && ($xfinallabel)) {
                    953:        $findupper=1;
                    954:    }
                    955: 
1.25      www       956: # if a hard value is set for the boundaries, it overrides the label
1.30      www       957:    if (($xinitial ne '') && ($xinitiallabel ne '') && ($xinitiallabel ne 'start')) {
                    958:       $li=&array_index($xmin,$xmax,$xinitial);
                    959:       $Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel}=$li;
                    960:    }
                    961:    if (($xfinal ne '') && ($xfinallabel ne '') && ($xfinallabel ne 'end')) {
                    962:       $lh=&array_index($xmin,$xmax,$xfinal);
                    963:       $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$lh;
1.25      www       964:    }
1.31      www       965: # if the label is defined, use it
1.25      www       966:    if (defined($Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel})) {
1.35      www       967:       &addlog("Using lower label $xinitiallabel");
1.30      www       968:       $li=$Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel};
                    969:    } else {
                    970:       $li=&array_index($xmin,$xmax,$xinitial);
1.25      www       971:    }
1.31      www       972:    unless ($findupper) {
                    973:       if (defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel})) {
1.35      www       974:          &addlog("Using upper label $xfinallabel");
1.33      www       975:          $lh=$Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}-1;
1.31      www       976:       } else {
                    977:          $lh=&array_index($xmin,$xmax,$xfinal);
                    978:       }
1.25      www       979:    }
                    980: # Basic sanity checks
1.30      www       981:    if ($li<0) { $li=0; }
                    982:    if ($lh>400) { $lh=400; }
1.38      www       983:    if (($li>$lh) || (!defined($lh))) {
1.30      www       984:        $lh=$li;
1.25      www       985:    }
1.31      www       986: 
1.35      www       987:    &addlog("Boundaries: x=".&actualval($li,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$li]."; index $li)) to x=".
                    988:                             &actualval($lh,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$lh]."; index $lh))");
                    989:    if ($findupper) {
                    990:       &addlog("Looking for label $xfinallabel");
                    991:    }
1.33      www       992:    my $tol=$percent*($ymax-$ymin)/100;
                    993:    if ($xmax>$xmin) {
                    994:       if ($derivative==2) {
                    995:          $tol=4.*$tol/($xmax-$xmin);
                    996:       } elsif ($derivative==1) {
                    997:          $tol=2.*$tol/($xmax-$xmin);
1.42      www       998:       } elsif ($derivative==-1) {
                    999:          $tol=$tol*($xmax-$xmin)/2.;
1.33      www      1000:       }
1.27      www      1001:    }
1.42      www      1002:    my $integral=0;
                   1003:    my $binwidth=($xmax-$xmin)/400.;
                   1004:    if (($derivative<0) && (!$findupper)) {
                   1005: # definite integral, calculate over whole length
                   1006:      &addlog("Calculating definite integral");
                   1007:      for (my $i=$li; $i<=$lh; $i++) {
                   1008:         $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
                   1009:      }
                   1010:      unless (&compare_rel($relationship,$value,$integral,$tol)) {
                   1011:         &addlog("Actual integral ".(defined($integral)?$integral:'undef').", expected $value, tolerance $tol");
                   1012:         &addlog("Rule $label failed.");
                   1013:         my $hintlabel=$label;
                   1014:         $hintlabel=~s/^R//;
                   1015:         push(@Apache::functionplotresponse::failedrules,$hintlabel);
                   1016:         &addlog("Set hint condition $hintlabel");
                   1017:         return 0;
                   1018:      } 
                   1019:    } else {
                   1020:      for (my $i=$li; $i<=$lh; $i++) {
1.25      www      1021:         my $val;
                   1022:         if ($derivative==2) {
1.27      www      1023:            $val=$Apache::functionplotresponse::d2funcdx2[$i];
1.25      www      1024:         } elsif ($derivative==1) {
1.27      www      1025:            $val=$Apache::functionplotresponse::dfuncdx[$i];
1.42      www      1026:         } elsif ($derivative==-1) {
                   1027:            $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
                   1028:            $val=$integral;      
1.25      www      1029:         } else {
1.27      www      1030:            $val=$Apache::functionplotresponse::func[$i];
1.25      www      1031:         }
1.31      www      1032:         unless (&compare_rel($relationship,$value,$val,$tol)) { 
1.37      www      1033:            &addlog("Actual value ".(defined($val)?$val:'undef').", expected $value, tolerance $tol");
1.35      www      1034:            &addlog("Condition not fulfilled at x=".&actualval($i,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$i]."; index $i)");
1.31      www      1035:            if (($findupper) && ($i>$li)) {
1.35      www      1036: # check for minimum and maximum lengths
                   1037:               my $length=&actualval($i,$xmin,$xmax)-&actualval($li,$xmin,$xmax);
                   1038:               if ($minimumlength) {
                   1039:                  if ($length<$minimumlength) {
                   1040:                     &addlog("Rule $label failed, actual length $length, minimum length $minimumlength");
                   1041:                     return 0;
                   1042:                  }
                   1043:               }
                   1044:               if ($maximumlength) {
                   1045:                  if ($length>$maximumlength) {
                   1046:                     &addlog("Rule $label failed, actual length $length, maximum length $maximumlength");
                   1047:                     return 0;
                   1048:                  }
                   1049:               }
1.31      www      1050:               $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$i;
1.35      www      1051:               &addlog("Rule $label passed, setting label $xfinallabel");
1.31      www      1052:               return 1;
                   1053:            } else {
1.35      www      1054:               &addlog("Rule $label failed.");
1.37      www      1055:               my $hintlabel=$label;
                   1056:               $hintlabel=~s/^R//;
                   1057:               push(@Apache::functionplotresponse::failedrules,$hintlabel);
                   1058:               &addlog("Set hint condition $hintlabel");
1.31      www      1059:               return 0; 
                   1060:            }
                   1061:         }
1.42      www      1062:      }
1.25      www      1063:    }
1.35      www      1064:    &addlog("Rule $label passed.");
1.27      www      1065:    return 1;
1.24      www      1066: }
                   1067: 
1.37      www      1068: sub start_functionplotruleset {
                   1069:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1070:    if ($target eq 'edit') {
                   1071:       return &Apache::edit::start_table($token).
                   1072:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Rule Set').'</span></td>'
                   1073:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
                   1074:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
                   1075:         &Apache::edit::insertlist($target,$token)
                   1076:        .'</span></td>'
                   1077:        ."<td>&nbsp;"
                   1078:        .&Apache::edit::end_row()
                   1079:        .&Apache::edit::start_spanning_row()
                   1080:        ."\n";
                   1081:    }
                   1082: }
1.3       www      1083: 
1.37      www      1084: sub end_functionplotruleset {
                   1085:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                   1086:     my $id=$Apache::inputtags::response[-1];
                   1087:     my $partid=$Apache::inputtags::part;
                   1088:     my $internalid = $partid.'_'.$id;
                   1089: 
                   1090:     if ($target eq 'edit' ) {
                   1091:         return &Apache::edit::end_table();
                   1092:     }  elsif ($target eq 'grade'
1.10      www      1093:          && &Apache::response::submitted()
                   1094:          && $Apache::lonhomework::type ne 'exam') {
1.12      www      1095: #
                   1096: # Actually grade
                   1097: #
1.41      www      1098:     my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
1.27      www      1099: 
1.24      www      1100:         my $ad='';
1.30      www      1101:         undef  %Apache::functionplotresponse::functionplotrulelabels;
1.35      www      1102:         $Apache::functionplotresponse::ruleslog='';
1.30      www      1103:         $Apache::functionplotresponse::functionplotrulelabels{'start'}=400;
                   1104:         $Apache::functionplotresponse::functionplotrulelabels{'end'}=0;
1.18      www      1105:         if (&populate_arrays($internalid,$xmin,$xmax) eq 'no_func') {
1.21      www      1106:            $ad='NOT_FUNCTION';
1.18      www      1107:         } else {
1.35      www      1108:            &addlog("Start of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'start'},$xmin,$xmax)." (index ".
                   1109:                                         $Apache::functionplotresponse::functionplotrulelabels{'start'}.")");
                   1110:            &addlog("End of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'end'},$xmin,$xmax)." (index ".
                   1111:                                         $Apache::functionplotresponse::functionplotrulelabels{'end'}.")");
                   1112: 
1.24      www      1113: # We have a function that we can actually grade, go through the spline rules.
1.25      www      1114:            foreach my $rule (@Apache::functionplotresponse::functionplotrules) {
1.33      www      1115:               unless (&functionplotrulecheck($rule,$xmin,$xmax,$ymin,$ymax)) {
1.24      www      1116:                  $ad='INCORRECT';
                   1117:                  last;
                   1118:               }
                   1119:            }
                   1120: # If it's not wrong, it's correct 
                   1121:            unless ($ad) { $ad='EXACT_ANS' };
1.18      www      1122:         }
1.37      www      1123:         &addlog("Set hint conditions: ".join(",",@Apache::functionplotresponse::failedrules));
                   1124:         &addlog("Assigned award detail: $ad");
                   1125: # Store for later to be assigned at end_functionplotresponse
                   1126:         $Apache::functionplotresponse::awarddetail=$ad;
                   1127:      }
                   1128: }
                   1129: 
                   1130: 
                   1131: sub end_functionplotresponse {
                   1132:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1133:   &Apache::response::end_response;
                   1134: 
                   1135:   my $result;
                   1136:   my $id=$Apache::inputtags::response[-1];
                   1137:   my $partid=$Apache::inputtags::part;
                   1138:   my $internalid = $partid.'_'.$id;
1.20      www      1139: 
1.37      www      1140:     if ($target eq 'edit') { $result=&Apache::edit::end_table(); }
                   1141:     if ($target eq 'grade'
                   1142:          && &Apache::response::submitted()
                   1143:          && $Apache::lonhomework::type eq 'exam') {
                   1144: 
                   1145:         &Apache::response::scored_response($partid,$id);
                   1146: 
                   1147:     } elsif ($target eq 'grade'
                   1148:          && &Apache::response::submitted()
                   1149:          && $Apache::lonhomework::type ne 'exam') {
                   1150:         my ($response,%coords)=&get_answer_from_form_fields($internalid);
                   1151:         $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
                   1152:         my %previous=&Apache::response::check_for_previous($response,$partid,$id);
                   1153: #
                   1154: # Assign grade
                   1155: #
                   1156:         my $ad=$Apache::functionplotresponse::awarddetail;
1.12      www      1157: #
                   1158: # Store grading info
                   1159: #
                   1160:         $Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
                   1161:         &Apache::response::handle_previous(\%previous,$ad);
1.10      www      1162:    } elsif ($target eq 'web') {
1.37      www      1163:         undef @Apache::functionplotresponse::failedrules;
                   1164:    }
                   1165:    return $result;
                   1166: }
                   1167: 
                   1168: sub end_functionplotelements {
                   1169:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                   1170:   my $result='';
                   1171:   my $id=$Apache::inputtags::response[-1];
                   1172:   my $partid=$Apache::inputtags::part;
                   1173:   my $internalid = $partid.'_'.$id;
                   1174:   if ($target eq 'edit' ) {
                   1175:      $result=&Apache::edit::end_table();
                   1176:   } elsif ($target eq 'web') {
1.47    ! www      1177:      my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
        !          1178: 
        !          1179: # Are we in show answer mode?
        !          1180:      my $showanswer=&Apache::response::show_answer();
        !          1181:      if ($showanswer) {
        !          1182: # Render answerdisplay
        !          1183:         my $answerdisplay=&Apache::lonxml::get_param('answerdisplay',$parstack,$safeeval,-2);
        !          1184:         if ($answerdisplay=~/\S/s) {
        !          1185:            foreach my $plot (split(/\s*\,\s*/,$answerdisplay)) {
        !          1186:               my ($func,$xl,$xh)=split(/\s*\:\s*/,$plot);
        !          1187:               if ((!defined($xl)) || ($xl eq '')) { $xl=$xmin; }
        !          1188:               if ((!defined($xh)) || ($xh eq '')) { $xh=$xmax; }
        !          1189:               $result.=&plot_script($internalid,$func,1,'','00aa00',$xl,$xh,6);
        !          1190:            }
        !          1191:         }
        !          1192:      }
        !          1193: 
1.6       www      1194: # Now is the time to render all of the stored splines
                   1195:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
1.40      www      1196:         $result.=&generate_spline($internalid,$label,$xmin,$xmax,$ymin,$ymax);
1.6       www      1197:      }
1.5       www      1198: # close the init script
1.3       www      1199:      $result.=&end_init_script();
1.17      www      1200: # register all splines in this response 
                   1201:      $result.='<input type="hidden" name="HWVAL_AllSplines_'.$internalid.'" value="'.
                   1202:                  join(',',keys(%Apache::functionplotresponse::splineorder)).'" />'."\n";
                   1203:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
                   1204:         $result.='<input type="hidden" name="HWVAL_SplineOrder_'.$internalid.'_'.$label.'" value="'.
                   1205:                  $Apache::functionplotresponse::splineorder{$label}.'" />'."\n";
                   1206:      }
1.9       www      1207: # generate the input fields
                   1208:      $result.=$Apache::functionplotresponse::inputfields;
1.5       www      1209: # actually start the <applet>-tag
1.3       www      1210:      $result.=&geogebra_startcode($internalid);
1.5       www      1211: # load the spline bytecode
1.3       www      1212:      $result.=&geogebra_spline_program();
1.5       www      1213: # set default parameters
1.3       www      1214:      $result.=&geogebra_default_parameters($internalid);
1.5       www      1215: # close the <applet>-tag
1.1       www      1216:      $result.=&geogebra_endcode();
                   1217:   }
                   1218:   return $result;
                   1219: }
                   1220: 
1.41      www      1221: sub boundaries {
                   1222:    my ($parstack,$safeeval,$level)=@_;
                   1223:    my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval,$level);
                   1224:    $xmin=(defined($xmin)?$xmin:-10);
                   1225:    my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval,$level);
                   1226:    $xmax=(defined($xmax)?$xmax:10);
                   1227:    my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval,$level);
                   1228:    $ymin=(defined($ymin)?$ymin:-10);
                   1229:    my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval,$level);
                   1230:    $ymax=(defined($ymax)?$ymax:10);
                   1231:    if ($xmax<=$xmin) {
                   1232:       $xmax=$xmin+20;
                   1233:    }
                   1234:    if ($ymax<=$ymin) {
                   1235:       $ymax=$ymin+20;
                   1236:    }
                   1237:    return ($xmin,$xmax,$ymin,$ymax);
                   1238: }
                   1239: 
1.37      www      1240: sub start_functionplotelements {
                   1241:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1242:    my $result='';
                   1243:    my $id=$Apache::inputtags::response[-1];
                   1244:    my $partid=$Apache::inputtags::part;
                   1245:    my $internalid = $partid.'_'.$id;
                   1246: 
                   1247:    if ($target eq 'edit') {
                   1248:       return &Apache::edit::start_table($token).
                   1249:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Elements').'</span></td>'
                   1250:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
                   1251:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
                   1252:         &Apache::edit::insertlist($target,$token)
                   1253:        .'</span></td>'
                   1254:        ."<td>&nbsp;"
                   1255:        .&Apache::edit::end_row()
                   1256:        .&Apache::edit::start_spanning_row()
                   1257:        ."\n";
                   1258:    } elsif ($target eq 'web') {
1.41      www      1259:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
1.37      www      1260:       my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1261:       my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1262:       my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1263:       my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval,-2);
                   1264:       my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval,-2);
                   1265: 
                   1266: 
                   1267: # paste in the update routine to receive stuff back from the applet
                   1268:      $result.=&update_script($internalid);
                   1269: # start the initscript for this applet
                   1270:      $result.=&start_init_script($internalid);
                   1271: # put the axis commands inside
                   1272:      $result.=&axes_script($internalid,$xmin,$xmax,$ymin,$ymax,$xaxisvisible,$yaxisvisible,$gridvisible);
1.45      www      1273:      $result.=&axes_label($internalid,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel);
1.37      www      1274: # init script is left open
                   1275:   }
                   1276:   return $result;
                   1277: }
                   1278: 
1.1       www      1279: 1;
                   1280: 
                   1281: __END__
                   1282:  
                   1283: =head1 NAME
                   1284: 
                   1285: Apache::functionplotresponse.pm;
                   1286: 
                   1287: =head1 SYNOPSIS
                   1288: 
                   1289: Handles tags associated with accepting function plots.
                   1290: 
                   1291: This is part of the LearningOnline Network with CAPA project
                   1292: described at http://www.lon-capa.org.
                   1293: 
                   1294: =head1 HANDLER SUBROUTINE
                   1295: 
                   1296: start_functionplotresponse()
                   1297: 
                   1298: =head1 OTHER SUBROUTINES
                   1299: 
                   1300: =over
                   1301: 
                   1302: =item end_functionplotresponse()
                   1303: 
                   1304: =back
                   1305: 
                   1306: =cut

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