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

1.1       www         1: # LearningOnline Network with CAPA
                      2: # option list style responses
                      3: #
1.52    ! www         4: # $Id: functionplotresponse.pm,v 1.51 2011/01/25 20:52:08 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.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') {
                    539:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.35      www       540:                                                  $safeeval,'index','derivativeorder',
                    541:                                                            'xinitial','xinitiallabel','xfinal','xfinallabel',
                    542:                                                            'minimumlength','maximumlength',
                    543:                                                            'relationship','value','percenterror');
1.29      www       544:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
1.13      www       545:    }
1.12      www       546:    return $result;
                    547: }
                    548: 
1.25      www       549: sub end_functionplotrule {
1.13      www       550:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    551:    my $result='';
                    552:    if ($target eq 'edit') {
                    553:        $result=&Apache::edit::end_table();
                    554:    }
                    555:    return $result;
1.12      www       556: }
                    557: 
                    558: 
                    559: #
1.23      www       560: # <spline index="..." order="1,2,3,4" initx="..." inity="..." scalex="..." scaley="..." />
1.6       www       561: #
                    562: # Unfortunately, GeoGebra seems to want all splines after everything else, so we need to store them
                    563: #
                    564: sub start_spline {
                    565:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.13      www       566:    my $result='';
                    567:    if ($target eq 'web') {
1.23      www       568:       my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
1.13      www       569:       $Apache::functionplotresponse::counter++;
                    570:       if ($label=~/\W/) {
1.23      www       571:          &Apache::lonxml::warning(&mt('Spline indices should only contain alphanumeric characters.'));
1.13      www       572:       }
                    573:       $label=~s/\W//gs;
1.23      www       574:       unless ($label) { 
                    575:          $label='S'.$Apache::functionplotresponse::counter; 
                    576:       } else {
                    577:          $label='S'.$label;
                    578:       }
1.13      www       579:       if ($Apache::functionplotresponse::splineorder{$label}) {
1.23      www       580:          &Apache::lonxml::error(&mt('Spline indices must be unique.'));
1.13      www       581:       }
                    582: 
                    583:       my $order=&Apache::lonxml::get_param('order',$parstack,$safeeval);
                    584:       if ($order<2) { $order=2; }
                    585:       if ($order>8) { $order=8; }
                    586:       $Apache::functionplotresponse::splineorder{$label}=$order;
                    587: 
                    588:       my $x=&Apache::lonxml::get_param('initx',$parstack,$safeeval);
                    589:       unless ($x) { $x=0; }
                    590:       $Apache::functionplotresponse::splineinitx{$label}=$x;
                    591: 
                    592:       my $y=&Apache::lonxml::get_param('inity',$parstack,$safeeval);
                    593:       unless ($y) { $y=0; }
                    594:       $Apache::functionplotresponse::splineinity{$label}=$y;
                    595: 
                    596:       my $sx=&Apache::lonxml::get_param('scalex',$parstack,$safeeval);
                    597:       unless ($sx) { $sx=$order; }
                    598:       $Apache::functionplotresponse::splinescalex{$label}=$sx;
                    599: 
                    600:       my $sy=&Apache::lonxml::get_param('scaley',$parstack,$safeeval);
                    601:       unless ($sy) { $sy=2; }
                    602:       $Apache::functionplotresponse::splinescaley{$label}=$sy;
                    603:    } elsif ($target eq 'edit') {
                    604:         $result=&Apache::edit::tag_start($target,$token,'Spline').
1.23      www       605:              &Apache::edit::text_arg('Index:','index',
1.14      www       606:                                      $token,'4').'&nbsp;'.
1.13      www       607:              &Apache::edit::select_arg('Order:','order',
1.44      www       608:                                   ['2','3','4','5','6','7','8'],$token).'&nbsp;'.
1.13      www       609:              &Apache::edit::text_arg('Initial x-value:','initx',
1.14      www       610:                                      $token,'4').'&nbsp;'.
1.13      www       611:              &Apache::edit::text_arg('Initial y-value:','inity',
1.14      www       612:                                      $token,'4').'&nbsp;'.
1.13      www       613:              &Apache::edit::text_arg('Scale x:','scalex',
1.14      www       614:                                      $token,'4').'&nbsp;'.
1.13      www       615:              &Apache::edit::text_arg('Scale y:','scaley',
                    616:                                      $token,'4').
                    617:              &Apache::edit::end_row();
                    618:   } elsif ($target eq 'modified') {
                    619:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.23      www       620:                                                  $safeeval,'index','order','initx','inity',
1.13      www       621:                                                            'scalex','scaley');
                    622:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    623:   }
                    624:   return $result;
1.6       www       625: }
                    626: 
                    627: sub end_spline {
1.13      www       628:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    629:    my $result='';
                    630:    if ($target eq 'edit') {
                    631:        $result=&Apache::edit::end_table();
                    632:    }
                    633:    return $result;
1.4       www       634: }
                    635:  
