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

1.1       www         1: # LearningOnline Network with CAPA
                      2: # option list style responses
                      3: #
1.49    ! www         4: # $Id: functionplotresponse.pm,v 1.48 2010/11/24 15:30:45 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.49    ! www       946:    if ((defined($minimumlength)) || (defined($maximumlength))) {
        !           947:       &addlog("Minimumlength $minimumlength Maximumlength $maximumlength");
        !           948:    }
1.30      www       949:    my $li=0;
                    950:    my $lh=400;
                    951: 
1.31      www       952: # Special case: the upper boundary was not defined
                    953: # and needs to be set to the value where
                    954: # the condition is not true anymore => set flag
                    955: 
                    956:    my $findupper=0;
                    957:    if (($xfinal eq '')
                    958:     && (!defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}))
                    959:     && ($xfinallabel)) {
                    960:        $findupper=1;
                    961:    }
                    962: 
1.25      www       963: # if a hard value is set for the boundaries, it overrides the label
1.30      www       964:    if (($xinitial ne '') && ($xinitiallabel ne '') && ($xinitiallabel ne 'start')) {
                    965:       $li=&array_index($xmin,$xmax,$xinitial);
                    966:       $Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel}=$li;
                    967:    }
                    968:    if (($xfinal ne '') && ($xfinallabel ne '') && ($xfinallabel ne 'end')) {
                    969:       $lh=&array_index($xmin,$xmax,$xfinal);
                    970:       $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$lh;
1.25      www       971:    }
1.31      www       972: # if the label is defined, use it
1.25      www       973:    if (defined($Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel})) {
1.35      www       974:       &addlog("Using lower label $xinitiallabel");
1.30      www       975:       $li=$Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel};
                    976:    } else {
                    977:       $li=&array_index($xmin,$xmax,$xinitial);
1.25      www       978:    }
1.31      www       979:    unless ($findupper) {
                    980:       if (defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel})) {
1.35      www       981:          &addlog("Using upper label $xfinallabel");
1.33      www       982:          $lh=$Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}-1;
1.31      www       983:       } else {
                    984:          $lh=&array_index($xmin,$xmax,$xfinal);
                    985:       }
1.25      www       986:    }
                    987: # Basic sanity checks
1.30      www       988:    if ($li<0) { $li=0; }
                    989:    if ($lh>400) { $lh=400; }
1.38      www       990:    if (($li>$lh) || (!defined($lh))) {
1.30      www       991:        $lh=$li;
1.25      www       992:    }
1.31      www       993: 
1.35      www       994:    &addlog("Boundaries: x=".&actualval($li,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$li]."; index $li)) to x=".
                    995:                             &actualval($lh,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$lh]."; index $lh))");
                    996:    if ($findupper) {
                    997:       &addlog("Looking for label $xfinallabel");
                    998:    }
