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

1.1       www         1: # LearningOnline Network with CAPA
                      2: # option list style responses
                      3: #
1.48    ! www         4: # $Id: functionplotresponse.pm,v 1.47 2010/11/24 02:53:13 www Exp $
1.1       www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
                     28: 
                     29: package Apache::functionplotresponse;
                     30: use strict;
                     31: use Apache::response();
                     32: use Apache::lonlocal;
                     33: use Apache::lonnet;
1.36      www        34:  
1.1       www        35: BEGIN {
1.37      www        36:   &Apache::lonxml::register('Apache::functionplotresponse',('functionplotresponse','backgroundplot','spline',
                     37:                                                             'functionplotrule','functionplotruleset',
                     38:                                                             'functionplotelements'));
1.1       www        39: }
                     40: 
1.5       www        41: #
                     42: # There can be a number of applets on a page, each called ggbApplet_$id, 
                     43: # where $id is the "_"-concatenated part and responseid
                     44: #
                     45: 
1.1       www        46: sub geogebra_startcode {
1.3       www        47:     my ($id)=@_;
1.1       www        48:     return (<<ENDSTARTCODE);
1.3       www        49: <applet name="ggbApplet_$id" code="geogebra.GeoGebraApplet" archive="geogebra.jar"
1.40      www        50:          codebase="/adm/geogebra/"  width="722" height="447" MAYSCRIPT>
1.1       www        51:        <param name="java_arguments" value="-Xmx512m -Djnlp.packEnabled=true"/>
                     52: ENDSTARTCODE
                     53: }
                     54: 
                     55: sub geogebra_endcode {
1.2       www        56:     return &Apache::lonhtmlcommon::java_not_enabled()."</applet>\n";
                     57: }
                     58: 
1.5       www        59: #
                     60: # This is the internal GeoGebra bytecode which defines the spline functions
                     61: #
1.2       www        62: sub geogebra_spline_program {
                     63:     return (<<ENDSPLINEPROGRAM);
1.42      www        64: <param name="ggbBase64" value="UEsDBBQACAAIANOAcz0AAAAAAAAAAAAAAAASAAAAZ2VvZ2VicmFfbWFjcm8ueG1s7Vxtb6tGGv3c/grEh1Vuu4njlzje2/hW5b1Sb3ulu1qttGorYhPHrQ0WJomnv74zA9hxgGuGNfYYnw/JYDwM8ByYM545z7n7fjWfKc9euJwG/lBtX12riuePgvHUnwzVp+jhcqB+/+Hru4kXTLz70FUegnDuRkO1e9VVldVy+t4Pfnbn3nLhjrzPo0dv7v4UjNyIt/YYRYv3rdbLy8tVevxVEE5ak0l0tVqO6fHzmb8cqsnGe9rc1kEvXV69c33dbv33409x85dTfxm5/shTFXpdc3cUBspoPmYXMVQ/L2ZT3+uoShQEs5xdjjdbrHf971P7n8pn+vepQ8vOr6oyHQW+NZ157JKWj8HLj/6/6UGaGw7VKHzy1PSEP/qLp0hxr4fqD6ritmnh0rIzVDVadGnhqq207i9P0bryc1JbS2o/82r0pEva/IgFTYmmUXx+9yl6DEK2NXYjtofW9Gbe3PMjJSILumcRTP1IVWbuvTdjV/Lh66/u2FUrwf0f3ihKrjn9/sGdLT12vq/u6Pd6MAtChTZP8Z7w//f8vztbPLp0iz4HvOrMJV6oPLsz9m2yhzb3MRh7W3tdfzrnqCvLyFuwBto0hAvPGycPVXzJdGNBm+QP16sLGgVBOF4qq/jEChmqPVb+FR/Lq/Cb/Tz9Kzlt9/XeiMxeX81dK4nTjohpjYhY54ARo4/5/x2yzs2NPEHrH+Ixa0rQevsO2moRektGPGkk3PvfV5R/Vot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hZgv6l61TSuOhxn88oxcNPevR2Oxbo8K+zMrr59P+tFdv3ek9/Z16mn3Y/f3L1Dplr0P+MbffP0yooHXvH3aIe4IvgF+btNuNTTplGnDfZ5WTbf1dKo/qp6z5wxCgOoxUM5NGbk4IrtV8V19Un0qJTv/i124EENGo5lc8W9RrEHXPqDsZOVtsv+hk3B79Zi14uplzTui833OXcaz98wvtheLSclrA4atfXRMtLY/oK2D2Zv7f3Rfi3CfYnfnOaM31SlsceWwZzOvQON34y3fwFQSwcI3KfwzsQEAAClDgAAUEsBAhQAFAAIAAgA04BzPTOjqPpOCgAAU0wBABIAAAAAAAAAAAAAAAAAAAAAAGdlb2dlYnJhX21hY3JvLnhtbFBLAQIUABQACAAIANOAcz1FzN5dGgAAABgAAAAWAAAAAAAAAAAAAAAAAI4KAABnZW9nZWJyYV9qYXZhc2NyaXB0LmpzUEsBAhQAFAAIAAgA04BzPdyn8M7EBAAApQ4AAAwAAAAAAAAAAAAAAAAA7AoAAGdlb2dlYnJhLnhtbFBLBQYAAAAAAwADAL4AAADqDwAAAAA=" />
1.2       www        65: ENDSPLINEPROGRAM
                     66: }
                     67: 
