]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
- fix two bugs
[flightgear.git] / src / Scripting / NasalSys.cxx
1
2 #ifdef HAVE_CONFIG_H
3 #  include "config.h"
4 #endif
5
6 #include <string.h>
7 #include <stdio.h>
8 #include <sys/types.h>
9 #include <sys/stat.h>
10
11 #include <plib/ul.h>
12
13 #include <simgear/nasal/nasal.h>
14 #include <simgear/props/props.hxx>
15 #include <simgear/math/sg_random.h>
16 #include <simgear/misc/sg_path.hxx>
17 #include <simgear/misc/interpolator.hxx>
18 #include <simgear/structure/commands.hxx>
19
20 #include <Main/globals.hxx>
21 #include <Main/fg_props.hxx>
22
23 #include "NasalSys.hxx"
24
25 // Read and return file contents in a single buffer.  Note use of
26 // stat() to get the file size.  This is a win32 function, believe it
27 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
28 // Text mode brain damage will kill us if we're trying to do bytewise
29 // I/O.
30 static char* readfile(const char* file, int* lenOut)
31 {
32     struct stat data;
33     if(stat(file, &data) != 0) return 0;
34     FILE* f = fopen(file, "rb");
35     if(!f) return 0;
36     char* buf = new char[data.st_size];
37     *lenOut = fread(buf, 1, data.st_size, f);
38     fclose(f);
39     if(*lenOut != data.st_size) {
40         // Shouldn't happen, but warn anyway since it represents a
41         // platform bug and not a typical runtime error (missing file,
42         // etc...)
43         SG_LOG(SG_NASAL, SG_ALERT,
44                "ERROR in Nasal initialization: " <<
45                "short count returned from fread() of " << file <<
46                ".  Check your C library!");
47         delete[] buf;
48         return 0;
49     }
50     return buf;
51 }
52
53 FGNasalSys::FGNasalSys()
54 {
55     _context = 0;
56     _globals = naNil();
57     _gcHash = naNil();
58     _nextGCKey = 0; // Any value will do
59 }
60
61 FGNasalSys::~FGNasalSys()
62 {
63     map<int, FGNasalListener *>::iterator it, end = _listener.end();
64     for (it = _listener.begin(); it != end; ++it)
65         delete it->second;
66
67     // Nasal doesn't have a "destroy context" API yet. :(
68     // Not a problem for a global subsystem that will never be
69     // destroyed.  And the context is actually a global, so no memory
70     // is technically leaked (although the GC pool memory obviously
71     // won't be freed).
72     _context = 0;
73     _globals = naNil();
74 }
75
76 bool FGNasalSys::parseAndRun(const char* sourceCode)
77 {
78     naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
79                        strlen(sourceCode));
80     if(naIsNil(code))
81         return false;
82
83     naCall(_context, code, 0, 0, naNil(), naNil());
84
85     if(!naGetError(_context)) return true;
86     logError(_context);
87     return false;
88 }
89
90 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
91 {
92     FGNasalScript* script = new FGNasalScript();
93     script->_gcKey = -1; // important, if we delete it on a parse
94     script->_nas = this; // error, don't clobber a real handle!
95
96     char buf[256];
97     if(!name) {
98         sprintf(buf, "FGNasalScript@%p", script);
99         name = buf;
100     }
101
102     script->_code = parse(name, src, strlen(src));
103     if(naIsNil(script->_code)) {
104         delete script;
105         return 0;
106     }
107
108     script->_gcKey = gcSave(script->_code);
109     return script;
110 }
111
112 // Utility.  Sets a named key in a hash by C string, rather than nasal
113 // string object.
114 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
115 {
116     naRef s = naNewString(_context);
117     naStr_fromdata(s, (char*)key, strlen(key));
118     naHash_set(hash, s, val);
119 }
120
121 // The get/setprop functions accept a *list* of strings and walk
122 // through the property tree with them to find the appropriate node.
123 // This allows a Nasal object to hold onto a property path and use it
124 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02).  This
125 // is the utility function that walks the property tree.
126 // Future enhancement: support integer arguments to specify array
127 // elements.
128 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
129 {
130     SGPropertyNode* p = globals->get_props();
131     try {
132         for(int i=0; i<len; i++) {
133             naRef a = vec[i];
134             if(!naIsString(a)) return 0;
135             p = p->getNode(naStr_data(a));
136             if(p == 0) return 0;
137         }
138     } catch (const string& err) {
139         naRuntimeError(c, (char *)err.c_str());
140         return 0;
141     }
142     return p;
143 }
144
145 // getprop() extension function.  Concatenates its string arguments as
146 // property names and returns the value of the specified property.  Or
147 // nil if it doesn't exist.
148 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
149 {
150     const SGPropertyNode* p = findnode(c, args, argc);
151     if(!p) return naNil();
152
153     switch(p->getType()) {
154     case SGPropertyNode::BOOL:   case SGPropertyNode::INT:
155     case SGPropertyNode::LONG:   case SGPropertyNode::FLOAT:
156     case SGPropertyNode::DOUBLE:
157         return naNum(p->getDoubleValue());
158
159     case SGPropertyNode::STRING:
160     case SGPropertyNode::UNSPECIFIED:
161         {
162             naRef nastr = naNewString(c);
163             const char* val = p->getStringValue();
164             naStr_fromdata(nastr, (char*)val, strlen(val));
165             return nastr;
166         }
167     case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
168     default:
169         return naNil();
170     }
171 }
172
173 // setprop() extension function.  Concatenates its string arguments as
174 // property names and sets the value of the specified property to the
175 // final argument.
176 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
177 {
178 #define BUFLEN 1024
179     char buf[BUFLEN + 1];
180     buf[BUFLEN] = 0;
181     char* p = buf;
182     int buflen = BUFLEN;
183     for(int i=0; i<argc-1; i++) {
184         naRef s = naStringValue(c, args[i]);
185         if(naIsNil(s)) return naNil();
186         strncpy(p, naStr_data(s), buflen);
187         p += naStr_len(s);
188         buflen = BUFLEN - (p - buf);
189         if(i < (argc-2) && buflen > 0) {
190             *p++ = '/';
191             buflen--;
192         }
193     }
194
195     SGPropertyNode* props = globals->get_props();
196     naRef val = args[argc-1];
197     try {
198         if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
199         else                props->setDoubleValue(buf, naNumValue(val).num);
200     } catch (const string& err) {
201         naRuntimeError(c, (char *)err.c_str());
202     }
203     return naNil();
204 #undef BUFLEN
205 }
206
207 // print() extension function.  Concatenates and prints its arguments
208 // to the FlightGear log.  Uses the highest log level (SG_ALERT), to
209 // make sure it appears.  Is there better way to do this?
210 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
211 {
212 #define BUFLEN 1024
213     char buf[BUFLEN + 1];
214     buf[BUFLEN] = 0; // extra nul to handle strncpy brain damage
215     buf[0] = 0; // Zero-length in case there are no arguments
216     char* p = buf;
217     int buflen = BUFLEN;
218     int n = argc;
219     for(int i=0; i<n; i++) {
220         naRef s = naStringValue(c, args[i]);
221         if(naIsNil(s)) continue;
222         strncpy(p, naStr_data(s), buflen);
223         p += naStr_len(s);
224         buflen = BUFLEN - (p - buf);
225         if(buflen <= 0) break;
226     }
227     SG_LOG(SG_GENERAL, SG_ALERT, buf);
228     return naNil();
229 #undef BUFLEN
230 }
231
232 // fgcommand() extension function.  Executes a named command via the
233 // FlightGear command manager.  Takes a single property node name as
234 // an argument.
235 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
236 {
237     if(argc < 2 || !naIsString(args[0]) || !naIsGhost(args[1]))
238         naRuntimeError(c, "bad arguments to fgcommand()");
239     naRef cmd = args[0], props = args[1];
240     SGPropertyNode_ptr* node = (SGPropertyNode_ptr*)naGhost_ptr(props);
241     globals->get_commands()->execute(naStr_data(cmd), *node);
242     return naNil();
243
244 }
245
246 // settimer(func, dt, simtime) extension function.  Falls through to
247 // FGNasalSys::setTimer().  See there for docs.
248 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
249 {
250     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
251     nasal->setTimer(argc, args);
252     return naNil();
253 }
254
255 // setlistener(func, property, bool) extension function.  Falls through to
256 // FGNasalSys::setListener().  See there for docs.
257 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
258 {
259     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
260     return nasal->setListener(argc, args);
261 }
262
263 // removelistener(int) extension function. Falls through to
264 // FGNasalSys::removeListener(). See there for docs.
265 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
266 {
267     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
268     return nasal->removeListener(argc, args);
269 }
270
271 // Returns a ghost handle to the argument to the currently executing
272 // command
273 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
274 {
275     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
276     return nasal->cmdArgGhost();
277 }
278
279 // Sets up a property interpolation.  The first argument is either a
280 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
281 // interpolate.  The second argument is a vector of pairs of
282 // value/delta numbers.
283 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
284 {
285     SGPropertyNode* node;
286     naRef prop = argc > 0 ? args[0] : naNil();
287     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
288     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
289     else return naNil();
290
291     naRef curve = argc > 1 ? args[1] : naNil();
292     if(!naIsVector(curve)) return naNil();
293     int nPoints = naVec_size(curve) / 2;
294     double* values = new double[nPoints];
295     double* deltas = new double[nPoints];
296     for(int i=0; i<nPoints; i++) {
297         values[i] = naNumValue(naVec_get(curve, 2*i)).num;
298         deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
299     }
300
301     ((SGInterpolator*)globals->get_subsystem("interpolator"))
302         ->interpolate(node, nPoints, values, deltas);
303
304     return naNil();
305 }
306
307 // This is a better RNG than the one in the default Nasal distribution
308 // (which is based on the C library rand() implementation). It will
309 // override.
310 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
311 {
312     return naNum(sg_random());
313 }
314
315 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
316 {
317     sg_srandom_time();
318     return naNum(0);
319 }
320
321 // Return an array listing of all files in a directory
322 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
323 {
324     if(argc != 1 || !naIsString(args[0]))
325         naRuntimeError(c, "bad arguments to directory()");
326     naRef ldir = args[0];
327     ulDir* dir = ulOpenDir(naStr_data(args[0]));
328     if(!dir) return naNil();
329     naRef result = naNewVector(c);
330     ulDirEnt* dent;
331     while((dent = ulReadDir(dir)))
332         naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
333                                             strlen(dent->d_name)));
334     ulCloseDir(dir);
335     return result;
336 }
337
338 // Table of extension functions.  Terminate with zeros.
339 static struct { char* name; naCFunction func; } funcs[] = {
340     { "getprop",   f_getprop },
341     { "setprop",   f_setprop },
342     { "print",     f_print },
343     { "_fgcommand", f_fgcommand },
344     { "settimer",  f_settimer },
345     { "_setlistener", f_setlistener },
346     { "removelistener", f_removelistener },
347     { "_cmdarg",  f_cmdarg },
348     { "_interpolate",  f_interpolate },
349     { "rand",  f_rand },
350     { "srand",  f_srand },
351     { "directory", f_directory },
352     { 0, 0 }
353 };
354
355 naRef FGNasalSys::cmdArgGhost()
356 {
357     return propNodeGhost(_cmdArg);
358 }
359
360 void FGNasalSys::init()
361 {
362     int i;
363
364     _context = naNewContext();
365
366     // Start with globals.  Add it to itself as a recursive
367     // sub-reference under the name "globals".  This gives client-code
368     // write access to the namespace if someone wants to do something
369     // fancy.
370     _globals = naStdLib(_context);
371     naSave(_context, _globals);
372     hashset(_globals, "globals", _globals);
373
374     // Add in the math library under "math"
375     hashset(_globals, "math", naMathLib(_context));
376
377     // Add in the IO library.  Disabled currently until after the
378     // 0.9.10 release.
379     // hashset(_globals, "io", naIOLib(_context));
380     // hashset(_globals, "bits", naBitsLib(_context));
381
382     // Add our custom extension functions:
383     for(i=0; funcs[i].name; i++)
384         hashset(_globals, funcs[i].name,
385                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
386
387     // And our SGPropertyNode wrapper
388     hashset(_globals, "props", genPropsModule());
389
390     // Make a "__gcsave" hash to hold the naRef objects which get
391     // passed to handles outside the interpreter (to protect them from
392     // begin garbage-collected).
393     _gcHash = naNewHash(_context);
394     hashset(_globals, "__gcsave", _gcHash);
395
396     // Now load the various source files in the Nasal directory
397     SGPath p(globals->get_fg_root());
398     p.append("Nasal");
399     ulDirEnt* dent;
400     ulDir* dir = ulOpenDir(p.c_str());
401     while(dir && (dent = ulReadDir(dir)) != 0) {
402         SGPath fullpath(p);
403         fullpath.append(dent->d_name);
404         SGPath file(dent->d_name);
405         if(file.extension() != "nas") continue;
406         loadModule(fullpath, file.base().c_str());
407     }
408     ulCloseDir(dir);
409
410     // Pull scripts out of the property tree, too
411     loadPropertyScripts();
412 }
413
414 // Loads the scripts found under /nasal in the global tree
415 void FGNasalSys::loadPropertyScripts()
416 {
417     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
418     if(!nasal) return;
419
420     for(int i=0; i<nasal->nChildren(); i++) {
421         SGPropertyNode* n = nasal->getChild(i);
422
423         const char* module = n->getName();
424         if(n->hasChild("module"))
425             module = n->getStringValue("module");
426
427         // allow multiple files to be specified within in a single
428         // Nasal module tag
429         int j = 0;
430         SGPropertyNode *fn;
431         bool file_specified = false;
432         while ( (fn = n->getChild("file", j)) != NULL ) {
433             file_specified = true;
434             const char* file = fn->getStringValue();
435             SGPath p(globals->get_fg_root());
436             p.append(file);
437             loadModule(p, module);
438             j++;
439         }
440
441         // Old code which only allowed a single file to be specified per module
442         /*
443         const char* file = n->getStringValue("file");
444         if(!n->hasChild("file")) file = 0; // Hrm...
445         if(file) {
446             SGPath p(globals->get_fg_root());
447             p.append(file);
448             loadModule(p, module);
449         }
450         */
451         
452         const char* src = n->getStringValue("script");
453         if(!n->hasChild("script")) src = 0; // Hrm...
454         if(src)
455             createModule(module, n->getPath(), src, strlen(src));
456
457         if(!file_specified && !src)
458             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
459                    "no <file> or <script> defined in " <<
460                    "/nasal/" << module);
461     }
462 }
463
464 // Logs a runtime error, with stack trace, to the FlightGear log stream
465 void FGNasalSys::logError(naContext context)
466 {
467     SG_LOG(SG_NASAL, SG_ALERT,
468            "Nasal runtime error: " << naGetError(context));
469     SG_LOG(SG_NASAL, SG_ALERT,
470            "  at " << naStr_data(naGetSourceFile(context, 0)) <<
471            ", line " << naGetLine(context, 0));
472     for(int i=1; i<naStackDepth(context); i++)
473         SG_LOG(SG_NASAL, SG_ALERT,
474                "  called from: " << naStr_data(naGetSourceFile(context, i)) <<
475                ", line " << naGetLine(context, i));
476 }
477
478 // Reads a script file, executes it, and places the resulting
479 // namespace into the global namespace under the specified module
480 // name.
481 void FGNasalSys::loadModule(SGPath file, const char* module)
482 {
483     int len = 0;
484     char* buf = readfile(file.c_str(), &len);
485     if(!buf) {
486         SG_LOG(SG_NASAL, SG_ALERT,
487                "Nasal error: could not read script file " << file.c_str()
488                << " into module " << module);
489         return;
490     }
491
492     createModule(module, file.c_str(), buf, len);
493     delete[] buf;
494 }
495
496 // Parse and run.  Save the local variables namespace, as it will
497 // become a sub-object of globals.  The optional "arg" argument can be
498 // used to pass an associated property node to the module, which can then
499 // be accessed via cmdarg().  (This is, for example, used by XML dialogs.)
500 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
501                               const char* src, int len, const SGPropertyNode* arg)
502 {
503     naRef code = parse(fileName, src, len);
504     if(naIsNil(code))
505         return;
506
507     // See if we already have a module hash to use.  This allows the
508     // user to, for example, add functions to the built-in math
509     // module.  Make a new one if necessary.
510     naRef locals;
511     naRef modname = naNewString(_context);
512     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
513     if(!naHash_get(_globals, modname, &locals))
514         locals = naNewHash(_context);
515
516     _cmdArg = (SGPropertyNode*)arg;
517
518     naCall(_context, code, 0, 0, naNil(), locals);
519     if(naGetError(_context)) {
520         logError(_context);
521         return;
522     }
523     hashset(_globals, moduleName, locals);
524 }
525
526 void FGNasalSys::deleteModule(const char* moduleName)
527 {
528     naRef modname = naNewString(_context);
529     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
530     naModLock();
531     naHash_delete(_globals, modname);
532     naModUnlock();
533 }
534
535 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
536 {
537     int errLine = -1;
538     naRef srcfile = naNewString(_context);
539     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
540     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
541     if(naIsNil(code)) {
542         SG_LOG(SG_NASAL, SG_ALERT,
543                "Nasal parse error: " << naGetError(_context) <<
544                " in "<< filename <<", line " << errLine);
545         return naNil();
546     }
547
548     // Bind to the global namespace before returning
549     return naBindFunction(_context, code, _globals);
550 }
551
552 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
553 {
554     const char* nasal = arg->getStringValue("script");
555     const char* moduleName = arg->getStringValue("module");
556     naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
557     if(naIsNil(code)) return false;
558
559     naContext c = naNewContext();
560     naRef locals = naNil();
561     if(moduleName[0]) {
562         naRef modname = naNewString(c);
563         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
564         if(!naHash_get(_globals, modname, &locals))
565             locals = naNewHash(c);
566     }
567     // Cache the command argument for inspection via cmdarg().  For
568     // performance reasons, we won't bother with it if the invoked
569     // code doesn't need it.
570     _cmdArg = (SGPropertyNode*)arg;
571
572     // Call it!
573     naModUnlock();
574     naRef result = naCall(c, code, 0, 0, naNil(), locals);
575     naModLock();
576     bool error = naGetError(c);
577     if(error)
578        logError(c);
579
580     naFreeContext(c);
581     return !error;
582 }
583
584 // settimer(func, dt, simtime) extension function.  The first argument
585 // is a Nasal function to call, the second is a delta time (from now),
586 // in seconds.  The third, if present, is a boolean value indicating
587 // that "real world" time (rather than simulator time) is to be used.
588 //
589 // Implementation note: the FGTimer objects don't live inside the
590 // garbage collector, so the Nasal handler functions have to be
591 // "saved" somehow lest they be inadvertently cleaned.  In this case,
592 // they are inserted into a globals.__gcsave hash and removed on
593 // expiration.
594 void FGNasalSys::setTimer(int argc, naRef* args)
595 {
596     // Extract the handler, delta, and simtime arguments:
597     naRef handler = argc > 0 ? args[0] : naNil();
598     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
599         return;
600
601     naRef delta = argc > 1 ? args[1] : naNil();
602     if(naIsNil(delta)) return;
603
604     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
605
606     // Generate and register a C++ timer handler
607     NasalTimer* t = new NasalTimer;
608     t->handler = handler;
609     t->gcKey = gcSave(handler);
610     t->nasal = this;
611
612     globals->get_event_mgr()->addEvent("NasalTimer",
613                                        t, &NasalTimer::timerExpired,
614                                        delta.num, simtime);
615 }
616
617 void FGNasalSys::handleTimer(NasalTimer* t)
618 {
619     naCall(_context, t->handler, 0, 0, naNil(), naNil());
620     if(naGetError(_context))
621         logError(_context);
622     gcRelease(t->gcKey);
623 }
624
625 int FGNasalSys::gcSave(naRef r)
626 {
627     int key = _nextGCKey++;
628     naHash_set(_gcHash, naNum(key), r);
629     return key;
630 }
631
632 void FGNasalSys::gcRelease(int key)
633 {
634     naHash_delete(_gcHash, naNum(key));
635 }
636
637 void FGNasalSys::NasalTimer::timerExpired()
638 {
639     nasal->handleTimer(this);
640     delete this;
641 }
642
643 int FGNasalSys::_listenerId = 0;
644
645 // setlistener(property, func, bool) extension function.  The first argument
646 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
647 // path), the second is a Nasal function, the optional third one a bool.
648 // If the bool is true, then the listener is executed initially. The
649 // setlistener() function returns a unique id number, that can be used
650 // as argument to the removelistener() function.
651 naRef FGNasalSys::setListener(int argc, naRef* args)
652 {
653     SGPropertyNode_ptr node;
654     naRef prop = argc > 0 ? args[0] : naNil();
655     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
656     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
657     else return naNil();
658
659     naRef handler = argc > 1 ? args[1] : naNil();
660     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
661         return naNil();
662
663     bool initial = argc > 2 && naTrue(args[2]);
664
665     FGNasalListener *nl = new FGNasalListener(node, handler, this,
666             gcSave(handler));
667     node->addChangeListener(nl, initial);
668
669     _listener[_listenerId] = nl;
670     return naNum(_listenerId++);
671 }
672
673 // removelistener(int) extension function. The argument is the id of
674 // a listener as returned by the setlistener() function.
675 naRef FGNasalSys::removeListener(int argc, naRef* args)
676 {
677     naRef id = argc > 0 ? args[0] : naNil();
678     if(!naIsNum(id))
679         return naNil();
680
681     int i = int(id.num);
682     if (_listener.find(i) == _listener.end())
683         return naNil();
684
685     FGNasalListener *nl = _listener[i];
686     _listener.erase(i);
687     delete nl;
688     return naNum(_listener.size());
689 }
690
691
692
693 // FGNasalListener class.
694
695 FGNasalListener::FGNasalListener(SGPropertyNode_ptr node, naRef handler,
696                                  FGNasalSys* nasal, int key) :
697     _node(node),
698     _handler(handler),
699     _gcKey(key),
700     _nas(nasal),
701     _active(0)
702 {
703 }
704
705 FGNasalListener::~FGNasalListener()
706 {
707     _node->removeChangeListener(this);
708     _nas->gcRelease(_gcKey);
709 }
710
711 void FGNasalListener::valueChanged(SGPropertyNode* node)
712 {
713     if (_active) {
714         SG_LOG(SG_NASAL, SG_ALERT, "Recursive listener call "
715                 "on property " << node->getPath());
716         return;
717     }
718     _active++;
719     _nas->_cmdArg = node;
720     naContext c = naNewContext();
721     naModUnlock();
722     naCall(c, _handler, 0, 0, naNil(), naNil());
723     naModLock();
724     if(naGetError(c))
725         _nas->logError(c);
726     naFreeContext(c);
727     _active--;
728 }
729
730
731
732
733 // FGNasalModelData class.  If sgLoad3DModel() is called with a pointer to
734 // such a class, then it lets modelLoaded() run the <load> script, and the
735 // destructor the <unload> script. The latter happens when the model branch
736 // is removed from the scene graph.
737
738 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
739                                    ssgBranch *)
740 {
741     SGPropertyNode *n = prop->getNode("nasal"), *load;
742     if (!n)
743         return;
744
745     load = n->getNode("load");
746     _unload = n->getNode("unload");
747     if (!load && !_unload)
748         return;
749
750     _module = path;
751     const char *s = load ? load->getStringValue() : "";
752     FGNasalSys *nas = (FGNasalSys *)globals->get_subsystem("nasal");
753     nas->createModule(_module.c_str(), _module.c_str(), s, strlen(s));
754 }
755
756 FGNasalModelData::~FGNasalModelData()
757 {
758     if (_module.empty())
759         return;
760
761     FGNasalSys *nas = (FGNasalSys *)globals->get_subsystem("nasal");
762     if (!nas) {
763         SG_LOG(SG_NASAL, SG_ALERT, "Trying to run an <unload> script "
764                 "without Nasal subsystem present.");
765         return;
766     }
767
768     if (_unload) {
769         const char *s = _unload->getStringValue();
770         nas->createModule(_module.c_str(), _module.c_str(), s, strlen(s));
771     }
772     nas->deleteModule(_module.c_str());
773 }
774
775