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

1.1       www         1: # LearningOnline Network with CAPA
1.70      www         2: # Functionplot responses
1.1       www         3: #
1.76    ! www         4: # $Id: functionplotresponse.pm,v 1.75 2011/11/19 13:45:36 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.65      www        34: use Apache::run;
1.36      www        35:  
1.1       www        36: BEGIN {
1.37      www        37:   &Apache::lonxml::register('Apache::functionplotresponse',('functionplotresponse','backgroundplot','spline',
1.76    ! www        38:                                                             'plotobject','plotvector','functionplotvectorrule','functionplotvectorsumrule',
1.37      www        39:                                                             'functionplotrule','functionplotruleset',
                     40:                                                             'functionplotelements'));
1.1       www        41: }
                     42: 
1.5       www        43: #
                     44: # There can be a number of applets on a page, each called ggbApplet_$id, 
                     45: # where $id is the "_"-concatenated part and responseid
                     46: #
                     47: 
1.1       www        48: sub geogebra_startcode {
1.3       www        49:     my ($id)=@_;
1.1       www        50:     return (<<ENDSTARTCODE);
1.3       www        51: <applet name="ggbApplet_$id" code="geogebra.GeoGebraApplet" archive="geogebra.jar"
1.40      www        52:          codebase="/adm/geogebra/"  width="722" height="447" MAYSCRIPT>
1.1       www        53:        <param name="java_arguments" value="-Xmx512m -Djnlp.packEnabled=true"/>
                     54: ENDSTARTCODE
                     55: }
                     56: 
                     57: sub geogebra_endcode {
1.2       www        58:     return &Apache::lonhtmlcommon::java_not_enabled()."</applet>\n";
                     59: }
                     60: 
1.5       www        61: #
                     62: # This is the internal GeoGebra bytecode which defines the spline functions
                     63: #
1.2       www        64: sub geogebra_spline_program {
                     65:     return (<<ENDSPLINEPROGRAM);
1.57      www        66: <param name="ggbBase64" value="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"/>
1.2       www        67: ENDSPLINEPROGRAM
                     68: }
                     69: 
1.5       www        70: #
                     71: # The standard set of parameters inside <applet>
                     72: #
1.2       www        73: sub geogebra_default_parameters {
1.3       www        74:    my ($id)=@_;
1.2       www        75:    return(<<ENDDEFAULTPARAMETERS);
                     76:         <param name="image" value="/adm/lonIcons/lonanim.gif"  />
                     77:         <param name="boxborder" value="false"  />
                     78:         <param name="centerimage" value="true"  />
1.62      www        79: 	<param name="cache_archive" value="geogebra.jar, geogebra_main.jar, geogebra_gui.jar, geogebra_cas.jar, geogebra_export.jar, geogebra_algos.jar, geogebra_javascript.jar, geogebra_properties.jar, jlatexmath.jar, jlm_cyrillic.jar, jlm_greek.jar" />
1.69      www        80: 	<param name="cache_version" value="4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0" />
1.2       www        81:         <param name="framePossible" value="false" />
                     82: 
                     83:         <param name="showResetIcon" value="false" />
                     84:         <param name="showAnimationButton" value="false" />
                     85:         <param name="enableRightClick" value="false" />
                     86:         <param name="errorDialogsActive" value="true" />
                     87:         <param name="enableLabelDrags" value="false" />
                     88:         <param name="showMenuBar" value="false" />
                     89:         <param name="showToolBar" value="false" />
                     90:         <param name="showToolBarHelp" value="false" />
                     91:         <param name="showAlgebraInput" value="false" />
                     92:         <param name="enableShiftDragZoom" value="false" />
                     93:         <param name="allowRescaling" value="false" />
                     94:         <param name="enableLabelDrags" value="false" />
1.3       www        95:         <param name="ggbOnInitParam" value="applet_$id" />
1.2       www        96: ENDDEFAULTPARAMETERS
1.1       www        97: }
                     98: 
1.5       www        99: #
                    100: # This subroutine is called by LON-CAPA at </problem>
                    101: # Each applet on the page will call function ggbOnInit when it is done loading
                    102: # This function in turn will call the respective function registered by start_init_script
                    103: # Which one of the registered functions is called is determined by ggbOnInitParam, which GeoGebra passes to ggbOnInit
                    104: #
                    105: 
1.3       www       106: sub init_script {
1.16      www       107:    if ($#Apache::functionplotresponse::callscripts>=0) {
                    108:       my $script='';
                    109:       foreach my $id (@Apache::functionplotresponse::callscripts) {
                    110:           $script.="if (param=='applet_$id') { loaded_$id=true; }\n";
                    111:       }
                    112:       $script.="if (".join(' && ',map { "loaded_$_" } (@Apache::functionplotresponse::callscripts)).
1.52      www       113:                ") { setTimeout('ggbInitAll()',200) }";
1.16      www       114:       my $calls=join("\n",map { "ggbInit_$_();" } (@Apache::functionplotresponse::callscripts)); 
1.3       www       115:       return (<<ENDGGBINIT);
                    116: <script type="text/javascript">
                    117: // <![CDATA[
1.16      www       118: // Function that each applet will call when loaded
                    119: // It will pass "its" parameter
                    120: // Set flags for when an applet is loaded, wait till all are loaded, and then some
1.3       www       121: function ggbOnInit(param) {
1.16      www       122: $script
                    123: }
                    124: function ggbInitAll() {
1.17      www       125: $calls
1.3       www       126: }
                    127: // ]]>
                    128: </script>
                    129: ENDGGBINIT
                    130:    }
                    131: }
                    132: 
1.5       www       133: #
                    134: # Each Geogebra applet is supposed to call this when parameters change
1.10      www       135: # Changes the hidden fields on the web page
1.5       www       136: #
                    137: sub update_script {
                    138:     my ($id)=@_;
                    139:     return (<<ENDUPDATESCRIPT);
                    140: <script type="text/javascript">
                    141: // <![CDATA[
                    142: function updatePointCoordinates_$id(coordinateName) {
                    143:             var x = document.ggbApplet_$id.getXcoord(coordinateName);
                    144:             var y = document.ggbApplet_$id.getYcoord(coordinateName);
1.9       www       145:             document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_x"].value = x;
                    146:             document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_y"].value = y;
1.5       www       147:         }
                    148: // ]]>
                    149: </script>
                    150: ENDUPDATESCRIPT
                    151: }
                    152: 
                    153: #
                    154: # Register the above update-handler for a variable
                    155: #
                    156: 
                    157: sub update_register {
                    158:    my ($id,$variable)=@_;
1.6       www       159:    return "document.ggbApplet_$id.registerObjectUpdateListener('$variable','updatePointCoordinates_$id');\n";
                    160: }
                    161: 
                    162: #
1.40      www       163: # Set a point coordinate variable
1.6       www       164: #
1.40      www       165: sub set_point_coordinate {
1.48      www       166:    my ($id,$variable,$x,$y,$fixed)=@_;
                    167:    my $mult=($fixed?'a*':'');
1.68      www       168: # Get rid of wild exponents, make sure it's a number
                    169:    $x=1.*$x;
                    170:    $y=1.*$y;
                    171: # GeoGebra does not understand "E"
                    172:    $x=~s/[e|E]/\*10\^/;
                    173:    $x=~s/\+//;
                    174:    $y=~s/[e|E]/\*10\^/;
                    175:    $y=~s/\+//;
1.6       www       176:    return (<<ENDSETVARIABLE);
1.48      www       177: document.ggbApplet_$id.evalCommand("a=1");
                    178: document.ggbApplet_$id.evalCommand("$variable=$mult($x,$y)");
1.40      www       179: document.ggbApplet_$id.setLabelVisible("$variable",false);
1.6       www       180: ENDSETVARIABLE
                    181: }
                    182: 
                    183: #
1.40      www       184: # Set a slope coordinate variable
                    185: #
                    186: sub set_slope_coordinate {
1.48      www       187:    my ($id,$variable,$xrel,$yrel,$xmin,$xmax,$ymin,$ymax,$pointname,$fixed)=@_;
1.40      www       188:    my $xvariable=$variable.'x';
                    189:    my $yvariable=$variable.'y';
                    190:    my $domain=$xmax-$xmin;
                    191:    my $range=$ymax-$ymin;
                    192:    my $xinterval=$domain/100.;
                    193:    my $yinterval=$range/200.;
1.48      www       194:    my $mult=($fixed?'a*':'');
1.40      www       195:    return (<<ENDSETSVARIABLE);
1.48      www       196: document.ggbApplet_$id.evalCommand("a=1");
1.51      www       197: document.ggbApplet_$id.evalCommand("$xvariable=Slider[$xinterval,$domain,$xinterval]");
1.40      www       198: document.ggbApplet_$id.setVisible("$xvariable", false);
                    199: document.ggbApplet_$id.evalCommand("$xvariable=$xrel");
                    200: document.ggbApplet_$id.evalCommand("$yvariable=Slider[-$range,$range,$yinterval]");
                    201: document.ggbApplet_$id.setVisible("$yvariable", false);
                    202: document.ggbApplet_$id.evalCommand("$yvariable=$yrel");
1.48      www       203: document.ggbApplet_$id.evalCommand("$variable=$mult($xvariable+x($pointname),$yvariable+y($pointname))");
1.40      www       204: document.ggbApplet_$id.setLabelVisible("$variable", false);
                    205: ENDSETSVARIABLE
                    206: }
                    207: 
                    208: #
1.9       www       209: # Input field name for a coordinate variable
                    210: #
                    211: 
                    212: sub field_name {
                    213:     my ($id,$variable,$name)=@_;
                    214:     return "HWVAL_$id\_$variable\_$name";
                    215: }
                    216: 
                    217: #
                    218: # Generate an input field for a coordinate variable
                    219: #
                    220: 
                    221: sub generate_input_field {
                    222:     my ($id,$variable,$x,$y)=@_;
                    223:     $Apache::functionplotresponse::inputfields.=
                    224:        "<input type='hidden' name='".&field_name($id,$variable,'x')."' value='$x' />\n".
                    225:        "<input type='hidden' name='".&field_name($id,$variable,'y')."' value='$y' />\n";
                    226: }
                    227: 
                    228: #
1.40      www       229: # Initialize a new point coordinate variable at set a listener on it
1.6       www       230: #
1.40      www       231: sub new_point_coordinate {
1.48      www       232:     my ($id,$variable,$x,$y,$fixed)=@_;
1.11      www       233:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
1.10      www       234:        $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
                    235:     }
1.11      www       236:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
1.10      www       237:        $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
                    238:     }
1.9       www       239:     &generate_input_field($id,$variable,$x,$y);
1.48      www       240:     return &set_point_coordinate($id,$variable,$x,$y,$fixed).&update_register($id,$variable);
1.40      www       241: }
                    242: 
                    243: #
                    244: # Initialize a new slope coordinate variable at set a listener on it
                    245: #
                    246: sub new_slope_coordinate {
1.48      www       247:     my ($id,$variable,$x,$y,$pointname,$xp,$yp,$xmin,$xmax,$ymin,$ymax,$fixed)=@_;
1.40      www       248: #
                    249: # $variable: name of the slope point
                    250: # $x, $y: coordinates of the slope point
                    251: # $pointname: name of the associated point point
                    252: # $xp $yp: coordinates of the point point
                    253: #
                    254:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
                    255:        $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
                    256:     }
                    257:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
                    258:        $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
                    259:     }
                    260:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$pointname,'x')})) {
                    261:        $xp=$Apache::functionplotresponse::previous{&field_name($id,$pointname,'x')};
                    262:     }
                    263:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$pointname,'y')})) {
                    264:        $yp=$Apache::functionplotresponse::previous{&field_name($id,$pointname,'y')};
                    265:     }
                    266: 
                    267:     &generate_input_field($id,$variable,$x,$y);
                    268:     my $xrel=$x-$xp;
                    269:     my $yrel=$y-$yp;
