]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
b38e0fbcd35137e43dd8d7cc8d78281380068995
[flightgear.git] / src / Scripting / NasalSys.cxx
1
2 #ifdef HAVE_CONFIG_H
3 #  include "config.h"
4 #endif
5
6 #ifdef HAVE_SYS_TIME_H
7 #  include <sys/time.h>  // gettimeofday
8 #endif
9
10 #include <string.h>
11 #include <stdio.h>
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <fstream>
15 #include <sstream>
16 #include <algorithm> // for std::sort
17
18 #include <simgear/nasal/nasal.h>
19 #include <simgear/props/props.hxx>
20 #include <simgear/math/sg_random.h>
21 #include <simgear/misc/sg_path.hxx>
22 #include <simgear/misc/sg_dir.hxx>
23 #include <simgear/misc/interpolator.hxx>
24 #include <simgear/structure/commands.hxx>
25 #include <simgear/math/sg_geodesy.hxx>
26 #include <simgear/structure/event_mgr.hxx>
27
28 #include "NasalSys.hxx"
29 #include "NasalPositioned.hxx"
30 #include "NasalCanvas.hxx"
31 #include "NasalClipboard.hxx"
32 #include "NasalCondition.hxx"
33
34 #include <Main/globals.hxx>
35 #include <Main/util.hxx>
36 #include <Main/fg_props.hxx>
37
38
39 using std::map;
40
41 static FGNasalSys* nasalSys = 0;
42
43 // Listener class for loading Nasal modules on demand
44 class FGNasalModuleListener : public SGPropertyChangeListener
45 {
46 public:
47     FGNasalModuleListener(SGPropertyNode* node);
48
49     virtual void valueChanged(SGPropertyNode* node);
50
51 private:
52     SGPropertyNode_ptr _node;
53 };
54
55 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
56 {
57 }
58
59 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
60 {
61     if (_node->getBoolValue("enabled",false)&&
62         !_node->getBoolValue("loaded",true))
63     {
64         nasalSys->loadPropertyScripts(_node);
65     }
66 }
67
68
69 // Read and return file contents in a single buffer.  Note use of
70 // stat() to get the file size.  This is a win32 function, believe it
71 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
72 // Text mode brain damage will kill us if we're trying to do bytewise
73 // I/O.
74 static char* readfile(const char* file, int* lenOut)
75 {
76     struct stat data;
77     if(stat(file, &data) != 0) return 0;
78     FILE* f = fopen(file, "rb");
79     if(!f) return 0;
80     char* buf = new char[data.st_size];
81     *lenOut = fread(buf, 1, data.st_size, f);
82     fclose(f);
83     if(*lenOut != data.st_size) {
84         // Shouldn't happen, but warn anyway since it represents a
85         // platform bug and not a typical runtime error (missing file,
86         // etc...)
87         SG_LOG(SG_NASAL, SG_ALERT,
88                "ERROR in Nasal initialization: " <<
89                "short count returned from fread() of " << file <<
90                ".  Check your C library!");
91         delete[] buf;
92         return 0;
93     }
94     return buf;
95 }
96
97 FGNasalSys::FGNasalSys()
98 {
99     nasalSys = this;
100     _context = 0;
101     _globals = naNil();
102     _gcHash = naNil();
103     _nextGCKey = 0; // Any value will do
104     _callCount = 0;
105 }
106
107 // Utility.  Sets a named key in a hash by C string, rather than nasal
108 // string object.
109 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
110 {
111     naRef s = naNewString(_context);
112     naStr_fromdata(s, (char*)key, strlen(key));
113     naHash_set(hash, s, val);
114 }
115
116 void FGNasalSys::globalsSet(const char* key, naRef val)
117 {
118   hashset(_globals, key, val);
119 }
120
121 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
122 {
123   return callMethod(code, naNil(), argc, args, locals);
124 }
125
126 // Does a naCall() in a new context.  Wrapped here to make lock
127 // tracking easier.  Extension functions are called with the lock, but
128 // we have to release it before making a new naCall().  So rather than
129 // drop the lock in every extension function that might call back into
130 // Nasal, we keep a stack depth counter here and only unlock/lock
131 // around the naCall if it isn't the first one.
132
133 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
134 {
135     naContext ctx = naNewContext();
136     if(_callCount) naModUnlock();
137     _callCount++;
138     naRef result = naCall(ctx, code, argc, args, self, locals);
139     if(naGetError(ctx))
140         logError(ctx);
141     _callCount--;
142     if(_callCount) naModLock();
143     naFreeContext(ctx);
144     return result;
145 }
146
147 FGNasalSys::~FGNasalSys()
148 {
149     nasalSys = 0;
150     map<int, FGNasalListener *>::iterator it, end = _listener.end();
151     for(it = _listener.begin(); it != end; ++it)
152         delete it->second;
153
154     naFreeContext(_context);
155     _globals = naNil();
156 }
157
158 bool FGNasalSys::parseAndRun(const char* sourceCode)
159 {
160     naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
161                        strlen(sourceCode));
162     if(naIsNil(code))
163         return false;
164     call(code, 0, 0, naNil());
165     return true;
166 }
167
168 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
169 {
170     FGNasalScript* script = new FGNasalScript();
171     script->_gcKey = -1; // important, if we delete it on a parse
172     script->_nas = this; // error, don't clobber a real handle!
173
174     char buf[256];
175     if(!name) {
176         sprintf(buf, "FGNasalScript@%p", (void *)script);
177         name = buf;
178     }
179
180     script->_code = parse(name, src, strlen(src));
181     if(naIsNil(script->_code)) {
182         delete script;
183         return 0;
184     }
185
186     script->_gcKey = gcSave(script->_code);
187     return script;
188 }
189
190 // The get/setprop functions accept a *list* of strings and walk
191 // through the property tree with them to find the appropriate node.
192 // This allows a Nasal object to hold onto a property path and use it
193 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02).  This
194 // is the utility function that walks the property tree.
195 // Future enhancement: support integer arguments to specify array
196 // elements.
197 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
198 {
199     SGPropertyNode* p = globals->get_props();
200     try {
201         for(int i=0; i<len; i++) {
202             naRef a = vec[i];
203             if(!naIsString(a)) return 0;
204             p = p->getNode(naStr_data(a));
205             if(p == 0) return 0;
206         }
207     } catch (const string& err) {
208         naRuntimeError(c, (char *)err.c_str());
209         return 0;
210     }
211     return p;
212 }
213
214 // getprop() extension function.  Concatenates its string arguments as
215 // property names and returns the value of the specified property.  Or
216 // nil if it doesn't exist.
217 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
218 {
219     using namespace simgear;
220     const SGPropertyNode* p = findnode(c, args, argc);
221     if(!p) return naNil();
222
223     switch(p->getType()) {
224     case props::BOOL:   case props::INT:
225     case props::LONG:   case props::FLOAT:
226     case props::DOUBLE:
227         {
228         double dv = p->getDoubleValue();
229         if (osg::isNaN(dv)) {
230           SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
231           return naNil();
232         }
233         
234         return naNum(dv);
235         }
236         
237     case props::STRING:
238     case props::UNSPECIFIED:
239         {
240             naRef nastr = naNewString(c);
241             const char* val = p->getStringValue();
242             naStr_fromdata(nastr, (char*)val, strlen(val));
243             return nastr;
244         }
245     case props::ALIAS: // <--- FIXME, recurse?
246     default:
247         return naNil();
248     }
249 }
250
251 // setprop() extension function.  Concatenates its string arguments as
252 // property names and sets the value of the specified property to the
253 // final argument.
254 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
255 {
256 #define BUFLEN 1024
257     char buf[BUFLEN + 1];
258     buf[BUFLEN] = 0;
259     char* p = buf;
260     int buflen = BUFLEN;
261     if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
262     for(int i=0; i<argc-1; i++) {
263         naRef s = naStringValue(c, args[i]);
264         if(naIsNil(s)) return naNil();
265         strncpy(p, naStr_data(s), buflen);
266         p += naStr_len(s);
267         buflen = BUFLEN - (p - buf);
268         if(i < (argc-2) && buflen > 0) {
269             *p++ = '/';
270             buflen--;
271         }
272     }
273
274     SGPropertyNode* props = globals->get_props();
275     naRef val = args[argc-1];
276     bool result = false;
277     try {
278         if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
279         else {
280             naRef n = naNumValue(val);
281             if(naIsNil(n))
282                 naRuntimeError(c, "setprop() value is not string or number");
283                 
284             if (osg::isNaN(n.num)) {
285                 naRuntimeError(c, "setprop() passed a NaN");
286             }
287             
288             result = props->setDoubleValue(buf, n.num);
289         }
290     } catch (const string& err) {
291         naRuntimeError(c, (char *)err.c_str());
292     }
293     return naNum(result);
294 #undef BUFLEN
295 }
296
297 // print() extension function.  Concatenates and prints its arguments
298 // to the FlightGear log.  Uses the highest log level (SG_ALERT), to
299 // make sure it appears.  Is there better way to do this?
300 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
301 {
302     string buf;
303     int n = argc;
304     for(int i=0; i<n; i++) {
305         naRef s = naStringValue(c, args[i]);
306         if(naIsNil(s)) continue;
307         buf += naStr_data(s);
308     }
309     SG_LOG(SG_NASAL, SG_ALERT, buf);
310     return naNum(buf.length());
311 }
312
313 // fgcommand() extension function.  Executes a named command via the
314 // FlightGear command manager.  Takes a single property node name as
315 // an argument.
316 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
317 {
318     naRef cmd = argc > 0 ? args[0] : naNil();
319     naRef props = argc > 1 ? args[1] : naNil();
320     if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
321         naRuntimeError(c, "bad arguments to fgcommand()");
322     SGPropertyNode_ptr tmp, *node;
323     if(!naIsNil(props))
324         node = (SGPropertyNode_ptr*)naGhost_ptr(props);
325     else {
326         tmp = new SGPropertyNode();
327         node = &tmp;
328     }
329     return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
330 }
331
332 // settimer(func, dt, simtime) extension function.  Falls through to
333 // FGNasalSys::setTimer().  See there for docs.
334 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
335 {
336     nasalSys->setTimer(c, argc, args);
337     return naNil();
338 }
339
340 // setlistener(func, property, bool) extension function.  Falls through to
341 // FGNasalSys::setListener().  See there for docs.
342 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
343 {
344     return nasalSys->setListener(c, argc, args);
345 }
346
347 // removelistener(int) extension function. Falls through to
348 // FGNasalSys::removeListener(). See there for docs.
349 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
350 {
351     return nasalSys->removeListener(c, argc, args);
352 }
353
354 // Returns a ghost handle to the argument to the currently executing
355 // command
356 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
357 {
358     return nasalSys->cmdArgGhost();
359 }
360
361 // Sets up a property interpolation.  The first argument is either a
362 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
363 // interpolate.  The second argument is a vector of pairs of
364 // value/delta numbers.
365 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
366 {
367     SGPropertyNode* node;
368     naRef prop = argc > 0 ? args[0] : naNil();
369     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
370     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
371     else return naNil();
372
373     naRef curve = argc > 1 ? args[1] : naNil();
374     if(!naIsVector(curve)) return naNil();
375     int nPoints = naVec_size(curve) / 2;
376     double* values = new double[nPoints];
377     double* deltas = new double[nPoints];
378     for(int i=0; i<nPoints; i++) {
379         values[i] = naNumValue(naVec_get(curve, 2*i)).num;
380         deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
381     }
382
383     ((SGInterpolator*)globals->get_subsystem_mgr()
384         ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
385         ->interpolate(node, nPoints, values, deltas);
386
387     delete[] values;
388     delete[] deltas;
389     return naNil();
390 }
391
392 // This is a better RNG than the one in the default Nasal distribution
393 // (which is based on the C library rand() implementation). It will
394 // override.
395 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
396 {
397     return naNum(sg_random());
398 }
399
400 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
401 {
402     sg_srandom_time();
403     return naNum(0);
404 }
405
406 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
407 {
408     abort();
409     return naNil();
410 }
411
412 // Return an array listing of all files in a directory
413 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
414 {
415     if(argc != 1 || !naIsString(args[0]))
416         naRuntimeError(c, "bad arguments to directory()");
417     
418     simgear::Dir d(SGPath(naStr_data(args[0])));
419     if(!d.exists()) return naNil();
420     naRef result = naNewVector(c);
421
422     simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
423     for (unsigned int i=0; i<paths.size(); ++i) {
424       std::string p = paths[i].file();
425       naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
426     }
427     
428     return result;
429 }
430
431 /**
432  * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
433  */
434 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
435 {
436     if(argc != 1 || !naIsString(args[0]))
437         naRuntimeError(c, "bad arguments to resolveDataPath()");
438
439     SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
440     const char* pdata = p.c_str();
441     return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
442 }
443
444 // Parse XML file.
445 //     parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
446 //
447 // <path>      ... absolute path to an XML file
448 // <start-tag> ... callback function with two args: tag name, attribute hash
449 // <end-tag>   ... callback function with one arg:  tag name
450 // <data>      ... callback function with one arg:  data
451 // <pi>        ... callback function with two args: target, data
452 //                 (pi = "processing instruction")
453 // All four callback functions are optional and default to nil.
454 // The function returns nil on error, or the validated file name otherwise.
455 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
456 {
457     if(argc < 1 || !naIsString(args[0]))
458         naRuntimeError(c, "parsexml(): path argument missing or not a string");
459     if(argc > 5) argc = 5;
460     for(int i=1; i<argc; i++)
461         if(!(naIsNil(args[i]) || naIsFunc(args[i])))
462             naRuntimeError(c, "parsexml(): callback argument not a function");
463
464     const char* file = fgValidatePath(naStr_data(args[0]), false);
465     if(!file) {
466         naRuntimeError(c, "parsexml(): reading '%s' denied "
467                 "(unauthorized access)", naStr_data(args[0]));
468         return naNil();
469     }
470     std::ifstream input(file);
471     NasalXMLVisitor visitor(c, argc, args);
472     try {
473         readXML(input, visitor);
474     } catch (const sg_exception& e) {
475         naRuntimeError(c, "parsexml(): file '%s' %s",
476                 file, e.getFormattedMessage().c_str());
477         return naNil();
478     }
479     return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
480 }
481
482 // Return UNIX epoch time in seconds.
483 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
484 {
485 #ifdef _WIN32
486     FILETIME ft;
487     GetSystemTimeAsFileTime(&ft);
488     double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
489     // Converts from 100ns units in 1601 epoch to unix epoch in sec
490     return naNum((t * 1e-7) - 11644473600.0);
491 #else
492     struct timeval td;
493     gettimeofday(&td, 0);
494     return naNum(td.tv_sec + 1e-6 * td.tv_usec);
495 #endif
496 }
497
498 // Table of extension functions.  Terminate with zeros.
499 static struct { const char* name; naCFunction func; } funcs[] = {
500     { "getprop",   f_getprop },
501     { "setprop",   f_setprop },
502     { "print",     f_print },
503     { "_fgcommand", f_fgcommand },
504     { "settimer",  f_settimer },
505     { "_setlistener", f_setlistener },
506     { "removelistener", f_removelistener },
507     { "_cmdarg",  f_cmdarg },
508     { "_interpolate",  f_interpolate },
509     { "rand",  f_rand },
510     { "srand",  f_srand },
511     { "abort", f_abort },
512     { "directory", f_directory },
513     { "resolvepath", f_resolveDataPath },
514     { "parsexml", f_parsexml },
515     { "systime", f_systime },
516     { 0, 0 }
517 };
518
519 naRef FGNasalSys::cmdArgGhost()
520 {
521     return propNodeGhost(_cmdArg);
522 }
523
524 void FGNasalSys::init()
525 {
526     int i;
527
528     _context = naNewContext();
529
530     // Start with globals.  Add it to itself as a recursive
531     // sub-reference under the name "globals".  This gives client-code
532     // write access to the namespace if someone wants to do something
533     // fancy.
534     _globals = naInit_std(_context);
535     naSave(_context, _globals);
536     hashset(_globals, "globals", _globals);
537
538     hashset(_globals, "math", naInit_math(_context));
539     hashset(_globals, "bits", naInit_bits(_context));
540     hashset(_globals, "io", naInit_io(_context));
541     hashset(_globals, "thread", naInit_thread(_context));
542     hashset(_globals, "utf8", naInit_utf8(_context));
543
544     // Add our custom extension functions:
545     for(i=0; funcs[i].name; i++)
546         hashset(_globals, funcs[i].name,
547                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
548
549
550   
551     // And our SGPropertyNode wrapper
552     hashset(_globals, "props", genPropsModule());
553
554     // Make a "__gcsave" hash to hold the naRef objects which get
555     // passed to handles outside the interpreter (to protect them from
556     // begin garbage-collected).
557     _gcHash = naNewHash(_context);
558     hashset(_globals, "__gcsave", _gcHash);
559
560     initNasalPositioned(_globals, _context, _gcHash);
561     initNasalCanvas(_globals, _context, _gcHash);
562     NasalClipboard::init(this);
563     initNasalCondition(_globals, _context, _gcHash);
564   
565     // Now load the various source files in the Nasal directory
566     simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
567     loadScriptDirectory(nasalDir);
568
569     // Add modules in Nasal subdirectories to property tree
570     simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
571             simgear::Dir::NO_DOT_OR_DOTDOT, "");
572     for (unsigned int i=0; i<directories.size(); ++i) {
573         simgear::Dir dir(directories[i]);
574         simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
575         addModule(directories[i].file(), scripts);
576     }
577
578     // set signal and remove node to avoid restoring at reinit
579     const char *s = "nasal-dir-initialized";
580     SGPropertyNode *signal = fgGetNode("/sim/signals", true);
581     signal->setBoolValue(s, true);
582     signal->removeChildren(s, false);
583
584     // Pull scripts out of the property tree, too
585     loadPropertyScripts();
586   
587     // now Nasal modules are loaded, we can do some delayed work
588     postinitNasalPositioned(_globals, _context);
589 }
590
591 void FGNasalSys::update(double)
592 {
593     if( NasalClipboard::getInstance() )
594         NasalClipboard::getInstance()->update();
595
596     if(!_dead_listener.empty()) {
597         vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
598         for(it = _dead_listener.begin(); it != end; ++it) delete *it;
599         _dead_listener.clear();
600     }
601
602     if (!_loadList.empty())
603     {
604         // process Nasal load hook (only one per update loop to avoid excessive lags)
605         _loadList.pop()->load();
606     }
607     else
608     if (!_unloadList.empty())
609     {
610         // process pending Nasal unload hooks after _all_ load hooks were processed
611         // (only unload one per update loop to avoid excessive lags)
612         _unloadList.pop()->unload();
613     }
614
615     // The global context is a legacy thing.  We use dynamically
616     // created contexts for naCall() now, so that we can call them
617     // recursively.  But there are still spots that want to use it for
618     // naNew*() calls, which end up leaking memory because the context
619     // only clears out its temporary vector when it's *used*.  So just
620     // junk it and fetch a new/reinitialized one every frame.  This is
621     // clumsy: the right solution would use the dynamic context in all
622     // cases and eliminate _context entirely.  But that's more work,
623     // and this works fine (yes, they say "New" and "Free", but
624     // they're very fast, just trust me). -Andy
625     naFreeContext(_context);
626     _context = naNewContext();
627 }
628
629 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
630 {
631   return p1.file() < p2.file();
632 }
633
634 // Loads all scripts in given directory 
635 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
636 {
637     simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
638     // sort scripts, avoid loading sequence effects due to file system's
639     // random directory order
640     std::sort(scripts.begin(), scripts.end(), pathSortPredicate);
641
642     for (unsigned int i=0; i<scripts.size(); ++i) {
643       SGPath fullpath(scripts[i]);
644       SGPath file = fullpath.file();
645       loadModule(fullpath, file.base().c_str());
646     }
647 }
648
649 // Create module with list of scripts
650 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
651 {
652     if (scripts.size()>0)
653     {
654         SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
655         SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
656         for (unsigned int i=0; i<scripts.size(); ++i) {
657             SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
658             pFileNode->setStringValue(scripts[i].c_str());
659         }
660         if (!module_node->hasChild("enabled",0))
661         {
662             SGPropertyNode* node = module_node->getChild("enabled",0,true);
663             node->setBoolValue(true);
664             node->setAttribute(SGPropertyNode::USERARCHIVE,true);
665         }
666     }
667 }
668
669 // Loads the scripts found under /nasal in the global tree
670 void FGNasalSys::loadPropertyScripts()
671 {
672     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
673     if(!nasal) return;
674
675     for(int i=0; i<nasal->nChildren(); i++)
676     {
677         SGPropertyNode* n = nasal->getChild(i);
678         loadPropertyScripts(n);
679     }
680 }
681
682 // Loads the scripts found under /nasal in the global tree
683 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
684 {
685     bool is_loaded = false;
686
687     const char* module = n->getName();
688     if(n->hasChild("module"))
689         module = n->getStringValue("module");
690     if (n->getBoolValue("enabled",true))
691     {
692         // allow multiple files to be specified within a single
693         // Nasal module tag
694         int j = 0;
695         SGPropertyNode *fn;
696         bool file_specified = false;
697         bool ok=true;
698         while((fn = n->getChild("file", j)) != NULL) {
699             file_specified = true;
700             const char* file = fn->getStringValue();
701             SGPath p(file);
702             if (!p.isAbsolute() || !p.exists())
703             {
704                 p = globals->resolve_maybe_aircraft_path(file);
705                 if (p.isNull())
706                 {
707                     SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
708                             file << "' for module '" << module << "'.");
709                 }
710             }
711             ok &= p.isNull() ? false : loadModule(p, module);
712             j++;
713         }
714
715         const char* src = n->getStringValue("script");
716         if(!n->hasChild("script")) src = 0; // Hrm...
717         if(src)
718             createModule(module, n->getPath().c_str(), src, strlen(src));
719
720         if(!file_specified && !src)
721         {
722             // module no longer exists - clear the archived "enable" flag
723             n->setAttribute(SGPropertyNode::USERARCHIVE,false);
724             SGPropertyNode* node = n->getChild("enabled",0,false);
725             if (node)
726                 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
727
728             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
729                     "no <file> or <script> defined in " <<
730                     "/nasal/" << module);
731         }
732         else
733             is_loaded = ok;
734     }
735     else
736     {
737         SGPropertyNode* enable = n->getChild("enabled");
738         if (enable)
739         {
740             FGNasalModuleListener* listener = new FGNasalModuleListener(n);
741             enable->addChangeListener(listener, false);
742         }
743     }
744     SGPropertyNode* loaded = n->getChild("loaded",0,true);
745     loaded->setAttribute(SGPropertyNode::PRESERVE,true);
746     loaded->setBoolValue(is_loaded);
747 }
748
749 // Logs a runtime error, with stack trace, to the FlightGear log stream
750 void FGNasalSys::logError(naContext context)
751 {
752     SG_LOG(SG_NASAL, SG_ALERT,
753            "Nasal runtime error: " << naGetError(context));
754     SG_LOG(SG_NASAL, SG_ALERT,
755            "  at " << naStr_data(naGetSourceFile(context, 0)) <<
756            ", line " << naGetLine(context, 0));
757     for(int i=1; i<naStackDepth(context); i++)
758         SG_LOG(SG_NASAL, SG_ALERT,
759                "  called from: " << naStr_data(naGetSourceFile(context, i)) <<
760                ", line " << naGetLine(context, i));
761 }
762
763 // Reads a script file, executes it, and places the resulting
764 // namespace into the global namespace under the specified module
765 // name.
766 bool FGNasalSys::loadModule(SGPath file, const char* module)
767 {
768     int len = 0;
769     char* buf = readfile(file.c_str(), &len);
770     if(!buf) {
771         SG_LOG(SG_NASAL, SG_ALERT,
772                "Nasal error: could not read script file " << file.c_str()
773                << " into module " << module);
774         return false;
775     }
776
777     bool ok = createModule(module, file.c_str(), buf, len);
778     delete[] buf;
779     return ok;
780 }
781
782 // Parse and run.  Save the local variables namespace, as it will
783 // become a sub-object of globals.  The optional "arg" argument can be
784 // used to pass an associated property node to the module, which can then
785 // be accessed via cmdarg().  (This is, for example, used by XML dialogs.)
786 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
787                               const char* src, int len,
788                               const SGPropertyNode* cmdarg,
789                               int argc, naRef* args)
790 {
791     naRef code = parse(fileName, src, len);
792     if(naIsNil(code))
793         return false;
794
795     // See if we already have a module hash to use.  This allows the
796     // user to, for example, add functions to the built-in math
797     // module.  Make a new one if necessary.
798     naRef locals;
799     naRef modname = naNewString(_context);
800     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
801     if(!naHash_get(_globals, modname, &locals))
802         locals = naNewHash(_context);
803
804     _cmdArg = (SGPropertyNode*)cmdarg;
805
806     call(code, argc, args, locals);
807     hashset(_globals, moduleName, locals);
808     return true;
809 }
810
811 void FGNasalSys::deleteModule(const char* moduleName)
812 {
813     naRef modname = naNewString(_context);
814     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
815     naHash_delete(_globals, modname);
816 }
817
818 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
819 {
820     int errLine = -1;
821     naRef srcfile = naNewString(_context);
822     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
823     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
824     if(naIsNil(code)) {
825         SG_LOG(SG_NASAL, SG_ALERT,
826                "Nasal parse error: " << naGetError(_context) <<
827                " in "<< filename <<", line " << errLine);
828         return naNil();
829     }
830
831     // Bind to the global namespace before returning
832     return naBindFunction(_context, code, _globals);
833 }
834
835 bool FGNasalSys::handleCommand( const char* moduleName,
836                                 const char* fileName,
837                                 const char* src,
838                                 const SGPropertyNode* arg )
839 {
840     naRef code = parse(fileName, src, strlen(src));
841     if(naIsNil(code)) return false;
842
843     // Commands can be run "in" a module.  Make sure that module
844     // exists, and set it up as the local variables hash for the
845     // command.
846     naRef locals = naNil();
847     if(moduleName[0]) {
848         naRef modname = naNewString(_context);
849         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
850         if(!naHash_get(_globals, modname, &locals)) {
851             locals = naNewHash(_context);
852             naHash_set(_globals, modname, locals);
853         }
854     }
855
856     // Cache this command's argument for inspection via cmdarg().  For
857     // performance reasons, we won't bother with it if the invoked
858     // code doesn't need it.
859     _cmdArg = (SGPropertyNode*)arg;
860
861     call(code, 0, 0, locals);
862     return true;
863 }
864
865 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
866 {
867   const char* src = arg->getStringValue("script");
868   const char* moduleName = arg->getStringValue("module");
869
870   return handleCommand( moduleName,
871                         arg ? arg->getPath(true).c_str() : moduleName,
872                         src,
873                         arg );
874 }
875
876 // settimer(func, dt, simtime) extension function.  The first argument
877 // is a Nasal function to call, the second is a delta time (from now),
878 // in seconds.  The third, if present, is a boolean value indicating
879 // that "real world" time (rather than simulator time) is to be used.
880 //
881 // Implementation note: the FGTimer objects don't live inside the
882 // garbage collector, so the Nasal handler functions have to be
883 // "saved" somehow lest they be inadvertently cleaned.  In this case,
884 // they are inserted into a globals.__gcsave hash and removed on
885 // expiration.
886 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
887 {
888     // Extract the handler, delta, and simtime arguments:
889     naRef handler = argc > 0 ? args[0] : naNil();
890     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
891         naRuntimeError(c, "settimer() with invalid function argument");
892         return;
893     }
894
895     naRef delta = argc > 1 ? args[1] : naNil();
896     if(naIsNil(delta)) {
897         naRuntimeError(c, "settimer() with invalid time argument");
898         return;
899     }
900
901     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
902
903     // Generate and register a C++ timer handler
904     NasalTimer* t = new NasalTimer;
905     t->handler = handler;
906     t->gcKey = gcSave(handler);
907     t->nasal = this;
908
909     globals->get_event_mgr()->addEvent("NasalTimer",
910                                        t, &NasalTimer::timerExpired,
911                                        delta.num, simtime);
912 }
913
914 void FGNasalSys::handleTimer(NasalTimer* t)
915 {
916     call(t->handler, 0, 0, naNil());
917     gcRelease(t->gcKey);
918 }
919
920 int FGNasalSys::gcSave(naRef r)
921 {
922     int key = _nextGCKey++;
923     naHash_set(_gcHash, naNum(key), r);
924     return key;
925 }
926
927 void FGNasalSys::gcRelease(int key)
928 {
929     naHash_delete(_gcHash, naNum(key));
930 }
931
932 void FGNasalSys::NasalTimer::timerExpired()
933 {
934     nasal->handleTimer(this);
935     delete this;
936 }
937
938 int FGNasalSys::_listenerId = 0;
939
940 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
941 // Attaches a callback function to a property (specified as a global
942 // property path string or a SGPropertyNode_ptr* ghost). If the third,
943 // optional argument (default=0) is set to 1, then the function is also
944 // called initially. If the fourth, optional argument is set to 0, then the
945 // function is only called when the property node value actually changes.
946 // Otherwise it's called independent of the value whenever the node is
947 // written to (default). The setlistener() function returns a unique
948 // id number, which is to be used as argument to the removelistener()
949 // function.
950 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
951 {
952     SGPropertyNode_ptr node;
953     naRef prop = argc > 0 ? args[0] : naNil();
954     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
955     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
956     else {
957         naRuntimeError(c, "setlistener() with invalid property argument");
958         return naNil();
959     }
960
961     if(node->isTied())
962         SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
963                 node->getPath());
964
965     naRef code = argc > 1 ? args[1] : naNil();
966     if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
967         naRuntimeError(c, "setlistener() with invalid function argument");
968         return naNil();
969     }
970
971     int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
972     int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
973     FGNasalListener *nl = new FGNasalListener(node, code, this,
974             gcSave(code), _listenerId, init, type);
975
976     node->addChangeListener(nl, init != 0);
977
978     _listener[_listenerId] = nl;
979     return naNum(_listenerId++);
980 }
981
982 // removelistener(int) extension function. The argument is the id of
983 // a listener as returned by the setlistener() function.
984 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
985 {
986     naRef id = argc > 0 ? args[0] : naNil();
987     map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
988
989     if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
990         naRuntimeError(c, "removelistener() with invalid listener id");
991         return naNil();
992     }
993
994     it->second->_dead = true;
995     _dead_listener.push_back(it->second);
996     _listener.erase(it);
997     return naNum(_listener.size());
998 }
999
1000
1001
1002 // FGNasalListener class.
1003
1004 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1005                                  FGNasalSys* nasal, int key, int id,
1006                                  int init, int type) :
1007     _node(node),
1008     _code(code),
1009     _gcKey(key),
1010     _id(id),
1011     _nas(nasal),
1012     _init(init),
1013     _type(type),
1014     _active(0),
1015     _dead(false),
1016     _last_int(0L),
1017     _last_float(0.0)
1018 {
1019     if(_type == 0 && !_init)
1020         changed(node);
1021 }
1022
1023 FGNasalListener::~FGNasalListener()
1024 {
1025     _node->removeChangeListener(this);
1026     _nas->gcRelease(_gcKey);
1027 }
1028
1029 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1030 {
1031     if(_active || _dead) return;
1032     SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1033     _active++;
1034     naRef arg[4];
1035     arg[0] = _nas->propNodeGhost(which);
1036     arg[1] = _nas->propNodeGhost(_node);
1037     arg[2] = mode;                  // value changed, child added/removed
1038     arg[3] = naNum(_node != which); // child event?
1039     _nas->call(_code, 4, arg, naNil());
1040     _active--;
1041 }
1042
1043 void FGNasalListener::valueChanged(SGPropertyNode* node)
1044 {
1045     if(_type < 2 && node != _node) return;   // skip child events
1046     if(_type > 0 || changed(_node) || _init)
1047         call(node, naNum(0));
1048
1049     _init = 0;
1050 }
1051
1052 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1053 {
1054     if(_type == 2) call(child, naNum(1));
1055 }
1056
1057 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1058 {
1059     if(_type == 2) call(child, naNum(-1));
1060 }
1061
1062 bool FGNasalListener::changed(SGPropertyNode* node)
1063 {
1064     using namespace simgear;
1065     props::Type type = node->getType();
1066     if(type == props::NONE) return false;
1067     if(type == props::UNSPECIFIED) return true;
1068
1069     bool result;
1070     switch(type) {
1071     case props::BOOL:
1072     case props::INT:
1073     case props::LONG:
1074         {
1075             long l = node->getLongValue();
1076             result = l != _last_int;
1077             _last_int = l;
1078             return result;
1079         }
1080     case props::FLOAT:
1081     case props::DOUBLE:
1082         {
1083             double d = node->getDoubleValue();
1084             result = d != _last_float;
1085             _last_float = d;
1086             return result;
1087         }
1088     default:
1089         {
1090             string s = node->getStringValue();
1091             result = s != _last_string;
1092             _last_string = s;
1093             return result;
1094         }
1095     }
1096 }
1097
1098
1099
1100 // FGNasalModelData class.  If sgLoad3DModel() is called with a pointer to
1101 // such a class, then it lets modelLoaded() run the <load> script, and the
1102 // destructor the <unload> script. The latter happens when the model branch
1103 // is removed from the scene graph.
1104
1105 unsigned int FGNasalModelData::_module_id = 0;
1106
1107 void FGNasalModelData::load()
1108 {
1109     std::stringstream m;
1110     m << "__model" << _module_id++;
1111     _module = m.str();
1112
1113     SG_LOG(SG_NASAL, SG_DEBUG, "Loading nasal module " << _module.c_str());
1114
1115     const char *s = _load ? _load->getStringValue() : "";
1116
1117     naRef arg[2];
1118     arg[0] = nasalSys->propNodeGhost(_root);
1119     arg[1] = nasalSys->propNodeGhost(_prop);
1120     nasalSys->createModule(_module.c_str(), _path.c_str(), s, strlen(s),
1121                            _root, 2, arg);
1122 }
1123
1124 void FGNasalModelData::unload()
1125 {
1126     if (_module.empty())
1127         return;
1128
1129     if(!nasalSys) {
1130         SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1131                 "without Nasal subsystem present.");
1132         return;
1133     }
1134
1135     SG_LOG(SG_NASAL, SG_DEBUG, "Unloading nasal module " << _module.c_str());
1136
1137     if (_unload)
1138     {
1139         const char *s = _unload->getStringValue();
1140         nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _root);
1141     }
1142
1143     nasalSys->deleteModule(_module.c_str());
1144 }
1145
1146 void FGNasalModelDataProxy::modelLoaded(const string& path, SGPropertyNode *prop,
1147                                    osg::Node *)
1148 {
1149     if(!nasalSys) {
1150         SG_LOG(SG_NASAL, SG_WARN, "Trying to run a <load> script "
1151                 "without Nasal subsystem present.");
1152         return;
1153     }
1154
1155     if(!prop)
1156         return;
1157
1158     SGPropertyNode *nasal = prop->getNode("nasal");
1159     if(!nasal)
1160         return;
1161
1162     SGPropertyNode* load   = nasal->getNode("load");
1163     SGPropertyNode* unload = nasal->getNode("unload");
1164
1165     if ((!load) && (!unload))
1166         return;
1167
1168     _data = new FGNasalModelData(_root, path, prop, load, unload);
1169
1170     // register Nasal module to be created and loaded in the main thread.
1171     nasalSys->registerToLoad(_data);
1172 }
1173
1174 FGNasalModelDataProxy::~FGNasalModelDataProxy()
1175 {
1176     // when necessary, register Nasal module to be destroyed/unloaded
1177     // in the main thread.
1178     if ((_data.valid())&&(nasalSys))
1179         nasalSys->registerToUnload(_data);
1180 }
1181
1182 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1183 //
1184 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1185     _c(naSubContext(c)),
1186     _start_element(argc > 1 ? args[1] : naNil()),
1187     _end_element(argc > 2 ? args[2] : naNil()),
1188     _data(argc > 3 ? args[3] : naNil()),
1189     _pi(argc > 4 ? args[4] : naNil())
1190 {
1191 }
1192
1193 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1194 {
1195     if(naIsNil(_start_element)) return;
1196     naRef attr = naNewHash(_c);
1197     for(int i=0; i<a.size(); i++) {
1198         naRef name = make_string(a.getName(i));
1199         naRef value = make_string(a.getValue(i));
1200         naHash_set(attr, name, value);
1201     }
1202     call(_start_element, 2, make_string(tag), attr);
1203 }
1204
1205 void NasalXMLVisitor::endElement(const char* tag)
1206 {
1207     if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1208 }
1209
1210 void NasalXMLVisitor::data(const char* str, int len)
1211 {
1212     if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1213 }
1214
1215 void NasalXMLVisitor::pi(const char* target, const char* data)
1216 {
1217     if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1218 }
1219
1220 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1221 {
1222     naRef args[2];
1223     args[0] = a;
1224     args[1] = b;
1225     naCall(_c, func, num, args, naNil(), naNil());
1226     if(naGetError(_c))
1227         naRethrowError(_c);
1228 }
1229
1230 naRef NasalXMLVisitor::make_string(const char* s, int n)
1231 {
1232     return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1233                           n < 0 ? strlen(s) : n);
1234 }
1235
1236