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