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