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