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