1.48      www       270:     return &set_slope_coordinate($id,$variable,$xrel,$yrel,$xmin,$xmax,$ymin,$ymax,$pointname,$fixed).&update_register($id,$variable);
1.5       www       271: }
                    272: 
                    273: #
                    274: # This registers the init-function call for ggbOnInit, which LON-CAPA will place at </problem>
                    275: # It then starts the right headers
                    276: #
1.3       www       277: sub start_init_script {
                    278:     my ($id)=@_;
1.16      www       279: # Add id to the list of ggbInit_$id functions that need to be called
                    280:     push(@Apache::functionplotresponse::callscripts,$id);
1.5       www       281: # ... and open this function
1.3       www       282:     return (<<ENDSTARTINIT);
                    283: <script type="text/javascript">
                    284: // <![CDATA[
1.5       www       285: // variable that will eventually be passed back to the server
                    286: var coordinateMap_$id = [];
1.16      www       287: // flag for not loaded yet
                    288: var loaded_$id=false;
1.5       www       289: // Init-function for applet
1.3       www       290: function ggbInit_$id() {
                    291: ENDSTARTINIT
                    292: }
                    293: 
1.5       www       294: #
                    295: # This sets the axes inside ggbInit_$id
                    296: #
                    297: 
1.4       www       298: sub axes_script {
                    299:     my ($id,$xmin,$xmax,$ymin,$ymax,$xvisible,$yvisible,$gvisible)=@_;
                    300:     return (<<ENDAXESSCRIPT);
                    301:             // changes (xmin, xmax, ymin, ymax)
                    302:             document.ggbApplet_$id.setCoordSystem($xmin,$xmax,$ymin,$ymax);
                    303: 
                    304:             // makes the (x,y) axis (in)visible
                    305:             document.ggbApplet_$id.setAxesVisible($xvisible,$yvisible);
                    306:             // makes the grid (in)visible
                    307:             document.ggbApplet_$id.setGridVisible($gvisible);
                    308: ENDAXESSCRIPT
                    309: }
                    310: 
1.14      www       311: sub axes_label {
1.45      www       312:     my ($id,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel)=@_;
1.14      www       313:     unless ($xlabel || $ylabel) { return ''; }
                    314:     my $return='document.ggbApplet_'.$id.'.evalCommand("topRight=Corner[3]");';
                    315:     if ($xlabel) {
1.45      www       316:       if (($ymin<0) && ($ymax>0)) {
1.14      www       317:        $return.=(<<ENDXAXISLABELSCRIPT);
                    318: document.ggbApplet_$id.evalCommand("Xlabel=(x(topRight)-AxisStepX[],AxisStepY[]/6)");
                    319: document.ggbApplet_$id.setVisible("Xlabel",false);
                    320: document.ggbApplet_$id.evalCommand("Text[\\"$xlabel\\", Xlabel]");
                    321: ENDXAXISLABELSCRIPT
1.45      www       322:       } else {
                    323:        $return.=(<<ENDXOFFAXISLABEL);
                    324: document.ggbApplet_$id.evalCommand("LowerRight=Corner[2]");
                    325: document.ggbApplet_$id.evalCommand("Text[\\"$xlabel\\", (x(LowerRight) - AxisStepX[], y(LowerRight) + AxisStepY[] / 2)]");
                    326: ENDXOFFAXISLABEL
                    327:       }
1.14      www       328:     }
                    329:     if ($ylabel) {
1.45      www       330:       if (($xmin<0) && ($xmax>0)) {
1.14      www       331:        $return.=(<<ENDYAXISLABELSCRIPT);
                    332: document.ggbApplet_$id.evalCommand("Ylabel=(AxisStepX[]/6,y(topRight)-AxisStepY[]/3)");
                    333: document.ggbApplet_$id.setVisible("Ylabel",false);
                    334: document.ggbApplet_$id.evalCommand("Text[\\"$ylabel\\", Ylabel]");
                    335: ENDYAXISLABELSCRIPT
1.45      www       336:       } else {
                    337:        $return.=(<<ENDYOFFAXISLABEL);
                    338: document.ggbApplet_$id.evalCommand("UpperLeft=Corner[4]");
                    339: document.ggbApplet_$id.evalCommand("Text[\\"$ylabel\\", (x(UpperLeft) + AxisStepX[] / 5, y(UpperLeft) - AxisStepY[] / 1.8)]");
                    340: ENDYOFFAXISLABEL
                    341:       }
1.14      www       342:     }
                    343:     return $return;
                    344: }
                    345: 
1.58      www       346: #
                    347: # Subroutine to produce background and answer plots
                    348: #
                    349: 
1.4       www       350: sub plot_script {
1.47      www       351:    my ($id,$function,$fixed,$label,$color,$xmin,$xmax,$thickness)=@_;
1.41      www       352:    $label=~s/\W//g;
                    353:    if (($label) && ($label!~/^[A-Za-z]/)) {
                    354:       $label='C'.$label;
                    355:    }
                    356:    my $visible=0;
                    357:    if ($label) {
                    358:       $visible="1";
                    359:    } else {
                    360:       $Apache::functionplotresponse::counter++;
                    361:       $label='C'.$Apache::functionplotresponse::counter;
                    362:    }
1.46      www       363:    my $rc=0;
                    364:    my $gc=0;
                    365:    my $bc=0;
                    366:    if ($color) {
                    367:       my ($rh,$gh,$bh)=($color=~/(..)(..)(..)/);
                    368:       $rc=hex($rh);
                    369:       $gc=hex($gh);
                    370:       $bc=hex($bh);
                    371:    }
1.6       www       372:    if ($fixed) {
1.43      www       373:       return "document.ggbApplet_$id.evalCommand('$label=Function[$function,$xmin,$xmax]');\n".
1.46      www       374:              ($visible?'':"document.ggbApplet_$id.setLabelVisible('$label', false);\n").
1.47      www       375:              ($color?"document.ggbApplet_$id.setColor('$label',$rc,$gc,$bc);\n":'').
                    376:              ($thickness?"document.ggbApplet_$id.setLineThickness('$label',$thickness);\n":'');
1.6       www       377:    } else {
1.46      www       378:        return "document.ggbApplet_$id.evalCommand('y=$function');\n";
1.6       www       379:    }
1.4       www       380: }
                    381: 
1.5       www       382: #
1.70      www       383: # Subroutine to produce objects
                    384: #
                    385: 
                    386: sub plotobject_script {
                    387:    my ($id,$label,$x,$y)=@_;
                    388:    unless ($label) {
                    389:       $Apache::functionplotresponse::counter++;
                    390:       $label='O'.$Apache::functionplotresponse::counter;
                    391:    }
                    392:    return "document.ggbApplet_$id.evalCommand('a=1');\n".
                    393:           "document.ggbApplet_$id.setVisible('a', false);\n".
                    394:           "document.ggbApplet_$id.setLabelVisible('a', false);\n".
                    395:           "document.ggbApplet_$id.evalCommand('$label=a*($x,$y)');\n".
                    396:           "document.ggbApplet_$id.setVisible('$label', true);\n".
                    397:           "document.ggbApplet_$id.setLabelVisible('$label', true);\n";
                    398: }
                    399: 
                    400: #
                    401: # Subroutine to produce vectors
                    402: #
                    403: 
                    404: sub plotvector_script {
1.72      www       405:    my ($id,$label,$xs,$ys,$xe,$ye,$xmin,$xmax)=@_;
1.70      www       406:    unless ($label) {
                    407:       $Apache::functionplotresponse::counter++;
                    408:       $label='V'.$Apache::functionplotresponse::counter;
                    409:    }
1.71      www       410:    my $startlabel=$label.'Start';
                    411:    my $endlabel=$label.'End';
                    412:    my $pointlabel=$label.'Point';
1.72      www       413:    my $pointx=2.*($xmax-$xmin)+$xmax;
1.71      www       414:    my $anglelabel=$label.'Angle';
1.74      www       415:    return 
                    416:        &new_point_coordinate($id,$startlabel,$xs,$ys,0).
                    417:        &new_point_coordinate($id,$endlabel,$xe,$ye,0).
                    418:        (<<ENDVECTOR);
1.71      www       419: document.ggbApplet_$id.evalCommand("$label=Vector[$startlabel,$endlabel]");
                    420: document.ggbApplet_$id.setLabelVisible("$label",true);
                    421: document.ggbApplet_$id.setLineThickness("$label",8);
1.72      www       422: document.ggbApplet_$id.evalCommand("$pointlabel=($pointx,y($startlabel))");
                    423: document.ggbApplet_$id.evalCommand("$anglelabel=Angle[$pointlabel,$startlabel,$endlabel]");
                    424: document.ggbApplet_$id.setLabelVisible("$anglelabel",true);
                    425: document.ggbApplet_$id.setLabelStyle("$anglelabel",VALUE=2);
1.70      www       426: ENDVECTOR
                    427: }
                    428: 
                    429: #
1.58      www       430: # Answer spline display
                    431: # 
                    432: # points: x,y,slope_x,slope_y
                    433: 
                    434: sub answer_spline_script {
                    435:    my ($id,@points)=@_;
                    436:    my $order=int(($#points+1)/4);
                    437:    if ($order<2) { $order=2; }
                    438:    if ($order>8) { $order=8; }
                    439:    $Apache::functionplotresponse::counter++;
1.60      www       440:    my $label='CSpline'.$Apache::functionplotresponse::counter;
1.59      www       441:    my $output='document.ggbApplet_'.$id.'.evalCommand("'.$label.'=Spline'.$order.'[';
                    442:    for (my $i=0;$i<=$#points;$i+=4) {
                    443:       $output.="($points[$i],$points[$i+1]),($points[$i+2],$points[$i+3]),";
                    444:    }
                    445:    $output=~s/\,$//;
                    446:    $output.=']");'."\n";
                    447:    for (my $i=2; $i<2*$order; $i+=2) {
1.61      www       448:        $output.='document.ggbApplet_'.$id.'.setColor("'.$label.'_'.($i>=10?'{':'').$i.($i>=10?'}':'').'",0,170,0);'."\n";
1.59      www       449:    }
1.60      www       450:    for (my $i=1; $i<2*$order; $i+=2) {
1.61      www       451:        $output.='document.ggbApplet_'.$id.'.setVisible("'.$label.'_'.($i>=10?'{':'').$i.($i>=10?'}':'').'",false);'."\n";
1.60      www       452:    }
                    453: 
1.59      www       454:    return $output;
1.58      www       455: }
                    456: 
                    457: #
1.7       www       458: # Subroutine that generates code for spline $label based on stored information
1.6       www       459: #
                    460: 
                    461: sub generate_spline {
1.48      www       462:    my ($id,$label,$xmin,$xmax,$ymin,$ymax,$fixed)=@_;
1.6       www       463:    my $result='';
1.7       www       464:    my $order=$Apache::functionplotresponse::splineorder{$label};
                    465:    my $x=$Apache::functionplotresponse::splineinitx{$label};
                    466:    my $y=$Apache::functionplotresponse::splineinity{$label};
                    467:    my $sx=$Apache::functionplotresponse::splinescalex{$label};
                    468:    my $sy=$Apache::functionplotresponse::splinescaley{$label};
                    469:    my @coords=();
                    470:    foreach my $i (1..$order) {
1.48      www       471:        $result.=&new_point_coordinate($id,$label.'P'.$i,$x,$y,$fixed);
1.40      www       472:        my $xp=$x;
1.8       www       473:        $x+=$sx/(2.*($order-1));
1.7       www       474:        push(@coords,$label.'P'.$i);
1.48      www       475:        $result.=&new_slope_coordinate($id,$label.'S'.$i,$x,$y+$sy,$label.'P'.$i,$xp,$y,$xmin,$xmax,$ymin,$ymax,$fixed);
1.8       www       476:        $x+=$sx/(2.*($order-1));
1.7       www       477:        push(@coords,$label.'S'.$i);
                    478:    }
                    479:    $result.='document.ggbApplet_'.$id.'.evalCommand("Spline'.$order.'['.join(',',@coords).']");'."\n";
1.6       www       480:    return $result;
                    481: }
1.70      www       482: 
                    483: #
                    484: # Object
                    485: #
                    486: 
                    487: sub start_plotobject {
                    488:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    489:    my $result='';
                    490:    my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
                    491:    my $x=&Apache::lonxml::get_param('x',$parstack,$safeeval);
                    492:    my $y=&Apache::lonxml::get_param('y',$parstack,$safeeval);
                    493:    my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
                    494:    $label=~s/\W//gs;
                    495:    $label=ucfirst($label);
                    496:    unless ($label) { $label="NewObject"; }
                    497:    if ($target eq 'web') {
                    498:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
                    499:       unless (defined($x)) { $x=$xmin; }
                    500:       unless (defined($y)) { $y=$ymin; }
                    501:       $result.=&plotobject_script($internalid,$label,$x,$y);
                    502:    } elsif ($target eq 'edit') {
                    503:         $result=&Apache::edit::tag_start($target,$token,'Plot Object').
                    504:              &Apache::edit::text_arg('Label on Plot:','label',
                    505:                                      $token,'16').
                    506:              &Apache::edit::text_arg('x:','x',
                    507:                                      $token,'8').
                    508:              &Apache::edit::text_arg('y:','y',
                    509:                                      $token,'8').
                    510:              &Apache::edit::end_row();
                    511:   } elsif ($target eq 'modified') {
1.76    ! www       512:     $env{'form.'.&Apache::edit::html_element_name('label')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('label')});
1.70      www       513:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,$safeeval,'label','x','y');
                    514:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    515:   }
                    516:   return $result;
                    517: }
                    518: 
                    519: sub end_plotobject {
                    520:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    521:    my $result='';
                    522:    if ($target eq 'edit') {
                    523:        $result=&Apache::edit::end_table();
                    524:    }
                    525:    return $result;
                    526: }
                    527: 
1.71      www       528: #
                    529: # Vector
                    530: #
                    531: 
                    532: sub start_plotvector {
                    533:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    534:    my $result='';
                    535:    my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
                    536:    my $tailx=&Apache::lonxml::get_param('tailx',$parstack,$safeeval);
                    537:    my $taily=&Apache::lonxml::get_param('taily',$parstack,$safeeval);
                    538:    my $tipx=&Apache::lonxml::get_param('tipx',$parstack,$safeeval);
                    539:    my $tipy=&Apache::lonxml::get_param('tipy',$parstack,$safeeval);
                    540: 
                    541:    my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
                    542:    $label=~s/\W//gs;
                    543:    $label=ucfirst($label);
                    544:    unless ($label) { $label="NewVector"; }
                    545:    if ($target eq 'web') {
                    546:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
                    547:       unless (defined($tailx)) { $tailx=$xmin; }
                    548:       unless (defined($taily)) { $taily=$ymin; }
                    549:       unless (defined($tipx)) { $tipx=$xmin; }
                    550:       unless (defined($tipy)) { $tipy=$ymin; }
1.72      www       551:       $result.=&plotvector_script($internalid,$label,$tailx,$taily,$tipx,$tipy,$xmin,$xmax);
1.71      www       552:    } elsif ($target eq 'edit') {
                    553:         $result=&Apache::edit::tag_start($target,$token,'Plot Vector').
                    554:              &Apache::edit::text_arg('Label on Plot:','label',
                    555:                                      $token,'16').
                    556:              &Apache::edit::text_arg('Tail x:','tailx',
                    557:                                      $token,'8').
                    558:              &Apache::edit::text_arg('Tail y:','taily',
                    559:                                      $token,'8').
                    560:              &Apache::edit::text_arg('Tip x:','tipx',
                    561:                                      $token,'8').
                    562:              &Apache::edit::text_arg('Tip y:','tipy',
                    563:                                      $token,'8').
                    564: 
                    565:              &Apache::edit::end_row();
                    566:   } elsif ($target eq 'modified') {
1.76    ! www       567:     $env{'form.'.&Apache::edit::html_element_name('label')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('label')});
1.71      www       568:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,$safeeval,'label','tailx','taily','tipx','tipy');
                    569:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    570:   }
                    571:   return $result;
                    572: }
                    573: 
                    574: sub end_plotvector {
                    575:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    576:    my $result='';
                    577:    if ($target eq 'edit') {
                    578:        $result=&Apache::edit::end_table();
                    579:    }
                    580:    return $result;
                    581: }
                    582: 
                    583: 
