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

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

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