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