1.70      www       584: 
1.6       www       585: #
                    586: # <backgroundplot function="..." fixed="yes/no" />
1.5       www       587: #
1.4       www       588: sub start_backgroundplot {
                    589:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    590:    my $result='';
                    591:    my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
                    592:    my $function=&Apache::lonxml::get_param('function',$parstack,$safeeval);
1.47      www       593:    my $xinitial=&Apache::lonxml::get_param('xinitial',$parstack,$safeeval);
                    594:    my $xfinal=&Apache::lonxml::get_param('xfinal',$parstack,$safeeval);
1.41      www       595:    my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
1.46      www       596:    my $color=&Apache::lonxml::get_param('color',$parstack,$safeeval);
                    597:    $color=~s/[^a-fA-F0-9]//gs;
                    598:    unless (length($color)==6) { $color=''; }
1.6       www       599:    my $fixed=(&Apache::lonxml::get_param('fixed',$parstack,$safeeval)=~/on|true|yes|1/i?1:0);
                    600:  
1.4       www       601:    unless ($function) { $function="0"; }
                    602:    if ($target eq 'web') {
1.41      www       603:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
1.47      www       604:       unless (defined($xinitial)) { $xinitial=$xmin; }
                    605:       unless (defined($xfinal)) { $xfinal=$xmax; }
                    606:       $result.=&plot_script($internalid,$function,$fixed,$label,$color,$xinitial,$xfinal);
1.13      www       607:    } elsif ($target eq 'edit') {
                    608:         $result=&Apache::edit::tag_start($target,$token,'Background Function Plot').
                    609:              &Apache::edit::text_arg('Function:','function',
                    610:                                      $token,'16').
1.47      www       611:              &Apache::edit::text_arg('Initial x-value (optional):','xinitial',
                    612:                                      $token,'8').
                    613:              &Apache::edit::text_arg('Final x-value (optional):','xfinal',
                    614:                                      $token,'8').
1.41      www       615:              &Apache::edit::text_arg('Label on Plot:','label',
                    616:                                      $token,'8').
1.46      www       617:              &Apache::edit::text_arg('Color (hex code):','color',
                    618:                                      $token,'8').
1.13      www       619:              &Apache::edit::select_arg('Fixed location:','fixed',
                    620:                                   ['yes','no'],$token).
                    621:              &Apache::edit::end_row();
                    622:   } elsif ($target eq 'modified') {
                    623:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.47      www       624:                                                  $safeeval,'function','label','xinitial','xfinal','color','fixed');
1.13      www       625:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    626:   }
                    627:   return $result;
1.4       www       628: }
                    629: 
                    630: sub end_backgroundplot {
1.13      www       631:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    632:    my $result='';
                    633:    if ($target eq 'edit') {
                    634:        $result=&Apache::edit::end_table();
                    635:    }
                    636:    return $result;
1.6       www       637: }
                    638: 
                    639: #
