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