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