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/structure/commands.hxx>
27 #include <simgear/math/sg_geodesy.hxx>
28 #include <simgear/structure/event_mgr.hxx>
29 #include <simgear/debug/BufferedLogCallback.hxx>
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>
36 #include "NasalSys.hxx"
37 #include "NasalSys_private.hxx"
38 #include "NasalModelData.hxx"
39 #include "NasalPositioned.hxx"
40 #include "NasalCanvas.hxx"
41 #include "NasalClipboard.hxx"
42 #include "NasalCondition.hxx"
43 #include "NasalHTTP.hxx"
44 #include "NasalString.hxx"
46 #include <Main/globals.hxx>
47 #include <Main/util.hxx>
48 #include <Main/fg_props.hxx>
52 void postinitNasalGUI(naRef globals, naContext c);
54 static FGNasalSys* nasalSys = 0;
56 // Listener class for loading Nasal modules on demand
57 class FGNasalModuleListener : public SGPropertyChangeListener
60 FGNasalModuleListener(SGPropertyNode* node);
62 virtual void valueChanged(SGPropertyNode* node);
65 SGPropertyNode_ptr _node;
68 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
72 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
74 if (_node->getBoolValue("enabled",false)&&
75 !_node->getBoolValue("loaded",true))
77 nasalSys->loadPropertyScripts(_node);
81 //////////////////////////////////////////////////////////////////////////
84 class TimerObj : public SGReferenced
87 TimerObj(FGNasalSys* sys, naRef f, naRef self, double interval) :
96 snprintf(nm, 128, "nasal-timer-%p", this);
98 _gcRoot = sys->gcSave(f);
99 _gcSelf = sys->gcSave(self);
105 _sys->gcRelease(_gcRoot);
106 _sys->gcRelease(_gcSelf);
109 bool isRunning() const { return _isRunning; }
114 globals->get_event_mgr()->removeTask(_name);
127 globals->get_event_mgr()->addEvent(_name, this, &TimerObj::invoke, _interval);
129 globals->get_event_mgr()->addTask(_name, this, &TimerObj::invoke,
130 _interval, _interval /* delay */);
134 // stop and then start -
135 void restart(double newInterval)
137 _interval = newInterval;
145 _sys->callMethod(_func, _self, 0, args, naNil() /* locals */);
151 void setSingleShot(bool aSingleShot)
153 _singleShot = aSingleShot;
156 bool isSingleShot() const
157 { return _singleShot; }
162 int _gcRoot, _gcSelf;
168 typedef SGSharedPtr<TimerObj> TimerObjRef;
169 typedef nasal::Ghost<TimerObjRef> NasalTimerObj;
171 ///////////////////////////////////////////////////////////////////////////
173 // Read and return file contents in a single buffer. Note use of
174 // stat() to get the file size. This is a win32 function, believe it
175 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
176 // Text mode brain damage will kill us if we're trying to do bytewise
178 static char* readfile(const char* file, int* lenOut)
181 if(stat(file, &data) != 0) return 0;
182 FILE* f = fopen(file, "rb");
184 char* buf = new char[data.st_size];
185 *lenOut = fread(buf, 1, data.st_size, f);
187 if(*lenOut != data.st_size) {
188 // Shouldn't happen, but warn anyway since it represents a
189 // platform bug and not a typical runtime error (missing file,
191 SG_LOG(SG_NASAL, SG_ALERT,
192 "ERROR in Nasal initialization: " <<
193 "short count returned from fread() of " << file <<
194 ". Check your C library!");
201 FGNasalSys::FGNasalSys()
208 _log = new simgear::BufferedLogCallback(SG_NASAL, SG_INFO);
209 _log->truncateAt(255);
210 sglog().addCallback(_log);
212 naSetErrorHandler(&logError);
215 // Utility. Sets a named key in a hash by C string, rather than nasal
217 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
219 naRef s = naNewString(_context);
220 naStr_fromdata(s, (char*)key, strlen(key));
221 naHash_set(hash, s, val);
224 void FGNasalSys::globalsSet(const char* key, naRef val)
226 hashset(_globals, key, val);
229 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
231 return callMethod(code, naNil(), argc, args, locals);
234 // Does a naCall() in a new context. Wrapped here to make lock
235 // tracking easier. Extension functions are called with the lock, but
236 // we have to release it before making a new naCall(). So rather than
237 // drop the lock in every extension function that might call back into
238 // Nasal, we keep a stack depth counter here and only unlock/lock
239 // around the naCall if it isn't the first one.
241 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
243 return naCallMethod(code, self, argc, args, locals);
246 FGNasalSys::~FGNasalSys()
251 bool FGNasalSys::parseAndRun(const char* sourceCode)
253 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
257 call(code, 0, 0, naNil());
262 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
264 FGNasalScript* script = new FGNasalScript();
265 script->_gcKey = -1; // important, if we delete it on a parse
266 script->_nas = this; // error, don't clobber a real handle!
270 sprintf(buf, "FGNasalScript@%p", (void *)script);
274 script->_code = parse(name, src, strlen(src));
275 if(naIsNil(script->_code)) {
280 script->_gcKey = gcSave(script->_code);
285 // The get/setprop functions accept a *list* of strings and walk
286 // through the property tree with them to find the appropriate node.
287 // This allows a Nasal object to hold onto a property path and use it
288 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
289 // is the utility function that walks the property tree.
290 // Future enhancement: support integer arguments to specify array
292 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
294 SGPropertyNode* p = globals->get_props();
296 for(int i=0; i<len; i++) {
298 if(!naIsString(a)) return 0;
299 p = p->getNode(naStr_data(a));
302 } catch (const string& err) {
303 naRuntimeError(c, (char *)err.c_str());
309 // getprop() extension function. Concatenates its string arguments as
310 // property names and returns the value of the specified property. Or
311 // nil if it doesn't exist.
312 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
314 using namespace simgear;
315 const SGPropertyNode* p = findnode(c, args, argc);
316 if(!p) return naNil();
318 switch(p->getType()) {
319 case props::BOOL: case props::INT:
320 case props::LONG: case props::FLOAT:
323 double dv = p->getDoubleValue();
324 if (SGMisc<double>::isNaN(dv)) {
325 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
333 case props::UNSPECIFIED:
335 naRef nastr = naNewString(c);
336 const char* val = p->getStringValue();
337 naStr_fromdata(nastr, (char*)val, strlen(val));
340 case props::ALIAS: // <--- FIXME, recurse?
346 // setprop() extension function. Concatenates its string arguments as
347 // property names and sets the value of the specified property to the
349 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
352 char buf[BUFLEN + 1];
356 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
357 for(int i=0; i<argc-1; i++) {
358 naRef s = naStringValue(c, args[i]);
359 if(naIsNil(s)) return naNil();
360 strncpy(p, naStr_data(s), buflen);
362 buflen = BUFLEN - (p - buf);
363 if(i < (argc-2) && buflen > 0) {
369 SGPropertyNode* props = globals->get_props();
370 naRef val = args[argc-1];
373 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
375 naRef n = naNumValue(val);
377 naRuntimeError(c, "setprop() value is not string or number");
379 if (SGMisc<double>::isNaN(n.num)) {
380 naRuntimeError(c, "setprop() passed a NaN");
383 result = props->setDoubleValue(buf, n.num);
385 } catch (const string& err) {
386 naRuntimeError(c, (char *)err.c_str());
388 return naNum(result);
392 // print() extension function. Concatenates and prints its arguments
393 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
394 // make sure it appears. Is there better way to do this?
395 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
399 for(int i=0; i<n; i++) {
400 naRef s = naStringValue(c, args[i]);
401 if(naIsNil(s)) continue;
402 buf += naStr_data(s);
404 SG_LOG(SG_NASAL, SG_ALERT, buf);
405 return naNum(buf.length());
408 // logprint() extension function. Same as above, all arguments after the
409 // first argument are concatenated. Argument 0 is the log-level, matching
411 static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
414 naRuntimeError(c, "no prioirty argument to logprint()");
416 naRef priority = args[0];
419 for(int i=1; i<n; i++) {
420 naRef s = naStringValue(c, args[i]);
421 if(naIsNil(s)) continue;
422 buf += naStr_data(s);
424 // use the nasal source file and line for the message location, since
425 // that's more useful than the location here!
426 sglog().log(SG_NASAL, (sgDebugPriority)(int) priority.num,
427 naStr_data(naGetSourceFile(c, 0)),
428 naGetLine(c, 0), buf);
429 return naNum(buf.length());
433 // fgcommand() extension function. Executes a named command via the
434 // FlightGear command manager. Takes a single property node name as
436 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
438 naRef cmd = argc > 0 ? args[0] : naNil();
439 naRef props = argc > 1 ? args[1] : naNil();
440 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
441 naRuntimeError(c, "bad arguments to fgcommand()");
442 SGPropertyNode_ptr tmp, *node;
444 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
446 tmp = new SGPropertyNode();
449 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
452 // settimer(func, dt, simtime) extension function. Falls through to
453 // FGNasalSys::setTimer(). See there for docs.
454 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
456 nasalSys->setTimer(c, argc, args);
460 static naRef f_makeTimer(naContext c, naRef me, int argc, naRef* args)
462 if (!naIsNum(args[0])) {
463 naRuntimeError(c, "bad interval argument to maketimer");
466 naRef func, self = naNil();
467 if (naIsFunc(args[1])) {
469 } else if ((argc == 3) && naIsFunc(args[2])) {
474 TimerObj* timerObj = new TimerObj(nasalSys, func, self, args[0].num);
475 return NasalTimerObj::create(c, timerObj);
478 // setlistener(func, property, bool) extension function. Falls through to
479 // FGNasalSys::setListener(). See there for docs.
480 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
482 return nasalSys->setListener(c, argc, args);
485 // removelistener(int) extension function. Falls through to
486 // FGNasalSys::removeListener(). See there for docs.
487 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
489 return nasalSys->removeListener(c, argc, args);
492 // Returns a ghost handle to the argument to the currently executing
494 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
496 return nasalSys->cmdArgGhost();
499 // Sets up a property interpolation. The first argument is either a
500 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
501 // interpolate. The second argument is a vector of pairs of
502 // value/delta numbers.
503 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
505 SGPropertyNode* node;
506 naRef prop = argc > 0 ? args[0] : naNil();
507 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
508 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
511 naRef curve = argc > 1 ? args[1] : naNil();
512 if(!naIsVector(curve)) return naNil();
513 int nPoints = naVec_size(curve) / 2;
515 simgear::PropertyList value_nodes;
516 value_nodes.reserve(nPoints);
518 deltas.reserve(nPoints);
520 for( int i = 0; i < nPoints; ++i )
522 SGPropertyNode* val = new SGPropertyNode;
523 val->setDoubleValue(naNumValue(naVec_get(curve, 2*i)).num);
524 value_nodes.push_back(val);
525 deltas.push_back(naNumValue(naVec_get(curve, 2*i+1)).num);
528 node->interpolate("numeric", value_nodes, deltas, "linear");
532 // This is a better RNG than the one in the default Nasal distribution
533 // (which is based on the C library rand() implementation). It will
535 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
537 return naNum(sg_random());
540 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
546 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
552 // Return an array listing of all files in a directory
553 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
555 if(argc != 1 || !naIsString(args[0]))
556 naRuntimeError(c, "bad arguments to directory()");
558 simgear::Dir d(SGPath(naStr_data(args[0])));
559 if(!d.exists()) return naNil();
560 naRef result = naNewVector(c);
562 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
563 for (unsigned int i=0; i<paths.size(); ++i) {
564 std::string p = paths[i].file();
565 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
572 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
574 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
576 if(argc != 1 || !naIsString(args[0]))
577 naRuntimeError(c, "bad arguments to resolveDataPath()");
579 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
580 const char* pdata = p.c_str();
581 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
584 static naRef f_findDataDir(naContext c, naRef me, int argc, naRef* args)
586 if(argc != 1 || !naIsString(args[0]))
587 naRuntimeError(c, "bad arguments to findDataDir()");
589 SGPath p = globals->find_data_dir(naStr_data(args[0]));
590 const char* pdata = p.c_str();
591 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
594 class NasalCommand : public SGCommandMgr::Command
597 NasalCommand(FGNasalSys* sys, naRef f, const std::string& name) :
602 globals->get_commands()->addCommandObject(_name, this);
603 _gcRoot = sys->gcSave(f);
606 virtual ~NasalCommand()
608 _sys->gcRelease(_gcRoot);
611 virtual bool operator()(const SGPropertyNode* aNode)
613 _sys->setCmdArg(const_cast<SGPropertyNode*>(aNode));
615 args[0] = _sys->wrappedPropsNode(const_cast<SGPropertyNode*>(aNode));
617 _sys->callMethod(_func, naNil(), 1, args, naNil() /* locals */);
629 static naRef f_addCommand(naContext c, naRef me, int argc, naRef* args)
631 if(argc != 2 || !naIsString(args[0]) || !naIsFunc(args[1]))
632 naRuntimeError(c, "bad arguments to addcommand()");
634 nasalSys->addCommand(args[1], naStr_data(args[0]));
638 static naRef f_removeCommand(naContext c, naRef me, int argc, naRef* args)
640 if ((argc < 1) || !naIsString(args[0]))
641 naRuntimeError(c, "bad argument to removecommand()");
643 globals->get_commands()->removeCommand(naStr_data(args[0]));
648 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
650 // <path> ... absolute path to an XML file
651 // <start-tag> ... callback function with two args: tag name, attribute hash
652 // <end-tag> ... callback function with one arg: tag name
653 // <data> ... callback function with one arg: data
654 // <pi> ... callback function with two args: target, data
655 // (pi = "processing instruction")
656 // All four callback functions are optional and default to nil.
657 // The function returns nil on error, or the validated file name otherwise.
658 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
660 if(argc < 1 || !naIsString(args[0]))
661 naRuntimeError(c, "parsexml(): path argument missing or not a string");
662 if(argc > 5) argc = 5;
663 for(int i=1; i<argc; i++)
664 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
665 naRuntimeError(c, "parsexml(): callback argument not a function");
667 const char* file = fgValidatePath(naStr_data(args[0]), false);
669 naRuntimeError(c, "parsexml(): reading '%s' denied "
670 "(unauthorized access)", naStr_data(args[0]));
673 std::ifstream input(file);
674 NasalXMLVisitor visitor(c, argc, args);
676 readXML(input, visitor);
677 } catch (const sg_exception& e) {
678 naRuntimeError(c, "parsexml(): file '%s' %s",
679 file, e.getFormattedMessage().c_str());
682 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
685 // Return UNIX epoch time in seconds.
686 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
690 GetSystemTimeAsFileTime(&ft);
691 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
692 // Converts from 100ns units in 1601 epoch to unix epoch in sec
693 return naNum((t * 1e-7) - 11644473600.0);
696 gettimeofday(&td, 0);
697 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
701 // Table of extension functions. Terminate with zeros.
702 static struct { const char* name; naCFunction func; } funcs[] = {
703 { "getprop", f_getprop },
704 { "setprop", f_setprop },
705 { "print", f_print },
706 { "logprint", f_logprint },
707 { "_fgcommand", f_fgcommand },
708 { "settimer", f_settimer },
709 { "maketimer", f_makeTimer },
710 { "_setlistener", f_setlistener },
711 { "removelistener", f_removelistener },
712 { "addcommand", f_addCommand },
713 { "removecommand", f_removeCommand },
714 { "_cmdarg", f_cmdarg },
715 { "_interpolate", f_interpolate },
717 { "srand", f_srand },
718 { "abort", f_abort },
719 { "directory", f_directory },
720 { "resolvepath", f_resolveDataPath },
721 { "finddata", f_findDataDir },
722 { "parsexml", f_parsexml },
723 { "systime", f_systime },
727 naRef FGNasalSys::cmdArgGhost()
729 return propNodeGhost(_cmdArg);
732 void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
737 void FGNasalSys::init()
741 _context = naNewContext();
743 // Start with globals. Add it to itself as a recursive
744 // sub-reference under the name "globals". This gives client-code
745 // write access to the namespace if someone wants to do something
747 _globals = naInit_std(_context);
748 naSave(_context, _globals);
749 hashset(_globals, "globals", _globals);
751 hashset(_globals, "math", naInit_math(_context));
752 hashset(_globals, "bits", naInit_bits(_context));
753 hashset(_globals, "io", naInit_io(_context));
754 hashset(_globals, "thread", naInit_thread(_context));
755 hashset(_globals, "utf8", naInit_utf8(_context));
757 // Add our custom extension functions:
758 for(i=0; funcs[i].name; i++)
759 hashset(_globals, funcs[i].name,
760 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
762 // And our SGPropertyNode wrapper
763 hashset(_globals, "props", genPropsModule());
765 // Add string methods
766 _string = naInit_string(_context);
767 naSave(_context, _string);
768 initNasalString(_globals, _string, _context);
770 initNasalPositioned(_globals, _context);
771 initNasalPositioned_cppbind(_globals, _context);
772 NasalClipboard::init(this);
773 initNasalCanvas(_globals, _context);
774 initNasalCondition(_globals, _context);
775 initNasalHTTP(_globals, _context);
777 if (!NasalTimerObj::isInit()) {
778 NasalTimerObj::init("Timer")
779 .method("start", &TimerObj::start)
780 .method("stop", &TimerObj::stop)
781 .method("restart", &TimerObj::restart)
782 .member("singleShot", &TimerObj::isSingleShot, &TimerObj::setSingleShot)
783 .member("isRunning", &TimerObj::isRunning);
786 // Now load the various source files in the Nasal directory
787 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
788 loadScriptDirectory(nasalDir);
790 // Add modules in Nasal subdirectories to property tree
791 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
792 simgear::Dir::NO_DOT_OR_DOTDOT, "");
793 for (unsigned int i=0; i<directories.size(); ++i) {
794 simgear::Dir dir(directories[i]);
795 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
796 addModule(directories[i].file(), scripts);
799 // set signal and remove node to avoid restoring at reinit
800 const char *s = "nasal-dir-initialized";
801 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
802 signal->setBoolValue(s, true);
803 signal->removeChildren(s, false);
805 // Pull scripts out of the property tree, too
806 loadPropertyScripts();
808 // now Nasal modules are loaded, we can do some delayed work
809 postinitNasalPositioned(_globals, _context);
810 postinitNasalGUI(_globals, _context);
813 void FGNasalSys::shutdown()
815 shutdownNasalPositioned();
817 map<int, FGNasalListener *>::iterator it, end = _listener.end();
818 for(it = _listener.begin(); it != end; ++it)
822 NasalCommandDict::iterator j = _commands.begin();
823 for (; j != _commands.end(); ++j) {
824 globals->get_commands()->removeCommand(j->first);
830 _string = naNil(); // will be freed by _context
831 naFreeContext(_context);
833 //setWatchedRef(_globals);
835 // remove the recursive reference in globals
836 hashset(_globals, "globals", naNil());
843 naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps)
845 static naRef wrapNodeFunc = naNil();
846 if (naIsNil(wrapNodeFunc)) {
847 nasal::Hash props = getGlobals().get<nasal::Hash>("props");
848 wrapNodeFunc = props.get("wrapNode");
852 args[0] = propNodeGhost(aProps);
853 return naCall(_context, wrapNodeFunc, 1, args, naNil(), naNil());
856 void FGNasalSys::update(double)
858 if( NasalClipboard::getInstance() )
859 NasalClipboard::getInstance()->update();
861 if(!_dead_listener.empty()) {
862 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
863 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
864 _dead_listener.clear();
867 if (!_loadList.empty())
872 // process Nasal load hook (only one per update loop to avoid excessive lags)
873 _loadList.pop()->load();
876 if (!_unloadList.empty())
878 // process pending Nasal unload hooks after _all_ load hooks were processed
879 // (only unload one per update loop to avoid excessive lags)
880 _unloadList.pop()->unload();
883 // The global context is a legacy thing. We use dynamically
884 // created contexts for naCall() now, so that we can call them
885 // recursively. But there are still spots that want to use it for
886 // naNew*() calls, which end up leaking memory because the context
887 // only clears out its temporary vector when it's *used*. So just
888 // junk it and fetch a new/reinitialized one every frame. This is
889 // clumsy: the right solution would use the dynamic context in all
890 // cases and eliminate _context entirely. But that's more work,
891 // and this works fine (yes, they say "New" and "Free", but
892 // they're very fast, just trust me). -Andy
893 naFreeContext(_context);
894 _context = naNewContext();
897 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
899 return p1.file() < p2.file();
902 // Loads all scripts in given directory
903 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
905 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
906 // Note: simgear::Dir already reports file entries in a deterministic order,
907 // so a fixed loading sequence is guaranteed (same for every user)
908 for (unsigned int i=0; i<scripts.size(); ++i) {
909 SGPath fullpath(scripts[i]);
910 SGPath file = fullpath.file();
911 loadModule(fullpath, file.base().c_str());
915 // Create module with list of scripts
916 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
918 if (! scripts.empty())
920 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
921 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
922 for (unsigned int i=0; i<scripts.size(); ++i) {
923 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
924 pFileNode->setStringValue(scripts[i].c_str());
926 if (!module_node->hasChild("enabled",0))
928 SGPropertyNode* node = module_node->getChild("enabled",0,true);
929 node->setBoolValue(true);
930 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
935 // Loads the scripts found under /nasal in the global tree
936 void FGNasalSys::loadPropertyScripts()
938 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
941 for(int i=0; i<nasal->nChildren(); i++)
943 SGPropertyNode* n = nasal->getChild(i);
944 loadPropertyScripts(n);
948 // Loads the scripts found under /nasal in the global tree
949 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
951 bool is_loaded = false;
953 const char* module = n->getName();
954 if(n->hasChild("module"))
955 module = n->getStringValue("module");
956 if (n->getBoolValue("enabled",true))
958 // allow multiple files to be specified within a single
962 bool file_specified = false;
964 while((fn = n->getChild("file", j)) != NULL) {
965 file_specified = true;
966 const char* file = fn->getStringValue();
968 if (!p.isAbsolute() || !p.exists())
970 p = globals->resolve_maybe_aircraft_path(file);
973 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
974 file << "' for module '" << module << "'.");
977 ok &= p.isNull() ? false : loadModule(p, module);
981 const char* src = n->getStringValue("script");
982 if(!n->hasChild("script")) src = 0; // Hrm...
984 createModule(module, n->getPath().c_str(), src, strlen(src));
986 if(!file_specified && !src)
988 // module no longer exists - clear the archived "enable" flag
989 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
990 SGPropertyNode* node = n->getChild("enabled",0,false);
992 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
994 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
995 "no <file> or <script> defined in " <<
996 "/nasal/" << module);
1003 SGPropertyNode* enable = n->getChild("enabled");
1006 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
1007 enable->addChangeListener(listener, false);
1010 SGPropertyNode* loaded = n->getChild("loaded",0,true);
1011 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
1012 loaded->setBoolValue(is_loaded);
1015 // Logs a runtime error, with stack trace, to the FlightGear log stream
1016 void FGNasalSys::logError(naContext context)
1018 SG_LOG(SG_NASAL, SG_ALERT, "Nasal runtime error: " << naGetError(context));
1019 int stack_depth = naStackDepth(context);
1020 if( stack_depth < 1 )
1022 SG_LOG(SG_NASAL, SG_ALERT,
1023 " at " << naStr_data(naGetSourceFile(context, 0)) <<
1024 ", line " << naGetLine(context, 0));
1025 for(int i=1; i<stack_depth; i++)
1026 SG_LOG(SG_NASAL, SG_ALERT,
1027 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
1028 ", line " << naGetLine(context, i));
1031 // Reads a script file, executes it, and places the resulting
1032 // namespace into the global namespace under the specified module
1034 bool FGNasalSys::loadModule(SGPath file, const char* module)
1037 char* buf = readfile(file.c_str(), &len);
1039 SG_LOG(SG_NASAL, SG_ALERT,
1040 "Nasal error: could not read script file " << file.c_str()
1041 << " into module " << module);
1045 bool ok = createModule(module, file.c_str(), buf, len);
1050 // Parse and run. Save the local variables namespace, as it will
1051 // become a sub-object of globals. The optional "arg" argument can be
1052 // used to pass an associated property node to the module, which can then
1053 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
1054 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1055 const char* src, int len,
1056 const SGPropertyNode* cmdarg,
1057 int argc, naRef* args)
1059 naRef code = parse(fileName, src, len);
1063 // See if we already have a module hash to use. This allows the
1064 // user to, for example, add functions to the built-in math
1065 // module. Make a new one if necessary.
1067 naRef modname = naNewString(_context);
1068 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1069 if(!naHash_get(_globals, modname, &locals))
1070 locals = naNewHash(_context);
1072 _cmdArg = (SGPropertyNode*)cmdarg;
1074 call(code, argc, args, locals);
1075 hashset(_globals, moduleName, locals);
1079 void FGNasalSys::deleteModule(const char* moduleName)
1081 naRef modname = naNewString(_context);
1082 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1083 naHash_delete(_globals, modname);
1086 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
1089 naRef srcfile = naNewString(_context);
1090 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1091 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
1093 SG_LOG(SG_NASAL, SG_ALERT,
1094 "Nasal parse error: " << naGetError(_context) <<
1095 " in "<< filename <<", line " << errLine);
1099 // Bind to the global namespace before returning
1100 return naBindFunction(_context, code, _globals);
1103 bool FGNasalSys::handleCommand( const char* moduleName,
1104 const char* fileName,
1106 const SGPropertyNode* arg )
1108 naRef code = parse(fileName, src, strlen(src));
1109 if(naIsNil(code)) return false;
1111 // Commands can be run "in" a module. Make sure that module
1112 // exists, and set it up as the local variables hash for the
1114 naRef locals = naNil();
1116 naRef modname = naNewString(_context);
1117 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1118 if(!naHash_get(_globals, modname, &locals)) {
1119 locals = naNewHash(_context);
1120 naHash_set(_globals, modname, locals);
1124 // Cache this command's argument for inspection via cmdarg(). For
1125 // performance reasons, we won't bother with it if the invoked
1126 // code doesn't need it.
1127 _cmdArg = (SGPropertyNode*)arg;
1129 call(code, 0, 0, locals);
1133 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1135 const char* src = arg->getStringValue("script");
1136 const char* moduleName = arg->getStringValue("module");
1138 return handleCommand( moduleName,
1139 arg ? arg->getPath(true).c_str() : moduleName,
1144 // settimer(func, dt, simtime) extension function. The first argument
1145 // is a Nasal function to call, the second is a delta time (from now),
1146 // in seconds. The third, if present, is a boolean value indicating
1147 // that "real world" time (rather than simulator time) is to be used.
1149 // Implementation note: the FGTimer objects don't live inside the
1150 // garbage collector, so the Nasal handler functions have to be
1151 // "saved" somehow lest they be inadvertently cleaned. In this case,
1152 // they are inserted into a globals.__gcsave hash and removed on
1154 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1156 // Extract the handler, delta, and simtime arguments:
1157 naRef handler = argc > 0 ? args[0] : naNil();
1158 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1159 naRuntimeError(c, "settimer() with invalid function argument");
1163 naRef delta = argc > 1 ? args[1] : naNil();
1164 if(naIsNil(delta)) {
1165 naRuntimeError(c, "settimer() with invalid time argument");
1169 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1171 // Generate and register a C++ timer handler
1172 NasalTimer* t = new NasalTimer;
1173 t->handler = handler;
1174 t->gcKey = gcSave(handler);
1177 globals->get_event_mgr()->addEvent("NasalTimer",
1178 t, &NasalTimer::timerExpired,
1179 delta.num, simtime);
1182 void FGNasalSys::handleTimer(NasalTimer* t)
1184 call(t->handler, 0, 0, naNil());
1185 gcRelease(t->gcKey);
1188 int FGNasalSys::gcSave(naRef r)
1193 void FGNasalSys::gcRelease(int key)
1198 void FGNasalSys::NasalTimer::timerExpired()
1200 nasal->handleTimer(this);
1204 int FGNasalSys::_listenerId = 0;
1206 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1207 // Attaches a callback function to a property (specified as a global
1208 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1209 // optional argument (default=0) is set to 1, then the function is also
1210 // called initially. If the fourth, optional argument is set to 0, then the
1211 // function is only called when the property node value actually changes.
1212 // Otherwise it's called independent of the value whenever the node is
1213 // written to (default). The setlistener() function returns a unique
1214 // id number, which is to be used as argument to the removelistener()
1216 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1218 SGPropertyNode_ptr node;
1219 naRef prop = argc > 0 ? args[0] : naNil();
1220 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1221 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1223 naRuntimeError(c, "setlistener() with invalid property argument");
1228 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1231 naRef code = argc > 1 ? args[1] : naNil();
1232 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1233 naRuntimeError(c, "setlistener() with invalid function argument");
1237 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1238 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1239 FGNasalListener *nl = new FGNasalListener(node, code, this,
1240 gcSave(code), _listenerId, init, type);
1242 node->addChangeListener(nl, init != 0);
1244 _listener[_listenerId] = nl;
1245 return naNum(_listenerId++);
1248 // removelistener(int) extension function. The argument is the id of
1249 // a listener as returned by the setlistener() function.
1250 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1252 naRef id = argc > 0 ? args[0] : naNil();
1253 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1255 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1256 naRuntimeError(c, "removelistener() with invalid listener id");
1260 it->second->_dead = true;
1261 _dead_listener.push_back(it->second);
1262 _listener.erase(it);
1263 return naNum(_listener.size());
1266 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1268 if( _loadList.empty() )
1270 _loadList.push(data);
1273 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1275 _unloadList.push(data);
1278 void FGNasalSys::addCommand(naRef func, const std::string& name)
1280 if (_commands.find(name) != _commands.end()) {
1281 SG_LOG(SG_NASAL, SG_WARN, "duplicate add of command:" << name);
1285 NasalCommand* cmd = new NasalCommand(this, func, name);
1286 _commands[name] = cmd;
1289 void FGNasalSys::removeCommand(const std::string& name)
1291 NasalCommandDict::iterator it = _commands.find(name);
1292 if (it == _commands.end()) {
1293 SG_LOG(SG_NASAL, SG_WARN, "remove of unknwon command:" << name);
1297 // will delete the NasalCommand instance
1298 globals->get_commands()->removeCommand(name);
1299 _commands.erase(it);
1302 //////////////////////////////////////////////////////////////////////////
1303 // FGNasalListener class.
1305 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1306 FGNasalSys* nasal, int key, int id,
1307 int init, int type) :
1320 if(_type == 0 && !_init)
1324 FGNasalListener::~FGNasalListener()
1326 _node->removeChangeListener(this);
1327 _nas->gcRelease(_gcKey);
1330 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1332 if(_active || _dead) return;
1335 arg[0] = _nas->propNodeGhost(which);
1336 arg[1] = _nas->propNodeGhost(_node);
1337 arg[2] = mode; // value changed, child added/removed
1338 arg[3] = naNum(_node != which); // child event?
1339 _nas->call(_code, 4, arg, naNil());
1343 void FGNasalListener::valueChanged(SGPropertyNode* node)
1345 if(_type < 2 && node != _node) return; // skip child events
1346 if(_type > 0 || changed(_node) || _init)
1347 call(node, naNum(0));
1352 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1354 if(_type == 2) call(child, naNum(1));
1357 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1359 if(_type == 2) call(child, naNum(-1));
1362 bool FGNasalListener::changed(SGPropertyNode* node)
1364 using namespace simgear;
1365 props::Type type = node->getType();
1366 if(type == props::NONE) return false;
1367 if(type == props::UNSPECIFIED) return true;
1375 long l = node->getLongValue();
1376 result = l != _last_int;
1383 double d = node->getDoubleValue();
1384 result = d != _last_float;
1390 string s = node->getStringValue();
1391 result = s != _last_string;
1398 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1400 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1401 _c(naSubContext(c)),
1402 _start_element(argc > 1 ? args[1] : naNil()),
1403 _end_element(argc > 2 ? args[2] : naNil()),
1404 _data(argc > 3 ? args[3] : naNil()),
1405 _pi(argc > 4 ? args[4] : naNil())
1409 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1411 if(naIsNil(_start_element)) return;
1412 naRef attr = naNewHash(_c);
1413 for(int i=0; i<a.size(); i++) {
1414 naRef name = make_string(a.getName(i));
1415 naRef value = make_string(a.getValue(i));
1416 naHash_set(attr, name, value);
1418 call(_start_element, 2, make_string(tag), attr);
1421 void NasalXMLVisitor::endElement(const char* tag)
1423 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1426 void NasalXMLVisitor::data(const char* str, int len)
1428 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1431 void NasalXMLVisitor::pi(const char* target, const char* data)
1433 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1436 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1441 naCall(_c, func, num, args, naNil(), naNil());
1446 naRef NasalXMLVisitor::make_string(const char* s, int n)
1448 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1449 n < 0 ? strlen(s) : n);