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