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