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