1.3       www       636: sub end_init_script {
                    637:     return (<<ENDENDINIT);
                    638: }
                    639: // ]]>
                    640: </script>
                    641: ENDENDINIT
                    642: }
                    643: 
1.10      www       644: #
                    645: # Storing and restoring spline coordinates from part answers
                    646: #
                    647: sub decode_previous_answer {
                    648:    my ($answer)=@_;
                    649:    foreach my $coordinate (split(/\,/,$answer)) {
                    650:       my ($key,$value)=split(/\=/,$coordinate);
                    651:       $Apache::functionplotresponse::previous{$key}=$value;
                    652:    }
                    653: }
                    654: 
                    655: sub get_answer_from_form_fields {
                    656:    my ($id)=@_;
                    657:    my $answer='';
                    658:    my %coords=();
                    659:    foreach my $field (keys(%env)) {
                    660:       if ($field=~/^form\.HWVAL\_$id/) {
                    661:          $field=~/^form\.(.*)$/;
                    662:          $coords{$1}=$env{$field};
                    663:       }
                    664:    }
                    665:    $answer=join(',',map { $_.'='.$coords{$_} } (sort(keys(%coords))));
                    666:    return ($answer,%coords);
                    667: }
                    668: 
1.15      www       669: #
                    670: # The following functions calculate the cubic-hermite splines server-side
                    671: #
                    672: 
                    673: sub cubic_hermite {
                    674:    my ($t,$p1,$s1,$p2,$s2)=@_;
1.42      www       675:    return (2.*$t*$t*$t-3.*$t*$t+1.)*$p1 + 3.*($t*$t*$t-2.*$t*$t+$t)*($s1-$p1)+
                    676:           (-2.*$t*$t*$t+3.*$t*$t)  *$p2 + 3.*($t*$t*$t-$t*$t)      *($s2-$p2);
1.15      www       677: }
                    678: 
                    679: #
                    680: # d/dt(...)
                    681: # 
                    682: 
                    683: sub ddt_cubic_hermite {
                    684:    my ($t,$p1,$s1,$p2,$s2)=@_;
1.42      www       685:    return (6.*$t*$t-6.*$t) *$p1 + 3.*(3.*$t*$t-4.*$t+1.)*($s1-$p1)+
                    686:           (-6.*$t*$t+6.*$t)*$p2 + 3.*(3.*$t*$t-2.*$t)   *($s2-$p2);
1.15      www       687: }
                    688: 
                    689: #
                    690: # d^2/dt^2(...)
                    691: #
                    692: 
                    693: sub d2dt2_cubic_hermite {
                    694:    my ($t,$p1,$s1,$p2,$s2)=@_;
1.42      www       695:    return (12.*$t-6.) *$p1 + 3.*(6.*$t-4.)*($s1-$p1)+
                    696:           (-12.*$t+6.)*$p2 + 3.*(6.*$t-2.)*($s2-$p2);
1.15      www       697: }
                    698: 
                    699: #
1.18      www       700: # Array index calculation
                    701: #
                    702: sub array_index {
                    703:    my ($xmin,$xmax,$x)=@_;
1.38      www       704:    if ($x ne '') {
                    705:       return int(($x-$xmin)/($xmax-$xmin)*400.+0.5);
                    706:    } else {
                    707:       return undef;
                    708:    }
1.20      www       709: }
                    710: 
                    711: #
