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