]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
Stop using property listener for fgValidatePath
[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 node;
462     if(!naIsNil(props))
463         node = static_cast<SGPropertyNode*>(naGhost_ptr(props));
464     else
465         node = new SGPropertyNode;
466
467     return naNum(globals->get_commands()->execute(naStr_data(cmd), node));
468 }
469
470 // settimer(func, dt, simtime) extension function.  Falls through to
471 // FGNasalSys::setTimer().  See there for docs.
472 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
473 {
474     nasalSys->setTimer(c, argc, args);
475     return naNil();
476 }
477
478 static naRef f_makeTimer(naContext c, naRef me, int argc, naRef* args)
479 {
480   if (!naIsNum(args[0])) {
481     naRuntimeError(c, "bad interval argument to maketimer");
482   }
483     
484   naRef func, self = naNil();
485   if (naIsFunc(args[1])) {
486     func = args[1];
487   } else if ((argc == 3) && naIsFunc(args[2])) {
488     self = args[1];
489     func = args[2];
490   }
491   
492   TimerObj* timerObj = new TimerObj(nasalSys, func, self, args[0].num);
493   return nasal::to_nasal(c, timerObj);
494 }
495
496 // setlistener(func, property, bool) extension function.  Falls through to
497 // FGNasalSys::setListener().  See there for docs.
498 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
499 {
500     return nasalSys->setListener(c, argc, args);
501 }
502
503 // removelistener(int) extension function. Falls through to
504 // FGNasalSys::removeListener(). See there for docs.
505 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
506 {
507     return nasalSys->removeListener(c, argc, args);
508 }
509
510 // Returns a ghost handle to the argument to the currently executing
511 // command
512 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
513 {
514     return nasalSys->cmdArgGhost();
515 }
516
517 // Sets up a property interpolation.  The first argument is either a
518 // ghost (SGPropertyNode*) or a string (global property path) to
519 // interpolate.  The second argument is a vector of pairs of
520 // value/delta numbers.
521 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
522 {
523   SGPropertyNode* node;
524   naRef prop = argc > 0 ? args[0] : naNil();
525   if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
526   else if(naIsGhost(prop)) node = static_cast<SGPropertyNode*>(naGhost_ptr(prop));
527   else return naNil();
528
529   naRef curve = argc > 1 ? args[1] : naNil();
530   if(!naIsVector(curve)) return naNil();
531   int nPoints = naVec_size(curve) / 2;
532
533   simgear::PropertyList value_nodes;
534   value_nodes.reserve(nPoints);
535   double_list deltas;
536   deltas.reserve(nPoints);
537
538   for( int i = 0; i < nPoints; ++i )
539   {
540     SGPropertyNode* val = new SGPropertyNode;
541     val->setDoubleValue(naNumValue(naVec_get(curve, 2*i)).num);
542     value_nodes.push_back(val);
543     deltas.push_back(naNumValue(naVec_get(curve, 2*i+1)).num);
544   }
545
546   node->interpolate("numeric", value_nodes, deltas, "linear");
547   return naNil();
548 }
549
550 // This is a better RNG than the one in the default Nasal distribution
551 // (which is based on the C library rand() implementation). It will
552 // override.
553 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
554 {
555     return naNum(sg_random());
556 }
557
558 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
559 {
560     sg_srandom_time();
561     return naNum(0);
562 }
563
564 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
565 {
566     abort();
567     return naNil();
568 }
569
570 // Return an array listing of all files in a directory
571 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
572 {
573     if(argc != 1 || !naIsString(args[0]))
574         naRuntimeError(c, "bad arguments to directory()");
575     
576     simgear::Dir d(SGPath(naStr_data(args[0])));
577     if(!d.exists()) return naNil();
578     naRef result = naNewVector(c);
579
580     simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
581     for (unsigned int i=0; i<paths.size(); ++i) {
582       std::string p = paths[i].file();
583       naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
584     }
585     
586     return result;
587 }
588
589 /**
590  * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
591  */
592 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
593 {
594     if(argc != 1 || !naIsString(args[0]))
595         naRuntimeError(c, "bad arguments to resolveDataPath()");
596
597     SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
598     const char* pdata = p.c_str();
599     return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
600 }
601
602 static naRef f_findDataDir(naContext c, naRef me, int argc, naRef* args)
603 {
604     if(argc != 1 || !naIsString(args[0]))
605         naRuntimeError(c, "bad arguments to findDataDir()");
606     
607     SGPath p = globals->find_data_dir(naStr_data(args[0]));
608     const char* pdata = p.c_str();
609     return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
610 }
611
612 class NasalCommand : public SGCommandMgr::Command
613 {
614 public:
615     NasalCommand(FGNasalSys* sys, naRef f, const std::string& name) :
616         _sys(sys),
617         _func(f),
618         _name(name)
619     {
620         globals->get_commands()->addCommandObject(_name, this);
621         _gcRoot =  sys->gcSave(f);
622     }
623     
624     virtual ~NasalCommand()
625     {
626         _sys->gcRelease(_gcRoot);
627     }
628     
629     virtual bool operator()(const SGPropertyNode* aNode)
630     {
631         _sys->setCmdArg(const_cast<SGPropertyNode*>(aNode));
632         naRef args[1];
633         args[0] = _sys->wrappedPropsNode(const_cast<SGPropertyNode*>(aNode));
634     
635         _sys->callMethod(_func, naNil(), 1, args, naNil() /* locals */);
636
637         return true;
638     }
639     
640 private:
641     FGNasalSys* _sys;
642     naRef _func;
643     int _gcRoot;
644     std::string _name;
645 };
646
647 static naRef f_addCommand(naContext c, naRef me, int argc, naRef* args)
648 {
649     if(argc != 2 || !naIsString(args[0]) || !naIsFunc(args[1]))
650         naRuntimeError(c, "bad arguments to addcommand()");
651     
652     nasalSys->addCommand(args[1], naStr_data(args[0]));
653     return naNil();
654 }
655
656 static naRef f_removeCommand(naContext c, naRef me, int argc, naRef* args)
657 {
658     if ((argc < 1) || !naIsString(args[0]))
659         naRuntimeError(c, "bad argument to removecommand()");
660     
661     globals->get_commands()->removeCommand(naStr_data(args[0]));
662     return naNil();
663 }
664
665 // Parse XML file.
666 //     parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
667 //
668 // <path>      ... absolute path to an XML file
669 // <start-tag> ... callback function with two args: tag name, attribute hash
670 // <end-tag>   ... callback function with one arg:  tag name
671 // <data>      ... callback function with one arg:  data
672 // <pi>        ... callback function with two args: target, data
673 //                 (pi = "processing instruction")
674 // All four callback functions are optional and default to nil.
675 // The function returns nil on error, or the validated file name otherwise.
676 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
677 {
678     if(argc < 1 || !naIsString(args[0]))
679         naRuntimeError(c, "parsexml(): path argument missing or not a string");
680     if(argc > 5) argc = 5;
681     for(int i=1; i<argc; i++)
682         if(!(naIsNil(args[i]) || naIsFunc(args[i])))
683             naRuntimeError(c, "parsexml(): callback argument not a function");
684
685     const char* file = fgValidatePath(naStr_data(args[0]), false);
686     if(!file) {
687         naRuntimeError(c, "parsexml(): reading '%s' denied "
688                 "(unauthorized access)", naStr_data(args[0]));
689         return naNil();
690     }
691     std::ifstream input(file);
692     NasalXMLVisitor visitor(c, argc, args);
693     try {
694         readXML(input, visitor);
695     } catch (const sg_exception& e) {
696         naRuntimeError(c, "parsexml(): file '%s' %s",
697                 file, e.getFormattedMessage().c_str());
698         return naNil();
699     }
700     return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
701 }
702
703 /**
704  * Parse very simple and small subset of markdown
705  *
706  * parse_markdown(src)
707  */
708 static naRef f_parse_markdown(naContext c, naRef me, int argc, naRef* args)
709 {
710   nasal::CallContext ctx(c, me, argc, args);
711   return ctx.to_nasal(
712     simgear::SimpleMarkdown::parse(ctx.requireArg<std::string>(0))
713   );
714 }
715
716 /**
717  * Create md5 hash from given string
718  *
719  * md5(str)
720  */
721 static naRef f_md5(naContext c, naRef me, int argc, naRef* args)
722 {
723   if( argc != 1 || !naIsString(args[0]) )
724     naRuntimeError(c, "md5(): wrong type or number of arguments");
725
726   return nasal::to_nasal(
727     c,
728     simgear::strutils::md5(naStr_data(args[0]), naStr_len(args[0]))
729   );
730 }
731
732 // Return UNIX epoch time in seconds.
733 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
734 {
735 #ifdef _WIN32
736     FILETIME ft;
737     GetSystemTimeAsFileTime(&ft);
738     double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
739     // Converts from 100ns units in 1601 epoch to unix epoch in sec
740     return naNum((t * 1e-7) - 11644473600.0);
741 #else
742     struct timeval td;
743     gettimeofday(&td, 0);
744     return naNum(td.tv_sec + 1e-6 * td.tv_usec);
745 #endif
746 }
747
748 // Table of extension functions.  Terminate with zeros.
749 static struct { const char* name; naCFunction func; } funcs[] = {
750     { "getprop",   f_getprop },
751     { "setprop",   f_setprop },
752     { "print",     f_print },
753     { "logprint",  f_logprint },
754     { "_fgcommand", f_fgcommand },
755     { "settimer",  f_settimer },
756     { "maketimer", f_makeTimer },
757     { "_setlistener", f_setlistener },
758     { "removelistener", f_removelistener },
759     { "addcommand", f_addCommand },
760     { "removecommand", f_removeCommand },
761     { "_cmdarg",  f_cmdarg },
762     { "_interpolate",  f_interpolate },
763     { "rand",  f_rand },
764     { "srand",  f_srand },
765     { "abort", f_abort },
766     { "directory", f_directory },
767     { "resolvepath", f_resolveDataPath },
768     { "finddata", f_findDataDir },
769     { "parsexml", f_parsexml },
770     { "parse_markdown", f_parse_markdown },
771     { "md5", f_md5 },
772     { "systime", f_systime },
773     { 0, 0 }
774 };
775
776 naRef FGNasalSys::cmdArgGhost()
777 {
778     return propNodeGhost(_cmdArg);
779 }
780
781 void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
782 {
783     _cmdArg = aNode;
784 }
785
786 void FGNasalSys::init()
787 {
788     if (_inited) {
789         SG_LOG(SG_GENERAL, SG_ALERT, "duplicate init of Nasal");
790     }
791     int i;
792
793     _context = naNewContext();
794
795     // Start with globals.  Add it to itself as a recursive
796     // sub-reference under the name "globals".  This gives client-code
797     // write access to the namespace if someone wants to do something
798     // fancy.
799     _globals = naInit_std(_context);
800     naSave(_context, _globals);
801     hashset(_globals, "globals", _globals);
802
803     hashset(_globals, "math", naInit_math(_context));
804     hashset(_globals, "bits", naInit_bits(_context));
805     hashset(_globals, "io", naInit_io(_context));
806     hashset(_globals, "thread", naInit_thread(_context));
807     hashset(_globals, "utf8", naInit_utf8(_context));
808
809     // Add our custom extension functions:
810     for(i=0; funcs[i].name; i++)
811         hashset(_globals, funcs[i].name,
812                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
813
814     // And our SGPropertyNode wrapper
815     hashset(_globals, "props", genPropsModule());
816
817     // Add string methods
818     _string = naInit_string(_context);
819     naSave(_context, _string);
820     initNasalString(_globals, _string, _context);
821
822     initNasalPositioned(_globals, _context);
823     initNasalPositioned_cppbind(_globals, _context);
824     initNasalAircraft(_globals, _context);
825     NasalClipboard::init(this);
826     initNasalCanvas(_globals, _context);
827     initNasalCondition(_globals, _context);
828     initNasalHTTP(_globals, _context);
829     initNasalSGPath(_globals, _context);
830   
831     NasalTimerObj::init("Timer")
832       .method("start", &TimerObj::start)
833       .method("stop", &TimerObj::stop)
834       .method("restart", &TimerObj::restart)
835       .member("singleShot", &TimerObj::isSingleShot, &TimerObj::setSingleShot)
836       .member("isRunning", &TimerObj::isRunning);
837
838     // Set allowed paths for Nasal I/O
839     fgInitAllowedPaths();
840     
841     // Now load the various source files in the Nasal directory
842     simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
843     loadScriptDirectory(nasalDir);
844
845     // Add modules in Nasal subdirectories to property tree
846     simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
847             simgear::Dir::NO_DOT_OR_DOTDOT, "");
848     for (unsigned int i=0; i<directories.size(); ++i) {
849         simgear::Dir dir(directories[i]);
850         simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
851         addModule(directories[i].file(), scripts);
852     }
853
854     // set signal and remove node to avoid restoring at reinit
855     const char *s = "nasal-dir-initialized";
856     SGPropertyNode *signal = fgGetNode("/sim/signals", true);
857     signal->setBoolValue(s, true);
858     signal->removeChildren(s);
859
860     if( !checkIOrules() )
861     {
862       SG_LOG(SG_NASAL, SG_ALERT, "Required IOrules check failed.");
863       exit(-1);
864     }
865
866     // Pull scripts out of the property tree, too
867     loadPropertyScripts();
868   
869     // now Nasal modules are loaded, we can do some delayed work
870     postinitNasalPositioned(_globals, _context);
871     postinitNasalGUI(_globals, _context);
872     
873     _inited = true;
874 }
875
876 void FGNasalSys::shutdown()
877 {
878     if (!_inited) {
879         return;
880     }
881     
882     shutdownNasalPositioned();
883     
884     map<int, FGNasalListener *>::iterator it, end = _listener.end();
885     for(it = _listener.begin(); it != end; ++it)
886         delete it->second;
887     _listener.clear();
888     
889     NasalCommandDict::iterator j = _commands.begin();
890     for (; j != _commands.end(); ++j) {
891         globals->get_commands()->removeCommand(j->first);
892     }
893     _commands.clear();
894     
895     std::vector<FGNasalModuleListener*>::iterator k = _moduleListeners.begin();
896     for(; k!= _moduleListeners.end(); ++k)
897         delete *k;
898     _moduleListeners.clear();
899     
900     naClearSaved();
901     
902     _string = naNil(); // will be freed by _context
903     naFreeContext(_context);
904    
905     //setWatchedRef(_globals);
906     
907     // remove the recursive reference in globals
908     hashset(_globals, "globals", naNil());
909     _globals = naNil();    
910     
911     naGC();
912     _inited = false;
913 }
914
915 naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps)
916 {
917     if (naIsNil(_wrappedNodeFunc)) {
918         nasal::Hash props = getGlobals().get<nasal::Hash>("props");
919         _wrappedNodeFunc = props.get("wrapNode");
920     }
921     
922     naRef args[1];
923     args[0] = propNodeGhost(aProps);
924     naContext ctx = naNewContext();
925     naRef wrapped = naCallMethodCtx(ctx, _wrappedNodeFunc, naNil(), 1, args, naNil());
926     naFreeContext(ctx);
927     return wrapped;
928 }
929
930 void FGNasalSys::update(double)
931 {
932     if( NasalClipboard::getInstance() )
933         NasalClipboard::getInstance()->update();
934
935     if(!_dead_listener.empty()) {
936         vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
937         for(it = _dead_listener.begin(); it != end; ++it) delete *it;
938         _dead_listener.clear();
939     }
940
941     if (!_loadList.empty())
942     {
943         if( _delay_load )
944           _delay_load = false;
945         else
946           // process Nasal load hook (only one per update loop to avoid excessive lags)
947           _loadList.pop()->load();
948     }
949     else
950     if (!_unloadList.empty())
951     {
952         // process pending Nasal unload hooks after _all_ load hooks were processed
953         // (only unload one per update loop to avoid excessive lags)
954         _unloadList.pop()->unload();
955     }
956
957     // Destroy all queued ghosts
958     nasal::ghostProcessDestroyList();
959
960     // The global context is a legacy thing.  We use dynamically
961     // created contexts for naCall() now, so that we can call them
962     // recursively.  But there are still spots that want to use it for
963     // naNew*() calls, which end up leaking memory because the context
964     // only clears out its temporary vector when it's *used*.  So just
965     // junk it and fetch a new/reinitialized one every frame.  This is
966     // clumsy: the right solution would use the dynamic context in all
967     // cases and eliminate _context entirely.  But that's more work,
968     // and this works fine (yes, they say "New" and "Free", but
969     // they're very fast, just trust me). -Andy
970     naFreeContext(_context);
971     _context = naNewContext();
972 }
973
974 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
975 {
976   return p1.file() < p2.file();
977 }
978
979 // Loads all scripts in given directory 
980 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
981 {
982     simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
983     // Note: simgear::Dir already reports file entries in a deterministic order,
984     // so a fixed loading sequence is guaranteed (same for every user)
985     for (unsigned int i=0; i<scripts.size(); ++i) {
986       SGPath fullpath(scripts[i]);
987       SGPath file = fullpath.file();
988       loadModule(fullpath, file.base().c_str());
989     }
990 }
991
992 // Create module with list of scripts
993 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
994 {
995     if (! scripts.empty())
996     {
997         SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
998         SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
999         for (unsigned int i=0; i<scripts.size(); ++i) {
1000             SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
1001             pFileNode->setStringValue(scripts[i].c_str());
1002         }
1003         if (!module_node->hasChild("enabled",0))
1004         {
1005             SGPropertyNode* node = module_node->getChild("enabled",0,true);
1006             node->setBoolValue(true);
1007             node->setAttribute(SGPropertyNode::USERARCHIVE,true);
1008         }
1009     }
1010 }
1011
1012 // Loads the scripts found under /nasal in the global tree
1013 void FGNasalSys::loadPropertyScripts()
1014 {
1015     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
1016     if(!nasal) return;
1017
1018     for(int i=0; i<nasal->nChildren(); i++)
1019     {
1020         SGPropertyNode* n = nasal->getChild(i);
1021         loadPropertyScripts(n);
1022     }
1023 }
1024
1025 // Loads the scripts found under /nasal in the global tree
1026 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
1027 {
1028     bool is_loaded = false;
1029
1030     const char* module = n->getName();
1031     if(n->hasChild("module"))
1032         module = n->getStringValue("module");
1033     if (n->getBoolValue("enabled",true))
1034     {
1035         // allow multiple files to be specified within a single
1036         // Nasal module tag
1037         int j = 0;
1038         SGPropertyNode *fn;
1039         bool file_specified = false;
1040         bool ok=true;
1041         while((fn = n->getChild("file", j)) != NULL) {
1042             file_specified = true;
1043             const char* file = fn->getStringValue();
1044             SGPath p(file);
1045             if (!p.isAbsolute() || !p.exists())
1046             {
1047                 p = globals->resolve_maybe_aircraft_path(file);
1048                 if (p.isNull())
1049                 {
1050                     SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
1051                             file << "' for module '" << module << "'.");
1052                 }
1053             }
1054             ok &= p.isNull() ? false : loadModule(p, module);
1055             j++;
1056         }
1057
1058         const char* src = n->getStringValue("script");
1059         if(!n->hasChild("script")) src = 0; // Hrm...
1060         if(src)
1061             createModule(module, n->getPath().c_str(), src, strlen(src));
1062
1063         if(!file_specified && !src)
1064         {
1065             // module no longer exists - clear the archived "enable" flag
1066             n->setAttribute(SGPropertyNode::USERARCHIVE,false);
1067             SGPropertyNode* node = n->getChild("enabled",0,false);
1068             if (node)
1069                 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
1070
1071             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
1072                     "no <file> or <script> defined in " <<
1073                     "/nasal/" << module);
1074         }
1075         else
1076             is_loaded = ok;
1077     }
1078     else
1079     {
1080         SGPropertyNode* enable = n->getChild("enabled");
1081         if (enable)
1082         {
1083             FGNasalModuleListener* listener = new FGNasalModuleListener(n);
1084             _moduleListeners.push_back(listener);
1085             enable->addChangeListener(listener, false);
1086         }
1087     }
1088     SGPropertyNode* loaded = n->getChild("loaded",0,true);
1089     loaded->setAttribute(SGPropertyNode::PRESERVE,true);
1090     loaded->setBoolValue(is_loaded);
1091 }
1092
1093 // Logs a runtime error, with stack trace, to the FlightGear log stream
1094 void FGNasalSys::logError(naContext context)
1095 {
1096     SG_LOG(SG_NASAL, SG_ALERT, "Nasal runtime error: " << naGetError(context));
1097     int stack_depth = naStackDepth(context);
1098     if( stack_depth < 1 )
1099       return;
1100     SG_LOG(SG_NASAL, SG_ALERT,
1101            "  at " << naStr_data(naGetSourceFile(context, 0)) <<
1102            ", line " << naGetLine(context, 0));
1103     for(int i=1; i<stack_depth; i++)
1104         SG_LOG(SG_NASAL, SG_ALERT,
1105                "  called from: " << naStr_data(naGetSourceFile(context, i)) <<
1106                ", line " << naGetLine(context, i));
1107 }
1108
1109 // Reads a script file, executes it, and places the resulting
1110 // namespace into the global namespace under the specified module
1111 // name.
1112 bool FGNasalSys::loadModule(SGPath file, const char* module)
1113 {
1114     int len = 0;
1115     char* buf = readfile(file.c_str(), &len);
1116     if(!buf) {
1117         SG_LOG(SG_NASAL, SG_ALERT,
1118                "Nasal error: could not read script file " << file.c_str()
1119                << " into module " << module);
1120         return false;
1121     }
1122
1123     bool ok = createModule(module, file.c_str(), buf, len);
1124     delete[] buf;
1125     return ok;
1126 }
1127
1128 // Parse and run.  Save the local variables namespace, as it will
1129 // become a sub-object of globals.  The optional "arg" argument can be
1130 // used to pass an associated property node to the module, which can then
1131 // be accessed via cmdarg().  (This is, for example, used by XML dialogs.)
1132 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1133                               const char* src, int len,
1134                               const SGPropertyNode* cmdarg,
1135                               int argc, naRef* args)
1136 {
1137     naContext ctx = naNewContext();
1138     naRef code = parse(ctx, fileName, src, len);
1139     if(naIsNil(code)) {
1140         naFreeContext(ctx);
1141         return false;
1142     }
1143
1144     
1145     // See if we already have a module hash to use.  This allows the
1146     // user to, for example, add functions to the built-in math
1147     // module.  Make a new one if necessary.
1148     naRef locals;
1149     naRef modname = naNewString(ctx);
1150     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1151     if(!naHash_get(_globals, modname, &locals))
1152         locals = naNewHash(ctx);
1153
1154     _cmdArg = (SGPropertyNode*)cmdarg;
1155
1156     callWithContext(ctx, code, argc, args, locals);
1157     hashset(_globals, moduleName, locals);
1158     
1159     naFreeContext(ctx);
1160     return true;
1161 }
1162
1163 void FGNasalSys::deleteModule(const char* moduleName)
1164 {
1165     if (!_inited) {
1166         // can occur on shutdown due to us being shutdown first, but other
1167         // subsystems having Nasal objects.
1168         return;
1169     }
1170     
1171     naContext ctx = naNewContext();
1172     naRef modname = naNewString(ctx);
1173     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1174     naHash_delete(_globals, modname);
1175     naFreeContext(ctx);
1176 }
1177
1178 naRef FGNasalSys::parse(naContext ctx, const char* filename, const char* buf, int len)
1179 {
1180     int errLine = -1;
1181     naRef srcfile = naNewString(ctx);
1182     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1183     naRef code = naParseCode(ctx, srcfile, 1, (char*)buf, len, &errLine);
1184     if(naIsNil(code)) {
1185         SG_LOG(SG_NASAL, SG_ALERT,
1186                "Nasal parse error: " << naGetError(ctx) <<
1187                " in "<< filename <<", line " << errLine);
1188         return naNil();
1189     }
1190
1191     // Bind to the global namespace before returning
1192     return naBindFunction(ctx, code, _globals);
1193 }
1194
1195 bool FGNasalSys::handleCommand( const char* moduleName,
1196                                 const char* fileName,
1197                                 const char* src,
1198                                 const SGPropertyNode* arg )
1199 {
1200     naContext ctx = naNewContext();
1201     naRef code = parse(ctx, fileName, src, strlen(src));
1202     if(naIsNil(code)) {
1203         naFreeContext(ctx);
1204         return false;
1205     }
1206
1207     // Commands can be run "in" a module.  Make sure that module
1208     // exists, and set it up as the local variables hash for the
1209     // command.
1210     naRef locals = naNil();
1211     if(moduleName[0]) {
1212         naRef modname = naNewString(ctx);
1213         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1214         if(!naHash_get(_globals, modname, &locals)) {
1215             locals = naNewHash(ctx);
1216             naHash_set(_globals, modname, locals);
1217         }
1218     }
1219
1220     // Cache this command's argument for inspection via cmdarg().  For
1221     // performance reasons, we won't bother with it if the invoked
1222     // code doesn't need it.
1223     _cmdArg = (SGPropertyNode*)arg;
1224
1225     callWithContext(ctx, code, 0, 0, locals);
1226     naFreeContext(ctx);
1227     return true;
1228 }
1229
1230 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1231 {
1232   const char* src = arg->getStringValue("script");
1233   const char* moduleName = arg->getStringValue("module");
1234
1235   return handleCommand( moduleName,
1236                         arg->getPath(true).c_str(),
1237                         src,
1238                         arg );
1239 }
1240
1241 // settimer(func, dt, simtime) extension function.  The first argument
1242 // is a Nasal function to call, the second is a delta time (from now),
1243 // in seconds.  The third, if present, is a boolean value indicating
1244 // that "real world" time (rather than simulator time) is to be used.
1245 //
1246 // Implementation note: the FGTimer objects don't live inside the
1247 // garbage collector, so the Nasal handler functions have to be
1248 // "saved" somehow lest they be inadvertently cleaned.  In this case,
1249 // they are inserted into a globals.__gcsave hash and removed on
1250 // expiration.
1251 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1252 {
1253     // Extract the handler, delta, and simtime arguments:
1254     naRef handler = argc > 0 ? args[0] : naNil();
1255     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1256         naRuntimeError(c, "settimer() with invalid function argument");
1257         return;
1258     }
1259
1260     naRef delta = argc > 1 ? args[1] : naNil();
1261     if(naIsNil(delta)) {
1262         naRuntimeError(c, "settimer() with invalid time argument");
1263         return;
1264     }
1265
1266     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1267
1268     // Generate and register a C++ timer handler
1269     NasalTimer* t = new NasalTimer;
1270     t->handler = handler;
1271     t->gcKey = gcSave(handler);
1272     t->nasal = this;
1273
1274     globals->get_event_mgr()->addEvent("NasalTimer",
1275                                        t, &NasalTimer::timerExpired,
1276                                        delta.num, simtime);
1277 }
1278
1279 void FGNasalSys::handleTimer(NasalTimer* t)
1280 {
1281     call(t->handler, 0, 0, naNil());
1282     gcRelease(t->gcKey);
1283 }
1284
1285 int FGNasalSys::gcSave(naRef r)
1286 {
1287     return naGCSave(r);
1288 }
1289
1290 void FGNasalSys::gcRelease(int key)
1291 {
1292     naGCRelease(key);
1293 }
1294
1295 //------------------------------------------------------------------------------
1296 bool FGNasalSys::checkIOrules()
1297 {
1298   // Ensure IOrules and path validation are working properly by trying to
1299   // access a folder/file which should never be accessible.
1300   const char* no_access_path =
1301 #ifdef _WIN32
1302     "Z:"
1303 #endif
1304     "/do-not-access";
1305
1306   bool success = true;
1307
1308   // write access
1309   if( fgValidatePath(no_access_path, true) )
1310   {
1311     success = false;
1312     SG_LOG
1313     (
1314       SG_GENERAL,
1315       SG_ALERT,
1316       "Check your IOrules! (write to '" << no_access_path << "' is allowed)"
1317     );
1318   }
1319
1320   // read access
1321   if( fgValidatePath(no_access_path, false) )
1322   {
1323     success = false;
1324     SG_LOG
1325     (
1326       SG_GENERAL,
1327       SG_ALERT,
1328       "Check your IOrules! (read from '" << no_access_path << "' is allowed)"
1329     );
1330   }
1331
1332   return success;
1333 }
1334
1335 //------------------------------------------------------------------------------
1336 void FGNasalSys::NasalTimer::timerExpired()
1337 {
1338     nasal->handleTimer(this);
1339     delete this;
1340 }
1341
1342 int FGNasalSys::_listenerId = 0;
1343
1344 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1345 // Attaches a callback function to a property (specified as a global
1346 // property path string or a SGPropertyNode* ghost). If the third,
1347 // optional argument (default=0) is set to 1, then the function is also
1348 // called initially. If the fourth, optional argument is set to 0, then the
1349 // function is only called when the property node value actually changes.
1350 // Otherwise it's called independent of the value whenever the node is
1351 // written to (default). The setlistener() function returns a unique
1352 // id number, which is to be used as argument to the removelistener()
1353 // function.
1354 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1355 {
1356     SGPropertyNode_ptr node;
1357     naRef prop = argc > 0 ? args[0] : naNil();
1358     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1359     else if(naIsGhost(prop)) node = static_cast<SGPropertyNode*>(naGhost_ptr(prop));
1360     else {
1361         naRuntimeError(c, "setlistener() with invalid property argument");
1362         return naNil();
1363     }
1364
1365     if(node->isTied())
1366         SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1367                 node->getPath());
1368
1369     naRef code = argc > 1 ? args[1] : naNil();
1370     if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1371         naRuntimeError(c, "setlistener() with invalid function argument");
1372         return naNil();
1373     }
1374
1375     int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1376     int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1377     FGNasalListener *nl = new FGNasalListener(node, code, this,
1378             gcSave(code), _listenerId, init, type);
1379
1380     node->addChangeListener(nl, init != 0);
1381
1382     _listener[_listenerId] = nl;
1383     return naNum(_listenerId++);
1384 }
1385
1386 // removelistener(int) extension function. The argument is the id of
1387 // a listener as returned by the setlistener() function.
1388 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1389 {
1390     naRef id = argc > 0 ? args[0] : naNil();
1391     map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1392
1393     if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1394         naRuntimeError(c, "removelistener() with invalid listener id");
1395         return naNil();
1396     }
1397
1398     it->second->_dead = true;
1399     _dead_listener.push_back(it->second);
1400     _listener.erase(it);
1401     return naNum(_listener.size());
1402 }
1403
1404 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1405 {
1406   if( _loadList.empty() )
1407     _delay_load = true;
1408   _loadList.push(data);
1409 }
1410
1411 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1412 {
1413     _unloadList.push(data);
1414 }
1415
1416 void FGNasalSys::addCommand(naRef func, const std::string& name)
1417 {
1418     if (_commands.find(name) != _commands.end()) {
1419         SG_LOG(SG_NASAL, SG_WARN, "duplicate add of command:" << name);
1420         return;
1421     }
1422     
1423     NasalCommand* cmd = new NasalCommand(this, func, name);
1424     _commands[name] = cmd;
1425 }
1426
1427 void FGNasalSys::removeCommand(const std::string& name)
1428 {
1429     NasalCommandDict::iterator it = _commands.find(name);
1430     if (it == _commands.end()) {
1431         SG_LOG(SG_NASAL, SG_WARN, "remove of unknwon command:" << name);
1432         return;
1433     }
1434
1435     // will delete the NasalCommand instance
1436     globals->get_commands()->removeCommand(name);
1437     _commands.erase(it);
1438 }
1439
1440 //////////////////////////////////////////////////////////////////////////
1441 // FGNasalListener class.
1442
1443 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1444                                  FGNasalSys* nasal, int key, int id,
1445                                  int init, int type) :
1446     _node(node),
1447     _code(code),
1448     _gcKey(key),
1449     _id(id),
1450     _nas(nasal),
1451     _init(init),
1452     _type(type),
1453     _active(0),
1454     _dead(false),
1455     _last_int(0L),
1456     _last_float(0.0)
1457 {
1458     if(_type == 0 && !_init)
1459         changed(node);
1460 }
1461
1462 FGNasalListener::~FGNasalListener()
1463 {
1464     _node->removeChangeListener(this);
1465     _nas->gcRelease(_gcKey);
1466 }
1467
1468 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1469 {
1470     if(_active || _dead) return;
1471     _active++;
1472     naRef arg[4];
1473     arg[0] = _nas->propNodeGhost(which);
1474     arg[1] = _nas->propNodeGhost(_node);
1475     arg[2] = mode;                  // value changed, child added/removed
1476     arg[3] = naNum(_node != which); // child event?
1477     _nas->call(_code, 4, arg, naNil());
1478     _active--;
1479 }
1480
1481 void FGNasalListener::valueChanged(SGPropertyNode* node)
1482 {
1483     if(_type < 2 && node != _node) return;   // skip child events
1484     if(_type > 0 || changed(_node) || _init)
1485         call(node, naNum(0));
1486
1487     _init = 0;
1488 }
1489
1490 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1491 {
1492     if(_type == 2) call(child, naNum(1));
1493 }
1494
1495 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1496 {
1497     if(_type == 2) call(child, naNum(-1));
1498 }
1499
1500 bool FGNasalListener::changed(SGPropertyNode* node)
1501 {
1502     using namespace simgear;
1503     props::Type type = node->getType();
1504     if(type == props::NONE) return false;
1505     if(type == props::UNSPECIFIED) return true;
1506
1507     bool result;
1508     switch(type) {
1509     case props::BOOL:
1510     case props::INT:
1511     case props::LONG:
1512         {
1513             long l = node->getLongValue();
1514             result = l != _last_int;
1515             _last_int = l;
1516             return result;
1517         }
1518     case props::FLOAT:
1519     case props::DOUBLE:
1520         {
1521             double d = node->getDoubleValue();
1522             result = d != _last_float;
1523             _last_float = d;
1524             return result;
1525         }
1526     default:
1527         {
1528             string s = node->getStringValue();
1529             result = s != _last_string;
1530             _last_string = s;
1531             return result;
1532         }
1533     }
1534 }
1535
1536 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1537 //
1538 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1539     _c(naSubContext(c)),
1540     _start_element(argc > 1 ? args[1] : naNil()),
1541     _end_element(argc > 2 ? args[2] : naNil()),
1542     _data(argc > 3 ? args[3] : naNil()),
1543     _pi(argc > 4 ? args[4] : naNil())
1544 {
1545 }
1546
1547 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1548 {
1549     if(naIsNil(_start_element)) return;
1550     naRef attr = naNewHash(_c);
1551     for(int i=0; i<a.size(); i++) {
1552         naRef name = make_string(a.getName(i));
1553         naRef value = make_string(a.getValue(i));
1554         naHash_set(attr, name, value);
1555     }
1556     call(_start_element, 2, make_string(tag), attr);
1557 }
1558
1559 void NasalXMLVisitor::endElement(const char* tag)
1560 {
1561     if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1562 }
1563
1564 void NasalXMLVisitor::data(const char* str, int len)
1565 {
1566     if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1567 }
1568
1569 void NasalXMLVisitor::pi(const char* target, const char* data)
1570 {
1571     if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1572 }
1573
1574 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1575 {
1576     naRef args[2];
1577     args[0] = a;
1578     args[1] = b;
1579     naCall(_c, func, num, args, naNil(), naNil());
1580     if(naGetError(_c))
1581         naRethrowError(_c);
1582 }
1583
1584 naRef NasalXMLVisitor::make_string(const char* s, int n)
1585 {
1586     return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1587                           n < 0 ? strlen(s) : n);
1588 }
1589
1590