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