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