1.5       www        68: #
                     69: # The standard set of parameters inside <applet>
                     70: #
1.2       www        71: sub geogebra_default_parameters {
1.3       www        72:    my ($id)=@_;
1.2       www        73:    return(<<ENDDEFAULTPARAMETERS);
                     74:         <param name="image" value="/adm/lonIcons/lonanim.gif"  />
                     75:         <param name="boxborder" value="false"  />
                     76:         <param name="centerimage" value="true"  />
1.39      www        77: 	<param name="cache_archive" value="geogebra.jar, geogebra_main.jar, geogebra_gui.jar, geogebra_cas.jar, geogebra_algos.jar, geogebra_export.jar, geogebra_javascript.jar, jlatexmath.jar, jlm_greek.jar, jlm_cyrillic.jar, geogebra_properties.jar" />
                     78: 	<param name="cache_version" value="3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0, 3.9.115.0" />
1.2       www        79:         <param name="framePossible" value="false" />
                     80: 
                     81:         <param name="showResetIcon" value="false" />
                     82:         <param name="showAnimationButton" value="false" />
                     83:         <param name="enableRightClick" value="false" />
                     84:         <param name="errorDialogsActive" value="true" />
                     85:         <param name="enableLabelDrags" value="false" />
                     86:         <param name="showMenuBar" value="false" />
                     87:         <param name="showToolBar" value="false" />
                     88:         <param name="showToolBarHelp" value="false" />
                     89:         <param name="showAlgebraInput" value="false" />
                     90:         <param name="enableShiftDragZoom" value="false" />
                     91:         <param name="allowRescaling" value="false" />
                     92:         <param name="enableLabelDrags" value="false" />
1.3       www        93:         <param name="ggbOnInitParam" value="applet_$id" />
1.2       www        94: ENDDEFAULTPARAMETERS
1.1       www        95: }
                     96: 
1.5       www        97: #
                     98: # This subroutine is called by LON-CAPA at </problem>
                     99: # Each applet on the page will call function ggbOnInit when it is done loading
                    100: # This function in turn will call the respective function registered by start_init_script
                    101: # Which one of the registered functions is called is determined by ggbOnInitParam, which GeoGebra passes to ggbOnInit
                    102: #
                    103: 
1.3       www       104: sub init_script {
1.16      www       105:    if ($#Apache::functionplotresponse::callscripts>=0) {
                    106:       my $script='';
                    107:       foreach my $id (@Apache::functionplotresponse::callscripts) {
                    108:           $script.="if (param=='applet_$id') { loaded_$id=true; }\n";
                    109:       }
                    110:       $script.="if (".join(' && ',map { "loaded_$_" } (@Apache::functionplotresponse::callscripts)).
1.17      www       111:                ") { setTimeout('ggbInitAll()',20) }";
1.16      www       112:       my $calls=join("\n",map { "ggbInit_$_();" } (@Apache::functionplotresponse::callscripts)); 
1.3       www       113:       return (<<ENDGGBINIT);
                    114: <script type="text/javascript">
                    115: // <![CDATA[
1.16      www       116: // Function that each applet will call when loaded
                    117: // It will pass "its" parameter
                    118: // Set flags for when an applet is loaded, wait till all are loaded, and then some
1.3       www       119: function ggbOnInit(param) {
1.16      www       120: $script
                    121: }
                    122: function ggbInitAll() {
1.17      www       123: $calls
1.3       www       124: }
                    125: // ]]>
                    126: </script>
                    127: ENDGGBINIT
                    128:    }
                    129: }
                    130: 
