]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
cc56043d570332d7e9f7ef2b6e98b68a424b6dc1
[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     // The global context is a legacy thing.  We use dynamically
930     // created contexts for naCall() now, so that we can call them
931     // recursively.  But there are still spots that want to use it for
932     // naNew*() calls, which end up leaking memory because the context
933     // only clears out its temporary vector when it's *used*.  So just
934     // junk it and fetch a new/reinitialized one every frame.  This is
935     // clumsy: the right solution would use the dynamic context in all
936     // cases and eliminate _context entirely.  But that's more work,
937     // and this works fine (yes, they say "New" and "Free", but
938     // they're very fast, just trust me). -Andy
939     naFreeContext(_context);
940     _context = naNewContext();
941 }
942
943 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
944 {
945   return p1.file() < p2.file();
946 }
947
948 // Loads all scripts in given directory 
949 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
950 {
951     simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
952     // Note: simgear::Dir already reports file entries in a deterministic order,
953     // so a fixed loading sequence is guaranteed (same for every user)
954     for (unsigned int i=0; i<scripts.size(); ++i) {
955       SGPath fullpath(scripts[i]);
956       SGPath file = fullpath.file();
957       loadModule(fullpath, file.base().c_str());
958     }
959 }
960
961 // Create module with list of scripts
962 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
963 {
964     if (! scripts.empty())
965     {
966         SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
967         SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
968         for (unsigned int i=0; i<scripts.size(); ++i) {
969             SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
970             pFileNode->setStringValue(scripts[i].c_str());
971         }
972         if (!module_node->hasChild("enabled",0))
973         {
974             SGPropertyNode* node = module_node->getChild("enabled",0,true);
975             node->setBoolValue(true);
976             node->setAttribute(SGPropertyNode::USERARCHIVE,true);
977         }
978     }
979 }
980
981 // Loads the scripts found under /nasal in the global tree
982 void FGNasalSys::loadPropertyScripts()
983 {
984     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
985     if(!nasal) return;
986
987     for(int i=0; i<nasal->nChildren(); i++)
988     {
989         SGPropertyNode* n = nasal->getChild(i);
990         loadPropertyScripts(n);
991     }
992 }
993
994 // Loads the scripts found under /nasal in the global tree
995 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
996 {
997     bool is_loaded = false;
998
999     const char* module = n->getName();
1000     if(n->hasChild("module"))
1001         module = n->getStringValue("module");
1002     if (n->getBoolValue("enabled",true))
1003     {
1004         // allow multiple files to be specified within a single
1005         // Nasal module tag
1006         int j = 0;
1007         SGPropertyNode *fn;
1008         bool file_specified = false;
1009         bool ok=true;
1010         while((fn = n->getChild("file", j)) != NULL) {
1011             file_specified = true;
1012             const char* file = fn->getStringValue();
1013             SGPath p(file);
1014             if (!p.isAbsolute() || !p.exists())
1015             {
1016                 p = globals->resolve_maybe_aircraft_path(file);
1017                 if (p.isNull())
1018                 {
1019                     SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
1020                             file << "' for module '" << module << "'.");
1021                 }
1022             }
1023             ok &= p.isNull() ? false : loadModule(p, module);
1024             j++;
1025         }
1026
1027         const char* src = n->getStringValue("script");
1028         if(!n->hasChild("script")) src = 0; // Hrm...
1029         if(src)
1030             createModule(module, n->getPath().c_str(), src, strlen(src));
1031
1032         if(!file_specified && !src)
1033         {
1034             // module no longer exists - clear the archived "enable" flag
1035             n->setAttribute(SGPropertyNode::USERARCHIVE,false);
1036             SGPropertyNode* node = n->getChild("enabled",0,false);
1037             if (node)
1038                 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
1039
1040             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
1041                     "no <file> or <script> defined in " <<
1042                     "/nasal/" << module);
1043         }
1044         else
1045             is_loaded = ok;
1046     }
1047     else
1048     {
1049         SGPropertyNode* enable = n->getChild("enabled");
1050         if (enable)
1051         {
1052             FGNasalModuleListener* listener = new FGNasalModuleListener(n);
1053             _moduleListeners.push_back(listener);
1054             enable->addChangeListener(listener, false);
1055         }
1056     }
1057     SGPropertyNode* loaded = n->getChild("loaded",0,true);
1058     loaded->setAttribute(SGPropertyNode::PRESERVE,true);
1059     loaded->setBoolValue(is_loaded);
1060 }
1061
1062 // Logs a runtime error, with stack trace, to the FlightGear log stream
1063 void FGNasalSys::logError(naContext context)
1064 {
1065     SG_LOG(SG_NASAL, SG_ALERT, "Nasal runtime error: " << naGetError(context));
1066     int stack_depth = naStackDepth(context);
1067     if( stack_depth < 1 )
1068       return;
1069     SG_LOG(SG_NASAL, SG_ALERT,
1070            "  at " << naStr_data(naGetSourceFile(context, 0)) <<
1071            ", line " << naGetLine(context, 0));
1072     for(int i=1; i<stack_depth; i++)
1073         SG_LOG(SG_NASAL, SG_ALERT,
1074                "  called from: " << naStr_data(naGetSourceFile(context, i)) <<
1075                ", line " << naGetLine(context, i));
1076 }
1077
1078 // Reads a script file, executes it, and places the resulting
1079 // namespace into the global namespace under the specified module
1080 // name.
1081 bool FGNasalSys::loadModule(SGPath file, const char* module)
1082 {
1083     int len = 0;
1084     char* buf = readfile(file.c_str(), &len);
1085     if(!buf) {
1086         SG_LOG(SG_NASAL, SG_ALERT,
1087                "Nasal error: could not read script file " << file.c_str()
1088                << " into module " << module);
1089         return false;
1090     }
1091
1092     bool ok = createModule(module, file.c_str(), buf, len);
1093     delete[] buf;
1094     return ok;
1095 }
1096
1097 // Parse and run.  Save the local variables namespace, as it will
1098 // become a sub-object of globals.  The optional "arg" argument can be
1099 // used to pass an associated property node to the module, which can then
1100 // be accessed via cmdarg().  (This is, for example, used by XML dialogs.)
1101 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1102                               const char* src, int len,
1103                               const SGPropertyNode* cmdarg,
1104                               int argc, naRef* args)
1105 {
1106     naContext ctx = naNewContext();
1107     naRef code = parse(ctx, fileName, src, len);
1108     if(naIsNil(code)) {
1109         naFreeContext(ctx);
1110         return false;
1111     }
1112
1113     
1114     // See if we already have a module hash to use.  This allows the
1115     // user to, for example, add functions to the built-in math
1116     // module.  Make a new one if necessary.
1117     naRef locals;
1118     naRef modname = naNewString(ctx);
1119     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1120     if(!naHash_get(_globals, modname, &locals))
1121         locals = naNewHash(ctx);
1122
1123     _cmdArg = (SGPropertyNode*)cmdarg;
1124
1125     callWithContext(ctx, code, argc, args, locals);
1126     hashset(_globals, moduleName, locals);
1127     
1128     naFreeContext(ctx);
1129     return true;
1130 }
1131
1132 void FGNasalSys::deleteModule(const char* moduleName)
1133 {
1134     if (!_inited) {
1135         // can occur on shutdown due to us being shutdown first, but other
1136         // subsystems having Nasal objects.
1137         return;
1138     }
1139     
1140     naContext ctx = naNewContext();
1141     naRef modname = naNewString(ctx);
1142     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1143     naHash_delete(_globals, modname);
1144     naFreeContext(ctx);
1145 }
1146
1147 naRef FGNasalSys::parse(naContext ctx, const char* filename, const char* buf, int len)
1148 {
1149     int errLine = -1;
1150     naRef srcfile = naNewString(ctx);
1151     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1152     naRef code = naParseCode(ctx, srcfile, 1, (char*)buf, len, &errLine);
1153     if(naIsNil(code)) {
1154         SG_LOG(SG_NASAL, SG_ALERT,
1155                "Nasal parse error: " << naGetError(ctx) <<
1156                " in "<< filename <<", line " << errLine);
1157         return naNil();
1158     }
1159
1160     // Bind to the global namespace before returning
1161     return naBindFunction(ctx, code, _globals);
1162 }
1163
1164 bool FGNasalSys::handleCommand( const char* moduleName,
1165                                 const char* fileName,
1166                                 const char* src,
1167                                 const SGPropertyNode* arg )
1168 {
1169     naContext ctx = naNewContext();
1170     naRef code = parse(ctx, fileName, src, strlen(src));
1171     if(naIsNil(code)) {
1172         naFreeContext(ctx);
1173         return false;
1174     }
1175
1176     // Commands can be run "in" a module.  Make sure that module
1177     // exists, and set it up as the local variables hash for the
1178     // command.
1179     naRef locals = naNil();
1180     if(moduleName[0]) {
1181         naRef modname = naNewString(ctx);
1182         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1183         if(!naHash_get(_globals, modname, &locals)) {
1184             locals = naNewHash(ctx);
1185             naHash_set(_globals, modname, locals);
1186         }
1187     }
1188
1189     // Cache this command's argument for inspection via cmdarg().  For
1190     // performance reasons, we won't bother with it if the invoked
1191     // code doesn't need it.
1192     _cmdArg = (SGPropertyNode*)arg;
1193
1194     callWithContext(ctx, code, 0, 0, locals);
1195     naFreeContext(ctx);
1196     return true;
1197 }
1198
1199 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1200 {
1201   const char* src = arg->getStringValue("script");
1202   const char* moduleName = arg->getStringValue("module");
1203
1204   return handleCommand( moduleName,
1205                         arg->getPath(true).c_str(),
1206                         src,
1207                         arg );
1208 }
1209
1210 // settimer(func, dt, simtime) extension function.  The first argument
1211 // is a Nasal function to call, the second is a delta time (from now),
1212 // in seconds.  The third, if present, is a boolean value indicating
1213 // that "real world" time (rather than simulator time) is to be used.
1214 //
1215 // Implementation note: the FGTimer objects don't live inside the
1216 // garbage collector, so the Nasal handler functions have to be
1217 // "saved" somehow lest they be inadvertently cleaned.  In this case,
1218 // they are inserted into a globals.__gcsave hash and removed on
1219 // expiration.
1220 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1221 {
1222     // Extract the handler, delta, and simtime arguments:
1223     naRef handler = argc > 0 ? args[0] : naNil();
1224     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1225         naRuntimeError(c, "settimer() with invalid function argument");
1226         return;
1227     }
1228
1229     naRef delta = argc > 1 ? args[1] : naNil();
1230     if(naIsNil(delta)) {
1231         naRuntimeError(c, "settimer() with invalid time argument");
1232         return;
1233     }
1234
1235     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1236
1237     // Generate and register a C++ timer handler
1238     NasalTimer* t = new NasalTimer;
1239     t->handler = handler;
1240     t->gcKey = gcSave(handler);
1241     t->nasal = this;
1242
1243     globals->get_event_mgr()->addEvent("NasalTimer",
1244                                        t, &NasalTimer::timerExpired,
1245                                        delta.num, simtime);
1246 }
1247
1248 void FGNasalSys::handleTimer(NasalTimer* t)
1249 {
1250     call(t->handler, 0, 0, naNil());
1251     gcRelease(t->gcKey);
1252 }
1253
1254 int FGNasalSys::gcSave(naRef r)
1255 {
1256     return naGCSave(r);
1257 }
1258
1259 void FGNasalSys::gcRelease(int key)
1260 {
1261     naGCRelease(key);
1262 }
1263
1264 void FGNasalSys::NasalTimer::timerExpired()
1265 {
1266     nasal->handleTimer(this);
1267     delete this;
1268 }
1269
1270 int FGNasalSys::_listenerId = 0;
1271
1272 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1273 // Attaches a callback function to a property (specified as a global
1274 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1275 // optional argument (default=0) is set to 1, then the function is also
1276 // called initially. If the fourth, optional argument is set to 0, then the
1277 // function is only called when the property node value actually changes.
1278 // Otherwise it's called independent of the value whenever the node is
1279 // written to (default). The setlistener() function returns a unique
1280 // id number, which is to be used as argument to the removelistener()
1281 // function.
1282 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1283 {
1284     SGPropertyNode_ptr node;
1285     naRef prop = argc > 0 ? args[0] : naNil();
1286     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1287     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1288     else {
1289         naRuntimeError(c, "setlistener() with invalid property argument");
1290         return naNil();
1291     }
1292
1293     if(node->isTied())
1294         SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1295                 node->getPath());
1296
1297     naRef code = argc > 1 ? args[1] : naNil();
1298     if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1299         naRuntimeError(c, "setlistener() with invalid function argument");
1300         return naNil();
1301     }
1302
1303     int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1304     int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1305     FGNasalListener *nl = new FGNasalListener(node, code, this,
1306             gcSave(code), _listenerId, init, type);
1307
1308     node->addChangeListener(nl, init != 0);
1309
1310     _listener[_listenerId] = nl;
1311     return naNum(_listenerId++);
1312 }
1313
1314 // removelistener(int) extension function. The argument is the id of
1315 // a listener as returned by the setlistener() function.
1316 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1317 {
1318     naRef id = argc > 0 ? args[0] : naNil();
1319     map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1320
1321     if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1322         naRuntimeError(c, "removelistener() with invalid listener id");
1323         return naNil();
1324     }
1325
1326     it->second->_dead = true;
1327     _dead_listener.push_back(it->second);
1328     _listener.erase(it);
1329     return naNum(_listener.size());
1330 }
1331
1332 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1333 {
1334   if( _loadList.empty() )
1335     _delay_load = true;
1336   _loadList.push(data);
1337 }
1338
1339 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1340 {
1341     _unloadList.push(data);
1342 }
1343
1344 void FGNasalSys::addCommand(naRef func, const std::string& name)
1345 {
1346     if (_commands.find(name) != _commands.end()) {
1347         SG_LOG(SG_NASAL, SG_WARN, "duplicate add of command:" << name);
1348         return;
1349     }
1350     
1351     NasalCommand* cmd = new NasalCommand(this, func, name);
1352     _commands[name] = cmd;
1353 }
1354
1355 void FGNasalSys::removeCommand(const std::string& name)
1356 {
1357     NasalCommandDict::iterator it = _commands.find(name);
1358     if (it == _commands.end()) {
1359         SG_LOG(SG_NASAL, SG_WARN, "remove of unknwon command:" << name);
1360         return;
1361     }
1362
1363     // will delete the NasalCommand instance
1364     globals->get_commands()->removeCommand(name);
1365     _commands.erase(it);
1366 }
1367
1368 //////////////////////////////////////////////////////////////////////////
1369 // FGNasalListener class.
1370
1371 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1372                                  FGNasalSys* nasal, int key, int id,
1373                                  int init, int type) :
1374     _node(node),
1375     _code(code),
1376     _gcKey(key),
1377     _id(id),
1378     _nas(nasal),
1379     _init(init),
1380     _type(type),
1381     _active(0),
1382     _dead(false),
1383     _last_int(0L),
1384     _last_float(0.0)
1385 {
1386     if(_type == 0 && !_init)
1387         changed(node);
1388 }
1389
1390 FGNasalListener::~FGNasalListener()
1391 {
1392     _node->removeChangeListener(this);
1393     _nas->gcRelease(_gcKey);
1394 }
1395
1396 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1397 {
1398     if(_active || _dead) return;
1399     _active++;
1400     naRef arg[4];
1401     arg[0] = _nas->propNodeGhost(which);
1402     arg[1] = _nas->propNodeGhost(_node);
1403     arg[2] = mode;                  // value changed, child added/removed
1404     arg[3] = naNum(_node != which); // child event?
1405     _nas->call(_code, 4, arg, naNil());
1406     _active--;
1407 }
1408
1409 void FGNasalListener::valueChanged(SGPropertyNode* node)
1410 {
1411     if(_type < 2 && node != _node) return;   // skip child events
1412     if(_type > 0 || changed(_node) || _init)
1413         call(node, naNum(0));
1414
1415     _init = 0;
1416 }
1417
1418 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1419 {
1420     if(_type == 2) call(child, naNum(1));
1421 }
1422
1423 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1424 {
1425     if(_type == 2) call(child, naNum(-1));
1426 }
1427
1428 bool FGNasalListener::changed(SGPropertyNode* node)
1429 {
1430     using namespace simgear;
1431     props::Type type = node->getType();
1432     if(type == props::NONE) return false;
1433     if(type == props::UNSPECIFIED) return true;
1434
1435     bool result;
1436     switch(type) {
1437     case props::BOOL:
1438     case props::INT:
1439     case props::LONG:
1440         {
1441             long l = node->getLongValue();
1442             result = l != _last_int;
1443             _last_int = l;
1444             return result;
1445         }
1446     case props::FLOAT:
1447     case props::DOUBLE:
1448         {
1449             double d = node->getDoubleValue();
1450             result = d != _last_float;
1451             _last_float = d;
1452             return result;
1453         }
1454     default:
1455         {
1456             string s = node->getStringValue();
1457             result = s != _last_string;
1458             _last_string = s;
1459             return result;
1460         }
1461     }
1462 }
1463
1464 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1465 //
1466 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1467     _c(naSubContext(c)),
1468     _start_element(argc > 1 ? args[1] : naNil()),
1469     _end_element(argc > 2 ? args[2] : naNil()),
1470     _data(argc > 3 ? args[3] : naNil()),
1471     _pi(argc > 4 ? args[4] : naNil())
1472 {
1473 }
1474
1475 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1476 {
1477     if(naIsNil(_start_element)) return;
1478     naRef attr = naNewHash(_c);
1479     for(int i=0; i<a.size(); i++) {
1480         naRef name = make_string(a.getName(i));
1481         naRef value = make_string(a.getValue(i));
1482         naHash_set(attr, name, value);
1483     }
1484     call(_start_element, 2, make_string(tag), attr);
1485 }
1486
1487 void NasalXMLVisitor::endElement(const char* tag)
1488 {
1489     if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1490 }
1491
1492 void NasalXMLVisitor::data(const char* str, int len)
1493 {
1494     if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1495 }
1496
1497 void NasalXMLVisitor::pi(const char* target, const char* data)
1498 {
1499     if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1500 }
1501
1502 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1503 {
1504     naRef args[2];
1505     args[0] = a;
1506     args[1] = b;
1507     naCall(_c, func, num, args, naNil(), naNil());
1508     if(naGetError(_c))
1509         naRethrowError(_c);
1510 }
1511
1512 naRef NasalXMLVisitor::make_string(const char* s, int n)
1513 {
1514     return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1515                           n < 0 ? strlen(s) : n);
1516 }
1517
1518