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