1.25      www       640: # <functionplotrule ... />
1.12      www       641: #
1.25      www       642: sub start_functionplotrule {
1.12      www       643:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    644:    my $result='';
1.24      www       645:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
                    646:    $Apache::functionplotresponse::counter++;
                    647:    if ($label=~/\W/) {
1.25      www       648:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
1.24      www       649:    }
                    650:    $label=~s/\W//gs;
                    651:    unless ($label) {
                    652:       $label='R'.$Apache::functionplotresponse::counter;
                    653:    } else {
                    654:       $label='R'.$label;
                    655:    }
                    656:    if ($Apache::functionplotresponse::splineorder{$label}) {
1.25      www       657:        &Apache::lonxml::error(&mt('Rule indices must be unique.'));
1.24      www       658:    }
                    659: 
                    660: 
                    661:    if ($target eq 'grade') {
                    662: # Simply remember - in order - for later
1.25      www       663:       my $beginninglabel=&Apache::lonxml::get_param('xinitiallabel',$parstack,$safeeval);
                    664:       my $endinglabel=&Apache::lonxml::get_param('xfinallabel',$parstack,$safeeval);
1.24      www       665:       if (($beginninglabel=~/\W/) || ($endinglabel=~/W/)) {
1.25      www       666:           &Apache::lonxml::warning(&mt('Rule labels must be alphanumeric.'));
1.24      www       667:       }
                    668:       $beginninglabel=~s/\W//gs;
                    669:       $endinglabel=~s/\W//gs;
                    670:       my $relationship=&Apache::lonxml::get_param('relationship',$parstack,$safeeval);
                    671:       $relationship=~s/\W//gs;
                    672:       $relationship=lc($relationship);
                    673:       unless ($relationship=~/^(eq|ge|gt|le|lt|ne)$/) {
1.25      www       674:           &Apache::lonxml::warning(&mt('Rule relationship not defined.'));
1.24      www       675:           $relationship='eq';
                    676:       }
1.35      www       677:       my $derivative=&Apache::lonxml::get_param('derivativeorder',$parstack,$safeeval);
1.42      www       678:       unless (($derivative==-1) || ($derivative==0) || ($derivative==1) || ($derivative==2)) {
1.25      www       679:          &Apache::lonxml::warning(&mt('Rule derivative not defined.'));
1.24      www       680:          $derivative=0;
                    681:       }
1.25      www       682:       push(@Apache::functionplotresponse::functionplotrules,join(':',(
1.24      www       683:            $label,
                    684:            $derivative,
1.25      www       685:            &Apache::lonxml::get_param('xinitial',$parstack,$safeeval),
1.24      www       686:            $beginninglabel,
1.25      www       687:            &Apache::lonxml::get_param('xfinal',$parstack,$safeeval),
1.24      www       688:            $endinglabel,
1.35      www       689:            &Apache::lonxml::get_param('minimumlength',$parstack,$safeeval),
                    690:            &Apache::lonxml::get_param('maximumlength',$parstack,$safeeval),
1.24      www       691:            $relationship,
1.33      www       692:            &Apache::lonxml::get_param('value',$parstack,$safeeval),
                    693:            &Apache::lonxml::get_param('percenterror',$parstack,$safeeval)
1.24      www       694:           )));
                    695:    } elsif ($target eq 'edit') {
1.75      www       696:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Graph Rule').
1.36      www       697:              &Apache::edit::text_arg('Index/Name:','index',
                    698:                                      $token,'10').'&nbsp;'.
1.35      www       699:              &Apache::edit::select_arg(&mt('Function:'),'derivativeorder',
1.29      www       700:                                   [['0','Function itself'],
                    701:                                    ['1','First derivative'],
1.42      www       702:                                    ['2','Second derivative'],
                    703:                                    ['-1','Integral']],$token).'<br />'.
1.44      www       704:              &Apache::edit::text_arg('Initial x-value:','xinitial',
1.35      www       705:                                       $token,'8').
1.44      www       706:              &Apache::edit::select_or_text_arg('Initial x-value label:','xinitiallabel',
                    707:                                                [['start','Start of Plot'],
                    708:                                                 ['end','End of Plot']],$token,'8').'<br />'.
1.30      www       709: 
1.44      www       710:              &Apache::edit::text_arg('Final x-value (optional):','xfinal',
1.35      www       711:                                       $token,'8').
1.44      www       712:              &Apache::edit::select_or_text_arg('Final x-value label (optional):','xfinallabel',
1.32      www       713:                                                [['end','End of Plot']],$token,'8').'<br />'.
1.44      www       714:              &Apache::edit::text_arg('Minimum length for range (optional):','minimumlength',
1.35      www       715:                                      $token,'8').
1.44      www       716:              &Apache::edit::text_arg('Maximum length for range (optional):','maximumlength',
1.35      www       717:                                      $token,'8').'<br />'.
1.38      www       718:              &Apache::edit::select_or_text_arg(&mt('Relationship:'),'relationship',
1.29      www       719:                                   [['eq','equal'],
                    720:                                    ['ne','not equal'],
                    721:                                    ['ge','greater than or equal'],
                    722:                                    ['gt','greater than'],
                    723:                                    ['lt','less than'],
                    724:                                    ['le','less than or equal']],$token).
                    725:              $result.= &Apache::edit::select_or_text_arg('Value:','value',
1.65      www       726:                                                [['undef','not defined']],$token,'30').
1.29      www       727:              &Apache::edit::text_arg('Percent error:','percenterror',
1.35      www       728:                                      $token,'8').
1.29      www       729:              &Apache::edit::end_row();
                    730:   } elsif ($target eq 'modified') {
1.54      www       731:     if (($env{'form.'.&Apache::edit::html_element_name('xinitial')} ne '') && ($env{'form.'.&Apache::edit::html_element_name('xinitiallabel')} eq 'start')) {
1.53      www       732:        $env{'form.'.&Apache::edit::html_element_name('xinitiallabel')}='';
                    733:     }
1.54      www       734:     if (($env{'form.'.&Apache::edit::html_element_name('xfinal')} ne '') && ($env{'form.'.&Apache::edit::html_element_name('xfinallabel')} eq 'end')) {
1.53      www       735:        $env{'form.'.&Apache::edit::html_element_name('xfinallabel')}='';
                    736:     }
1.29      www       737:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.35      www       738:                                                  $safeeval,'index','derivativeorder',
                    739:                                                            'xinitial','xinitiallabel','xfinal','xfinallabel',
                    740:                                                            'minimumlength','maximumlength',
                    741:                                                            'relationship','value','percenterror');
1.29      www       742:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
1.13      www       743:    }
1.12      www       744:    return $result;
                    745: }
                    746: 
1.25      www       747: sub end_functionplotrule {
1.13      www       748:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    749:    my $result='';
                    750:    if ($target eq 'edit') {
                    751:        $result=&Apache::edit::end_table();
                    752:    }
                    753:    return $result;
1.12      www       754: }
                    755: 
                    756: 
                    757: #
1.75      www       758: # <functionplotvectorrule ... />
                    759: #
                    760: sub start_functionplotvectorrule {
                    761:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    762:    my $result='';
                    763:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
                    764:    $Apache::functionplotresponse::counter++;
                    765:    if ($label=~/\W/) {
                    766:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
                    767:    }
                    768:    $label=~s/\W//gs;
                    769:    unless ($label) {
                    770:       $label='V'.$Apache::functionplotresponse::counter;
                    771:    } else {
                    772:       $label='V'.$label;
                    773:    }
                    774:    if ($Apache::functionplotresponse::splineorder{$label}) {
                    775:        &Apache::lonxml::error(&mt('Rule indices must be unique.'));
                    776:    }
                    777: 
                    778:    if ($target eq 'grade') {
                    779: # Simply remember - in order - for later
                    780:       my $vector=&Apache::lonxml::get_param('vector',$parstack,$safeeval);
                    781:       $vector=~s/\W//gs;
                    782:       $vector=ucfirst($vector);
1.76    ! www       783: 
        !           784:       my $attachpoint=&Apache::lonxml::get_param('attachpoint',$parstack,$safeeval);
        !           785:       $attachpoint=~s/\W//gs;
        !           786:       $attachpoint=ucfirst($attachpoint);
        !           787: 
        !           788:       my $notattachpoint=&Apache::lonxml::get_param('notattachpoint',$parstack,$safeeval);
        !           789:       $notattachpoint=~s/\W//gs;
        !           790:       $notattachpoint=ucfirst($notattachpoint);
        !           791: 
1.75      www       792:       my $tailpoint=&Apache::lonxml::get_param('tailpoint',$parstack,$safeeval);
                    793:       $tailpoint=~s/\W//gs;
                    794:       $tailpoint=ucfirst($tailpoint);
                    795:       my $tippoint=&Apache::lonxml::get_param('tippoint',$parstack,$safeeval);
                    796:       $tippoint=~s/\W//gs;
                    797:       $tippoint=ucfirst($tippoint);
                    798: 
                    799:       my $nottailpoint=&Apache::lonxml::get_param('nottailpoint',$parstack,$safeeval);
                    800:       $nottailpoint=~s/\W//gs;
                    801:       $nottailpoint=ucfirst($nottailpoint);
                    802:       my $nottippoint=&Apache::lonxml::get_param('nottippoint',$parstack,$safeeval);
                    803:       $nottippoint=~s/\W//gs;
                    804:       $nottippoint=ucfirst($nottippoint);
                    805: 
                    806:       push(@Apache::functionplotresponse::functionplotvectorrules,join(':',(
                    807:            $label,
1.76    ! www       808:            'vector',
1.75      www       809:            $vector,
1.76    ! www       810:            $attachpoint,
        !           811:            $notattachpoint,
1.75      www       812:            $tailpoint,
                    813:            $tippoint,
                    814:            $nottailpoint,
                    815:            $nottippoint,
                    816:            &Apache::lonxml::get_param('length',$parstack,$safeeval),
                    817:            &Apache::lonxml::get_param('angle',$parstack,$safeeval),
                    818:            &Apache::lonxml::get_param('lengthpercenterror',$parstack,$safeeval),
                    819:            &Apache::lonxml::get_param('anglepercenterror',$parstack,$safeeval),
                    820:           )));
                    821:    } elsif ($target eq 'edit') {
                    822:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Vector Rule').
                    823:              &Apache::edit::text_arg('Index/Name:','index',
                    824:                                      $token,'10').'&nbsp;'.
                    825:              &Apache::edit::text_arg('Vector:','vector',
                    826:                                       $token,'16').'<br />'.
1.76    ! www       827:              &Apache::edit::text_arg('Attached to object:','attachpoint',
        !           828:                                       $token,'16').
        !           829:              &Apache::edit::text_arg('Not attached to object:','notattachpoint',
        !           830:                                       $token,'16').'<br />'.
1.75      www       831:              &Apache::edit::text_arg('Tail attached to object:','tailpoint',
                    832:                                       $token,'16').
                    833:              &Apache::edit::text_arg('Tip attached to object:','tippoint',
                    834:                                       $token,'16').
                    835:              &Apache::edit::text_arg('Tail not attached to object:','nottailpoint',
                    836:                                       $token,'16').
                    837:              &Apache::edit::text_arg('Tip not attached to object:','nottippoint',
                    838:                                       $token,'16').'<br />'.
                    839:              &Apache::edit::text_arg('Length:','length',
                    840:                                      $token,'16').
                    841:              &Apache::edit::text_arg('Angle:','angle',
                    842:                                      $token,'16').
                    843:              &Apache::edit::text_arg('Percent error length:','lengthpercenterror',
                    844:                                      $token,'8').
                    845:              &Apache::edit::text_arg('Percent error angle:','anglepercenterror',
                    846:                                      $token,'8').
                    847:              &Apache::edit::end_row();
                    848:   } elsif ($target eq 'modified') {
1.76    ! www       849:     $env{'form.'.&Apache::edit::html_element_name('vector')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('vector')});
        !           850:     $env{'form.'.&Apache::edit::html_element_name('attachpoint')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('attachpoint')});
        !           851:     $env{'form.'.&Apache::edit::html_element_name('notattachpoint')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('notattachpoint')});
        !           852:     $env{'form.'.&Apache::edit::html_element_name('tailpoint')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('tailpoint')});
        !           853:     $env{'form.'.&Apache::edit::html_element_name('tippoint')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('tippoint')});
        !           854:     $env{'form.'.&Apache::edit::html_element_name('nottailpoint')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('nottailpoint')});
        !           855:     $env{'form.'.&Apache::edit::html_element_name('nottippoint')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('nottippoint')});
1.75      www       856:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.76    ! www       857:                                                  $safeeval,'index','vector','attachpoint','notattachpoint',
1.75      www       858:                                                            'tailpoint','tippoint','nottailpoint','nottipoint',
                    859:                                                            'length','angle',
                    860:                                                            'lengthpercenterror','anglepercenterror');
                    861:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                    862:    }
                    863:    return $result;
                    864: }
                    865: 
                    866: sub end_functionplotvectorrule {
                    867:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                    868:    my $result='';
                    869:    if ($target eq 'edit') {
                    870:        $result=&Apache::edit::end_table();
                    871:    }
                    872:    return $result;
                    873: }
                    874: 
