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