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