1.33      www       999:    my $tol=$percent*($ymax-$ymin)/100;
                   1000:    if ($xmax>$xmin) {
                   1001:       if ($derivative==2) {
                   1002:          $tol=4.*$tol/($xmax-$xmin);
                   1003:       } elsif ($derivative==1) {
                   1004:          $tol=2.*$tol/($xmax-$xmin);
1.42      www      1005:       } elsif ($derivative==-1) {
                   1006:          $tol=$tol*($xmax-$xmin)/2.;
1.33      www      1007:       }
1.27      www      1008:    }
1.42      www      1009:    my $integral=0;
                   1010:    my $binwidth=($xmax-$xmin)/400.;
                   1011:    if (($derivative<0) && (!$findupper)) {
                   1012: # definite integral, calculate over whole length
                   1013:      &addlog("Calculating definite integral");
                   1014:      for (my $i=$li; $i<=$lh; $i++) {
                   1015:         $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
                   1016:      }
                   1017:      unless (&compare_rel($relationship,$value,$integral,$tol)) {
                   1018:         &addlog("Actual integral ".(defined($integral)?$integral:'undef').", expected $value, tolerance $tol");
                   1019:         &addlog("Rule $label failed.");
                   1020:         my $hintlabel=$label;
                   1021:         $hintlabel=~s/^R//;
                   1022:         push(@Apache::functionplotresponse::failedrules,$hintlabel);
                   1023:         &addlog("Set hint condition $hintlabel");
                   1024:         return 0;
                   1025:      } 
                   1026:    } else {
                   1027:      for (my $i=$li; $i<=$lh; $i++) {
1.25      www      1028:         my $val;
                   1029:         if ($derivative==2) {
1.27      www      1030:            $val=$Apache::functionplotresponse::d2funcdx2[$i];
1.25      www      1031:         } elsif ($derivative==1) {
1.27      www      1032:            $val=$Apache::functionplotresponse::dfuncdx[$i];
1.42      www      1033:         } elsif ($derivative==-1) {
                   1034:            $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
                   1035:            $val=$integral;      
1.25      www      1036:         } else {
1.27      www      1037:            $val=$Apache::functionplotresponse::func[$i];
1.25      www      1038:         }
1.31      www      1039:         unless (&compare_rel($relationship,$value,$val,$tol)) { 
1.37      www      1040:            &addlog("Actual value ".(defined($val)?$val:'undef').", expected $value, tolerance $tol");
1.35      www      1041:            &addlog("Condition not fulfilled at x=".&actualval($i,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$i]."; index $i)");
1.31      www      1042:            if (($findupper) && ($i>$li)) {
1.49    ! www      1043: # Check lengths
        !          1044:               unless (&checklength($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
        !          1045: # Successfully found a new label, set it
1.31      www      1046:               $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$i;
1.35      www      1047:               &addlog("Rule $label passed, setting label $xfinallabel");
1.31      www      1048:               return 1;
                   1049:            } else {
1.35      www      1050:               &addlog("Rule $label failed.");
1.49    ! www      1051:               &setfailed($label);
1.31      www      1052:               return 0; 
                   1053:            }
                   1054:         }
1.42      www      1055:      }
1.25      www      1056:    }
1.49    ! www      1057: # Corner case where this makes sense: using start or stop as defined labels
        !          1058:    unless (&checklength($lh,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
1.35      www      1059:    &addlog("Rule $label passed.");
1.27      www      1060:    return 1;
1.24      www      1061: }
                   1062: 
1.49    ! www      1063: #
        !          1064: # check for minimum and maximum lengths
        !          1065: #
        !          1066: 
        !          1067: sub checklength {
        !          1068:     my ($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)=@_;
        !          1069:     unless (($minimumlength) || ($maximumlength)) { return 1; }
        !          1070:     my $length=&actualval($i,$xmin,$xmax)-&actualval($li,$xmin,$xmax);
        !          1071:     if ($minimumlength) {
        !          1072:        if ($length<$minimumlength) {
        !          1073:           &addlog("Rule $label failed, actual length $length, minimum length $minimumlength");
        !          1074:           &setfailed($label);
        !          1075:           return 0;
        !          1076:        }
        !          1077:     }
        !          1078:     if ($maximumlength) {
        !          1079:        if ($length>$maximumlength) {
        !          1080:           &addlog("Rule $label failed, actual length $length, maximum length $maximumlength");
        !          1081:           &setfailed($label);
        !          1082:           return 0;
        !          1083:        }
        !          1084:     }
        !          1085:     return 1;
        !          1086: }
        !          1087: 
        !          1088: sub setfailed {
        !          1089:    my ($label)=@_;
        !          1090:    my $hintlabel=$label;
        !          1091:    $hintlabel=~s/^R//;
        !          1092:    push(@Apache::functionplotresponse::failedrules,$hintlabel);
        !          1093:    &addlog("Set hint condition $hintlabel");
        !          1094: }
        !          1095: 
1.37      www      1096: sub start_functionplotruleset {
                   1097:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1098:    if ($target eq 'edit') {
                   1099:       return &Apache::edit::start_table($token).
                   1100:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Rule Set').'</span></td>'
                   1101:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
                   1102:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
                   1103:         &Apache::edit::insertlist($target,$token)
                   1104:        .'</span></td>'
                   1105:        ."<td>&nbsp;"
                   1106:        .&Apache::edit::end_row()
                   1107:        .&Apache::edit::start_spanning_row()
                   1108:        ."\n";
                   1109:    }
                   1110: }
1.3       www      1111: 
1.37      www      1112: sub end_functionplotruleset {
                   1113:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                   1114:     my $id=$Apache::inputtags::response[-1];
                   1115:     my $partid=$Apache::inputtags::part;
                   1116:     my $internalid = $partid.'_'.$id;
                   1117: 
                   1118:     if ($target eq 'edit' ) {
                   1119:         return &Apache::edit::end_table();
                   1120:     }  elsif ($target eq 'grade'
1.10      www      1121:          && &Apache::response::submitted()
                   1122:          && $Apache::lonhomework::type ne 'exam') {
1.12      www      1123: #
                   1124: # Actually grade
                   1125: #
1.41      www      1126:     my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
1.27      www      1127: 
1.24      www      1128:         my $ad='';
1.30      www      1129:         undef  %Apache::functionplotresponse::functionplotrulelabels;
1.35      www      1130:         $Apache::functionplotresponse::ruleslog='';
1.30      www      1131:         $Apache::functionplotresponse::functionplotrulelabels{'start'}=400;
                   1132:         $Apache::functionplotresponse::functionplotrulelabels{'end'}=0;
1.18      www      1133:         if (&populate_arrays($internalid,$xmin,$xmax) eq 'no_func') {
1.21      www      1134:            $ad='NOT_FUNCTION';
1.18      www      1135:         } else {
1.35      www      1136:            &addlog("Start of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'start'},$xmin,$xmax)." (index ".
                   1137:                                         $Apache::functionplotresponse::functionplotrulelabels{'start'}.")");
                   1138:            &addlog("End of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'end'},$xmin,$xmax)." (index ".
                   1139:                                         $Apache::functionplotresponse::functionplotrulelabels{'end'}.")");
                   1140: 
1.24      www      1141: # We have a function that we can actually grade, go through the spline rules.
1.25      www      1142:            foreach my $rule (@Apache::functionplotresponse::functionplotrules) {
1.33      www      1143:               unless (&functionplotrulecheck($rule,$xmin,$xmax,$ymin,$ymax)) {
1.24      www      1144:                  $ad='INCORRECT';
                   1145:                  last;
                   1146:               }
                   1147:            }
                   1148: # If it's not wrong, it's correct 
                   1149:            unless ($ad) { $ad='EXACT_ANS' };
1.18      www      1150:         }
1.37      www      1151:         &addlog("Set hint conditions: ".join(",",@Apache::functionplotresponse::failedrules));
                   1152:         &addlog("Assigned award detail: $ad");
                   1153: # Store for later to be assigned at end_functionplotresponse
                   1154:         $Apache::functionplotresponse::awarddetail=$ad;
                   1155:      }
                   1156: }
                   1157: 
                   1158: 
                   1159: sub end_functionplotresponse {
                   1160:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1161:   &Apache::response::end_response;
                   1162: 
                   1163:   my $result;
                   1164:   my $id=$Apache::inputtags::response[-1];
                   1165:   my $partid=$Apache::inputtags::part;
                   1166:   my $internalid = $partid.'_'.$id;
1.20      www      1167: 
1.37      www      1168:     if ($target eq 'edit') { $result=&Apache::edit::end_table(); }
                   1169:     if ($target eq 'grade'
                   1170:          && &Apache::response::submitted()
                   1171:          && $Apache::lonhomework::type eq 'exam') {
                   1172: 
                   1173:         &Apache::response::scored_response($partid,$id);
                   1174: 
                   1175:     } elsif ($target eq 'grade'
                   1176:          && &Apache::response::submitted()
                   1177:          && $Apache::lonhomework::type ne 'exam') {
                   1178:         my ($response,%coords)=&get_answer_from_form_fields($internalid);
                   1179:         $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
                   1180:         my %previous=&Apache::response::check_for_previous($response,$partid,$id);
                   1181: #
                   1182: # Assign grade
                   1183: #
                   1184:         my $ad=$Apache::functionplotresponse::awarddetail;
1.12      www      1185: #
                   1186: # Store grading info
                   1187: #
                   1188:         $Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
                   1189:         &Apache::response::handle_previous(\%previous,$ad);
1.10      www      1190:    } elsif ($target eq 'web') {
1.37      www      1191:         undef @Apache::functionplotresponse::failedrules;
                   1192:    }
                   1193:    return $result;
                   1194: }
                   1195: 
                   1196: sub end_functionplotelements {
                   1197:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                   1198:   my $result='';
                   1199:   my $id=$Apache::inputtags::response[-1];
                   1200:   my $partid=$Apache::inputtags::part;
                   1201:   my $internalid = $partid.'_'.$id;
                   1202:   if ($target eq 'edit' ) {
                   1203:      $result=&Apache::edit::end_table();
                   1204:   } elsif ($target eq 'web') {
1.47      www      1205:      my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
                   1206: 
                   1207: # Are we in show answer mode?
                   1208:      my $showanswer=&Apache::response::show_answer();
                   1209:      if ($showanswer) {
                   1210: # Render answerdisplay
                   1211:         my $answerdisplay=&Apache::lonxml::get_param('answerdisplay',$parstack,$safeeval,-2);
                   1212:         if ($answerdisplay=~/\S/s) {
                   1213:            foreach my $plot (split(/\s*\,\s*/,$answerdisplay)) {
                   1214:               my ($func,$xl,$xh)=split(/\s*\:\s*/,$plot);
                   1215:               if ((!defined($xl)) || ($xl eq '')) { $xl=$xmin; }
                   1216:               if ((!defined($xh)) || ($xh eq '')) { $xh=$xmax; }
                   1217:               $result.=&plot_script($internalid,$func,1,'','00aa00',$xl,$xh,6);
                   1218:            }
                   1219:         }
                   1220:      }
1.48      www      1221:      my $fixed=0;
                   1222:      if (($showanswer) || (&Apache::response::check_status()>=2)) { $fixed=1; }
1.6       www      1223: # Now is the time to render all of the stored splines
                   1224:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
1.48      www      1225:         $result.=&generate_spline($internalid,$label,$xmin,$xmax,$ymin,$ymax,$fixed);
1.6       www      1226:      }
1.5       www      1227: # close the init script
1.3       www      1228:      $result.=&end_init_script();
1.17      www      1229: # register all splines in this response 
                   1230:      $result.='<input type="hidden" name="HWVAL_AllSplines_'.$internalid.'" value="'.
                   1231:                  join(',',keys(%Apache::functionplotresponse::splineorder)).'" />'."\n";
                   1232:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
                   1233:         $result.='<input type="hidden" name="HWVAL_SplineOrder_'.$internalid.'_'.$label.'" value="'.
                   1234:                  $Apache::functionplotresponse::splineorder{$label}.'" />'."\n";
                   1235:      }
1.9       www      1236: # generate the input fields
                   1237:      $result.=$Apache::functionplotresponse::inputfields;
1.5       www      1238: # actually start the <applet>-tag
1.3       www      1239:      $result.=&geogebra_startcode($internalid);
1.5       www      1240: # load the spline bytecode
1.3       www      1241:      $result.=&geogebra_spline_program();
1.5       www      1242: # set default parameters
1.3       www      1243:      $result.=&geogebra_default_parameters($internalid);
1.5       www      1244: # close the <applet>-tag
1.1       www      1245:      $result.=&geogebra_endcode();
                   1246:   }
                   1247:   return $result;
                   1248: }
                   1249: 
1.41      www      1250: sub boundaries {
                   1251:    my ($parstack,$safeeval,$level)=@_;
                   1252:    my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval,$level);
                   1253:    $xmin=(defined($xmin)?$xmin:-10);
                   1254:    my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval,$level);
                   1255:    $xmax=(defined($xmax)?$xmax:10);
                   1256:    my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval,$level);
                   1257:    $ymin=(defined($ymin)?$ymin:-10);
                   1258:    my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval,$level);
                   1259:    $ymax=(defined($ymax)?$ymax:10);
                   1260:    if ($xmax<=$xmin) {
                   1261:       $xmax=$xmin+20;
                   1262:    }
                   1263:    if ($ymax<=$ymin) {
                   1264:       $ymax=$ymin+20;
                   1265:    }
                   1266:    return ($xmin,$xmax,$ymin,$ymax);
                   1267: }
                   1268: 
