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