10 #ifdef HAVE_SYS_TIME_H
11 # include <sys/time.h> // gettimeofday
16 #include <sys/types.h>
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/misc/interpolator.hxx>
27 #include <simgear/structure/commands.hxx>
28 #include <simgear/math/sg_geodesy.hxx>
29 #include <simgear/structure/event_mgr.hxx>
30 #include <simgear/debug/BufferedLogCallback.hxx>
32 #include "NasalSys.hxx"
33 #include "NasalSys_private.hxx"
34 #include "NasalModelData.hxx"
35 #include "NasalPositioned.hxx"
36 #include "NasalCanvas.hxx"
37 #include "NasalClipboard.hxx"
38 #include "NasalCondition.hxx"
39 #include "NasalString.hxx"
41 #include <Main/globals.hxx>
42 #include <Main/util.hxx>
43 #include <Main/fg_props.hxx>
48 void postinitNasalGUI(naRef globals, naContext c);
50 static FGNasalSys* nasalSys = 0;
52 // Listener class for loading Nasal modules on demand
53 class FGNasalModuleListener : public SGPropertyChangeListener
56 FGNasalModuleListener(SGPropertyNode* node);
58 virtual void valueChanged(SGPropertyNode* node);
61 SGPropertyNode_ptr _node;
64 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
68 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
70 if (_node->getBoolValue("enabled",false)&&
71 !_node->getBoolValue("loaded",true))
73 nasalSys->loadPropertyScripts(_node);
78 // Read and return file contents in a single buffer. Note use of
79 // stat() to get the file size. This is a win32 function, believe it
80 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
81 // Text mode brain damage will kill us if we're trying to do bytewise
83 static char* readfile(const char* file, int* lenOut)
86 if(stat(file, &data) != 0) return 0;
87 FILE* f = fopen(file, "rb");
89 char* buf = new char[data.st_size];
90 *lenOut = fread(buf, 1, data.st_size, f);
92 if(*lenOut != data.st_size) {
93 // Shouldn't happen, but warn anyway since it represents a
94 // platform bug and not a typical runtime error (missing file,
96 SG_LOG(SG_NASAL, SG_ALERT,
97 "ERROR in Nasal initialization: " <<
98 "short count returned from fread() of " << file <<
99 ". Check your C library!");
106 FGNasalSys::FGNasalSys()
113 _nextGCKey = 0; // Any value will do
116 _log = new simgear::BufferedLogCallback(SG_NASAL, SG_INFO);
117 _log->truncateAt(255);
118 sglog().addCallback(_log);
121 // Utility. Sets a named key in a hash by C string, rather than nasal
123 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
125 naRef s = naNewString(_context);
126 naStr_fromdata(s, (char*)key, strlen(key));
127 naHash_set(hash, s, val);
130 void FGNasalSys::globalsSet(const char* key, naRef val)
132 hashset(_globals, key, val);
135 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
137 return callMethod(code, naNil(), argc, args, locals);
140 // Does a naCall() in a new context. Wrapped here to make lock
141 // tracking easier. Extension functions are called with the lock, but
142 // we have to release it before making a new naCall(). So rather than
143 // drop the lock in every extension function that might call back into
144 // Nasal, we keep a stack depth counter here and only unlock/lock
145 // around the naCall if it isn't the first one.
147 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
149 naContext ctx = naNewContext();
150 if(_callCount) naModUnlock();
152 naRef result = naCall(ctx, code, argc, args, self, locals);
156 if(_callCount) naModLock();
161 FGNasalSys::~FGNasalSys()
164 map<int, FGNasalListener *>::iterator it, end = _listener.end();
165 for(it = _listener.begin(); it != end; ++it)
168 naFreeContext(_context);
173 bool FGNasalSys::parseAndRun(const char* sourceCode)
175 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
179 call(code, 0, 0, naNil());
184 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
186 FGNasalScript* script = new FGNasalScript();
187 script->_gcKey = -1; // important, if we delete it on a parse
188 script->_nas = this; // error, don't clobber a real handle!
192 sprintf(buf, "FGNasalScript@%p", (void *)script);
196 script->_code = parse(name, src, strlen(src));
197 if(naIsNil(script->_code)) {
202 script->_gcKey = gcSave(script->_code);
207 // The get/setprop functions accept a *list* of strings and walk
208 // through the property tree with them to find the appropriate node.
209 // This allows a Nasal object to hold onto a property path and use it
210 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
211 // is the utility function that walks the property tree.
212 // Future enhancement: support integer arguments to specify array
214 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
216 SGPropertyNode* p = globals->get_props();
218 for(int i=0; i<len; i++) {
220 if(!naIsString(a)) return 0;
221 p = p->getNode(naStr_data(a));
224 } catch (const string& err) {
225 naRuntimeError(c, (char *)err.c_str());
231 // getprop() extension function. Concatenates its string arguments as
232 // property names and returns the value of the specified property. Or
233 // nil if it doesn't exist.
234 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
236 using namespace simgear;
237 const SGPropertyNode* p = findnode(c, args, argc);
238 if(!p) return naNil();
240 switch(p->getType()) {
241 case props::BOOL: case props::INT:
242 case props::LONG: case props::FLOAT:
245 double dv = p->getDoubleValue();
246 if (SGMisc<double>::isNaN(dv)) {
247 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
255 case props::UNSPECIFIED:
257 naRef nastr = naNewString(c);
258 const char* val = p->getStringValue();
259 naStr_fromdata(nastr, (char*)val, strlen(val));
262 case props::ALIAS: // <--- FIXME, recurse?
268 // setprop() extension function. Concatenates its string arguments as
269 // property names and sets the value of the specified property to the
271 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
274 char buf[BUFLEN + 1];
278 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
279 for(int i=0; i<argc-1; i++) {
280 naRef s = naStringValue(c, args[i]);
281 if(naIsNil(s)) return naNil();
282 strncpy(p, naStr_data(s), buflen);
284 buflen = BUFLEN - (p - buf);
285 if(i < (argc-2) && buflen > 0) {
291 SGPropertyNode* props = globals->get_props();
292 naRef val = args[argc-1];
295 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
297 naRef n = naNumValue(val);
299 naRuntimeError(c, "setprop() value is not string or number");
301 if (SGMisc<double>::isNaN(n.num)) {
302 naRuntimeError(c, "setprop() passed a NaN");
305 result = props->setDoubleValue(buf, n.num);
307 } catch (const string& err) {
308 naRuntimeError(c, (char *)err.c_str());
310 return naNum(result);
314 // print() extension function. Concatenates and prints its arguments
315 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
316 // make sure it appears. Is there better way to do this?
317 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
321 for(int i=0; i<n; i++) {
322 naRef s = naStringValue(c, args[i]);
323 if(naIsNil(s)) continue;
324 buf += naStr_data(s);
326 SG_LOG(SG_NASAL, SG_ALERT, buf);
327 return naNum(buf.length());
330 // logprint() extension function. Same as above, all arguments after the
331 // first argument are concatenated. Argument 0 is the log-level, matching
333 static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
336 naRuntimeError(c, "no prioirty argument to logprint()");
338 naRef priority = args[0];
341 for(int i=1; i<n; i++) {
342 naRef s = naStringValue(c, args[i]);
343 if(naIsNil(s)) continue;
344 buf += naStr_data(s);
346 // use the nasal source file and line for the message location, since
347 // that's more useful than the location here!
348 sglog().log(SG_NASAL, (sgDebugPriority)(int) priority.num,
349 naStr_data(naGetSourceFile(c, 0)),
350 naGetLine(c, 0), buf);
351 return naNum(buf.length());
355 // fgcommand() extension function. Executes a named command via the
356 // FlightGear command manager. Takes a single property node name as
358 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
360 naRef cmd = argc > 0 ? args[0] : naNil();
361 naRef props = argc > 1 ? args[1] : naNil();
362 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
363 naRuntimeError(c, "bad arguments to fgcommand()");
364 SGPropertyNode_ptr tmp, *node;
366 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
368 tmp = new SGPropertyNode();
371 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
374 // settimer(func, dt, simtime) extension function. Falls through to
375 // FGNasalSys::setTimer(). See there for docs.
376 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
378 nasalSys->setTimer(c, argc, args);
382 // setlistener(func, property, bool) extension function. Falls through to
383 // FGNasalSys::setListener(). See there for docs.
384 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
386 return nasalSys->setListener(c, argc, args);
389 // removelistener(int) extension function. Falls through to
390 // FGNasalSys::removeListener(). See there for docs.
391 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
393 return nasalSys->removeListener(c, argc, args);
396 // Returns a ghost handle to the argument to the currently executing
398 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
400 return nasalSys->cmdArgGhost();
403 // Sets up a property interpolation. The first argument is either a
404 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
405 // interpolate. The second argument is a vector of pairs of
406 // value/delta numbers.
407 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
409 SGPropertyNode* node;
410 naRef prop = argc > 0 ? args[0] : naNil();
411 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
412 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
415 naRef curve = argc > 1 ? args[1] : naNil();
416 if(!naIsVector(curve)) return naNil();
417 int nPoints = naVec_size(curve) / 2;
418 double* values = new double[nPoints];
419 double* deltas = new double[nPoints];
420 for(int i=0; i<nPoints; i++) {
421 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
422 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
425 ((SGInterpolator*)globals->get_subsystem_mgr()
426 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
427 ->interpolate(node, nPoints, values, deltas);
434 // This is a better RNG than the one in the default Nasal distribution
435 // (which is based on the C library rand() implementation). It will
437 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
439 return naNum(sg_random());
442 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
448 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
454 // Return an array listing of all files in a directory
455 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
457 if(argc != 1 || !naIsString(args[0]))
458 naRuntimeError(c, "bad arguments to directory()");
460 simgear::Dir d(SGPath(naStr_data(args[0])));
461 if(!d.exists()) return naNil();
462 naRef result = naNewVector(c);
464 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
465 for (unsigned int i=0; i<paths.size(); ++i) {
466 std::string p = paths[i].file();
467 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
474 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
476 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
478 if(argc != 1 || !naIsString(args[0]))
479 naRuntimeError(c, "bad arguments to resolveDataPath()");
481 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
482 const char* pdata = p.c_str();
483 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
486 class NasalCommand : public SGCommandMgr::Command
489 NasalCommand(FGNasalSys* sys, naRef f) :
493 _gcRoot = sys->gcSave(f);
496 virtual ~NasalCommand()
498 _sys->gcRelease(_gcRoot);
501 virtual bool operator()(const SGPropertyNode* aNode)
503 _sys->setCmdArg(const_cast<SGPropertyNode*>(aNode));
505 args[0] = _sys->cmdArgGhost();
507 _sys->callMethod(_func, naNil(), 1, args, naNil() /* locals */);
518 static naRef f_addCommand(naContext c, naRef me, int argc, naRef* args)
520 if(argc != 2 || !naIsString(args[0]) || !naIsFunc(args[1]))
521 naRuntimeError(c, "bad arguments to addcommand()");
523 naRef func = args[1];
524 NasalCommand* cmd = new NasalCommand(nasalSys, func);
525 globals->get_commands()->addCommandObject(naStr_data(args[0]), cmd);
529 static naRef f_removeCommand(naContext c, naRef me, int argc, naRef* args)
531 SGCommandMgr::Command* cmd = globals->get_commands()->getCommand(naStr_data(args[0]));
533 // SGCommandMgr::Command* cmd = globals->get_commands()->removeCommand(naStr_data(args[0]))
541 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
543 // <path> ... absolute path to an XML file
544 // <start-tag> ... callback function with two args: tag name, attribute hash
545 // <end-tag> ... callback function with one arg: tag name
546 // <data> ... callback function with one arg: data
547 // <pi> ... callback function with two args: target, data
548 // (pi = "processing instruction")
549 // All four callback functions are optional and default to nil.
550 // The function returns nil on error, or the validated file name otherwise.
551 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
553 if(argc < 1 || !naIsString(args[0]))
554 naRuntimeError(c, "parsexml(): path argument missing or not a string");
555 if(argc > 5) argc = 5;
556 for(int i=1; i<argc; i++)
557 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
558 naRuntimeError(c, "parsexml(): callback argument not a function");
560 const char* file = fgValidatePath(naStr_data(args[0]), false);
562 naRuntimeError(c, "parsexml(): reading '%s' denied "
563 "(unauthorized access)", naStr_data(args[0]));
566 std::ifstream input(file);
567 NasalXMLVisitor visitor(c, argc, args);
569 readXML(input, visitor);
570 } catch (const sg_exception& e) {
571 naRuntimeError(c, "parsexml(): file '%s' %s",
572 file, e.getFormattedMessage().c_str());
575 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
578 // Return UNIX epoch time in seconds.
579 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
583 GetSystemTimeAsFileTime(&ft);
584 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
585 // Converts from 100ns units in 1601 epoch to unix epoch in sec
586 return naNum((t * 1e-7) - 11644473600.0);
589 gettimeofday(&td, 0);
590 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
594 // Table of extension functions. Terminate with zeros.
595 static struct { const char* name; naCFunction func; } funcs[] = {
596 { "getprop", f_getprop },
597 { "setprop", f_setprop },
598 { "print", f_print },
599 { "logprint", f_logprint },
600 { "_fgcommand", f_fgcommand },
601 { "settimer", f_settimer },
602 { "_setlistener", f_setlistener },
603 { "removelistener", f_removelistener },
604 { "addcommand", f_addCommand },
605 { "removecommand", f_removeCommand },
606 { "_cmdarg", f_cmdarg },
607 { "_interpolate", f_interpolate },
609 { "srand", f_srand },
610 { "abort", f_abort },
611 { "directory", f_directory },
612 { "resolvepath", f_resolveDataPath },
613 { "parsexml", f_parsexml },
614 { "systime", f_systime },
618 naRef FGNasalSys::cmdArgGhost()
620 return propNodeGhost(_cmdArg);
623 void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
628 void FGNasalSys::init()
632 _context = naNewContext();
634 // Start with globals. Add it to itself as a recursive
635 // sub-reference under the name "globals". This gives client-code
636 // write access to the namespace if someone wants to do something
638 _globals = naInit_std(_context);
639 naSave(_context, _globals);
640 hashset(_globals, "globals", _globals);
642 hashset(_globals, "math", naInit_math(_context));
643 hashset(_globals, "bits", naInit_bits(_context));
644 hashset(_globals, "io", naInit_io(_context));
645 hashset(_globals, "thread", naInit_thread(_context));
646 hashset(_globals, "utf8", naInit_utf8(_context));
648 // Add our custom extension functions:
649 for(i=0; funcs[i].name; i++)
650 hashset(_globals, funcs[i].name,
651 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
653 // And our SGPropertyNode wrapper
654 hashset(_globals, "props", genPropsModule());
656 // Make a "__gcsave" hash to hold the naRef objects which get
657 // passed to handles outside the interpreter (to protect them from
658 // begin garbage-collected).
659 _gcHash = naNewHash(_context);
660 hashset(_globals, "__gcsave", _gcHash);
662 // Add string methods
663 _string = naInit_string(_context);
664 naSave(_context, _string);
665 initNasalString(_globals, _string, _context, _gcHash);
667 initNasalPositioned(_globals, _context, _gcHash);
668 initNasalPositioned_cppbind(_globals, _context, _gcHash);
669 NasalClipboard::init(this);
670 initNasalCanvas(_globals, _context, _gcHash);
671 initNasalCondition(_globals, _context, _gcHash);
673 // Now load the various source files in the Nasal directory
674 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
675 loadScriptDirectory(nasalDir);
677 // Add modules in Nasal subdirectories to property tree
678 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
679 simgear::Dir::NO_DOT_OR_DOTDOT, "");
680 for (unsigned int i=0; i<directories.size(); ++i) {
681 simgear::Dir dir(directories[i]);
682 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
683 addModule(directories[i].file(), scripts);
686 // set signal and remove node to avoid restoring at reinit
687 const char *s = "nasal-dir-initialized";
688 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
689 signal->setBoolValue(s, true);
690 signal->removeChildren(s, false);
692 // Pull scripts out of the property tree, too
693 loadPropertyScripts();
695 // now Nasal modules are loaded, we can do some delayed work
696 postinitNasalPositioned(_globals, _context);
697 postinitNasalGUI(_globals, _context);
700 void FGNasalSys::update(double)
702 if( NasalClipboard::getInstance() )
703 NasalClipboard::getInstance()->update();
705 if(!_dead_listener.empty()) {
706 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
707 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
708 _dead_listener.clear();
711 if (!_loadList.empty())
713 // process Nasal load hook (only one per update loop to avoid excessive lags)
714 _loadList.pop()->load();
717 if (!_unloadList.empty())
719 // process pending Nasal unload hooks after _all_ load hooks were processed
720 // (only unload one per update loop to avoid excessive lags)
721 _unloadList.pop()->unload();
724 // The global context is a legacy thing. We use dynamically
725 // created contexts for naCall() now, so that we can call them
726 // recursively. But there are still spots that want to use it for
727 // naNew*() calls, which end up leaking memory because the context
728 // only clears out its temporary vector when it's *used*. So just
729 // junk it and fetch a new/reinitialized one every frame. This is
730 // clumsy: the right solution would use the dynamic context in all
731 // cases and eliminate _context entirely. But that's more work,
732 // and this works fine (yes, they say "New" and "Free", but
733 // they're very fast, just trust me). -Andy
734 naFreeContext(_context);
735 _context = naNewContext();
738 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
740 return p1.file() < p2.file();
743 // Loads all scripts in given directory
744 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
746 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
747 // Note: simgear::Dir already reports file entries in a deterministic order,
748 // so a fixed loading sequence is guaranteed (same for every user)
749 for (unsigned int i=0; i<scripts.size(); ++i) {
750 SGPath fullpath(scripts[i]);
751 SGPath file = fullpath.file();
752 loadModule(fullpath, file.base().c_str());
756 // Create module with list of scripts
757 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
759 if (scripts.size()>0)
761 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
762 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
763 for (unsigned int i=0; i<scripts.size(); ++i) {
764 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
765 pFileNode->setStringValue(scripts[i].c_str());
767 if (!module_node->hasChild("enabled",0))
769 SGPropertyNode* node = module_node->getChild("enabled",0,true);
770 node->setBoolValue(true);
771 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
776 // Loads the scripts found under /nasal in the global tree
777 void FGNasalSys::loadPropertyScripts()
779 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
782 for(int i=0; i<nasal->nChildren(); i++)
784 SGPropertyNode* n = nasal->getChild(i);
785 loadPropertyScripts(n);
789 // Loads the scripts found under /nasal in the global tree
790 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
792 bool is_loaded = false;
794 const char* module = n->getName();
795 if(n->hasChild("module"))
796 module = n->getStringValue("module");
797 if (n->getBoolValue("enabled",true))
799 // allow multiple files to be specified within a single
803 bool file_specified = false;
805 while((fn = n->getChild("file", j)) != NULL) {
806 file_specified = true;
807 const char* file = fn->getStringValue();
809 if (!p.isAbsolute() || !p.exists())
811 p = globals->resolve_maybe_aircraft_path(file);
814 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
815 file << "' for module '" << module << "'.");
818 ok &= p.isNull() ? false : loadModule(p, module);
822 const char* src = n->getStringValue("script");
823 if(!n->hasChild("script")) src = 0; // Hrm...
825 createModule(module, n->getPath().c_str(), src, strlen(src));
827 if(!file_specified && !src)
829 // module no longer exists - clear the archived "enable" flag
830 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
831 SGPropertyNode* node = n->getChild("enabled",0,false);
833 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
835 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
836 "no <file> or <script> defined in " <<
837 "/nasal/" << module);
844 SGPropertyNode* enable = n->getChild("enabled");
847 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
848 enable->addChangeListener(listener, false);
851 SGPropertyNode* loaded = n->getChild("loaded",0,true);
852 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
853 loaded->setBoolValue(is_loaded);
856 // Logs a runtime error, with stack trace, to the FlightGear log stream
857 void FGNasalSys::logError(naContext context)
859 SG_LOG(SG_NASAL, SG_ALERT,
860 "Nasal runtime error: " << naGetError(context));
861 SG_LOG(SG_NASAL, SG_ALERT,
862 " at " << naStr_data(naGetSourceFile(context, 0)) <<
863 ", line " << naGetLine(context, 0));
864 for(int i=1; i<naStackDepth(context); i++)
865 SG_LOG(SG_NASAL, SG_ALERT,
866 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
867 ", line " << naGetLine(context, i));
870 // Reads a script file, executes it, and places the resulting
871 // namespace into the global namespace under the specified module
873 bool FGNasalSys::loadModule(SGPath file, const char* module)
876 char* buf = readfile(file.c_str(), &len);
878 SG_LOG(SG_NASAL, SG_ALERT,
879 "Nasal error: could not read script file " << file.c_str()
880 << " into module " << module);
884 bool ok = createModule(module, file.c_str(), buf, len);
889 // Parse and run. Save the local variables namespace, as it will
890 // become a sub-object of globals. The optional "arg" argument can be
891 // used to pass an associated property node to the module, which can then
892 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
893 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
894 const char* src, int len,
895 const SGPropertyNode* cmdarg,
896 int argc, naRef* args)
898 naRef code = parse(fileName, src, len);
902 // See if we already have a module hash to use. This allows the
903 // user to, for example, add functions to the built-in math
904 // module. Make a new one if necessary.
906 naRef modname = naNewString(_context);
907 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
908 if(!naHash_get(_globals, modname, &locals))
909 locals = naNewHash(_context);
911 _cmdArg = (SGPropertyNode*)cmdarg;
913 call(code, argc, args, locals);
914 hashset(_globals, moduleName, locals);
918 void FGNasalSys::deleteModule(const char* moduleName)
920 naRef modname = naNewString(_context);
921 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
922 naHash_delete(_globals, modname);
925 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
928 naRef srcfile = naNewString(_context);
929 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
930 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
932 SG_LOG(SG_NASAL, SG_ALERT,
933 "Nasal parse error: " << naGetError(_context) <<
934 " in "<< filename <<", line " << errLine);
938 // Bind to the global namespace before returning
939 return naBindFunction(_context, code, _globals);
942 bool FGNasalSys::handleCommand( const char* moduleName,
943 const char* fileName,
945 const SGPropertyNode* arg )
947 naRef code = parse(fileName, src, strlen(src));
948 if(naIsNil(code)) return false;
950 // Commands can be run "in" a module. Make sure that module
951 // exists, and set it up as the local variables hash for the
953 naRef locals = naNil();
955 naRef modname = naNewString(_context);
956 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
957 if(!naHash_get(_globals, modname, &locals)) {
958 locals = naNewHash(_context);
959 naHash_set(_globals, modname, locals);
963 // Cache this command's argument for inspection via cmdarg(). For
964 // performance reasons, we won't bother with it if the invoked
965 // code doesn't need it.
966 _cmdArg = (SGPropertyNode*)arg;
968 call(code, 0, 0, locals);
972 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
974 const char* src = arg->getStringValue("script");
975 const char* moduleName = arg->getStringValue("module");
977 return handleCommand( moduleName,
978 arg ? arg->getPath(true).c_str() : moduleName,
983 // settimer(func, dt, simtime) extension function. The first argument
984 // is a Nasal function to call, the second is a delta time (from now),
985 // in seconds. The third, if present, is a boolean value indicating
986 // that "real world" time (rather than simulator time) is to be used.
988 // Implementation note: the FGTimer objects don't live inside the
989 // garbage collector, so the Nasal handler functions have to be
990 // "saved" somehow lest they be inadvertently cleaned. In this case,
991 // they are inserted into a globals.__gcsave hash and removed on
993 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
995 // Extract the handler, delta, and simtime arguments:
996 naRef handler = argc > 0 ? args[0] : naNil();
997 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
998 naRuntimeError(c, "settimer() with invalid function argument");
1002 naRef delta = argc > 1 ? args[1] : naNil();
1003 if(naIsNil(delta)) {
1004 naRuntimeError(c, "settimer() with invalid time argument");
1008 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1010 // Generate and register a C++ timer handler
1011 NasalTimer* t = new NasalTimer;
1012 t->handler = handler;
1013 t->gcKey = gcSave(handler);
1016 globals->get_event_mgr()->addEvent("NasalTimer",
1017 t, &NasalTimer::timerExpired,
1018 delta.num, simtime);
1021 void FGNasalSys::handleTimer(NasalTimer* t)
1023 call(t->handler, 0, 0, naNil());
1024 gcRelease(t->gcKey);
1027 int FGNasalSys::gcSave(naRef r)
1029 int key = _nextGCKey++;
1030 naHash_set(_gcHash, naNum(key), r);
1034 void FGNasalSys::gcRelease(int key)
1036 naHash_delete(_gcHash, naNum(key));
1039 void FGNasalSys::NasalTimer::timerExpired()
1041 nasal->handleTimer(this);
1045 int FGNasalSys::_listenerId = 0;
1047 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1048 // Attaches a callback function to a property (specified as a global
1049 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1050 // optional argument (default=0) is set to 1, then the function is also
1051 // called initially. If the fourth, optional argument is set to 0, then the
1052 // function is only called when the property node value actually changes.
1053 // Otherwise it's called independent of the value whenever the node is
1054 // written to (default). The setlistener() function returns a unique
1055 // id number, which is to be used as argument to the removelistener()
1057 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1059 SGPropertyNode_ptr node;
1060 naRef prop = argc > 0 ? args[0] : naNil();
1061 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1062 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1064 naRuntimeError(c, "setlistener() with invalid property argument");
1069 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1072 naRef code = argc > 1 ? args[1] : naNil();
1073 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1074 naRuntimeError(c, "setlistener() with invalid function argument");
1078 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1079 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1080 FGNasalListener *nl = new FGNasalListener(node, code, this,
1081 gcSave(code), _listenerId, init, type);
1083 node->addChangeListener(nl, init != 0);
1085 _listener[_listenerId] = nl;
1086 return naNum(_listenerId++);
1089 // removelistener(int) extension function. The argument is the id of
1090 // a listener as returned by the setlistener() function.
1091 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1093 naRef id = argc > 0 ? args[0] : naNil();
1094 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1096 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1097 naRuntimeError(c, "removelistener() with invalid listener id");
1101 it->second->_dead = true;
1102 _dead_listener.push_back(it->second);
1103 _listener.erase(it);
1104 return naNum(_listener.size());
1107 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1109 _loadList.push(data);
1112 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1114 _unloadList.push(data);
1118 // FGNasalListener class.
1120 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1121 FGNasalSys* nasal, int key, int id,
1122 int init, int type) :
1135 if(_type == 0 && !_init)
1139 FGNasalListener::~FGNasalListener()
1141 _node->removeChangeListener(this);
1142 _nas->gcRelease(_gcKey);
1145 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1147 if(_active || _dead) return;
1148 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1151 arg[0] = _nas->propNodeGhost(which);
1152 arg[1] = _nas->propNodeGhost(_node);
1153 arg[2] = mode; // value changed, child added/removed
1154 arg[3] = naNum(_node != which); // child event?
1155 _nas->call(_code, 4, arg, naNil());
1159 void FGNasalListener::valueChanged(SGPropertyNode* node)
1161 if(_type < 2 && node != _node) return; // skip child events
1162 if(_type > 0 || changed(_node) || _init)
1163 call(node, naNum(0));
1168 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1170 if(_type == 2) call(child, naNum(1));
1173 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1175 if(_type == 2) call(child, naNum(-1));
1178 bool FGNasalListener::changed(SGPropertyNode* node)
1180 using namespace simgear;
1181 props::Type type = node->getType();
1182 if(type == props::NONE) return false;
1183 if(type == props::UNSPECIFIED) return true;
1191 long l = node->getLongValue();
1192 result = l != _last_int;
1199 double d = node->getDoubleValue();
1200 result = d != _last_float;
1206 string s = node->getStringValue();
1207 result = s != _last_string;
1214 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1216 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1217 _c(naSubContext(c)),
1218 _start_element(argc > 1 ? args[1] : naNil()),
1219 _end_element(argc > 2 ? args[2] : naNil()),
1220 _data(argc > 3 ? args[3] : naNil()),
1221 _pi(argc > 4 ? args[4] : naNil())
1225 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1227 if(naIsNil(_start_element)) return;
1228 naRef attr = naNewHash(_c);
1229 for(int i=0; i<a.size(); i++) {
1230 naRef name = make_string(a.getName(i));
1231 naRef value = make_string(a.getValue(i));
1232 naHash_set(attr, name, value);
1234 call(_start_element, 2, make_string(tag), attr);
1237 void NasalXMLVisitor::endElement(const char* tag)
1239 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1242 void NasalXMLVisitor::data(const char* str, int len)
1244 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1247 void NasalXMLVisitor::pi(const char* target, const char* data)
1249 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1252 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1257 naCall(_c, func, num, args, naNil(), naNil());
1262 naRef NasalXMLVisitor::make_string(const char* s, int n)
1264 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1265 n < 0 ? strlen(s) : n);