]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
add error messages for invalid args to settimer()
[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 static FGNasalSys* nasalSys = 0;
26
27
28 // Read and return file contents in a single buffer.  Note use of
29 // stat() to get the file size.  This is a win32 function, believe it
30 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
31 // Text mode brain damage will kill us if we're trying to do bytewise
32 // I/O.
33 static char* readfile(const char* file, int* lenOut)
34 {
35     struct stat data;
36     if(stat(file, &data) != 0) return 0;
37     FILE* f = fopen(file, "rb");
38     if(!f) return 0;
39     char* buf = new char[data.st_size];
40     *lenOut = fread(buf, 1, data.st_size, f);
41     fclose(f);
42     if(*lenOut != data.st_size) {
43         // Shouldn't happen, but warn anyway since it represents a
44         // platform bug and not a typical runtime error (missing file,
45         // etc...)
46         SG_LOG(SG_NASAL, SG_ALERT,
47                "ERROR in Nasal initialization: " <<
48                "short count returned from fread() of " << file <<
49                ".  Check your C library!");
50         delete[] buf;
51         return 0;
52     }
53     return buf;
54 }
55
56 FGNasalSys::FGNasalSys()
57 {
58     nasalSys = this;
59     _context = 0;
60     _globals = naNil();
61     _gcHash = naNil();
62     _nextGCKey = 0; // Any value will do
63     _callCount = 0;
64     _purgeListeners = false;
65 }
66
67 // Does a naCall() in a new context.  Wrapped here to make lock
68 // tracking easier.  Extension functions are called with the lock, but
69 // we have to release it before making a new naCall().  So rather than
70 // drop the lock in every extension function that might call back into
71 // Nasal, we keep a stack depth counter here and only unlock/lock
72 // around the naCall if it isn't the first one.
73 naRef FGNasalSys::call(naRef code, naRef locals)
74 {
75     naContext ctx = naNewContext();
76     if(_callCount) naModUnlock();
77     _callCount++;
78     naRef result = naCall(ctx, code, 0, 0, naNil(), locals);
79     if(naGetError(ctx))
80         logError(ctx);
81     _callCount--;
82     if(_callCount) naModLock();
83     naFreeContext(ctx);
84     return result;
85 }
86
87 FGNasalSys::~FGNasalSys()
88 {
89     nasalSys = 0;
90     map<int, FGNasalListener *>::iterator it, end = _listener.end();
91     for(it = _listener.begin(); it != end; ++it)
92         delete it->second;
93
94     naFreeContext(_context);
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     nasalSys->setTimer(c, argc, args);
263     return naNil();
264 }
265
266 // setlistener(func, property, bool) extension function.  Falls through to
267 // FGNasalSys::setListener().  See there for docs.
268 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
269 {
270     return nasalSys->setListener(c, argc, args);
271 }
272
273 // removelistener(int) extension function. Falls through to
274 // FGNasalSys::removeListener(). See there for docs.
275 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
276 {
277     return nasalSys->removeListener(c, argc, args);
278 }
279
280 // Returns a ghost handle to the argument to the currently executing
281 // command
282 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
283 {
284     return nasalSys->cmdArgGhost();
285 }
286
287 // Sets up a property interpolation.  The first argument is either a
288 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
289 // interpolate.  The second argument is a vector of pairs of
290 // value/delta numbers.
291 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
292 {
293     SGPropertyNode* node;
294     naRef prop = argc > 0 ? args[0] : naNil();
295     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
296     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
297     else return naNil();
298
299     naRef curve = argc > 1 ? args[1] : naNil();
300     if(!naIsVector(curve)) return naNil();
301     int nPoints = naVec_size(curve) / 2;
302     double* values = new double[nPoints];
303     double* deltas = new double[nPoints];
304     for(int i=0; i<nPoints; i++) {
305         values[i] = naNumValue(naVec_get(curve, 2*i)).num;
306         deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
307     }
308
309     ((SGInterpolator*)globals->get_subsystem_mgr()
310         ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
311         ->interpolate(node, nPoints, values, deltas);
312
313     return naNil();
314 }
315
316 // This is a better RNG than the one in the default Nasal distribution
317 // (which is based on the C library rand() implementation). It will
318 // override.
319 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
320 {
321     return naNum(sg_random());
322 }
323
324 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
325 {
326     sg_srandom_time();
327     return naNum(0);
328 }
329
330 // Return an array listing of all files in a directory
331 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
332 {
333     if(argc != 1 || !naIsString(args[0]))
334         naRuntimeError(c, "bad arguments to directory()");
335     naRef ldir = args[0];
336     ulDir* dir = ulOpenDir(naStr_data(args[0]));
337     if(!dir) return naNil();
338     naRef result = naNewVector(c);
339     ulDirEnt* dent;
340     while((dent = ulReadDir(dir)))
341         naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
342                                             strlen(dent->d_name)));
343     ulCloseDir(dir);
344     return result;
345 }
346
347 // Table of extension functions.  Terminate with zeros.
348 static struct { char* name; naCFunction func; } funcs[] = {
349     { "getprop",   f_getprop },
350     { "setprop",   f_setprop },
351     { "print",     f_print },
352     { "_fgcommand", f_fgcommand },
353     { "settimer",  f_settimer },
354     { "_setlistener", f_setlistener },
355     { "removelistener", f_removelistener },
356     { "_cmdarg",  f_cmdarg },
357     { "_interpolate",  f_interpolate },
358     { "rand",  f_rand },
359     { "srand",  f_srand },
360     { "directory", f_directory },
361     { 0, 0 }
362 };
363
364 naRef FGNasalSys::cmdArgGhost()
365 {
366     return propNodeGhost(_cmdArg);
367 }
368
369 void FGNasalSys::init()
370 {
371     int i;
372
373     _context = naNewContext();
374
375     // Start with globals.  Add it to itself as a recursive
376     // sub-reference under the name "globals".  This gives client-code
377     // write access to the namespace if someone wants to do something
378     // fancy.
379     _globals = naInit_std(_context);
380     naSave(_context, _globals);
381     hashset(_globals, "globals", _globals);
382
383     hashset(_globals, "math", naInit_math(_context));
384     hashset(_globals, "bits", naInit_bits(_context));
385     hashset(_globals, "io", naInit_io(_context));
386     hashset(_globals, "thread", naInit_thread(_context));
387     hashset(_globals, "utf8", naInit_utf8(_context));
388
389     // Add our custom extension functions:
390     for(i=0; funcs[i].name; i++)
391         hashset(_globals, funcs[i].name,
392                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
393
394     // And our SGPropertyNode wrapper
395     hashset(_globals, "props", genPropsModule());
396
397     // Make a "__gcsave" hash to hold the naRef objects which get
398     // passed to handles outside the interpreter (to protect them from
399     // begin garbage-collected).
400     _gcHash = naNewHash(_context);
401     hashset(_globals, "__gcsave", _gcHash);
402
403     // Now load the various source files in the Nasal directory
404     SGPath p(globals->get_fg_root());
405     p.append("Nasal");
406     ulDirEnt* dent;
407     ulDir* dir = ulOpenDir(p.c_str());
408     while(dir && (dent = ulReadDir(dir)) != 0) {
409         SGPath fullpath(p);
410         fullpath.append(dent->d_name);
411         SGPath file(dent->d_name);
412         if(file.extension() != "nas") continue;
413         loadModule(fullpath, file.base().c_str());
414     }
415     ulCloseDir(dir);
416
417     // set signal and remove node to avoid restoring at reinit
418     const char *s = "nasal-dir-initialized";
419     SGPropertyNode *signal = fgGetNode("/sim/signals", true);
420     signal->setBoolValue(s, true);
421     signal->removeChildren(s);
422
423     // Pull scripts out of the property tree, too
424     loadPropertyScripts();
425 }
426
427 void FGNasalSys::update(double)
428 {
429     if(_purgeListeners) {
430         _purgeListeners = false;
431         map<int, FGNasalListener *>::iterator it;
432         for(it = _listener.begin(); it != _listener.end();) {
433             FGNasalListener *nl = it->second;
434             if(nl->_dead) {
435                 _listener.erase(it++);
436                 delete nl;
437             } else {
438                 ++it;
439             }
440         }
441     }
442 }
443
444 // Loads the scripts found under /nasal in the global tree
445 void FGNasalSys::loadPropertyScripts()
446 {
447     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
448     if(!nasal) return;
449
450     for(int i=0; i<nasal->nChildren(); i++) {
451         SGPropertyNode* n = nasal->getChild(i);
452
453         const char* module = n->getName();
454         if(n->hasChild("module"))
455             module = n->getStringValue("module");
456
457         // allow multiple files to be specified within in a single
458         // Nasal module tag
459         int j = 0;
460         SGPropertyNode *fn;
461         bool file_specified = false;
462         while ( (fn = n->getChild("file", j)) != NULL ) {
463             file_specified = true;
464             const char* file = fn->getStringValue();
465             SGPath p(globals->get_fg_root());
466             p.append(file);
467             loadModule(p, module);
468             j++;
469         }
470
471         // Old code which only allowed a single file to be specified per module
472         /*
473         const char* file = n->getStringValue("file");
474         if(!n->hasChild("file")) file = 0; // Hrm...
475         if(file) {
476             SGPath p(globals->get_fg_root());
477             p.append(file);
478             loadModule(p, module);
479         }
480         */
481         
482         const char* src = n->getStringValue("script");
483         if(!n->hasChild("script")) src = 0; // Hrm...
484         if(src)
485             createModule(module, n->getPath(), src, strlen(src));
486
487         if(!file_specified && !src)
488             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
489                    "no <file> or <script> defined in " <<
490                    "/nasal/" << module);
491     }
492 }
493
494 // Logs a runtime error, with stack trace, to the FlightGear log stream
495 void FGNasalSys::logError(naContext context)
496 {
497     SG_LOG(SG_NASAL, SG_ALERT,
498            "Nasal runtime error: " << naGetError(context));
499     SG_LOG(SG_NASAL, SG_ALERT,
500            "  at " << naStr_data(naGetSourceFile(context, 0)) <<
501            ", line " << naGetLine(context, 0));
502     for(int i=1; i<naStackDepth(context); i++)
503         SG_LOG(SG_NASAL, SG_ALERT,
504                "  called from: " << naStr_data(naGetSourceFile(context, i)) <<
505                ", line " << naGetLine(context, i));
506 }
507
508 // Reads a script file, executes it, and places the resulting
509 // namespace into the global namespace under the specified module
510 // name.
511 void FGNasalSys::loadModule(SGPath file, const char* module)
512 {
513     int len = 0;
514     char* buf = readfile(file.c_str(), &len);
515     if(!buf) {
516         SG_LOG(SG_NASAL, SG_ALERT,
517                "Nasal error: could not read script file " << file.c_str()
518                << " into module " << module);
519         return;
520     }
521
522     createModule(module, file.c_str(), buf, len);
523     delete[] buf;
524 }
525
526 // Parse and run.  Save the local variables namespace, as it will
527 // become a sub-object of globals.  The optional "arg" argument can be
528 // used to pass an associated property node to the module, which can then
529 // be accessed via cmdarg().  (This is, for example, used by XML dialogs.)
530 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
531                               const char* src, int len, const SGPropertyNode* arg)
532 {
533     naRef code = parse(fileName, src, len);
534     if(naIsNil(code))
535         return;
536
537     // See if we already have a module hash to use.  This allows the
538     // user to, for example, add functions to the built-in math
539     // module.  Make a new one if necessary.
540     naRef locals;
541     naRef modname = naNewString(_context);
542     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
543     if(!naHash_get(_globals, modname, &locals))
544         locals = naNewHash(_context);
545
546     _cmdArg = (SGPropertyNode*)arg;
547
548     call(code, locals);
549     hashset(_globals, moduleName, locals);
550 }
551
552 void FGNasalSys::deleteModule(const char* moduleName)
553 {
554     naRef modname = naNewString(_context);
555     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
556     naHash_delete(_globals, modname);
557 }
558
559 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
560 {
561     int errLine = -1;
562     naRef srcfile = naNewString(_context);
563     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
564     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
565     if(naIsNil(code)) {
566         SG_LOG(SG_NASAL, SG_ALERT,
567                "Nasal parse error: " << naGetError(_context) <<
568                " in "<< filename <<", line " << errLine);
569         return naNil();
570     }
571
572     // Bind to the global namespace before returning
573     return naBindFunction(_context, code, _globals);
574 }
575
576 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
577 {
578     const char* nasal = arg->getStringValue("script");
579     const char* moduleName = arg->getStringValue("module");
580     naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
581     if(naIsNil(code)) return false;
582
583     // Commands can be run "in" a module.  Make sure that module
584     // exists, and set it up as the local variables hash for the
585     // command.
586     naRef locals = naNil();
587     if(moduleName[0]) {
588         naRef modname = naNewString(_context);
589         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
590         if(!naHash_get(_globals, modname, &locals)) {
591             locals = naNewHash(_context);
592             naHash_set(_globals, modname, locals);
593         }
594     }
595
596     // Cache this command's argument for inspection via cmdarg().  For
597     // performance reasons, we won't bother with it if the invoked
598     // code doesn't need it.
599     _cmdArg = (SGPropertyNode*)arg;
600
601     call(code, locals);
602     return true;
603 }
604
605 // settimer(func, dt, simtime) extension function.  The first argument
606 // is a Nasal function to call, the second is a delta time (from now),
607 // in seconds.  The third, if present, is a boolean value indicating
608 // that "real world" time (rather than simulator time) is to be used.
609 //
610 // Implementation note: the FGTimer objects don't live inside the
611 // garbage collector, so the Nasal handler functions have to be
612 // "saved" somehow lest they be inadvertently cleaned.  In this case,
613 // they are inserted into a globals.__gcsave hash and removed on
614 // expiration.
615 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
616 {
617     // Extract the handler, delta, and simtime arguments:
618     naRef handler = argc > 0 ? args[0] : naNil();
619     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
620         naRuntimeError(c, "settimer() with invalid function argument");
621         return;
622     }
623
624     naRef delta = argc > 1 ? args[1] : naNil();
625     if(naIsNil(delta)) {
626         naRuntimeError(c, "settimer() with invalid time argument");
627         return;
628     }
629
630     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
631
632     // Generate and register a C++ timer handler
633     NasalTimer* t = new NasalTimer;
634     t->handler = handler;
635     t->gcKey = gcSave(handler);
636     t->nasal = this;
637
638     globals->get_event_mgr()->addEvent("NasalTimer",
639                                        t, &NasalTimer::timerExpired,
640                                        delta.num, simtime);
641 }
642
643 void FGNasalSys::handleTimer(NasalTimer* t)
644 {
645     call(t->handler, naNil());
646     gcRelease(t->gcKey);
647 }
648
649 int FGNasalSys::gcSave(naRef r)
650 {
651     int key = _nextGCKey++;
652     naHash_set(_gcHash, naNum(key), r);
653     return key;
654 }
655
656 void FGNasalSys::gcRelease(int key)
657 {
658     naHash_delete(_gcHash, naNum(key));
659 }
660
661 void FGNasalSys::NasalTimer::timerExpired()
662 {
663     nasal->handleTimer(this);
664     delete this;
665 }
666
667 int FGNasalSys::_listenerId = 0;
668
669 // setlistener(property, func, bool) extension function.  The first argument
670 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
671 // path), the second is a Nasal function, the optional third one a bool.
672 // If the bool is true, then the listener is executed initially. The
673 // setlistener() function returns a unique id number, that can be used
674 // as argument to the removelistener() function.
675 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
676 {
677     SGPropertyNode_ptr node;
678     naRef prop = argc > 0 ? args[0] : naNil();
679     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
680     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
681     else {
682         naRuntimeError(c, "setlistener() with invalid property argument");
683         return naNil();
684     }
685
686     if(node->isTied())
687         SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
688                 node->getPath());
689
690     naRef handler = argc > 1 ? args[1] : naNil();
691     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
692         naRuntimeError(c, "setlistener() with invalid function argument");
693         return naNil();
694     }
695
696     bool initial = argc > 2 && naTrue(args[2]);
697
698     FGNasalListener *nl = new FGNasalListener(node, handler, this,
699             gcSave(handler), _listenerId);
700     node->addChangeListener(nl, initial);
701
702     _listener[_listenerId] = nl;
703     return naNum(_listenerId++);
704 }
705
706 // removelistener(int) extension function. The argument is the id of
707 // a listener as returned by the setlistener() function.
708 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
709 {
710     naRef id = argc > 0 ? args[0] : naNil();
711     map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
712
713     if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
714         naRuntimeError(c, "removelistener() with invalid listener id");
715         return naNil();
716     }
717
718     FGNasalListener *nl = it->second;
719     if(nl->_active) {
720         nl->_dead = true;
721         _purgeListeners = true;
722         return naNum(-1);
723     }
724
725     _listener.erase(it);
726     delete nl;
727     return naNum(_listener.size());
728 }
729
730
731
732 // FGNasalListener class.
733
734 FGNasalListener::FGNasalListener(SGPropertyNode_ptr node, naRef handler,
735                                  FGNasalSys* nasal, int key, int id) :
736     _node(node),
737     _handler(handler),
738     _gcKey(key),
739     _id(id),
740     _nas(nasal),
741     _active(0),
742     _dead(false)
743 {
744 }
745
746 FGNasalListener::~FGNasalListener()
747 {
748     _node->removeChangeListener(this);
749     _nas->gcRelease(_gcKey);
750 }
751
752 void FGNasalListener::valueChanged(SGPropertyNode* node)
753 {
754     // drop recursive listener calls
755     if(_active || _dead)
756         return;
757
758     SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
759     _active++;
760     _nas->_cmdArg = node;
761     _nas->call(_handler, naNil());
762     _active--;
763 }
764
765
766
767
768 // FGNasalModelData class.  If sgLoad3DModel() is called with a pointer to
769 // such a class, then it lets modelLoaded() run the <load> script, and the
770 // destructor the <unload> script. The latter happens when the model branch
771 // is removed from the scene graph.
772
773 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
774                                    osg::Node *)
775 {
776     SGPropertyNode *n = prop->getNode("nasal"), *load;
777     if(!n)
778         return;
779
780     load = n->getNode("load");
781     _unload = n->getNode("unload");
782     if(!load && !_unload)
783         return;
784
785     _module = path;
786     const char *s = load ? load->getStringValue() : "";
787     nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
788 }
789
790 FGNasalModelData::~FGNasalModelData()
791 {
792     if(_module.empty())
793         return;
794
795     if(!nasalSys) {
796         SG_LOG(SG_NASAL, SG_ALERT, "Trying to run an <unload> script "
797                 "without Nasal subsystem present.");
798         return;
799     }
800
801     if(_unload) {
802         const char *s = _unload->getStringValue();
803         nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
804     }
805     nasalSys->deleteModule(_module.c_str());
806 }
807
808