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