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