1.5       www       131: #
                    132: # Each Geogebra applet is supposed to call this when parameters change
1.10      www       133: # Changes the hidden fields on the web page
1.5       www       134: #
                    135: sub update_script {
                    136:     my ($id)=@_;
                    137:     return (<<ENDUPDATESCRIPT);
                    138: <script type="text/javascript">
                    139: // <![CDATA[
                    140: function updatePointCoordinates_$id(coordinateName) {
                    141:             var x = document.ggbApplet_$id.getXcoord(coordinateName);
                    142:             var y = document.ggbApplet_$id.getYcoord(coordinateName);
1.9       www       143:             document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_x"].value = x;
                    144:             document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_y"].value = y;
1.5       www       145:         }
                    146: // ]]>
                    147: </script>
                    148: ENDUPDATESCRIPT
                    149: }
                    150: 
                    151: #
                    152: # Register the above update-handler for a variable
                    153: #
                    154: 
                    155: sub update_register {
                    156:    my ($id,$variable)=@_;
1.6       www       157:    return "document.ggbApplet_$id.registerObjectUpdateListener('$variable','updatePointCoordinates_$id');\n";
                    158: }
                    159: 
                    160: #
1.40      www       161: # Set a point coordinate variable
1.6       www       162: #
1.40      www       163: sub set_point_coordinate {
1.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.40      www       187: document.ggbApplet_$id.evalCommand("$xvariable=Slider[0,$domain,$xinterval]");
                    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;'
                    819:        .&Apache::edit::insertlist($target,$token)
1.12      www       820:        .'</span></td>'
                    821:        ."<td>&nbsp;"
                    822:        .&Apache::edit::end_row()
                    823:        .&Apache::edit::start_spanning_row()
                    824:        ."\n";
1.14      www       825:     $result.=&Apache::edit::text_arg('Label x-axis:','xlabel',
                    826:                                      $token,'6').'&nbsp;'.
                    827:              &Apache::edit::text_arg('Minimum x-value:','xmin',
                    828:                                      $token,'4').'&nbsp;'.
1.12      www       829:              &Apache::edit::text_arg('Maximum x-value:','xmax',
1.14      www       830:                                      $token,'4').'&nbsp;'.
1.12      www       831:              &Apache::edit::select_arg('x-axis visible:','xaxisvisible',
1.32      www       832:                                   ['yes','no'],$token).'<br />'.
1.14      www       833:              &Apache::edit::text_arg('Label y-axis:','ylabel',
                    834:                                      $token,'6').'&nbsp;'.
1.12      www       835:              &Apache::edit::text_arg('Minimum y-value:','ymin',
1.14      www       836:                                      $token,'4').'&nbsp;'.
1.12      www       837:              &Apache::edit::text_arg('Maximum y-value:','ymax',
1.14      www       838:                                      $token,'4').'&nbsp;'.
1.12      www       839:              &Apache::edit::select_arg('y-axis visible:','yaxisvisible',
1.32      www       840:                                   ['yes','no'],$token).'<br />'.
1.12      www       841:              &Apache::edit::select_arg('Grid visible:','gridvisible',
1.47      www       842:                                   ['yes','no'],$token).'<br />'.
                    843:              &Apache::edit::text_arg('Background plot(s) for answer (function:xmin:xmax,function:xmin:xmax,...):',
                    844:                                          'answerdisplay',$token,'50');
                    845: 
1.12      www       846:              &Apache::edit::end_row().&Apache::edit::start_spanning_row();
                    847:   } elsif ($target eq 'modified') {
                    848:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.14      www       849:                                                  $safeeval,'xlabel','xmin','xmax','ylabel','ymin','ymax',
1.47      www       850:                                                            'xaxisvisible','yaxisvisible','gridvisible','answerdisplay');
1.12      www       851:     if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
1.3       www       852: 
1.12      www       853:   } elsif ($target eq 'meta') {
1.10      www       854:        $result=&Apache::response::meta_package_write('functionplotresponse');
1.35      www       855:   } elsif (($target eq 'answer') &&
                    856:             ($env{'form.answer_output_mode'} ne 'tex') &&
                    857:             ($Apache::lonhomework::viewgrades == 'F')) {
                    858:       my (undef,undef,$udom,$uname)=&Apache::lonnet::whichuser();
                    859:       my $windowopen=&Apache::lonhtmlcommon::javascript_docopen();
                    860:       my $start_page = &Apache::loncommon::start_page('Rules Log', undef,
                    861:                                                {'only_body' => 1,
                    862:                                                 'bgcolor'   => '#FFFFFF',
                    863:                                                 'js_ready'  => 1,});
                    864:       my $end_page = &Apache::loncommon::end_page({'js_ready' => 1,});
                    865:       $uname =~s/\W//g;
                    866:       $udom  =~s/\W//g;
                    867:       my $function_name =
                    868:                 join('_','LONCAPA_scriptvars',$uname,$udom,
                    869:                      $env{'form.counter'},$Apache::lonxml::curdepth);
                    870:       my $rules_var ="<script type=\"text/javascript\">
                    871: // <![CDATA[
                    872:     function $function_name() {newWindow=open('','new_W','width=500,height=500,scrollbars=1,resizable=yes');newWindow.$windowopen;newWindow.document.writeln('$start_page<pre>".
                    873:     $Apache::functionplotresponse::ruleslog.
                    874:     "<\\/pre>$end_page');newWindow.document.close();newWindow.focus()}
                    875: // ]]>
                    876: </script><a href=\"javascript:$function_name();void(0);\">".&mt('Rules Log')."</a><br />";
                    877:             &Apache::lonxml::add_script_result($rules_var);
                    878:         }
                    879: 
1.1       www       880:   return $result;
                    881: }
                    882: 
1.25      www       883: sub compare_rel {
1.26      www       884:    my ($relationship,$value,$realval,$tol)=@_;
1.36      www       885: # is the real value undefined?
1.26      www       886:    unless (defined($realval)) {
1.36      www       887: # the real value is not defined
1.26      www       888:       if ($relationship eq 'eq') {
                    889:          if ($value eq 'undef') {
                    890:             return 1;
                    891:          } else {
                    892:             return 0;
                    893:          }
                    894:       } elsif ($relationship eq 'ne') {
                    895:          if ($value eq 'undef') {
                    896:             return 0;
                    897:          } else {
                    898:             return 1;
                    899:          }
                    900:       } else {
                    901:          return 0;
                    902:       }
                    903:    }
                    904: 
1.36      www       905: # is the expected value undefined?
                    906:    if ($value eq 'undef') {
                    907: # but by now we know that the real value is defined
                    908:       return 0;
                    909:    }
                    910: 
                    911: # both are defined.
1.26      www       912:    if ($relationship eq 'gt') {
                    913:       return ($realval>$value);
                    914:    } elsif ($relationship eq 'ge') {
                    915:       return ($realval>$value-$tol);
                    916:    } elsif ($relationship eq 'lt') {
                    917:       return ($realval<$value);
                    918:    } elsif ($relationship eq 'le') {
                    919:       return ($realval<$value+$tol);
                    920:    } elsif ($relationship eq 'ne') {
                    921:       return (abs($value-$realval)>$tol);
                    922:    } else {
                    923:       return (abs($value-$realval)<$tol);
                    924:    }
1.25      www       925:    return 0;
                    926: }
                    927: 
1.35      www       928: sub addlog {
                    929:    my ($text)=@_;
                    930:    $Apache::functionplotresponse::ruleslog.=$text.'<br />';
                    931: }
                    932: 
                    933: sub actualval {
                    934:    my ($i,$xmin,$xmax)=@_;
                    935:    return $xmin+$i/400.*($xmax-$xmin);
                    936: }
                    937:  
1.25      www       938: sub functionplotrulecheck {
1.33      www       939:    my ($rule,$xmin,$xmax,$ymin,$ymax)=@_;
                    940: 
1.35      www       941:    my ($label,$derivative,$xinitial,$xinitiallabel,$xfinal,$xfinallabel,$minimumlength,$maximumlength,$relationship,$value,$percent)
1.25      www       942:       =split(/\:/,$rule);
1.33      www       943:    $percent=($percent>0?$percent:5);
1.35      www       944:    &addlog("=================");
1.42      www       945:    &addlog("Rule $label for ".($derivative<0?'integral':('function itself','first derivative','second derivative')[$derivative])." $relationship $value");
1.30      www       946:    my $li=0;
                    947:    my $lh=400;
                    948: 
1.31      www       949: # Special case: the upper boundary was not defined
                    950: # and needs to be set to the value where
                    951: # the condition is not true anymore => set flag
                    952: 
                    953:    my $findupper=0;
                    954:    if (($xfinal eq '')
                    955:     && (!defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}))
                    956:     && ($xfinallabel)) {
                    957:        $findupper=1;
                    958:    }
                    959: 
