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