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