1.37      www      1269: sub start_functionplotelements {
                   1270:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1271:    my $result='';
                   1272:    my $id=$Apache::inputtags::response[-1];
                   1273:    my $partid=$Apache::inputtags::part;
                   1274:    my $internalid = $partid.'_'.$id;
                   1275: 
                   1276:    if ($target eq 'edit') {
                   1277:       return &Apache::edit::start_table($token).
                   1278:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Elements').'</span></td>'
                   1279:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
                   1280:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
                   1281:         &Apache::edit::insertlist($target,$token)
                   1282:        .'</span></td>'
                   1283:        ."<td>&nbsp;"
                   1284:        .&Apache::edit::end_row()
                   1285:        .&Apache::edit::start_spanning_row()
                   1286:        ."\n";
                   1287:    } elsif ($target eq 'web') {
1.41      www      1288:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
1.37      www      1289:       my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1290:       my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1291:       my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1292:       my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval,-2);
                   1293:       my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval,-2);
                   1294: 
                   1295: 
                   1296: # paste in the update routine to receive stuff back from the applet
                   1297:      $result.=&update_script($internalid);
                   1298: # start the initscript for this applet
                   1299:      $result.=&start_init_script($internalid);
                   1300: # put the axis commands inside
                   1301:      $result.=&axes_script($internalid,$xmin,$xmax,$ymin,$ymax,$xaxisvisible,$yaxisvisible,$gridvisible);
1.45      www      1302:      $result.=&axes_label($internalid,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel);
1.37      www      1303: # init script is left open
                   1304:   }
                   1305:   return $result;
                   1306: }
                   1307: 
1.1       www      1308: 1;
                   1309: 
                   1310: __END__
                   1311:  
                   1312: =head1 NAME
                   1313: 
                   1314: Apache::functionplotresponse.pm;
                   1315: 
                   1316: =head1 SYNOPSIS
                   1317: 
                   1318: Handles tags associated with accepting function plots.
                   1319: 
                   1320: This is part of the LearningOnline Network with CAPA project
                   1321: described at http://www.lon-capa.org.
                   1322: 
                   1323: =head1 HANDLER SUBROUTINE
                   1324: 
                   1325: start_functionplotresponse()
                   1326: 
                   1327: =head1 OTHER SUBROUTINES
                   1328: 
                   1329: =over
                   1330: 
                   1331: =item end_functionplotresponse()
                   1332: 
                   1333: =back
                   1334: 
                   1335: =cut

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