1.76    ! www       875: #
        !           876: # <functionplotvectorsumrule ... />
        !           877: #
        !           878: sub start_functionplotvectorsumrule {
        !           879:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
        !           880:    my $result='';
        !           881:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
        !           882:    $Apache::functionplotresponse::counter++;
        !           883:    if ($label=~/\W/) {
        !           884:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
        !           885:    }
        !           886:    $label=~s/\W//gs;
        !           887:    unless ($label) {
        !           888:       $label='V'.$Apache::functionplotresponse::counter;
        !           889:    } else {
        !           890:       $label='V'.$label;
        !           891:    }
        !           892:    if ($Apache::functionplotresponse::splineorder{$label}) {
        !           893:        &Apache::lonxml::error(&mt('Rule indices must be unique.'));
        !           894:    }
        !           895:    if ($target eq 'grade') {
        !           896: # Simply remember - in order - for later
        !           897:       my $object=&Apache::lonxml::get_param('object',$parstack,$safeeval);
        !           898:       $object=~s/\W//gs;
        !           899:       $object=ucfirst($object);
        !           900:       push(@Apache::functionplotresponse::functionplotvectorrules,join(':',(
        !           901:            $label,
        !           902:            'sum',
        !           903:            $object,
        !           904:            &Apache::lonxml::get_param('length',$parstack,$safeeval),
        !           905:            &Apache::lonxml::get_param('angle',$parstack,$safeeval),
        !           906:            &Apache::lonxml::get_param('lengthpercenterror',$parstack,$safeeval),
        !           907:            &Apache::lonxml::get_param('lengthabserror',$parstack,$safeeval),
        !           908:            &Apache::lonxml::get_param('anglepercenterror',$parstack,$safeeval),
        !           909:           )));
        !           910:    } elsif ($target eq 'edit') {
        !           911:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Vector Sum Rule').
        !           912:              &Apache::edit::text_arg('Index/Name:','index',
        !           913:                                      $token,'10').'&nbsp;'.
        !           914:              &Apache::edit::text_arg('Vectors attached to object:','object',
        !           915:                                       $token,'16').'<br />'.
        !           916:              &Apache::edit::text_arg('Sum vector length:','length',
        !           917:                                      $token,'16').
        !           918:              &Apache::edit::text_arg('Sum vector angle:','angle',
        !           919:                                      $token,'16').
        !           920:              &Apache::edit::text_arg('Percent error length:','lengthpercenterror',
        !           921:                                      $token,'8').
        !           922:              &Apache::edit::text_arg('Absolute error length:','lengthabserror',
        !           923:                                      $token,'8').
        !           924:              &Apache::edit::text_arg('Percent error angle:','anglepercenterror',
        !           925:                                      $token,'8').
        !           926:              &Apache::edit::end_row();
        !           927:   } elsif ($target eq 'modified') {
        !           928:     $env{'form.'.&Apache::edit::html_element_name('object')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('object')});
        !           929:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
        !           930:                                                  $safeeval,'index','object',
        !           931:                                                            'length','angle',
        !           932:                                                            'lengthpercenterror','lengthabserror','anglepercenterror');
        !           933:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
        !           934:    }
        !           935:    return $result;
        !           936: }
1.75      www       937: 
1.76    ! www       938: sub end_functionplotvectorsumrule {
        !           939:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
        !           940:    my $result='';
        !           941:    if ($target eq 'edit') {
        !           942:        $result=&Apache::edit::end_table();
        !           943:    }
        !           944:    return $result;
        !           945: }
1.75      www       946: 
                    947: #
1.23      www       948: # <spline index="..." order="1,2,3,4" initx="..." inity="..." scalex="..." scaley="..." />
1.6       www       949: #
                    950: # Unfortunately, GeoGebra seems to want all splines after everything else, so we need to store them
                    951: #
                    952: sub start_spline {
                    953:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.13      www       954:    my $result='';
                    955:    if ($target eq 'web') {
1.23      www       956:       my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
1.13      www       957:       $Apache::functionplotresponse::counter++;
                    958:       if ($label=~/\W/) {
1.23      www       959:          &Apache::lonxml::warning(&mt('Spline indices should only contain alphanumeric characters.'));
1.13      www       960:       }
                    961:       $label=~s/\W//gs;
1.23      www       962:       unless ($label) { 
                    963:          $label='S'.$Apache::functionplotresponse::counter; 
                    964:       } else {
                    965:          $label='S'.$label;
                    966:       }
1.13      www       967:       if ($Apache::functionplotresponse::splineorder{$label}) {
1.23      www       968:          &Apache::lonxml::error(&mt('Spline indices must be unique.'));
1.13      www       969:       }
                    970: 
                    971:       my $order=&Apache::lonxml::get_param('order',$parstack,$safeeval);
                    972:       if ($order<2) { $order=2; }
                    973:       if ($order>8) { $order=8; }
                    974:       $Apache::functionplotresponse::splineorder{$label}=$order;
                    975: 
                    976:       my $x=&Apache::lonxml::get_param('initx',$parstack,$safeeval);
                    977:       unless ($x) { $x=0; }
                    978:       $Apache::functionplotresponse::splineinitx{$label}=$x;
                    979: 
                    980:       my $y=&Apache::lonxml::get_param('inity',$parstack,$safeeval);
                    981:       unless ($y) { $y=0; }
                    982:       $Apache::functionplotresponse::splineinity{$label}=$y;
                    983: 
                    984:       my $sx=&Apache::lonxml::get_param('scalex',$parstack,$safeeval);
                    985:       unless ($sx) { $sx=$order; }
                    986:       $Apache::functionplotresponse::splinescalex{$label}=$sx;
                    987: 
                    988:       my $sy=&Apache::lonxml::get_param('scaley',$parstack,$safeeval);
                    989:       unless ($sy) { $sy=2; }
                    990:       $Apache::functionplotresponse::splinescaley{$label}=$sy;
                    991:    } elsif ($target eq 'edit') {
                    992:         $result=&Apache::edit::tag_start($target,$token,'Spline').
1.23      www       993:              &Apache::edit::text_arg('Index:','index',
1.14      www       994:                                      $token,'4').'&nbsp;'.
1.13      www       995:              &Apache::edit::select_arg('Order:','order',
1.44      www       996:                                   ['2','3','4','5','6','7','8'],$token).'&nbsp;'.
1.13      www       997:              &Apache::edit::text_arg('Initial x-value:','initx',
1.14      www       998:                                      $token,'4').'&nbsp;'.
1.13      www       999:              &Apache::edit::text_arg('Initial y-value:','inity',
1.14      www      1000:                                      $token,'4').'&nbsp;'.
1.13      www      1001:              &Apache::edit::text_arg('Scale x:','scalex',
1.14      www      1002:                                      $token,'4').'&nbsp;'.
1.13      www      1003:              &Apache::edit::text_arg('Scale y:','scaley',
                   1004:                                      $token,'4').
                   1005:              &Apache::edit::end_row();
                   1006:   } elsif ($target eq 'modified') {
                   1007:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.23      www      1008:                                                  $safeeval,'index','order','initx','inity',
1.13      www      1009:                                                            'scalex','scaley');
                   1010:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
                   1011:   }
                   1012:   return $result;
1.6       www      1013: }
                   1014: 
                   1015: sub end_spline {
1.13      www      1016:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1017:    my $result='';
                   1018:    if ($target eq 'edit') {
                   1019:        $result=&Apache::edit::end_table();
                   1020:    }
                   1021:    return $result;
1.4       www      1022: }
                   1023:  
1.3       www      1024: sub end_init_script {
                   1025:     return (<<ENDENDINIT);
                   1026: }
                   1027: // ]]>
                   1028: </script>
                   1029: ENDENDINIT
                   1030: }
                   1031: 
1.10      www      1032: #
                   1033: # Storing and restoring spline coordinates from part answers
                   1034: #
                   1035: sub decode_previous_answer {
                   1036:    my ($answer)=@_;
                   1037:    foreach my $coordinate (split(/\,/,$answer)) {
                   1038:       my ($key,$value)=split(/\=/,$coordinate);
                   1039:       $Apache::functionplotresponse::previous{$key}=$value;
                   1040:    }
                   1041: }
                   1042: 
                   1043: sub get_answer_from_form_fields {
                   1044:    my ($id)=@_;
                   1045:    my $answer='';
                   1046:    my %coords=();
                   1047:    foreach my $field (keys(%env)) {
                   1048:       if ($field=~/^form\.HWVAL\_$id/) {
                   1049:          $field=~/^form\.(.*)$/;
                   1050:          $coords{$1}=$env{$field};
                   1051:       }
                   1052:    }
                   1053:    $answer=join(',',map { $_.'='.$coords{$_} } (sort(keys(%coords))));
                   1054:    return ($answer,%coords);
                   1055: }
                   1056: 
1.15      www      1057: #
                   1058: # The following functions calculate the cubic-hermite splines server-side
                   1059: #
                   1060: 
                   1061: sub cubic_hermite {
                   1062:    my ($t,$p1,$s1,$p2,$s2)=@_;
1.42      www      1063:    return (2.*$t*$t*$t-3.*$t*$t+1.)*$p1 + 3.*($t*$t*$t-2.*$t*$t+$t)*($s1-$p1)+
                   1064:           (-2.*$t*$t*$t+3.*$t*$t)  *$p2 + 3.*($t*$t*$t-$t*$t)      *($s2-$p2);
1.15      www      1065: }
                   1066: 
                   1067: #
                   1068: # d/dt(...)
                   1069: # 
                   1070: 
                   1071: sub ddt_cubic_hermite {
                   1072:    my ($t,$p1,$s1,$p2,$s2)=@_;
1.42      www      1073:    return (6.*$t*$t-6.*$t) *$p1 + 3.*(3.*$t*$t-4.*$t+1.)*($s1-$p1)+
                   1074:           (-6.*$t*$t+6.*$t)*$p2 + 3.*(3.*$t*$t-2.*$t)   *($s2-$p2);
1.15      www      1075: }
                   1076: 
                   1077: #
                   1078: # d^2/dt^2(...)
                   1079: #
                   1080: 
                   1081: sub d2dt2_cubic_hermite {
                   1082:    my ($t,$p1,$s1,$p2,$s2)=@_;
1.42      www      1083:    return (12.*$t-6.) *$p1 + 3.*(6.*$t-4.)*($s1-$p1)+
                   1084:           (-12.*$t+6.)*$p2 + 3.*(6.*$t-2.)*($s2-$p2);
1.15      www      1085: }
                   1086: 
                   1087: #
1.18      www      1088: # Array index calculation
                   1089: #
                   1090: sub array_index {
                   1091:    my ($xmin,$xmax,$x)=@_;
1.38      www      1092:    if ($x ne '') {
                   1093:       return int(($x-$xmin)/($xmax-$xmin)*400.+0.5);
                   1094:    } else {
                   1095:       return undef;
                   1096:    }
1.20      www      1097: }
                   1098: 
                   1099: #