1.18      www       712: # Populate the arrays
                    713: #
                    714: 
                    715: sub populate_arrays {
                    716:     my ($id,$xmin,$xmax)=@_;
1.26      www       717:     for (my $i=0; $i<=400; $i++) {
1.35      www       718:        $Apache::functionplotresponse::actualxval[$i]=undef;
1.19      www       719:        $Apache::functionplotresponse::func[$i]=undef;
1.22      www       720:        $Apache::functionplotresponse::dfuncdx[$i]=undef;
1.19      www       721:        $Apache::functionplotresponse::d2funcd2x[$i]=undef;
1.18      www       722:     }
1.19      www       723:     unless ($xmax>$xmin) { return 'no_func'; }
1.18      www       724: # Run over all splines in response
                    725:     foreach my $label (split(/\,/,$env{"form.HWVAL_AllSplines_$id"})) {
1.19      www       726:         my $xiold=-1;
1.18      www       727: # Run over all points in spline
1.19      www       728:         for (my $i=1; $i<$env{"form.HWVAL_SplineOrder_".$id."_".$label}; $i++) {
1.18      www       729:             my $ni=$i+1;
                    730:             my @xparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_x'},
                    731:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_x'},
                    732:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_x'},
                    733:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_x'});
                    734:             my @yparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_y'},
                    735:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_y'},
                    736:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_y'},
                    737:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_y'});
                    738: # Run in small steps over spline parameter
1.26      www       739:             for (my $t=0; $t<=1; $t+=0.0001) {
1.35      www       740:                 my $xreal=&cubic_hermite($t,@xparms);
                    741:                 my $xi=&array_index($xmin,$xmax,$xreal);
1.19      www       742:                 if ($xi<$xiold) { return 'no_func'; }
1.26      www       743:                 if (($xi>$xiold) && ($xi>=0) && ($xi<=400)) {
1.19      www       744:                    if (defined($Apache::functionplotresponse::func[$xi])) { return 'no_func'; }
1.18      www       745:                    $xiold=$xi;
1.35      www       746:                    $Apache::functionplotresponse::actualxval[$xi]=$xreal;
1.22      www       747: # Function value
1.30      www       748:                    my $funcval=&cubic_hermite($t,@yparms);
                    749:                    $Apache::functionplotresponse::func[$xi]=$funcval;
                    750:                    if (defined($funcval)) {
                    751:                       if ($xi<$Apache::functionplotresponse::functionplotrulelabels{'start'}) {
                    752:                          $Apache::functionplotresponse::functionplotrulelabels{'start'}=$xi;
                    753:                       }
                    754:                       if ($xi>$Apache::functionplotresponse::functionplotrulelabels{'end'}) {
                    755:                          $Apache::functionplotresponse::functionplotrulelabels{'end'}=$xi;
                    756:                       }
                    757:                    }
1.28      www       758: # Chain rule
1.22      www       759: # dy/dx=dy/dt/(dx/dt)
                    760:                    my $dxdt=&ddt_cubic_hermite($t,@xparms);
                    761:                    if ($dxdt) {
                    762:                       $Apache::functionplotresponse::dfuncdx[$xi]=&ddt_cubic_hermite($t,@yparms)/$dxdt;
1.34      www       763: # Second derivative
1.28      www       764:                       $Apache::functionplotresponse::d2funcdx2[$xi]=
1.34      www       765:                          ($dxdt*&d2dt2_cubic_hermite($t,@yparms)-&ddt_cubic_hermite($t,@yparms)*&d2dt2_cubic_hermite($t,@xparms))/
                    766:                          ($dxdt*$dxdt*$dxdt);
1.22      www       767:                    }
1.18      www       768:                 }
                    769:             }
                    770:         }
                    771:     }
                    772: }
                    773: 
                    774: #
1.37      www       775: # Implementation of <functionplotresponse>
1.15      www       776: #
                    777: 
1.1       www       778: sub start_functionplotresponse {
                    779:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    780:   my $result='';
1.6       www       781: # To remember the splines - somehow, they need to come last
                    782:   undef %Apache::functionplotresponse::splineorder;
                    783:   undef %Apache::functionplotresponse::splineinitx;
                    784:   undef %Apache::functionplotresponse::splineinity;
                    785:   undef %Apache::functionplotresponse::splinescalex;
                    786:   undef %Apache::functionplotresponse::splinescaley;
1.10      www       787: # Remember input fields, etc
                    788:   undef %Apache::functionplotresponse::previous;
1.9       www       789:   $Apache::functionplotresponse::inputfields='';
1.6       www       790:   $Apache::functionplotresponse::counter=0;
1.24      www       791: # Remember rules
1.25      www       792:   undef @Apache::functionplotresponse::functionplotrules;
1.37      www       793: # Remember failed rules
                    794:   if ($target eq 'grade') {
                    795:      undef @Apache::functionplotresponse::failedrules;
                    796:   }
                    797: # Delete previous awards
                    798:   undef $Apache::functionplotresponse::awarddetail;
1.10      www       799: # Part and ID
                    800:   my $partid=$Apache::inputtags::part;
                    801:   my $id=&Apache::response::start_response($parstack,$safeeval);
1.6       www       802: # Internal ID to mark the applet and its coordinates
1.10      www       803:   my $internalid = $partid.'_'.$id;
                    804: # Previous answer
                    805:   &decode_previous_answer($Apache::lonhomework::history{"resource.$partid.$id.submission"});
                    806: 
1.6       www       807: # Parameters of <functionplotresponse>
1.41      www       808:   my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval);
1.6       www       809:   my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
                    810:   my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
                    811:   my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
1.14      www       812:   my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval);
                    813:   my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval);
