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