1.25      www       960: # if a hard value is set for the boundaries, it overrides the label
1.30      www       961:    if (($xinitial ne '') && ($xinitiallabel ne '') && ($xinitiallabel ne 'start')) {
                    962:       $li=&array_index($xmin,$xmax,$xinitial);
                    963:       $Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel}=$li;
                    964:    }
                    965:    if (($xfinal ne '') && ($xfinallabel ne '') && ($xfinallabel ne 'end')) {
                    966:       $lh=&array_index($xmin,$xmax,$xfinal);
                    967:       $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$lh;
1.25      www       968:    }
1.31      www       969: # if the label is defined, use it
1.25      www       970:    if (defined($Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel})) {
1.35      www       971:       &addlog("Using lower label $xinitiallabel");
1.30      www       972:       $li=$Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel};
                    973:    } else {
                    974:       $li=&array_index($xmin,$xmax,$xinitial);
1.25      www       975:    }
1.31      www       976:    unless ($findupper) {
                    977:       if (defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel})) {
1.35      www       978:          &addlog("Using upper label $xfinallabel");
1.33      www       979:          $lh=$Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}-1;
1.31      www       980:       } else {
                    981:          $lh=&array_index($xmin,$xmax,$xfinal);
                    982:       }
1.25      www       983:    }
                    984: # Basic sanity checks
