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