1.12      www       814:   if ($target eq 'edit') {
                    815:     $result.=&Apache::edit::start_table($token)
                    816:        .'<tr><td><span class="LC_nobreak">'.&mt('Function Plot Question').'</span></td>'
                    817:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
1.37      www       818:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'
1.50      www       819:        .&Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
                    820:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Question','Function Plot Responses')
1.12      www       821:        .'</span></td>'
                    822:        ."<td>&nbsp;"
                    823:        .&Apache::edit::end_row()
                    824:        .&Apache::edit::start_spanning_row()
                    825:        ."\n";
1.14      www       826:     $result.=&Apache::edit::text_arg('Label x-axis:','xlabel',
                    827:                                      $token,'6').'&nbsp;'.
                    828:              &Apache::edit::text_arg('Minimum x-value:','xmin',
                    829:                                      $token,'4').'&nbsp;'.
1.12      www       830:              &Apache::edit::text_arg('Maximum x-value:','xmax',
1.14      www       831:                                      $token,'4').'&nbsp;'.
1.12      www       832:              &Apache::edit::select_arg('x-axis visible:','xaxisvisible',
1.32      www       833:                                   ['yes','no'],$token).'<br />'.
1.14      www       834:              &Apache::edit::text_arg('Label y-axis:','ylabel',
                    835:                                      $token,'6').'&nbsp;'.
1.12      www       836:              &Apache::edit::text_arg('Minimum y-value:','ymin',
1.14      www       837:                                      $token,'4').'&nbsp;'.
1.12      www       838:              &Apache::edit::text_arg('Maximum y-value:','ymax',
1.14      www       839:                                      $token,'4').'&nbsp;'.
1.12      www       840:              &Apache::edit::select_arg('y-axis visible:','yaxisvisible',
1.32      www       841:                                   ['yes','no'],$token).'<br />'.
1.12      www       842:              &Apache::edit::select_arg('Grid visible:','gridvisible',
1.47      www       843:                                   ['yes','no'],$token).'<br />'.
                    844:              &Apache::edit::text_arg('Background plot(s) for answer (function:xmin:xmax,function:xmin:xmax,...):',
                    845:                                          'answerdisplay',$token,'50');
                    846: 
1.12      www       847:              &Apache::edit::end_row().&Apache::edit::start_spanning_row();
                    848:   } elsif ($target eq 'modified') {
                    849:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.14      www       850:                                                  $safeeval,'xlabel','xmin','xmax','ylabel','ymin','ymax',
1.47      www       851:                                                            'xaxisvisible','yaxisvisible','gridvisible','answerdisplay');
1.12      www       852:     if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
1.3       www       853: 
1.12      www       854:   } elsif ($target eq 'meta') {
1.10      www       855:        $result=&Apache::response::meta_package_write('functionplotresponse');
1.35      www       856:   } elsif (($target eq 'answer') &&
                    857:             ($env{'form.answer_output_mode'} ne 'tex') &&
                    858:             ($Apache::lonhomework::viewgrades == 'F')) {
                    859:       my (undef,undef,$udom,$uname)=&Apache::lonnet::whichuser();
                    860:       my $windowopen=&Apache::lonhtmlcommon::javascript_docopen();
                    861:       my $start_page = &Apache::loncommon::start_page('Rules Log', undef,
                    862:                                                {'only_body' => 1,
                    863:                                                 'bgcolor'   => '#FFFFFF',
                    864:                                                 'js_ready'  => 1,});
                    865:       my $end_page = &Apache::loncommon::end_page({'js_ready' => 1,});
                    866:       $uname =~s/\W//g;
                    867:       $udom  =~s/\W//g;
                    868:       my $function_name =
                    869:                 join('_','LONCAPA_scriptvars',$uname,$udom,
                    870:                      $env{'form.counter'},$Apache::lonxml::curdepth);
                    871:       my $rules_var ="<script type=\"text/javascript\">
                    872: // <![CDATA[
                    873:     function $function_name() {newWindow=open('','new_W','width=500,height=500,scrollbars=1,resizable=yes');newWindow.$windowopen;newWindow.document.writeln('$start_page<pre>".
                    874:     $Apache::functionplotresponse::ruleslog.
                    875:     "<\\/pre>$end_page');newWindow.document.close();newWindow.focus()}
                    876: // ]]>
                    877: </script><a href=\"javascript:$function_name();void(0);\">".&mt('Rules Log')."</a><br />";
                    878:             &Apache::lonxml::add_script_result($rules_var);
                    879:         }
                    880: 
1.1       www       881:   return $result;
                    882: }
                    883: 
1.25      www       884: sub compare_rel {
1.26      www       885:    my ($relationship,$value,$realval,$tol)=@_;
1.36      www       886: # is the real value undefined?
1.26      www       887:    unless (defined($realval)) {
1.36      www       888: # the real value is not defined
1.26      www       889:       if ($relationship eq 'eq') {
                    890:          if ($value eq 'undef') {
                    891:             return 1;
                    892:          } else {
                    893:             return 0;
                    894:          }
                    895:       } elsif ($relationship eq 'ne') {
                    896:          if ($value eq 'undef') {
                    897:             return 0;
                    898:          } else {
                    899:             return 1;
                    900:          }
                    901:       } else {
                    902:          return 0;
                    903:       }
                    904:    }
                    905: 
1.36      www       906: # is the expected value undefined?
                    907:    if ($value eq 'undef') {
                    908: # but by now we know that the real value is defined
                    909:       return 0;
                    910:    }
                    911: 
                    912: # both are defined.
1.26      www       913:    if ($relationship eq 'gt') {
                    914:       return ($realval>$value);
                    915:    } elsif ($relationship eq 'ge') {
                    916:       return ($realval>$value-$tol);
                    917:    } elsif ($relationship eq 'lt') {
                    918:       return ($realval<$value);
                    919:    } elsif ($relationship eq 'le') {
                    920:       return ($realval<$value+$tol);
                    921:    } elsif ($relationship eq 'ne') {
                    922:       return (abs($value-$realval)>$tol);
                    923:    } else {
                    924:       return (abs($value-$realval)<$tol);
                    925:    }
1.25      www       926:    return 0;
                    927: }
                    928: 
1.35      www       929: sub addlog {
                    930:    my ($text)=@_;
                    931:    $Apache::functionplotresponse::ruleslog.=$text.'<br />';
                    932: }
                    933: 
                    934: sub actualval {
                    935:    my ($i,$xmin,$xmax)=@_;
                    936:    return $xmin+$i/400.*($xmax-$xmin);
                    937: }
                    938:  
1.25      www       939: sub functionplotrulecheck {
1.33      www       940:    my ($rule,$xmin,$xmax,$ymin,$ymax)=@_;
                    941: 
1.35      www       942:    my ($label,$derivative,$xinitial,$xinitiallabel,$xfinal,$xfinallabel,$minimumlength,$maximumlength,$relationship,$value,$percent)
1.25      www       943:       =split(/\:/,$rule);
1.33      www       944:    $percent=($percent>0?$percent:5);
1.35      www       945:    &addlog("=================");
1.42      www       946:    &addlog("Rule $label for ".($derivative<0?'integral':('function itself','first derivative','second derivative')[$derivative])." $relationship $value");
1.49      www       947:    if ((defined($minimumlength)) || (defined($maximumlength))) {
                    948:       &addlog("Minimumlength $minimumlength Maximumlength $maximumlength");
                    949:    }
1.30      www       950:    my $li=0;
                    951:    my $lh=400;
                    952: 
1.31      www       953: # Special case: the upper boundary was not defined
                    954: # and needs to be set to the value where
                    955: # the condition is not true anymore => set flag
                    956: 
                    957:    my $findupper=0;
                    958:    if (($xfinal eq '')
                    959:     && (!defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}))
                    960:     && ($xfinallabel)) {
                    961:        $findupper=1;
                    962:    }
                    963: 