1.30      www       985:    if ($li<0) { $li=0; }
                    986:    if ($lh>400) { $lh=400; }
1.38      www       987:    if (($li>$lh) || (!defined($lh))) {
1.30      www       988:        $lh=$li;
1.25      www       989:    }
1.31      www       990: 
1.35      www       991:    &addlog("Boundaries: x=".&actualval($li,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$li]."; index $li)) to x=".
                    992:                             &actualval($lh,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$lh]."; index $lh))");
                    993:    if ($findupper) {
                    994:       &addlog("Looking for label $xfinallabel");
                    995:    }
1.33      www       996:    my $tol=$percent*($ymax-$ymin)/100;
                    997:    if ($xmax>$xmin) {
                    998:       if ($derivative==2) {
                    999:          $tol=4.*$tol/($xmax-$xmin);
                   1000:       } elsif ($derivative==1) {
                   1001:          $tol=2.*$tol/($xmax-$xmin);
1.42      www      1002:       } elsif ($derivative==-1) {
                   1003:          $tol=$tol*($xmax-$xmin)/2.;
1.33      www      1004:       }
1.27      www      1005:    }
1.42      www      1006:    my $integral=0;
                   1007:    my $binwidth=($xmax-$xmin)/400.;
                   1008:    if (($derivative<0) && (!$findupper)) {
                   1009: # definite integral, calculate over whole length
                   1010:      &addlog("Calculating definite integral");
                   1011:      for (my $i=$li; $i<=$lh; $i++) {
                   1012:         $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
                   1013:      }
                   1014:      unless (&compare_rel($relationship,$value,$integral,$tol)) {
                   1015:         &addlog("Actual integral ".(defined($integral)?$integral:'undef').", expected $value, tolerance $tol");
                   1016:         &addlog("Rule $label failed.");
                   1017:         my $hintlabel=$label;
                   1018:         $hintlabel=~s/^R//;
                   1019:         push(@Apache::functionplotresponse::failedrules,$hintlabel);
                   1020:         &addlog("Set hint condition $hintlabel");
                   1021:         return 0;
                   1022:      } 
                   1023:    } else {
                   1024:      for (my $i=$li; $i<=$lh; $i++) {
1.25      www      1025:         my $val;
                   1026:         if ($derivative==2) {
1.27      www      1027:            $val=$Apache::functionplotresponse::d2funcdx2[$i];
1.25      www      1028:         } elsif ($derivative==1) {
1.27      www      1029:            $val=$Apache::functionplotresponse::dfuncdx[$i];
1.42      www      1030:         } elsif ($derivative==-1) {
                   1031:            $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
                   1032:            $val=$integral;      
1.25      www      1033:         } else {
1.27      www      1034:            $val=$Apache::functionplotresponse::func[$i];
1.25      www      1035:         }
1.31      www      1036:         unless (&compare_rel($relationship,$value,$val,$tol)) { 
1.37      www      1037:            &addlog("Actual value ".(defined($val)?$val:'undef').", expected $value, tolerance $tol");
1.35      www      1038:            &addlog("Condition not fulfilled at x=".&actualval($i,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$i]."; index $i)");
1.31      www      1039:            if (($findupper) && ($i>$li)) {
1.35      www      1040: # check for minimum and maximum lengths
                   1041:               my $length=&actualval($i,$xmin,$xmax)-&actualval($li,$xmin,$xmax);
                   1042:               if ($minimumlength) {
                   1043:                  if ($length<$minimumlength) {
                   1044:                     &addlog("Rule $label failed, actual length $length, minimum length $minimumlength");
                   1045:                     return 0;
                   1046:                  }
                   1047:               }
                   1048:               if ($maximumlength) {
                   1049:                  if ($length>$maximumlength) {
                   1050:                     &addlog("Rule $label failed, actual length $length, maximum length $maximumlength");
                   1051:                     return 0;
                   1052:                  }
                   1053:               }
1.31      www      1054:               $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$i;
1.35      www      1055:               &addlog("Rule $label passed, setting label $xfinallabel");
1.31      www      1056:               return 1;
                   1057:            } else {
1.35      www      1058:               &addlog("Rule $label failed.");
1.37      www      1059:               my $hintlabel=$label;
                   1060:               $hintlabel=~s/^R//;
                   1061:               push(@Apache::functionplotresponse::failedrules,$hintlabel);
                   1062:               &addlog("Set hint condition $hintlabel");
1.31      www      1063:               return 0; 
                   1064:            }
                   1065:         }
1.42      www      1066:      }
1.25      www      1067:    }
1.35      www      1068:    &addlog("Rule $label passed.");
1.27      www      1069:    return 1;
1.24      www      1070: }
                   1071: 
