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