1.18      www      1100: # Populate the arrays
                   1101: #
                   1102: 
                   1103: sub populate_arrays {
1.64      www      1104:     my ($id,$xmin,$xmax,$ymin,$ymax)=@_;
1.26      www      1105:     for (my $i=0; $i<=400; $i++) {
1.35      www      1106:        $Apache::functionplotresponse::actualxval[$i]=undef;
1.19      www      1107:        $Apache::functionplotresponse::func[$i]=undef;
1.22      www      1108:        $Apache::functionplotresponse::dfuncdx[$i]=undef;
1.19      www      1109:        $Apache::functionplotresponse::d2funcd2x[$i]=undef;
1.18      www      1110:     }
1.19      www      1111:     unless ($xmax>$xmin) { return 'no_func'; }
1.18      www      1112: # Run over all splines in response
                   1113:     foreach my $label (split(/\,/,$env{"form.HWVAL_AllSplines_$id"})) {
1.19      www      1114:         my $xiold=-1;
1.18      www      1115: # Run over all points in spline
1.19      www      1116:         for (my $i=1; $i<$env{"form.HWVAL_SplineOrder_".$id."_".$label}; $i++) {
1.18      www      1117:             my $ni=$i+1;
                   1118:             my @xparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_x'},
                   1119:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_x'},
                   1120:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_x'},
                   1121:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_x'});
                   1122:             my @yparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_y'},
                   1123:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_y'},
                   1124:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_y'},
                   1125:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_y'});
                   1126: # Run in small steps over spline parameter
1.26      www      1127:             for (my $t=0; $t<=1; $t+=0.0001) {
1.35      www      1128:                 my $xreal=&cubic_hermite($t,@xparms);
                   1129:                 my $xi=&array_index($xmin,$xmax,$xreal);
1.19      www      1130:                 if ($xi<$xiold) { return 'no_func'; }
1.26      www      1131:                 if (($xi>$xiold) && ($xi>=0) && ($xi<=400)) {
1.18      www      1132:                    $xiold=$xi;
1.35      www      1133:                    $Apache::functionplotresponse::actualxval[$xi]=$xreal;
1.22      www      1134: # Function value
1.30      www      1135:                    my $funcval=&cubic_hermite($t,@yparms);
1.64      www      1136: 
                   1137: # Do we already have a value for this point, and is it different from the new one?
                   1138:                    if ((defined($Apache::functionplotresponse::func[$xi])) &&
                   1139:                        (abs($Apache::functionplotresponse::func[$xi]-$funcval)>($ymax-$ymin)/100.)) { 
                   1140:                        return 'no_func'; 
                   1141:                    }
                   1142: # Okay, remember the new point
1.30      www      1143:                    $Apache::functionplotresponse::func[$xi]=$funcval;
1.64      www      1144: 
1.30      www      1145:                    if (defined($funcval)) {
                   1146:                       if ($xi<$Apache::functionplotresponse::functionplotrulelabels{'start'}) {
                   1147:                          $Apache::functionplotresponse::functionplotrulelabels{'start'}=$xi;
                   1148:                       }
                   1149:                       if ($xi>$Apache::functionplotresponse::functionplotrulelabels{'end'}) {
                   1150:                          $Apache::functionplotresponse::functionplotrulelabels{'end'}=$xi;
                   1151:                       }
                   1152:                    }
1.28      www      1153: # Chain rule
1.22      www      1154: # dy/dx=dy/dt/(dx/dt)
                   1155:                    my $dxdt=&ddt_cubic_hermite($t,@xparms);
                   1156:                    if ($dxdt) {
                   1157:                       $Apache::functionplotresponse::dfuncdx[$xi]=&ddt_cubic_hermite($t,@yparms)/$dxdt;
1.34      www      1158: # Second derivative
1.28      www      1159:                       $Apache::functionplotresponse::d2funcdx2[$xi]=
1.34      www      1160:                          ($dxdt*&d2dt2_cubic_hermite($t,@yparms)-&ddt_cubic_hermite($t,@yparms)*&d2dt2_cubic_hermite($t,@xparms))/
                   1161:                          ($dxdt*$dxdt*$dxdt);
1.22      www      1162:                    }
1.18      www      1163:                 }
                   1164:             }
                   1165:         }
                   1166:     }
                   1167: }
                   1168: 
                   1169: #
1.37      www      1170: # Implementation of <functionplotresponse>
1.15      www      1171: #
                   1172: 
1.1       www      1173: sub start_functionplotresponse {
                   1174:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1175:   my $result='';
1.6       www      1176: # To remember the splines - somehow, they need to come last
                   1177:   undef %Apache::functionplotresponse::splineorder;
                   1178:   undef %Apache::functionplotresponse::splineinitx;
                   1179:   undef %Apache::functionplotresponse::splineinity;
                   1180:   undef %Apache::functionplotresponse::splinescalex;
                   1181:   undef %Apache::functionplotresponse::splinescaley;
1.10      www      1182: # Remember input fields, etc
                   1183:   undef %Apache::functionplotresponse::previous;
1.9       www      1184:   $Apache::functionplotresponse::inputfields='';
1.6       www      1185:   $Apache::functionplotresponse::counter=0;
1.24      www      1186: # Remember rules
1.25      www      1187:   undef @Apache::functionplotresponse::functionplotrules;
1.75      www      1188:   undef @Apache::functionplotresponse::functionplotvectorrules;
1.37      www      1189: # Remember failed rules
                   1190:   if ($target eq 'grade') {
                   1191:      undef @Apache::functionplotresponse::failedrules;
                   1192:   }
                   1193: # Delete previous awards
                   1194:   undef $Apache::functionplotresponse::awarddetail;
1.10      www      1195: # Part and ID
                   1196:   my $partid=$Apache::inputtags::part;
                   1197:   my $id=&Apache::response::start_response($parstack,$safeeval);
1.6       www      1198: # Internal ID to mark the applet and its coordinates
1.10      www      1199:   my $internalid = $partid.'_'.$id;
                   1200: # Previous answer
                   1201:   &decode_previous_answer($Apache::lonhomework::history{"resource.$partid.$id.submission"});
                   1202: 
1.6       www      1203: # Parameters of <functionplotresponse>
1.41      www      1204:   my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval);
1.6       www      1205:   my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
                   1206:   my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
                   1207:   my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
1.14      www      1208:   my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval);
                   1209:   my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval);
1.12      www      1210:   if ($target eq 'edit') {
                   1211:     $result.=&Apache::edit::start_table($token)
                   1212:        .'<tr><td><span class="LC_nobreak">'.&mt('Function Plot Question').'</span></td>'
                   1213:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
1.37      www      1214:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'
1.50      www      1215:        .&Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
                   1216:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Question','Function Plot Responses')
1.12      www      1217:        .'</span></td>'
                   1218:        ."<td>&nbsp;"
                   1219:        .&Apache::edit::end_row()
                   1220:        .&Apache::edit::start_spanning_row()
                   1221:        ."\n";
1.14      www      1222:     $result.=&Apache::edit::text_arg('Label x-axis:','xlabel',
                   1223:                                      $token,'6').'&nbsp;'.
                   1224:              &Apache::edit::text_arg('Minimum x-value:','xmin',
                   1225:                                      $token,'4').'&nbsp;'.
1.12      www      1226:              &Apache::edit::text_arg('Maximum x-value:','xmax',
1.14      www      1227:                                      $token,'4').'&nbsp;'.
1.12      www      1228:              &Apache::edit::select_arg('x-axis visible:','xaxisvisible',
1.32      www      1229:                                   ['yes','no'],$token).'<br />'.
1.14      www      1230:              &Apache::edit::text_arg('Label y-axis:','ylabel',
                   1231:                                      $token,'6').'&nbsp;'.
1.12      www      1232:              &Apache::edit::text_arg('Minimum y-value:','ymin',
1.14      www      1233:                                      $token,'4').'&nbsp;'.
1.12      www      1234:              &Apache::edit::text_arg('Maximum y-value:','ymax',
1.14      www      1235:                                      $token,'4').'&nbsp;'.
1.12      www      1236:              &Apache::edit::select_arg('y-axis visible:','yaxisvisible',
1.32      www      1237:                                   ['yes','no'],$token).'<br />'.
1.12      www      1238:              &Apache::edit::select_arg('Grid visible:','gridvisible',
1.47      www      1239:                                   ['yes','no'],$token).'<br />'.
1.58      www      1240:              &Apache::edit::text_arg('Background plot(s) for answer (function(x):xmin:xmax,function(x):xmin:xmax,x1:y1:sx1:sy1:x2:y2:sx2:sy2,...):',
1.63      raeburn  1241:                                          'answerdisplay',$token,'50').
1.12      www      1242:              &Apache::edit::end_row().&Apache::edit::start_spanning_row();
                   1243:   } elsif ($target eq 'modified') {
                   1244:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
1.14      www      1245:                                                  $safeeval,'xlabel','xmin','xmax','ylabel','ymin','ymax',
1.47      www      1246:                                                            'xaxisvisible','yaxisvisible','gridvisible','answerdisplay');
1.12      www      1247:     if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
1.3       www      1248: 
1.12      www      1249:   } elsif ($target eq 'meta') {
1.10      www      1250:        $result=&Apache::response::meta_package_write('functionplotresponse');
1.35      www      1251:   } elsif (($target eq 'answer') &&
                   1252:             ($env{'form.answer_output_mode'} ne 'tex') &&
                   1253:             ($Apache::lonhomework::viewgrades == 'F')) {
                   1254:       my (undef,undef,$udom,$uname)=&Apache::lonnet::whichuser();
                   1255:       my $windowopen=&Apache::lonhtmlcommon::javascript_docopen();
                   1256:       my $start_page = &Apache::loncommon::start_page('Rules Log', undef,
                   1257:                                                {'only_body' => 1,
                   1258:                                                 'bgcolor'   => '#FFFFFF',
                   1259:                                                 'js_ready'  => 1,});
                   1260:       my $end_page = &Apache::loncommon::end_page({'js_ready' => 1,});
                   1261:       $uname =~s/\W//g;
                   1262:       $udom  =~s/\W//g;
                   1263:       my $function_name =
                   1264:                 join('_','LONCAPA_scriptvars',$uname,$udom,
                   1265:                      $env{'form.counter'},$Apache::lonxml::curdepth);
                   1266:       my $rules_var ="<script type=\"text/javascript\">
                   1267: // <![CDATA[
                   1268:     function $function_name() {newWindow=open('','new_W','width=500,height=500,scrollbars=1,resizable=yes');newWindow.$windowopen;newWindow.document.writeln('$start_page<pre>".
                   1269:     $Apache::functionplotresponse::ruleslog.
                   1270:     "<\\/pre>$end_page');newWindow.document.close();newWindow.focus()}
                   1271: // ]]>
                   1272: </script><a href=\"javascript:$function_name();void(0);\">".&mt('Rules Log')."</a><br />";
                   1273:             &Apache::lonxml::add_script_result($rules_var);
                   1274:         }
                   1275: 
1.1       www      1276:   return $result;
                   1277: }
                   1278: 
1.25      www      1279: sub compare_rel {
1.26      www      1280:    my ($relationship,$value,$realval,$tol)=@_;
1.36      www      1281: # is the real value undefined?
1.26      www      1282:    unless (defined($realval)) {
1.36      www      1283: # the real value is not defined
1.26      www      1284:       if ($relationship eq 'eq') {
                   1285:          if ($value eq 'undef') {
                   1286:             return 1;
                   1287:          } else {
                   1288:             return 0;
                   1289:          }
                   1290:       } elsif ($relationship eq 'ne') {
                   1291:          if ($value eq 'undef') {
                   1292:             return 0;
                   1293:          } else {
                   1294:             return 1;
                   1295:          }
                   1296:       } else {
                   1297:          return 0;
                   1298:       }
                   1299:    }
                   1300: 
1.36      www      1301: # is the expected value undefined?
                   1302:    if ($value eq 'undef') {
                   1303: # but by now we know that the real value is defined
                   1304:       return 0;
                   1305:    }
                   1306: 
                   1307: # both are defined.
1.26      www      1308:    if ($relationship eq 'gt') {
                   1309:       return ($realval>$value);
                   1310:    } elsif ($relationship eq 'ge') {
                   1311:       return ($realval>$value-$tol);
                   1312:    } elsif ($relationship eq 'lt') {
                   1313:       return ($realval<$value);
                   1314:    } elsif ($relationship eq 'le') {
                   1315:       return ($realval<$value+$tol);
                   1316:    } elsif ($relationship eq 'ne') {
                   1317:       return (abs($value-$realval)>$tol);
                   1318:    } else {
                   1319:       return (abs($value-$realval)<$tol);
                   1320:    }
1.25      www      1321:    return 0;
                   1322: }
                   1323: 
1.35      www      1324: sub addlog {
                   1325:    my ($text)=@_;
1.67      www      1326:    $text=~s/\'/\\\'/g;
1.35      www      1327:    $Apache::functionplotresponse::ruleslog.=$text.'<br />';
                   1328: }
                   1329: 
                   1330: sub actualval {
                   1331:    my ($i,$xmin,$xmax)=@_;
                   1332:    return $xmin+$i/400.*($xmax-$xmin);
                   1333: }
1.65      www      1334: 
1.66      www      1335: sub fpr_val {
                   1336:    my ($arg)=@_;
                   1337:    return &actualval($Apache::functionplotresponse::functionplotrulelabels{$arg},
                   1338:                      $Apache::functionplotresponse::fpr_xmin,
                   1339:                      $Apache::functionplotresponse::fpr_xmax);
                   1340: }
                   1341: 
1.65      www      1342: sub fpr_f {
                   1343:    my ($arg)=@_;
                   1344:    return $Apache::functionplotresponse::func[&array_index($Apache::functionplotresponse::fpr_xmin,
                   1345:                                                            $Apache::functionplotresponse::fpr_xmax,
                   1346:                                                            $arg)];
                   1347: }
                   1348: 
                   1349: sub fpr_dfdx {
                   1350:    my ($arg)=@_;
                   1351:    return $Apache::functionplotresponse::dfuncdx[&array_index($Apache::functionplotresponse::fpr_xmin,
                   1352:                                                               $Apache::functionplotresponse::fpr_xmax,
                   1353:                                                               $arg)];
                   1354: }
                   1355: 
                   1356: sub fpr_d2fdx2 {
                   1357:    my ($arg)=@_;
                   1358:    return $Apache::functionplotresponse::d2funcdx2[&array_index($Apache::functionplotresponse::fpr_xmin,
                   1359:                                                                 $Apache::functionplotresponse::fpr_xmax,
                   1360:                                                                 $arg)];
                   1361: }
1.35      www      1362:  
1.25      www      1363: sub functionplotrulecheck {
1.65      www      1364:    my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
1.33      www      1365: 
1.35      www      1366:    my ($label,$derivative,$xinitial,$xinitiallabel,$xfinal,$xfinallabel,$minimumlength,$maximumlength,$relationship,$value,$percent)
1.25      www      1367:       =split(/\:/,$rule);
1.33      www      1368:    $percent=($percent>0?$percent:5);
1.35      www      1369:    &addlog("=================");
1.42      www      1370:    &addlog("Rule $label for ".($derivative<0?'integral':('function itself','first derivative','second derivative')[$derivative])." $relationship $value");
1.65      www      1371: #
                   1372: # Evaluate the value
                   1373: #
                   1374:    if ($value=~/\D/) {
                   1375:       $Apache::functionplotresponse::fpr_xmin=$xmin;
                   1376:       $Apache::functionplotresponse::fpr_xmax=$xmax;
                   1377:       $value=&Apache::run::run($value,$safeeval);
                   1378:       &addlog("Value evaluated to $value");
                   1379:    }
                   1380: 
                   1381: #
                   1382: # Minimum and maximum lengths of the interval
                   1383: #
1.49      www      1384:    if ((defined($minimumlength)) || (defined($maximumlength))) {
                   1385:       &addlog("Minimumlength $minimumlength Maximumlength $maximumlength");
                   1386:    }
1.30      www      1387:    my $li=0;
                   1388:    my $lh=400;
                   1389: 
1.31      www      1390: # Special case: the upper boundary was not defined
                   1391: # and needs to be set to the value where
                   1392: # the condition is not true anymore => set flag
                   1393: 
                   1394:    my $findupper=0;
                   1395:    if (($xfinal eq '')
                   1396:     && (!defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}))
                   1397:     && ($xfinallabel)) {
                   1398:        $findupper=1;
                   1399:    }
                   1400: 