1.25      www       964: # if a hard value is set for the boundaries, it overrides the label
1.30      www       965:    if (($xinitial ne '') && ($xinitiallabel ne '') && ($xinitiallabel ne 'start')) {
                    966:       $li=&array_index($xmin,$xmax,$xinitial);
                    967:       $Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel}=$li;
                    968:    }
                    969:    if (($xfinal ne '') && ($xfinallabel ne '') && ($xfinallabel ne 'end')) {
                    970:       $lh=&array_index($xmin,$xmax,$xfinal);
                    971:       $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$lh;
1.25      www       972:    }
1.31      www       973: # if the label is defined, use it
1.25      www       974:    if (defined($Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel})) {
1.35      www       975:       &addlog("Using lower label $xinitiallabel");
1.30      www       976:       $li=$Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel};
                    977:    } else {
                    978:       $li=&array_index($xmin,$xmax,$xinitial);
1.25      www       979:    }
1.31      www       980:    unless ($findupper) {
                    981:       if (defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel})) {
1.35      www       982:          &addlog("Using upper label $xfinallabel");
1.33      www       983:          $lh=$Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}-1;
1.31      www       984:       } else {
                    985:          $lh=&array_index($xmin,$xmax,$xfinal);
                    986:       }
1.25      www       987:    }
                    988: # Basic sanity checks
1.30      www       989:    if ($li<0) { $li=0; }
                    990:    if ($lh>400) { $lh=400; }
1.38      www       991:    if (($li>$lh) || (!defined($lh))) {
1.30      www       992:        $lh=$li;
1.25      www       993:    }
1.31      www       994: 
1.35      www       995:    &addlog("Boundaries: x=".&actualval($li,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$li]."; index $li)) to x=".
                    996:                             &actualval($lh,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$lh]."; index $lh))");
                    997:    if ($findupper) {
                    998:       &addlog("Looking for label $xfinallabel");
                    999:    }
