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