1.37      www      1072: sub start_functionplotruleset {
                   1073:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1074:    if ($target eq 'edit') {
                   1075:       return &Apache::edit::start_table($token).
                   1076:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Rule Set').'</span></td>'
                   1077:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
                   1078:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
                   1079:         &Apache::edit::insertlist($target,$token)
                   1080:        .'</span></td>'
                   1081:        ."<td>&nbsp;"
                   1082:        .&Apache::edit::end_row()
                   1083:        .&Apache::edit::start_spanning_row()
                   1084:        ."\n";
                   1085:    }
                   1086: }
1.3       www      1087: 
1.37      www      1088: sub end_functionplotruleset {
                   1089:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                   1090:     my $id=$Apache::inputtags::response[-1];
                   1091:     my $partid=$Apache::inputtags::part;
                   1092:     my $internalid = $partid.'_'.$id;
                   1093: 
                   1094:     if ($target eq 'edit' ) {
                   1095:         return &Apache::edit::end_table();
                   1096:     }  elsif ($target eq 'grade'
1.10      www      1097:          && &Apache::response::submitted()
                   1098:          && $Apache::lonhomework::type ne 'exam') {
1.12      www      1099: #
                   1100: # Actually grade
                   1101: #
1.41      www      1102:     my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
1.27      www      1103: 
1.24      www      1104:         my $ad='';
1.30      www      1105:         undef  %Apache::functionplotresponse::functionplotrulelabels;
1.35      www      1106:         $Apache::functionplotresponse::ruleslog='';
1.30      www      1107:         $Apache::functionplotresponse::functionplotrulelabels{'start'}=400;
                   1108:         $Apache::functionplotresponse::functionplotrulelabels{'end'}=0;
1.18      www      1109:         if (&populate_arrays($internalid,$xmin,$xmax) eq 'no_func') {
1.21      www      1110:            $ad='NOT_FUNCTION';
1.18      www      1111:         } else {
1.35      www      1112:            &addlog("Start of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'start'},$xmin,$xmax)." (index ".
                   1113:                                         $Apache::functionplotresponse::functionplotrulelabels{'start'}.")");
                   1114:            &addlog("End of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'end'},$xmin,$xmax)." (index ".
                   1115:                                         $Apache::functionplotresponse::functionplotrulelabels{'end'}.")");
                   1116: 
1.24      www      1117: # We have a function that we can actually grade, go through the spline rules.
1.25      www      1118:            foreach my $rule (@Apache::functionplotresponse::functionplotrules) {
1.33      www      1119:               unless (&functionplotrulecheck($rule,$xmin,$xmax,$ymin,$ymax)) {
1.24      www      1120:                  $ad='INCORRECT';
                   1121:                  last;
                   1122:               }
                   1123:            }
                   1124: # If it's not wrong, it's correct 
                   1125:            unless ($ad) { $ad='EXACT_ANS' };
1.18      www      1126:         }
1.37      www      1127:         &addlog("Set hint conditions: ".join(",",@Apache::functionplotresponse::failedrules));
                   1128:         &addlog("Assigned award detail: $ad");
                   1129: # Store for later to be assigned at end_functionplotresponse
                   1130:         $Apache::functionplotresponse::awarddetail=$ad;
                   1131:      }
                   1132: }
                   1133: 
                   1134: 
                   1135: sub end_functionplotresponse {
                   1136:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1137:   &Apache::response::end_response;
                   1138: 
                   1139:   my $result;
                   1140:   my $id=$Apache::inputtags::response[-1];
                   1141:   my $partid=$Apache::inputtags::part;
                   1142:   my $internalid = $partid.'_'.$id;
1.20      www      1143: 
1.37      www      1144:     if ($target eq 'edit') { $result=&Apache::edit::end_table(); }
                   1145:     if ($target eq 'grade'
                   1146:          && &Apache::response::submitted()
                   1147:          && $Apache::lonhomework::type eq 'exam') {
                   1148: 
                   1149:         &Apache::response::scored_response($partid,$id);
                   1150: 
                   1151:     } elsif ($target eq 'grade'
                   1152:          && &Apache::response::submitted()
                   1153:          && $Apache::lonhomework::type ne 'exam') {
                   1154:         my ($response,%coords)=&get_answer_from_form_fields($internalid);
                   1155:         $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
                   1156:         my %previous=&Apache::response::check_for_previous($response,$partid,$id);
                   1157: #
                   1158: # Assign grade
                   1159: #
                   1160:         my $ad=$Apache::functionplotresponse::awarddetail;
1.12      www      1161: #
                   1162: # Store grading info
                   1163: #
                   1164:         $Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
                   1165:         &Apache::response::handle_previous(\%previous,$ad);
1.10      www      1166:    } elsif ($target eq 'web') {
1.37      www      1167:         undef @Apache::functionplotresponse::failedrules;
                   1168:    }
                   1169:    return $result;
                   1170: }
                   1171: 
                   1172: sub end_functionplotelements {
                   1173:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                   1174:   my $result='';
                   1175:   my $id=$Apache::inputtags::response[-1];
                   1176:   my $partid=$Apache::inputtags::part;
                   1177:   my $internalid = $partid.'_'.$id;
                   1178:   if ($target eq 'edit' ) {
                   1179:      $result=&Apache::edit::end_table();
                   1180:   } elsif ($target eq 'web') {
1.47      www      1181:      my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
                   1182: 
                   1183: # Are we in show answer mode?
                   1184:      my $showanswer=&Apache::response::show_answer();
                   1185:      if ($showanswer) {
                   1186: # Render answerdisplay
                   1187:         my $answerdisplay=&Apache::lonxml::get_param('answerdisplay',$parstack,$safeeval,-2);
                   1188:         if ($answerdisplay=~/\S/s) {
                   1189:            foreach my $plot (split(/\s*\,\s*/,$answerdisplay)) {
                   1190:               my ($func,$xl,$xh)=split(/\s*\:\s*/,$plot);
                   1191:               if ((!defined($xl)) || ($xl eq '')) { $xl=$xmin; }
                   1192:               if ((!defined($xh)) || ($xh eq '')) { $xh=$xmax; }
                   1193:               $result.=&plot_script($internalid,$func,1,'','00aa00',$xl,$xh,6);
                   1194:            }
                   1195:         }
                   1196:      }
1.48    ! www      1197:      my $fixed=0;
        !          1198:      if (($showanswer) || (&Apache::response::check_status()>=2)) { $fixed=1; }
1.6       www      1199: # Now is the time to render all of the stored splines
                   1200:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
1.48    ! www      1201:         $result.=&generate_spline($internalid,$label,$xmin,$xmax,$ymin,$ymax,$fixed);
1.6       www      1202:      }
1.5       www      1203: # close the init script
1.3       www      1204:      $result.=&end_init_script();
1.17      www      1205: # register all splines in this response 
                   1206:      $result.='<input type="hidden" name="HWVAL_AllSplines_'.$internalid.'" value="'.
                   1207:                  join(',',keys(%Apache::functionplotresponse::splineorder)).'" />'."\n";
                   1208:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
                   1209:         $result.='<input type="hidden" name="HWVAL_SplineOrder_'.$internalid.'_'.$label.'" value="'.
                   1210:                  $Apache::functionplotresponse::splineorder{$label}.'" />'."\n";
                   1211:      }
1.9       www      1212: # generate the input fields
                   1213:      $result.=$Apache::functionplotresponse::inputfields;
1.5       www      1214: # actually start the <applet>-tag
1.3       www      1215:      $result.=&geogebra_startcode($internalid);
1.5       www      1216: # load the spline bytecode
1.3       www      1217:      $result.=&geogebra_spline_program();
1.5       www      1218: # set default parameters
1.3       www      1219:      $result.=&geogebra_default_parameters($internalid);
1.5       www      1220: # close the <applet>-tag
1.1       www      1221:      $result.=&geogebra_endcode();
                   1222:   }
                   1223:   return $result;
                   1224: }
                   1225: 