1.25      www      1401: # if a hard value is set for the boundaries, it overrides the label
1.30      www      1402:    if (($xinitial ne '') && ($xinitiallabel ne '') && ($xinitiallabel ne 'start')) {
                   1403:       $li=&array_index($xmin,$xmax,$xinitial);
                   1404:       $Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel}=$li;
                   1405:    }
                   1406:    if (($xfinal ne '') && ($xfinallabel ne '') && ($xfinallabel ne 'end')) {
                   1407:       $lh=&array_index($xmin,$xmax,$xfinal);
                   1408:       $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$lh;
1.25      www      1409:    }
1.31      www      1410: # if the label is defined, use it
1.25      www      1411:    if (defined($Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel})) {
1.35      www      1412:       &addlog("Using lower label $xinitiallabel");
1.30      www      1413:       $li=$Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel};
                   1414:    } else {
                   1415:       $li=&array_index($xmin,$xmax,$xinitial);
1.25      www      1416:    }
1.31      www      1417:    unless ($findupper) {
                   1418:       if (defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel})) {
1.35      www      1419:          &addlog("Using upper label $xfinallabel");
1.33      www      1420:          $lh=$Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}-1;
1.31      www      1421:       } else {
                   1422:          $lh=&array_index($xmin,$xmax,$xfinal);
                   1423:       }
1.25      www      1424:    }
                   1425: # Basic sanity checks
1.30      www      1426:    if ($li<0) { $li=0; }
                   1427:    if ($lh>400) { $lh=400; }
1.38      www      1428:    if (($li>$lh) || (!defined($lh))) {
1.30      www      1429:        $lh=$li;
1.25      www      1430:    }
1.31      www      1431: 
1.35      www      1432:    &addlog("Boundaries: x=".&actualval($li,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$li]."; index $li)) to x=".
                   1433:                             &actualval($lh,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$lh]."; index $lh))");
                   1434:    if ($findupper) {
                   1435:       &addlog("Looking for label $xfinallabel");
                   1436:    }
