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