]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
Nasal: update for simgear changes.
[flightgear.git] / src / Scripting / NasalSys.cxx
1
2 #ifdef HAVE_CONFIG_H
3 #  include "config.h"
4 #endif
5
6 #ifdef HAVE_WINDOWS_H
7 #include <windows.h>
8 #endif
9
10 #ifdef HAVE_SYS_TIME_H
11 #  include <sys/time.h>  // gettimeofday
12 #endif
13
14 #include <string.h>
15 #include <stdio.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <fstream>
19 #include <sstream>
20
21 #include <simgear/nasal/nasal.h>
22 #include <simgear/props/props.hxx>
23 #include <simgear/math/sg_random.h>
24 #include <simgear/misc/sg_path.hxx>
25 #include <simgear/misc/sg_dir.hxx>
26 #include <simgear/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, me, argc, args);
709   return ctx.to_nasal(
710     simgear::SimpleMarkdown::parse(ctx.requireArg<std::string>(0))
711   );
712 }
713
714 /**
715  * Create md5 hash from given string
716  *
717  * md5(str)
718  */
719 static naRef f_md5(naContext c, naRef me, int argc, naRef* args)
720 {
721   if( argc != 1 || !naIsString(args[0]) )
722     naRuntimeError(c, "md5(): wrong type or number of arguments");
723
724   return nasal::to_nasal(
725     c,
726     simgear::strutils::md5(naStr_data(args[0]), naStr_len(args[0]))
727   );
728 }
729
730 // Return UNIX epoch time in seconds.
731 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
732 {
733 #ifdef _WIN32
734     FILETIME ft;
735     GetSystemTimeAsFileTime(&ft);
736     double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
737     // Converts from 100ns units in 1601 epoch to unix epoch in sec
738     return naNum((t * 1e-7) - 11644473600.0);
739 #else
740     struct timeval td;
741     gettimeofday(&td, 0);
742     return naNum(td.tv_sec + 1e-6 * td.tv_usec);
743 #endif
744 }
745
746 // Table of extension functions.  Terminate with zeros.
747 static struct { const char* name; naCFunction func; } funcs[] = {
748     { "getprop",   f_getprop },
749     { "setprop",   f_setprop },
750     { "print",     f_print },
751     { "logprint",  f_logprint },
752     { "_fgcommand", f_fgcommand },
753     { "settimer",  f_settimer },
754     { "maketimer", f_makeTimer },
755     { "_setlistener", f_setlistener },
756     { "removelistener", f_removelistener },
757     { "addcommand", f_addCommand },
758     { "removecommand", f_removeCommand },
759     { "_cmdarg",  f_cmdarg },
760     { "_interpolate",  f_interpolate },
761     { "rand",  f_rand },
762     { "srand",  f_srand },
763     { "abort", f_abort },
764     { "directory", f_directory },
765     { "resolvepath", f_resolveDataPath },
766     { "finddata", f_findDataDir },
767     { "parsexml", f_parsexml },
768     { "parse_markdown", f_parse_markdown },
769     { "md5", f_md5 },
770     { "systime", f_systime },
771     { 0, 0 }
772 };
773
774 naRef FGNasalSys::cmdArgGhost()
775 {
776     return propNodeGhost(_cmdArg);
777 }
778
779 void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
780 {
781     _cmdArg = aNode;
782 }
783
784 void FGNasalSys::init()
785 {
786     if (_inited) {
787         SG_LOG(SG_GENERAL, SG_ALERT, "duplicate init of Nasal");
788     }
789     int i;
790
791     _context = naNewContext();
792
793     // Start with globals.  Add it to itself as a recursive
794     // sub-reference under the name "globals".  This gives client-code
795     // write access to the namespace if someone wants to do something
796     // fancy.
797     _globals = naInit_std(_context);
798     naSave(_context, _globals);
799     hashset(_globals, "globals", _globals);
800
801     hashset(_globals, "math", naInit_math(_context));
802     hashset(_globals, "bits", naInit_bits(_context));
803     hashset(_globals, "io", naInit_io(_context));
804     hashset(_globals, "thread", naInit_thread(_context));
805     hashset(_globals, "utf8", naInit_utf8(_context));
806
807     // Add our custom extension functions:
808     for(i=0; funcs[i].name; i++)
809         hashset(_globals, funcs[i].name,
810                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
811
812     // And our SGPropertyNode wrapper
813     hashset(_globals, "props", genPropsModule());
814
815     // Add string methods
816     _string = naInit_string(_context);
817     naSave(_context, _string);
818     initNasalString(_globals, _string, _context);
819
820     initNasalPositioned(_globals, _context);
821     initNasalPositioned_cppbind(_globals, _context);
822     initNasalAircraft(_globals, _context);
823     NasalClipboard::init(this);
824     initNasalCanvas(_globals, _context);
825     initNasalCondition(_globals, _context);
826     initNasalHTTP(_globals, _context);
827     initNasalSGPath(_globals, _context);
828   
829     NasalTimerObj::init("Timer")
830       .method("start", &TimerObj::start)
831       .method("stop", &TimerObj::stop)
832       .method("restart", &TimerObj::restart)
833       .member("singleShot", &TimerObj::isSingleShot, &TimerObj::setSingleShot)
834       .member("isRunning", &TimerObj::isRunning);
835
836     // Now load the various source files in the Nasal directory
837     simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
838     loadScriptDirectory(nasalDir);
839
840     // Add modules in Nasal subdirectories to property tree
841     simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
842             simgear::Dir::NO_DOT_OR_DOTDOT, "");
843     for (unsigned int i=0; i<directories.size(); ++i) {
844         simgear::Dir dir(directories[i]);
845         simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
846         addModule(directories[i].file(), scripts);
847     }
848
849     // set signal and remove node to avoid restoring at reinit
850     const char *s = "nasal-dir-initialized";
851     SGPropertyNode *signal = fgGetNode("/sim/signals", true);
852     signal->setBoolValue(s, true);
853     signal->removeChildren(s);
854
855     // Pull scripts out of the property tree, too
856     loadPropertyScripts();
857   
858     // now Nasal modules are loaded, we can do some delayed work
859     postinitNasalPositioned(_globals, _context);
860     postinitNasalGUI(_globals, _context);
861     
862     _inited = true;
863 }
864
865 void FGNasalSys::shutdown()
866 {
867     if (!_inited) {
868         return;
869     }
870     
871     shutdownNasalPositioned();
872     
873     map<int, FGNasalListener *>::iterator it, end = _listener.end();
874     for(it = _listener.begin(); it != end; ++it)
875         delete it->second;
876     _listener.clear();
877     
878     NasalCommandDict::iterator j = _commands.begin();
879     for (; j != _commands.end(); ++j) {
880         globals->get_commands()->removeCommand(j->first);
881     }
882     _commands.clear();
883     
884     std::vector<FGNasalModuleListener*>::iterator k = _moduleListeners.begin();
885     for(; k!= _moduleListeners.end(); ++k)
886         delete *k;
887     _moduleListeners.clear();
888     
889     naClearSaved();
890     
891     _string = naNil(); // will be freed by _context
892     naFreeContext(_context);
893    
894     //setWatchedRef(_globals);
895     
896     // remove the recursive reference in globals
897     hashset(_globals, "globals", naNil());
898     _globals = naNil();    
899     
900     naGC();
901     _inited = false;
902 }
903
904 naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps)
905 {
906     if (naIsNil(_wrappedNodeFunc)) {
907         nasal::Hash props = getGlobals().get<nasal::Hash>("props");
908         _wrappedNodeFunc = props.get("wrapNode");
909     }
910     
911     naRef args[1];
912     args[0] = propNodeGhost(aProps);
913     naContext ctx = naNewContext();
914     naRef wrapped = naCall(ctx, _wrappedNodeFunc, 1, args, naNil(), naNil());
915     naFreeContext(ctx);
916     return wrapped;
917 }
918
919 void FGNasalSys::update(double)
920 {
921     if( NasalClipboard::getInstance() )
922         NasalClipboard::getInstance()->update();
923
924     if(!_dead_listener.empty()) {
925         vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
926         for(it = _dead_listener.begin(); it != end; ++it) delete *it;
927         _dead_listener.clear();
928     }
929
930     if (!_loadList.empty())
931     {
932         if( _delay_load )
933           _delay_load = false;
934         else
935           // process Nasal load hook (only one per update loop to avoid excessive lags)
936           _loadList.pop()->load();
937     }
938     else
939     if (!_unloadList.empty())
940     {
941         // process pending Nasal unload hooks after _all_ load hooks were processed
942         // (only unload one per update loop to avoid excessive lags)
943         _unloadList.pop()->unload();
944     }
945
946     // Destroy all queued ghosts
947     nasal::ghostProcessDestroyList();
948
949     // The global context is a legacy thing.  We use dynamically
950     // created contexts for naCall() now, so that we can call them
951     // recursively.  But there are still spots that want to use it for
952     // naNew*() calls, which end up leaking memory because the context
953     // only clears out its temporary vector when it's *used*.  So just
954     // junk it and fetch a new/reinitialized one every frame.  This is
955     // clumsy: the right solution would use the dynamic context in all
956     // cases and eliminate _context entirely.  But that's more work,
957     // and this works fine (yes, they say "New" and "Free", but
958     // they're very fast, just trust me). -Andy
959     naFreeContext(_context);
960     _context = naNewContext();
961 }
962
963 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
964 {
965   return p1.file() < p2.file();
966 }
967
968 // Loads all scripts in given directory 
969 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
970 {
971     simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
972     // Note: simgear::Dir already reports file entries in a deterministic order,
973     // so a fixed loading sequence is guaranteed (same for every user)
974     for (unsigned int i=0; i<scripts.size(); ++i) {
975       SGPath fullpath(scripts[i]);
976       SGPath file = fullpath.file();
977       loadModule(fullpath, file.base().c_str());
978     }
979 }
980
981 // Create module with list of scripts
982 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
983 {
984     if (! scripts.empty())
985     {
986         SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
987         SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
988         for (unsigned int i=0; i<scripts.size(); ++i) {
989             SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
990             pFileNode->setStringValue(scripts[i].c_str());
991         }
992         if (!module_node->hasChild("enabled",0))
993         {
994             SGPropertyNode* node = module_node->getChild("enabled",0,true);
995             node->setBoolValue(true);
996             node->setAttribute(SGPropertyNode::USERARCHIVE,true);
997         }
998     }
999 }
1000
1001 // Loads the scripts found under /nasal in the global tree
1002 void FGNasalSys::loadPropertyScripts()
1003 {
1004     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
1005     if(!nasal) return;
1006
1007     for(int i=0; i<nasal->nChildren(); i++)
1008     {
1009         SGPropertyNode* n = nasal->getChild(i);
1010         loadPropertyScripts(n);
1011     }
1012 }
1013
1014 // Loads the scripts found under /nasal in the global tree
1015 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
1016 {
1017     bool is_loaded = false;
1018
1019     const char* module = n->getName();
1020     if(n->hasChild("module"))
1021         module = n->getStringValue("module");
1022     if (n->getBoolValue("enabled",true))
1023     {
1024         // allow multiple files to be specified within a single
1025         // Nasal module tag
1026         int j = 0;
1027         SGPropertyNode *fn;
1028         bool file_specified = false;
1029         bool ok=true;
1030         while((fn = n->getChild("file", j)) != NULL) {
1031             file_specified = true;
1032             const char* file = fn->getStringValue();
1033             SGPath p(file);
1034             if (!p.isAbsolute() || !p.exists())
1035             {
1036                 p = globals->resolve_maybe_aircraft_path(file);
1037                 if (p.isNull())
1038                 {
1039                     SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
1040                             file << "' for module '" << module << "'.");
1041                 }
1042             }
1043             ok &= p.isNull() ? false : loadModule(p, module);
1044             j++;
1045         }
1046
1047         const char* src = n->getStringValue("script");
1048         if(!n->hasChild("script")) src = 0; // Hrm...
1049         if(src)
1050             createModule(module, n->getPath().c_str(), src, strlen(src));
1051
1052         if(!file_specified && !src)
1053         {
1054             // module no longer exists - clear the archived "enable" flag
1055             n->setAttribute(SGPropertyNode::USERARCHIVE,false);
1056             SGPropertyNode* node = n->getChild("enabled",0,false);
1057             if (node)
1058                 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
1059
1060             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
1061                     "no <file> or <script> defined in " <<
1062                     "/nasal/" << module);
1063         }
1064         else
1065             is_loaded = ok;
1066     }
1067     else
1068     {
1069         SGPropertyNode* enable = n->getChild("enabled");
1070         if (enable)
1071         {
1072             FGNasalModuleListener* listener = new FGNasalModuleListener(n);
1073             _moduleListeners.push_back(listener);
1074             enable->addChangeListener(listener, false);
1075         }
1076     }
1077     SGPropertyNode* loaded = n->getChild("loaded",0,true);
1078     loaded->setAttribute(SGPropertyNode::PRESERVE,true);
1079     loaded->setBoolValue(is_loaded);
1080 }
1081
1082 // Logs a runtime error, with stack trace, to the FlightGear log stream
1083 void FGNasalSys::logError(naContext context)
1084 {
1085     SG_LOG(SG_NASAL, SG_ALERT, "Nasal runtime error: " << naGetError(context));
1086     int stack_depth = naStackDepth(context);
1087     if( stack_depth < 1 )
1088       return;
1089     SG_LOG(SG_NASAL, SG_ALERT,
1090            "  at " << naStr_data(naGetSourceFile(context, 0)) <<
1091            ", line " << naGetLine(context, 0));
1092     for(int i=1; i<stack_depth; i++)
1093         SG_LOG(SG_NASAL, SG_ALERT,
1094                "  called from: " << naStr_data(naGetSourceFile(context, i)) <<
1095                ", line " << naGetLine(context, i));
1096 }
1097
1098 // Reads a script file, executes it, and places the resulting
1099 // namespace into the global namespace under the specified module
1100 // name.
1101 bool FGNasalSys::loadModule(SGPath file, const char* module)
1102 {
1103     int len = 0;
1104     char* buf = readfile(file.c_str(), &len);
1105     if(!buf) {
1106         SG_LOG(SG_NASAL, SG_ALERT,
1107                "Nasal error: could not read script file " << file.c_str()
1108                << " into module " << module);
1109         return false;
1110     }
1111
1112     bool ok = createModule(module, file.c_str(), buf, len);
1113     delete[] buf;
1114     return ok;
1115 }
1116
1117 // Parse and run.  Save the local variables namespace, as it will
1118 // become a sub-object of globals.  The optional "arg" argument can be
1119 // used to pass an associated property node to the module, which can then
1120 // be accessed via cmdarg().  (This is, for example, used by XML dialogs.)
1121 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1122                               const char* src, int len,
1123                               const SGPropertyNode* cmdarg,
1124                               int argc, naRef* args)
1125 {
1126     naContext ctx = naNewContext();
1127     naRef code = parse(ctx, fileName, src, len);
1128     if(naIsNil(code)) {
1129         naFreeContext(ctx);
1130         return false;
1131     }
1132
1133     
1134     // See if we already have a module hash to use.  This allows the
1135     // user to, for example, add functions to the built-in math
1136     // module.  Make a new one if necessary.
1137     naRef locals;
1138     naRef modname = naNewString(ctx);
1139     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1140     if(!naHash_get(_globals, modname, &locals))
1141         locals = naNewHash(ctx);
1142
1143     _cmdArg = (SGPropertyNode*)cmdarg;
1144
1145     callWithContext(ctx, code, argc, args, locals);
1146     hashset(_globals, moduleName, locals);
1147     
1148     naFreeContext(ctx);
1149     return true;
1150 }
1151
1152 void FGNasalSys::deleteModule(const char* moduleName)
1153 {
1154     if (!_inited) {
1155         // can occur on shutdown due to us being shutdown first, but other
1156         // subsystems having Nasal objects.
1157         return;
1158     }
1159     
1160     naContext ctx = naNewContext();
1161     naRef modname = naNewString(ctx);
1162     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1163     naHash_delete(_globals, modname);
1164     naFreeContext(ctx);
1165 }
1166
1167 naRef FGNasalSys::parse(naContext ctx, const char* filename, const char* buf, int len)
1168 {
1169     int errLine = -1;
1170     naRef srcfile = naNewString(ctx);
1171     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1172     naRef code = naParseCode(ctx, srcfile, 1, (char*)buf, len, &errLine);
1173     if(naIsNil(code)) {
1174         SG_LOG(SG_NASAL, SG_ALERT,
1175                "Nasal parse error: " << naGetError(ctx) <<
1176                " in "<< filename <<", line " << errLine);
1177         return naNil();
1178     }
1179
1180     // Bind to the global namespace before returning
1181     return naBindFunction(ctx, code, _globals);
1182 }
1183
1184 bool FGNasalSys::handleCommand( const char* moduleName,
1185                                 const char* fileName,
1186                                 const char* src,
1187                                 const SGPropertyNode* arg )
1188 {
1189     naContext ctx = naNewContext();
1190     naRef code = parse(ctx, fileName, src, strlen(src));
1191     if(naIsNil(code)) {
1192         naFreeContext(ctx);
1193         return false;
1194     }
1195
1196     // Commands can be run "in" a module.  Make sure that module
1197     // exists, and set it up as the local variables hash for the
1198     // command.
1199     naRef locals = naNil();
1200     if(moduleName[0]) {
1201         naRef modname = naNewString(ctx);
1202         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1203         if(!naHash_get(_globals, modname, &locals)) {
1204             locals = naNewHash(ctx);
1205             naHash_set(_globals, modname, locals);
1206         }
1207     }
1208
1209     // Cache this command's argument for inspection via cmdarg().  For
1210     // performance reasons, we won't bother with it if the invoked
1211     // code doesn't need it.
1212     _cmdArg = (SGPropertyNode*)arg;
1213
1214     callWithContext(ctx, code, 0, 0, locals);
1215     naFreeContext(ctx);
1216     return true;
1217 }
1218
1219 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1220 {
1221   const char* src = arg->getStringValue("script");
1222   const char* moduleName = arg->getStringValue("module");
1223
1224   return handleCommand( moduleName,
1225                         arg->getPath(true).c_str(),
1226                         src,
1227                         arg );
1228 }
1229
1230 // settimer(func, dt, simtime) extension function.  The first argument
1231 // is a Nasal function to call, the second is a delta time (from now),
1232 // in seconds.  The third, if present, is a boolean value indicating
1233 // that "real world" time (rather than simulator time) is to be used.
1234 //
1235 // Implementation note: the FGTimer objects don't live inside the
1236 // garbage collector, so the Nasal handler functions have to be
1237 // "saved" somehow lest they be inadvertently cleaned.  In this case,
1238 // they are inserted into a globals.__gcsave hash and removed on
1239 // expiration.
1240 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1241 {
1242     // Extract the handler, delta, and simtime arguments:
1243     naRef handler = argc > 0 ? args[0] : naNil();
1244     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1245         naRuntimeError(c, "settimer() with invalid function argument");
1246         return;
1247     }
1248
1249     naRef delta = argc > 1 ? args[1] : naNil();
1250     if(naIsNil(delta)) {
1251         naRuntimeError(c, "settimer() with invalid time argument");
1252         return;
1253     }
1254
1255     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1256
1257     // Generate and register a C++ timer handler
1258     NasalTimer* t = new NasalTimer;
1259     t->handler = handler;
1260     t->gcKey = gcSave(handler);
1261     t->nasal = this;
1262
1263     globals->get_event_mgr()->addEvent("NasalTimer",
1264                                        t, &NasalTimer::timerExpired,
1265                                        delta.num, simtime);
1266 }
1267
1268 void FGNasalSys::handleTimer(NasalTimer* t)
1269 {
1270     call(t->handler, 0, 0, naNil());
1271     gcRelease(t->gcKey);
1272 }
1273
1274 int FGNasalSys::gcSave(naRef r)
1275 {
1276     return naGCSave(r);
1277 }
1278
1279 void FGNasalSys::gcRelease(int key)
1280 {
1281     naGCRelease(key);
1282 }
1283
1284 void FGNasalSys::NasalTimer::timerExpired()
1285 {
1286     nasal->handleTimer(this);
1287     delete this;
1288 }
1289
1290 int FGNasalSys::_listenerId = 0;
1291
1292 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1293 // Attaches a callback function to a property (specified as a global
1294 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1295 // optional argument (default=0) is set to 1, then the function is also
1296 // called initially. If the fourth, optional argument is set to 0, then the
1297 // function is only called when the property node value actually changes.
1298 // Otherwise it's called independent of the value whenever the node is
1299 // written to (default). The setlistener() function returns a unique
1300 // id number, which is to be used as argument to the removelistener()
1301 // function.
1302 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1303 {
1304     SGPropertyNode_ptr node;
1305     naRef prop = argc > 0 ? args[0] : naNil();
1306     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1307     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1308     else {
1309         naRuntimeError(c, "setlistener() with invalid property argument");
1310         return naNil();
1311     }
1312
1313     if(node->isTied())
1314         SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1315                 node->getPath());
1316
1317     naRef code = argc > 1 ? args[1] : naNil();
1318     if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1319         naRuntimeError(c, "setlistener() with invalid function argument");
1320         return naNil();
1321     }
1322
1323     int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1324     int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1325     FGNasalListener *nl = new FGNasalListener(node, code, this,
1326             gcSave(code), _listenerId, init, type);
1327
1328     node->addChangeListener(nl, init != 0);
1329
1330     _listener[_listenerId] = nl;
1331     return naNum(_listenerId++);
1332 }
1333
1334 // removelistener(int) extension function. The argument is the id of
1335 // a listener as returned by the setlistener() function.
1336 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1337 {
1338     naRef id = argc > 0 ? args[0] : naNil();
1339     map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1340
1341     if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1342         naRuntimeError(c, "removelistener() with invalid listener id");
1343         return naNil();
1344     }
1345
1346     it->second->_dead = true;
1347     _dead_listener.push_back(it->second);
1348     _listener.erase(it);
1349     return naNum(_listener.size());
1350 }
1351
1352 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1353 {
1354   if( _loadList.empty() )
1355     _delay_load = true;
1356   _loadList.push(data);
1357 }
1358
1359 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1360 {
1361     _unloadList.push(data);
1362 }
1363
1364 void FGNasalSys::addCommand(naRef func, const std::string& name)
1365 {
1366     if (_commands.find(name) != _commands.end()) {
1367         SG_LOG(SG_NASAL, SG_WARN, "duplicate add of command:" << name);
1368         return;
1369     }
1370     
1371     NasalCommand* cmd = new NasalCommand(this, func, name);
1372     _commands[name] = cmd;
1373 }
1374
1375 void FGNasalSys::removeCommand(const std::string& name)
1376 {
1377     NasalCommandDict::iterator it = _commands.find(name);
1378     if (it == _commands.end()) {
1379         SG_LOG(SG_NASAL, SG_WARN, "remove of unknwon command:" << name);
1380         return;
1381     }
1382
1383     // will delete the NasalCommand instance
1384     globals->get_commands()->removeCommand(name);
1385     _commands.erase(it);
1386 }
1387
1388 //////////////////////////////////////////////////////////////////////////
1389 // FGNasalListener class.
1390
1391 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1392                                  FGNasalSys* nasal, int key, int id,
1393                                  int init, int type) :
1394     _node(node),
1395     _code(code),
1396     _gcKey(key),
1397     _id(id),
1398     _nas(nasal),
1399     _init(init),
1400     _type(type),
1401     _active(0),
1402     _dead(false),
1403     _last_int(0L),
1404     _last_float(0.0)
1405 {
1406     if(_type == 0 && !_init)
1407         changed(node);
1408 }
1409
1410 FGNasalListener::~FGNasalListener()
1411 {
1412     _node->removeChangeListener(this);
1413     _nas->gcRelease(_gcKey);
1414 }
1415
1416 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1417 {
1418     if(_active || _dead) return;
1419     _active++;
1420     naRef arg[4];
1421     arg[0] = _nas->propNodeGhost(which);
1422     arg[1] = _nas->propNodeGhost(_node);
1423     arg[2] = mode;                  // value changed, child added/removed
1424     arg[3] = naNum(_node != which); // child event?
1425     _nas->call(_code, 4, arg, naNil());
1426     _active--;
1427 }
1428
1429 void FGNasalListener::valueChanged(SGPropertyNode* node)
1430 {
1431     if(_type < 2 && node != _node) return;   // skip child events
1432     if(_type > 0 || changed(_node) || _init)
1433         call(node, naNum(0));
1434
1435     _init = 0;
1436 }
1437
1438 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1439 {
1440     if(_type == 2) call(child, naNum(1));
1441 }
1442
1443 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1444 {
1445     if(_type == 2) call(child, naNum(-1));
1446 }
1447
1448 bool FGNasalListener::changed(SGPropertyNode* node)
1449 {
1450     using namespace simgear;
1451     props::Type type = node->getType();
1452     if(type == props::NONE) return false;
1453     if(type == props::UNSPECIFIED) return true;
1454
1455     bool result;
1456     switch(type) {
1457     case props::BOOL:
1458     case props::INT:
1459     case props::LONG:
1460         {
1461             long l = node->getLongValue();
1462             result = l != _last_int;
1463             _last_int = l;
1464             return result;
1465         }
1466     case props::FLOAT:
1467     case props::DOUBLE:
1468         {
1469             double d = node->getDoubleValue();
1470             result = d != _last_float;
1471             _last_float = d;
1472             return result;
1473         }
1474     default:
1475         {
1476             string s = node->getStringValue();
1477             result = s != _last_string;
1478             _last_string = s;
1479             return result;
1480         }
1481     }
1482 }
1483
1484 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1485 //
1486 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1487     _c(naSubContext(c)),
1488     _start_element(argc > 1 ? args[1] : naNil()),
1489     _end_element(argc > 2 ? args[2] : naNil()),
1490     _data(argc > 3 ? args[3] : naNil()),
1491     _pi(argc > 4 ? args[4] : naNil())
1492 {
1493 }
1494
1495 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1496 {
1497     if(naIsNil(_start_element)) return;
1498     naRef attr = naNewHash(_c);
1499     for(int i=0; i<a.size(); i++) {
1500         naRef name = make_string(a.getName(i));
1501         naRef value = make_string(a.getValue(i));
1502         naHash_set(attr, name, value);
1503     }
1504     call(_start_element, 2, make_string(tag), attr);
1505 }
1506
1507 void NasalXMLVisitor::endElement(const char* tag)
1508 {
1509     if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1510 }
1511
1512 void NasalXMLVisitor::data(const char* str, int len)
1513 {
1514     if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1515 }
1516
1517 void NasalXMLVisitor::pi(const char* target, const char* data)
1518 {
1519     if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1520 }
1521
1522 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1523 {
1524     naRef args[2];
1525     args[0] = a;
1526     args[1] = b;
1527     naCall(_c, func, num, args, naNil(), naNil());
1528     if(naGetError(_c))
1529         naRethrowError(_c);
1530 }
1531
1532 naRef NasalXMLVisitor::make_string(const char* s, int n)
1533 {
1534     return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1535                           n < 0 ? strlen(s) : n);
1536 }
1537
1538