1.33      www      1437:    my $tol=$percent*($ymax-$ymin)/100;
                   1438:    if ($xmax>$xmin) {
                   1439:       if ($derivative==2) {
                   1440:          $tol=4.*$tol/($xmax-$xmin);
                   1441:       } elsif ($derivative==1) {
                   1442:          $tol=2.*$tol/($xmax-$xmin);
1.42      www      1443:       } elsif ($derivative==-1) {
                   1444:          $tol=$tol*($xmax-$xmin)/2.;
1.33      www      1445:       }
1.27      www      1446:    }
1.42      www      1447:    my $integral=0;
                   1448:    my $binwidth=($xmax-$xmin)/400.;
                   1449:    if (($derivative<0) && (!$findupper)) {
                   1450: # definite integral, calculate over whole length
                   1451:      &addlog("Calculating definite integral");
                   1452:      for (my $i=$li; $i<=$lh; $i++) {
                   1453:         $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
                   1454:      }
                   1455:      unless (&compare_rel($relationship,$value,$integral,$tol)) {
                   1456:         &addlog("Actual integral ".(defined($integral)?$integral:'undef').", expected $value, tolerance $tol");
                   1457:         &addlog("Rule $label failed.");
                   1458:         my $hintlabel=$label;
                   1459:         $hintlabel=~s/^R//;
                   1460:         push(@Apache::functionplotresponse::failedrules,$hintlabel);
                   1461:         &addlog("Set hint condition $hintlabel");
                   1462:         return 0;
                   1463:      } 
                   1464:    } else {
                   1465:      for (my $i=$li; $i<=$lh; $i++) {
1.25      www      1466:         my $val;
                   1467:         if ($derivative==2) {
1.27      www      1468:            $val=$Apache::functionplotresponse::d2funcdx2[$i];
1.25      www      1469:         } elsif ($derivative==1) {
1.27      www      1470:            $val=$Apache::functionplotresponse::dfuncdx[$i];
1.42      www      1471:         } elsif ($derivative==-1) {
                   1472:            $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
                   1473:            $val=$integral;      
1.25      www      1474:         } else {
1.27      www      1475:            $val=$Apache::functionplotresponse::func[$i];
1.25      www      1476:         }
1.31      www      1477:         unless (&compare_rel($relationship,$value,$val,$tol)) { 
1.37      www      1478:            &addlog("Actual value ".(defined($val)?$val:'undef').", expected $value, tolerance $tol");
1.35      www      1479:            &addlog("Condition not fulfilled at x=".&actualval($i,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$i]."; index $i)");
1.31      www      1480:            if (($findupper) && ($i>$li)) {
1.49      www      1481: # Check lengths
                   1482:               unless (&checklength($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
                   1483: # Successfully found a new label, set it
1.31      www      1484:               $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$i;
1.35      www      1485:               &addlog("Rule $label passed, setting label $xfinallabel");
1.31      www      1486:               return 1;
                   1487:            } else {
1.35      www      1488:               &addlog("Rule $label failed.");
1.49      www      1489:               &setfailed($label);
1.31      www      1490:               return 0; 
                   1491:            }
                   1492:         }
1.42      www      1493:      }
1.25      www      1494:    }
1.49      www      1495: # Corner case where this makes sense: using start or stop as defined labels
                   1496:    unless (&checklength($lh,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
1.35      www      1497:    &addlog("Rule $label passed.");
1.27      www      1498:    return 1;
1.24      www      1499: }
                   1500: 
1.49      www      1501: #
                   1502: # check for minimum and maximum lengths
                   1503: #
                   1504: 
                   1505: sub checklength {
                   1506:     my ($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)=@_;
                   1507:     unless (($minimumlength) || ($maximumlength)) { return 1; }
                   1508:     my $length=&actualval($i,$xmin,$xmax)-&actualval($li,$xmin,$xmax);
                   1509:     if ($minimumlength) {
                   1510:        if ($length<$minimumlength) {
                   1511:           &addlog("Rule $label failed, actual length $length, minimum length $minimumlength");
                   1512:           &setfailed($label);
                   1513:           return 0;
                   1514:        }
                   1515:     }
                   1516:     if ($maximumlength) {
                   1517:        if ($length>$maximumlength) {
                   1518:           &addlog("Rule $label failed, actual length $length, maximum length $maximumlength");
                   1519:           &setfailed($label);
                   1520:           return 0;
                   1521:        }
                   1522:     }
                   1523:     return 1;
                   1524: }
                   1525: 
                   1526: sub setfailed {
                   1527:    my ($label)=@_;
                   1528:    my $hintlabel=$label;
                   1529:    $hintlabel=~s/^R//;
                   1530:    push(@Apache::functionplotresponse::failedrules,$hintlabel);
                   1531:    &addlog("Set hint condition $hintlabel");
                   1532: }
                   1533: 
1.37      www      1534: sub start_functionplotruleset {
                   1535:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1536:    if ($target eq 'edit') {
                   1537:       return &Apache::edit::start_table($token).
                   1538:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Rule Set').'</span></td>'
                   1539:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
                   1540:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
1.50      www      1541:         &Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
                   1542:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Rule_Set','Function Plot Rules')
1.37      www      1543:        .'</span></td>'
                   1544:        ."<td>&nbsp;"
                   1545:        .&Apache::edit::end_row()
                   1546:        .&Apache::edit::start_spanning_row()
                   1547:        ."\n";
                   1548:    }
                   1549: }
1.3       www      1550: 
1.37      www      1551: sub end_functionplotruleset {
                   1552:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                   1553:     my $id=$Apache::inputtags::response[-1];
                   1554:     my $partid=$Apache::inputtags::part;
                   1555:     my $internalid = $partid.'_'.$id;
                   1556: 
                   1557:     if ($target eq 'edit' ) {
                   1558:         return &Apache::edit::end_table();
                   1559:     }  elsif ($target eq 'grade'
1.10      www      1560:          && &Apache::response::submitted()
                   1561:          && $Apache::lonhomework::type ne 'exam') {
1.12      www      1562: #
                   1563: # Actually grade
                   1564: #
1.41      www      1565:     my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
1.27      www      1566: 
1.24      www      1567:         my $ad='';
1.30      www      1568:         undef  %Apache::functionplotresponse::functionplotrulelabels;
1.35      www      1569:         $Apache::functionplotresponse::ruleslog='';
1.30      www      1570:         $Apache::functionplotresponse::functionplotrulelabels{'start'}=400;
                   1571:         $Apache::functionplotresponse::functionplotrulelabels{'end'}=0;
1.64      www      1572:         if (&populate_arrays($internalid,$xmin,$xmax,$ymin,$ymax) eq 'no_func') {
1.21      www      1573:            $ad='NOT_FUNCTION';
1.18      www      1574:         } else {
1.35      www      1575:            &addlog("Start of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'start'},$xmin,$xmax)." (index ".
                   1576:                                         $Apache::functionplotresponse::functionplotrulelabels{'start'}.")");
                   1577:            &addlog("End of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'end'},$xmin,$xmax)." (index ".
                   1578:                                         $Apache::functionplotresponse::functionplotrulelabels{'end'}.")");
                   1579: 
1.24      www      1580: # We have a function that we can actually grade, go through the spline rules.
1.25      www      1581:            foreach my $rule (@Apache::functionplotresponse::functionplotrules) {
1.65      www      1582:               unless (&functionplotrulecheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)) {
1.24      www      1583:                  $ad='INCORRECT';
                   1584:                  last;
                   1585:               }
                   1586:            }
                   1587: # If it's not wrong, it's correct 
                   1588:            unless ($ad) { $ad='EXACT_ANS' };
1.18      www      1589:         }
1.37      www      1590:         &addlog("Set hint conditions: ".join(",",@Apache::functionplotresponse::failedrules));
                   1591:         &addlog("Assigned award detail: $ad");
                   1592: # Store for later to be assigned at end_functionplotresponse
                   1593:         $Apache::functionplotresponse::awarddetail=$ad;
                   1594:      }
                   1595: }
                   1596: 
                   1597: 
                   1598: sub end_functionplotresponse {
                   1599:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1600:   &Apache::response::end_response;
                   1601: 
                   1602:   my $result;
                   1603:   my $id=$Apache::inputtags::response[-1];
                   1604:   my $partid=$Apache::inputtags::part;
                   1605:   my $internalid = $partid.'_'.$id;
1.20      www      1606: 
1.37      www      1607:     if ($target eq 'edit') { $result=&Apache::edit::end_table(); }
                   1608:     if ($target eq 'grade'
                   1609:          && &Apache::response::submitted()
                   1610:          && $Apache::lonhomework::type eq 'exam') {
                   1611: 
                   1612:         &Apache::response::scored_response($partid,$id);
                   1613: 
                   1614:     } elsif ($target eq 'grade'
                   1615:          && &Apache::response::submitted()
                   1616:          && $Apache::lonhomework::type ne 'exam') {
                   1617:         my ($response,%coords)=&get_answer_from_form_fields($internalid);
                   1618:         $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
                   1619:         my %previous=&Apache::response::check_for_previous($response,$partid,$id);
                   1620: #
                   1621: # Assign grade
                   1622: #
                   1623:         my $ad=$Apache::functionplotresponse::awarddetail;
1.12      www      1624: #
                   1625: # Store grading info
                   1626: #
                   1627:         $Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
                   1628:         &Apache::response::handle_previous(\%previous,$ad);
1.10      www      1629:    } elsif ($target eq 'web') {
1.37      www      1630:         undef @Apache::functionplotresponse::failedrules;
                   1631:    }
                   1632:    return $result;
                   1633: }
                   1634: 
                   1635: sub end_functionplotelements {
                   1636:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
                   1637:   my $result='';
                   1638:   my $id=$Apache::inputtags::response[-1];
                   1639:   my $partid=$Apache::inputtags::part;
                   1640:   my $internalid = $partid.'_'.$id;
                   1641:   if ($target eq 'edit' ) {
                   1642:      $result=&Apache::edit::end_table();
                   1643:   } elsif ($target eq 'web') {
1.47      www      1644:      my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
                   1645: 
                   1646: # Are we in show answer mode?
                   1647:      my $showanswer=&Apache::response::show_answer();
                   1648:      if ($showanswer) {
                   1649: # Render answerdisplay
                   1650:         my $answerdisplay=&Apache::lonxml::get_param('answerdisplay',$parstack,$safeeval,-2);
                   1651:         if ($answerdisplay=~/\S/s) {
                   1652:            foreach my $plot (split(/\s*\,\s*/,$answerdisplay)) {
1.58      www      1653:               my @components=split(/\s*\:\s*/,$plot);
                   1654:               if ($#components<3) {
                   1655: # Just a simple plot
                   1656:                  my ($func,$xl,$xh)=@components;
                   1657:                  if ((!defined($xl)) || ($xl eq '')) { $xl=$xmin; }
                   1658:                  if ((!defined($xh)) || ($xh eq '')) { $xh=$xmax; }
                   1659:                  $result.=&plot_script($internalid,$func,1,'','00aa00',$xl,$xh,6);
                   1660:               } else {
                   1661: # This is a spline
1.59      www      1662:                  $result.=&answer_spline_script($internalid,@components);
1.58      www      1663:               }
1.47      www      1664:            }
                   1665:         }
                   1666:      }
1.48      www      1667:      my $fixed=0;
                   1668:      if (($showanswer) || (&Apache::response::check_status()>=2)) { $fixed=1; }
1.6       www      1669: # Now is the time to render all of the stored splines
                   1670:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
1.48      www      1671:         $result.=&generate_spline($internalid,$label,$xmin,$xmax,$ymin,$ymax,$fixed);
1.6       www      1672:      }
1.5       www      1673: # close the init script
1.3       www      1674:      $result.=&end_init_script();
1.17      www      1675: # register all splines in this response 
                   1676:      $result.='<input type="hidden" name="HWVAL_AllSplines_'.$internalid.'" value="'.
                   1677:                  join(',',keys(%Apache::functionplotresponse::splineorder)).'" />'."\n";
                   1678:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
                   1679:         $result.='<input type="hidden" name="HWVAL_SplineOrder_'.$internalid.'_'.$label.'" value="'.
                   1680:                  $Apache::functionplotresponse::splineorder{$label}.'" />'."\n";
                   1681:      }
1.9       www      1682: # generate the input fields
                   1683:      $result.=$Apache::functionplotresponse::inputfields;
1.5       www      1684: # actually start the <applet>-tag
1.3       www      1685:      $result.=&geogebra_startcode($internalid);
1.5       www      1686: # load the spline bytecode
1.3       www      1687:      $result.=&geogebra_spline_program();
1.5       www      1688: # set default parameters
1.3       www      1689:      $result.=&geogebra_default_parameters($internalid);
1.5       www      1690: # close the <applet>-tag
1.1       www      1691:      $result.=&geogebra_endcode();
                   1692:   }
                   1693:   return $result;
                   1694: }
                   1695: 
1.41      www      1696: sub boundaries {
                   1697:    my ($parstack,$safeeval,$level)=@_;
                   1698:    my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval,$level);
                   1699:    $xmin=(defined($xmin)?$xmin:-10);
                   1700:    my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval,$level);
                   1701:    $xmax=(defined($xmax)?$xmax:10);
                   1702:    my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval,$level);
                   1703:    $ymin=(defined($ymin)?$ymin:-10);
                   1704:    my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval,$level);
                   1705:    $ymax=(defined($ymax)?$ymax:10);
                   1706:    if ($xmax<=$xmin) {
                   1707:       $xmax=$xmin+20;
                   1708:    }
                   1709:    if ($ymax<=$ymin) {
                   1710:       $ymax=$ymin+20;
                   1711:    }
                   1712:    return ($xmin,$xmax,$ymin,$ymax);
                   1713: }
                   1714: 
1.37      www      1715: sub start_functionplotelements {
                   1716:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
                   1717:    my $result='';
                   1718:    my $id=$Apache::inputtags::response[-1];
                   1719:    my $partid=$Apache::inputtags::part;
                   1720:    my $internalid = $partid.'_'.$id;
                   1721: 
                   1722:    if ($target eq 'edit') {
                   1723:       return &Apache::edit::start_table($token).
                   1724:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Elements').'</span></td>'
                   1725:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
                   1726:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
1.50      www      1727:         &Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
                   1728:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Elements','Function Plot Elements')
1.37      www      1729:        .'</span></td>'
                   1730:        ."<td>&nbsp;"
                   1731:        .&Apache::edit::end_row()
                   1732:        .&Apache::edit::start_spanning_row()
                   1733:        ."\n";
                   1734:    } elsif ($target eq 'web') {
1.41      www      1735:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
1.37      www      1736:       my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1737:       my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1738:       my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
                   1739:       my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval,-2);
                   1740:       my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval,-2);
                   1741: 
                   1742: 
                   1743: # paste in the update routine to receive stuff back from the applet
                   1744:      $result.=&update_script($internalid);
                   1745: # start the initscript for this applet
                   1746:      $result.=&start_init_script($internalid);
                   1747: # put the axis commands inside
                   1748:      $result.=&axes_script($internalid,$xmin,$xmax,$ymin,$ymax,$xaxisvisible,$yaxisvisible,$gridvisible);
1.45      www      1749:      $result.=&axes_label($internalid,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel);
1.37      www      1750: # init script is left open
                   1751:   }
                   1752:   return $result;
                   1753: }
                   1754: 
1.1       www      1755: 1;
                   1756: 
                   1757: __END__
                   1758:  
                   1759: =head1 NAME
                   1760: 
                   1761: Apache::functionplotresponse.pm;
                   1762: 
                   1763: =head1 SYNOPSIS
                   1764: 
                   1765: Handles tags associated with accepting function plots.
                   1766: 
                   1767: This is part of the LearningOnline Network with CAPA project
                   1768: described at http://www.lon-capa.org.
                   1769: 
                   1770: =head1 HANDLER SUBROUTINE
                   1771: 
                   1772: start_functionplotresponse()
                   1773: 
                   1774: =head1 OTHER SUBROUTINES
                   1775: 
                   1776: =over
                   1777: 
                   1778: =item end_functionplotresponse()
                   1779: 
                   1780: =back
                   1781: 
                   1782: =cut

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