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