1.33      www      1000:    my $tol=$percent*($ymax-$ymin)/100;
                   1001:    if ($xmax>$xmin) {
                   1002:       if ($derivative==2) {
                   1003:          $tol=4.*$tol/($xmax-$xmin);
                   1004:       } elsif ($derivative==1) {
                   1005:          $tol=2.*$tol/($xmax-$xmin);
1.42      www      1006:       } elsif ($derivative==-1) {
                   1007:          $tol=$tol*($xmax-$xmin)/2.;
1.33      www      1008:       }
1.27      www      1009:    }
1.42      www      1010:    my $integral=0;
                   1011:    my $binwidth=($xmax-$xmin)/400.;
                   1012:    if (($derivative<0) && (!$findupper)) {
                   1013: # definite integral, calculate over whole length
                   1014:      &addlog("Calculating definite integral");
                   1015:      for (my $i=$li; $i<=$lh; $i++) {
                   1016:         $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
                   1017:      }
                   1018:      unless (&compare_rel($relationship,$value,$integral,$tol)) {
                   1019:         &addlog("Actual integral ".(defined($integral)?$integral:'undef').", expected $value, tolerance $tol");
                   1020:         &addlog("Rule $label failed.");
                   1021:         my $hintlabel=$label;
                   1022:         $hintlabel=~s/^R//;
                   1023:         push(@Apache::functionplotresponse::failedrules,$hintlabel);
                   1024:         &addlog("Set hint condition $hintlabel");
                   1025:         return 0;
                   1026:      } 
                   1027:    } else {
                   1028:      for (my $i=$li; $i<=$lh; $i++) {
1.25      www      1029:         my $val;
                   1030:         if ($derivative==2) {
1.27      www      1031:            $val=$Apache::functionplotresponse::d2funcdx2[$i];
1.25      www      1032:         } elsif ($derivative==1) {
1.27      www      1033:            $val=$Apache::functionplotresponse::dfuncdx[$i];
1.42      www      1034:         } elsif ($derivative==-1) {
                   1035:            $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
                   1036:            $val=$integral;      
1.25      www      1037:         } else {
1.27      www      1038:            $val=$Apache::functionplotresponse::func[$i];
1.25      www      1039:         }
1.31      www      1040:         unless (&compare_rel($relationship,$value,$val,$tol)) { 
1.37      www      1041:            &addlog("Actual value ".(defined($val)?$val:'undef').", expected $value, tolerance $tol");
1.35      www      1042:            &addlog("Condition not fulfilled at x=".&actualval($i,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$i]."; index $i)");
1.31      www      1043:            if (($findupper) && ($i>$li)) {
1.49      www      1044: # Check lengths
                   1045:               unless (&checklength($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
                   1046: # Successfully found a new label, set it
1.31      www      1047:               $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$i;
1.35      www      1048:               &addlog("Rule $label passed, setting label $xfinallabel");
1.31      www      1049:               return 1;
                   1050:            } else {
1.35      www      1051:               &addlog("Rule $label failed.");
1.49      www      1052:               &setfailed($label);
1.31      www      1053:               return 0; 
                   1054:            }
                   1055:         }
1.42      www      1056:      }
1.25      www      1057:    }
1.49      www      1058: # Corner case where this makes sense: using start or stop as defined labels
                   1059:    unless (&checklength($lh,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
1.35      www      1060:    &addlog("Rule $label passed.");
1.27      www      1061:    return 1;
1.24      www      1062: }
                   1063: 
1.49      www      1064: #
                   1065: # check for minimum and maximum lengths
                   1066: #
                   1067: 
                   1068: sub checklength {
                   1069:     my ($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)=@_;
                   1070:     unless (($minimumlength) || ($maximumlength)) { return 1; }
                   1071:     my $length=&actualval($i,$xmin,$xmax)-&actualval($li,$xmin,$xmax);
                   1072:     if ($minimumlength) {
                   1073:        if ($length<$minimumlength) {
                   1074:           &addlog("Rule $label failed, actual length $length, minimum length $minimumlength");
                   1075:           &setfailed($label);
                   1076:           return 0;
                   1077:        }
                   1078:     }
                   1079:     if ($maximumlength) {
                   1080:        if ($length>$maximumlength) {
                   1081:           &addlog("Rule $label failed, actual length $length, maximum length $maximumlength");
                   1082:           &setfailed($label);
                   1083:           return 0;
                   1084:        }
                   1085:     }
                   1086:     return 1;
                   1087: }
                   1088: 
                   1089: sub setfailed {
                   1090:    my ($label)=@_;
                   1091:    my $hintlabel=$label;
                   1092:    $hintlabel=~s/^R//;
                   1093:    push(@Apache::functionplotresponse::failedrules,$hintlabel);
                   1094:    &addlog("Set hint condition $hintlabel");
                   1095: }
                   1096: 
1.37      www      1097: sub start_functionplotruleset {
                   1098:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1099:    if ($target eq 'edit') {
                   1100:       return &Apache::edit::start_table($token).
                   1101:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Rule Set').'</span></td>'
                   1102:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
                   1103:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
1.50      www      1104:         &Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
                   1105:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Rule_Set','Function Plot Rules')
1.37      www      1106:        .'</span></td>'
                   1107:        ."<td>&nbsp;"
                   1108:        .&Apache::edit::end_row()
                   1109:        .&Apache::edit::start_spanning_row()
                   1110:        ."\n";
                   1111:    }
                   1112: }
1.3       www      1113: 
1.37      www      1114: sub end_functionplotruleset {
                   1115:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                   1116:     my $id=$Apache::inputtags::response[-1];
                   1117:     my $partid=$Apache::inputtags::part;
                   1118:     my $internalid = $partid.'_'.$id;
                   1119: 
                   1120:     if ($target eq 'edit' ) {
                   1121:         return &Apache::edit::end_table();
                   1122:     }  elsif ($target eq 'grade'
1.10      www      1123:          && &Apache::response::submitted()
                   1124:          && $Apache::lonhomework::type ne 'exam') {
1.12      www      1125: #
                   1126: # Actually grade
                   1127: #
1.41      www      1128:     my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
1.27      www      1129: 
1.24      www      1130:         my $ad='';
1.30      www      1131:         undef  %Apache::functionplotresponse::functionplotrulelabels;
1.35      www      1132:         $Apache::functionplotresponse::ruleslog='';
1.30      www      1133:         $Apache::functionplotresponse::functionplotrulelabels{'start'}=400;
                   1134:         $Apache::functionplotresponse::functionplotrulelabels{'end'}=0;
1.18      www      1135:         if (&populate_arrays($internalid,$xmin,$xmax) eq 'no_func') {
1.21      www      1136:            $ad='NOT_FUNCTION';
1.18      www      1137:         } else {
1.35      www      1138:            &addlog("Start of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'start'},$xmin,$xmax)." (index ".
                   1139:                                         $Apache::functionplotresponse::functionplotrulelabels{'start'}.")");
                   1140:            &addlog("End of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'end'},$xmin,$xmax)." (index ".
                   1141:                                         $Apache::functionplotresponse::functionplotrulelabels{'end'}.")");
                   1142: 
1.24      www      1143: # We have a function that we can actually grade, go through the spline rules.
1.25      www      1144:            foreach my $rule (@Apache::functionplotresponse::functionplotrules) {
1.33      www      1145:               unless (&functionplotrulecheck($rule,$xmin,$xmax,$ymin,$ymax)) {
1.24      www      1146:                  $ad='INCORRECT';
                   1147:                  last;
                   1148:               }
                   1149:            }
                   1150: # If it's not wrong, it's correct 
                   1151:            unless ($ad) { $ad='EXACT_ANS' };
1.18      www      1152:         }
1.37      www      1153:         &addlog("Set hint conditions: ".join(",",@Apache::functionplotresponse::failedrules));
                   1154:         &addlog("Assigned award detail: $ad");
                   1155: # Store for later to be assigned at end_functionplotresponse
                   1156:         $Apache::functionplotresponse::awarddetail=$ad;
                   1157:      }
                   1158: }
                   1159: 
                   1160: 
                   1161: sub end_functionplotresponse {
                   1162:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1163:   &Apache::response::end_response;
                   1164: 
                   1165:   my $result;
                   1166:   my $id=$Apache::inputtags::response[-1];
                   1167:   my $partid=$Apache::inputtags::part;
                   1168:   my $internalid = $partid.'_'.$id;
1.20      www      1169: 
1.37      www      1170:     if ($target eq 'edit') { $result=&Apache::edit::end_table(); }
                   1171:     if ($target eq 'grade'
                   1172:          && &Apache::response::submitted()
                   1173:          && $Apache::lonhomework::type eq 'exam') {
                   1174: 
                   1175:         &Apache::response::scored_response($partid,$id);
                   1176: 
                   1177:     } elsif ($target eq 'grade'
                   1178:          && &Apache::response::submitted()
                   1179:          && $Apache::lonhomework::type ne 'exam') {
                   1180:         my ($response,%coords)=&get_answer_from_form_fields($internalid);
                   1181:         $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
                   1182:         my %previous=&Apache::response::check_for_previous($response,$partid,$id);
                   1183: #
                   1184: # Assign grade
                   1185: #
                   1186:         my $ad=$Apache::functionplotresponse::awarddetail;
1.12      www      1187: #
                   1188: # Store grading info
                   1189: #
                   1190:         $Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
                   1191:         &Apache::response::handle_previous(\%previous,$ad);
1.10      www      1192:    } elsif ($target eq 'web') {
1.37      www      1193:         undef @Apache::functionplotresponse::failedrules;
                   1194:    }
                   1195:    return $result;
                   1196: }
                   1197: 
                   1198: sub end_functionplotelements {
                   1199:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                   1200:   my $result='';
                   1201:   my $id=$Apache::inputtags::response[-1];
                   1202:   my $partid=$Apache::inputtags::part;
                   1203:   my $internalid = $partid.'_'.$id;
                   1204:   if ($target eq 'edit' ) {
                   1205:      $result=&Apache::edit::end_table();
                   1206:   } elsif ($target eq 'web') {
1.47      www      1207:      my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
                   1208: 
                   1209: # Are we in show answer mode?
                   1210:      my $showanswer=&Apache::response::show_answer();
                   1211:      if ($showanswer) {
                   1212: # Render answerdisplay
                   1213:         my $answerdisplay=&Apache::lonxml::get_param('answerdisplay',$parstack,$safeeval,-2);
                   1214:         if ($answerdisplay=~/\S/s) {
                   1215:            foreach my $plot (split(/\s*\,\s*/,$answerdisplay)) {
                   1216:               my ($func,$xl,$xh)=split(/\s*\:\s*/,$plot);
                   1217:               if ((!defined($xl)) || ($xl eq '')) { $xl=$xmin; }
                   1218:               if ((!defined($xh)) || ($xh eq '')) { $xh=$xmax; }
                   1219:               $result.=&plot_script($internalid,$func,1,'','00aa00',$xl,$xh,6);
                   1220:            }
                   1221:         }
                   1222:      }
1.48      www      1223:      my $fixed=0;
                   1224:      if (($showanswer) || (&Apache::response::check_status()>=2)) { $fixed=1; }
1.6       www      1225: # Now is the time to render all of the stored splines
                   1226:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
1.48      www      1227:         $result.=&generate_spline($internalid,$label,$xmin,$xmax,$ymin,$ymax,$fixed);
1.6       www      1228:      }
1.5       www      1229: # close the init script
1.3       www      1230:      $result.=&end_init_script();
1.17      www      1231: # register all splines in this response 
                   1232:      $result.='<input type="hidden" name="HWVAL_AllSplines_'.$internalid.'" value="'.
                   1233:                  join(',',keys(%Apache::functionplotresponse::splineorder)).'" />'."\n";
                   1234:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
                   1235:         $result.='<input type="hidden" name="HWVAL_SplineOrder_'.$internalid.'_'.$label.'" value="'.
                   1236:                  $Apache::functionplotresponse::splineorder{$label}.'" />'."\n";
                   1237:      }
1.9       www      1238: # generate the input fields
                   1239:      $result.=$Apache::functionplotresponse::inputfields;
1.5       www      1240: # actually start the <applet>-tag
1.3       www      1241:      $result.=&geogebra_startcode($internalid);
1.5       www      1242: # load the spline bytecode
1.3       www      1243:      $result.=&geogebra_spline_program();
1.5       www      1244: # set default parameters
1.3       www      1245:      $result.=&geogebra_default_parameters($internalid);
1.5       www      1246: # close the <applet>-tag
1.1       www      1247:      $result.=&geogebra_endcode();
                   1248:   }
                   1249:   return $result;
                   1250: }
                   1251: 
1.41      www      1252: sub boundaries {
                   1253:    my ($parstack,$safeeval,$level)=@_;
                   1254:    my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval,$level);
                   1255:    $xmin=(defined($xmin)?$xmin:-10);
                   1256:    my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval,$level);
                   1257:    $xmax=(defined($xmax)?$xmax:10);
                   1258:    my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval,$level);
                   1259:    $ymin=(defined($ymin)?$ymin:-10);
                   1260:    my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval,$level);
                   1261:    $ymax=(defined($ymax)?$ymax:10);
                   1262:    if ($xmax<=$xmin) {
                   1263:       $xmax=$xmin+20;
                   1264:    }
                   1265:    if ($ymax<=$ymin) {
                   1266:       $ymax=$ymin+20;
                   1267:    }
                   1268:    return ($xmin,$xmax,$ymin,$ymax);
                   1269: }
                   1270: 