1.41      www      1226: sub boundaries {
                   1227:    my ($parstack,$safeeval,$level)=@_;
                   1228:    my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval,$level);
                   1229:    $xmin=(defined($xmin)?$xmin:-10);
                   1230:    my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval,$level);
                   1231:    $xmax=(defined($xmax)?$xmax:10);
                   1232:    my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval,$level);
                   1233:    $ymin=(defined($ymin)?$ymin:-10);
                   1234:    my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval,$level);
                   1235:    $ymax=(defined($ymax)?$ymax:10);
                   1236:    if ($xmax<=$xmin) {
                   1237:       $xmax=$xmin+20;
                   1238:    }
                   1239:    if ($ymax<=$ymin) {
                   1240:       $ymax=$ymin+20;
                   1241:    }
                   1242:    return ($xmin,$xmax,$ymin,$ymax);
                   1243: }
                   1244: 
1.37      www      1245: sub start_functionplotelements {
                   1246:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1247:    my $result='';
                   1248:    my $id=$Apache::inputtags::response[-1];
                   1249:    my $partid=$Apache::inputtags::part;
                   1250:    my $internalid = $partid.'_'.$id;
                   1251: 
                   1252:    if ($target eq 'edit') {
                   1253:       return &Apache::edit::start_table($token).
                   1254:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Elements').'</span></td>'
                   1255:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
                   1256:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
                   1257:         &Apache::edit::insertlist($target,$token)
                   1258:        .'</span></td>'
                   1259:        ."<td>&nbsp;"
                   1260:        .&Apache::edit::end_row()
                   1261:        .&Apache::edit::start_spanning_row()
                   1262:        ."\n";
                   1263:    } elsif ($target eq 'web') {
1.41      www      1264:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
1.37      www      1265:       my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1266:       my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1267:       my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1268:       my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval,-2);
                   1269:       my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval,-2);
                   1270: 
                   1271: 
                   1272: # paste in the update routine to receive stuff back from the applet
                   1273:      $result.=&update_script($internalid);
                   1274: # start the initscript for this applet
                   1275:      $result.=&start_init_script($internalid);
                   1276: # put the axis commands inside
                   1277:      $result.=&axes_script($internalid,$xmin,$xmax,$ymin,$ymax,$xaxisvisible,$yaxisvisible,$gridvisible);
1.45      www      1278:      $result.=&axes_label($internalid,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel);
1.37      www      1279: # init script is left open
                   1280:   }
                   1281:   return $result;
                   1282: }
                   1283: 
1.1       www      1284: 1;
                   1285: 
                   1286: __END__
                   1287:  
                   1288: =head1 NAME
                   1289: 
                   1290: Apache::functionplotresponse.pm;
                   1291: 
                   1292: =head1 SYNOPSIS
                   1293: 
                   1294: Handles tags associated with accepting function plots.
                   1295: 
                   1296: This is part of the LearningOnline Network with CAPA project
                   1297: described at http://www.lon-capa.org.
                   1298: 
                   1299: =head1 HANDLER SUBROUTINE
                   1300: 
                   1301: start_functionplotresponse()
                   1302: 
                   1303: =head1 OTHER SUBROUTINES
                   1304: 
                   1305: =over
                   1306: 
                   1307: =item end_functionplotresponse()
                   1308: 
                   1309: =back
                   1310: 
                   1311: =cut

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