1.37      www      1271: sub start_functionplotelements {
                   1272:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1273:    my $result='';
                   1274:    my $id=$Apache::inputtags::response[-1];
                   1275:    my $partid=$Apache::inputtags::part;
                   1276:    my $internalid = $partid.'_'.$id;
                   1277: 
                   1278:    if ($target eq 'edit') {
                   1279:       return &Apache::edit::start_table($token).
                   1280:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Elements').'</span></td>'
                   1281:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
                   1282:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
1.50      www      1283:         &Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
                   1284:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Elements','Function Plot Elements')
1.37      www      1285:        .'</span></td>'
                   1286:        ."<td>&nbsp;"
                   1287:        .&Apache::edit::end_row()
                   1288:        .&Apache::edit::start_spanning_row()
                   1289:        ."\n";
                   1290:    } elsif ($target eq 'web') {
1.41      www      1291:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
1.37      www      1292:       my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1293:       my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1294:       my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1295:       my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval,-2);
                   1296:       my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval,-2);
                   1297: 
                   1298: 
                   1299: # paste in the update routine to receive stuff back from the applet
                   1300:      $result.=&update_script($internalid);
                   1301: # start the initscript for this applet
                   1302:      $result.=&start_init_script($internalid);
                   1303: # put the axis commands inside
                   1304:      $result.=&axes_script($internalid,$xmin,$xmax,$ymin,$ymax,$xaxisvisible,$yaxisvisible,$gridvisible);
1.45      www      1305:      $result.=&axes_label($internalid,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel);
1.37      www      1306: # init script is left open
                   1307:   }
                   1308:   return $result;
                   1309: }
                   1310: 
1.1       www      1311: 1;
                   1312: 
                   1313: __END__
                   1314:  
                   1315: =head1 NAME
                   1316: 
                   1317: Apache::functionplotresponse.pm;
                   1318: 
                   1319: =head1 SYNOPSIS
                   1320: 
                   1321: Handles tags associated with accepting function plots.
                   1322: 
                   1323: This is part of the LearningOnline Network with CAPA project
                   1324: described at http://www.lon-capa.org.
                   1325: 
                   1326: =head1 HANDLER SUBROUTINE
                   1327: 
                   1328: start_functionplotresponse()
                   1329: 
                   1330: =head1 OTHER SUBROUTINES
                   1331: 
                   1332: =over
                   1333: 
                   1334: =item end_functionplotresponse()
                   1335: 
                   1336: =back
                   1337: 
                   1338: =cut

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