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/SimpleMarkdown.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 <simgear/nasal/cppbind/from_nasal.hxx>
33 #include <simgear/nasal/cppbind/to_nasal.hxx>
34 #include <simgear/nasal/cppbind/Ghost.hxx>
35 #include <simgear/nasal/cppbind/NasalHash.hxx>
37 #include "NasalSGPath.hxx"
38 #include "NasalSys.hxx"
39 #include "NasalSys_private.hxx"
40 #include "NasalAircraft.hxx"
41 #include "NasalModelData.hxx"
42 #include "NasalPositioned.hxx"
43 #include "NasalCanvas.hxx"
44 #include "NasalClipboard.hxx"
45 #include "NasalCondition.hxx"
46 #include "NasalHTTP.hxx"
47 #include "NasalString.hxx"
49 #include <Main/globals.hxx>
50 #include <Main/util.hxx>
51 #include <Main/fg_props.hxx>
57 void postinitNasalGUI(naRef globals, naContext c);
59 static FGNasalSys* nasalSys = 0;
61 // Listener class for loading Nasal modules on demand
62 class FGNasalModuleListener : public SGPropertyChangeListener
65 FGNasalModuleListener(SGPropertyNode* node);
67 virtual void valueChanged(SGPropertyNode* node);
70 SGPropertyNode_ptr _node;
73 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
77 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
79 if (_node->getBoolValue("enabled",false)&&
80 !_node->getBoolValue("loaded",true))
82 nasalSys->loadPropertyScripts(_node);
86 //////////////////////////////////////////////////////////////////////////
89 class TimerObj : public SGReferenced
92 TimerObj(FGNasalSys* sys, naRef f, naRef self, double interval) :
101 snprintf(nm, 128, "nasal-timer-%p", this);
103 _gcRoot = sys->gcSave(f);
104 _gcSelf = sys->gcSave(self);
110 _sys->gcRelease(_gcRoot);
111 _sys->gcRelease(_gcSelf);
114 bool isRunning() const { return _isRunning; }
119 globals->get_event_mgr()->removeTask(_name);
132 globals->get_event_mgr()->addEvent(_name, this, &TimerObj::invoke, _interval);
134 globals->get_event_mgr()->addTask(_name, this, &TimerObj::invoke,
135 _interval, _interval /* delay */);
139 // stop and then start -
140 void restart(double newInterval)
142 _interval = newInterval;
150 _sys->callMethod(_func, _self, 0, args, naNil() /* locals */);
156 void setSingleShot(bool aSingleShot)
158 _singleShot = aSingleShot;
161 bool isSingleShot() const
162 { return _singleShot; }
167 int _gcRoot, _gcSelf;
173 typedef SGSharedPtr<TimerObj> TimerObjRef;
174 typedef nasal::Ghost<TimerObjRef> NasalTimerObj;
176 ///////////////////////////////////////////////////////////////////////////
178 // Read and return file contents in a single buffer. Note use of
179 // stat() to get the file size. This is a win32 function, believe it
180 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
181 // Text mode brain damage will kill us if we're trying to do bytewise
183 static char* readfile(const char* file, int* lenOut)
186 if(stat(file, &data) != 0) return 0;
187 FILE* f = fopen(file, "rb");
189 char* buf = new char[data.st_size];
190 *lenOut = fread(buf, 1, data.st_size, f);
192 if(*lenOut != data.st_size) {
193 // Shouldn't happen, but warn anyway since it represents a
194 // platform bug and not a typical runtime error (missing file,
196 SG_LOG(SG_NASAL, SG_ALERT,
197 "ERROR in Nasal initialization: " <<
198 "short count returned from fread() of " << file <<
199 ". Check your C library!");
206 FGNasalSys::FGNasalSys() :
213 _wrappedNodeFunc = naNil();
215 _log = new simgear::BufferedLogCallback(SG_NASAL, SG_INFO);
216 _log->truncateAt(255);
217 sglog().addCallback(_log);
219 naSetErrorHandler(&logError);
222 // Utility. Sets a named key in a hash by C string, rather than nasal
224 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
226 naRef s = naNewString(_context);
227 naStr_fromdata(s, (char*)key, strlen(key));
228 naHash_set(hash, s, val);
231 void FGNasalSys::globalsSet(const char* key, naRef val)
233 hashset(_globals, key, val);
236 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
238 return callMethod(code, naNil(), argc, args, locals);
241 naRef FGNasalSys::callWithContext(naContext ctx, naRef code, int argc, naRef* args, naRef locals)
243 return callMethodWithContext(ctx, code, naNil(), argc, args, locals);
246 // Does a naCall() in a new context. Wrapped here to make lock
247 // tracking easier. Extension functions are called with the lock, but
248 // we have to release it before making a new naCall(). So rather than
249 // drop the lock in every extension function that might call back into
250 // Nasal, we keep a stack depth counter here and only unlock/lock
251 // around the naCall if it isn't the first one.
253 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
255 return naCallMethod(code, self, argc, args, locals);
258 naRef FGNasalSys::callMethodWithContext(naContext ctx, naRef code, naRef self, int argc, naRef* args, naRef locals)
260 return naCallMethodCtx(ctx, code, self, argc, args, locals);
263 FGNasalSys::~FGNasalSys()
266 SG_LOG(SG_GENERAL, SG_ALERT, "Nasal was not shutdown");
271 bool FGNasalSys::parseAndRun(const char* sourceCode)
273 naContext ctx = naNewContext();
274 naRef code = parse(ctx, "FGNasalSys::parseAndRun()", sourceCode,
280 callWithContext(ctx, code, 0, 0, naNil());
286 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
288 FGNasalScript* script = new FGNasalScript();
289 script->_gcKey = -1; // important, if we delete it on a parse
290 script->_nas = this; // error, don't clobber a real handle!
294 sprintf(buf, "FGNasalScript@%p", (void *)script);
298 script->_code = parse(name, src, strlen(src));
299 if(naIsNil(script->_code)) {
304 script->_gcKey = gcSave(script->_code);
309 // The get/setprop functions accept a *list* of strings and walk
310 // through the property tree with them to find the appropriate node.
311 // This allows a Nasal object to hold onto a property path and use it
312 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
313 // is the utility function that walks the property tree.
314 static SGPropertyNode* findnode(naContext c, naRef* vec, int len, bool create=false)
316 SGPropertyNode* p = globals->get_props();
318 for(int i=0; i<len; i++) {
321 naRuntimeError(c, "bad argument to setprop/getprop path: expected a string");
323 naRef b = i < len-1 ? naNumValue(vec[i+1]) : naNil();
325 p = p->getNode(naStr_data(a), (int)b.num, create);
328 p = p->getNode(naStr_data(a), create);
332 } catch (const string& err) {
333 naRuntimeError(c, (char *)err.c_str());
338 // getprop() extension function. Concatenates its string arguments as
339 // property names and returns the value of the specified property. Or
340 // nil if it doesn't exist.
341 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
343 using namespace simgear;
345 naRuntimeError(c, "getprop() expects at least 1 argument");
347 const SGPropertyNode* p = findnode(c, args, argc, false);
348 if(!p) return naNil();
350 switch(p->getType()) {
351 case props::BOOL: case props::INT:
352 case props::LONG: case props::FLOAT:
355 double dv = p->getDoubleValue();
356 if (SGMisc<double>::isNaN(dv)) {
357 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
365 case props::UNSPECIFIED:
367 naRef nastr = naNewString(c);
368 const char* val = p->getStringValue();
369 naStr_fromdata(nastr, (char*)val, strlen(val));
372 case props::ALIAS: // <--- FIXME, recurse?
378 // setprop() extension function. Concatenates its string arguments as
379 // property names and sets the value of the specified property to the
381 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
384 naRuntimeError(c, "setprop() expects at least 2 arguments");
386 naRef val = args[argc - 1];
387 SGPropertyNode* p = findnode(c, args, argc-1, true);
391 if(naIsString(val)) result = p->setStringValue(naStr_data(val));
394 naRuntimeError(c, "setprop() value is not string or number");
396 if (SGMisc<double>::isNaN(val.num)) {
397 naRuntimeError(c, "setprop() passed a NaN");
400 result = p->setDoubleValue(val.num);
402 } catch (const string& err) {
403 naRuntimeError(c, (char *)err.c_str());
405 return naNum(result);
408 // print() extension function. Concatenates and prints its arguments
409 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
410 // make sure it appears. Is there better way to do this?
411 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
415 for(int i=0; i<n; i++) {
416 naRef s = naStringValue(c, args[i]);
417 if(naIsNil(s)) continue;
418 buf += naStr_data(s);
420 SG_LOG(SG_NASAL, SG_ALERT, buf);
421 return naNum(buf.length());
424 // logprint() extension function. Same as above, all arguments after the
425 // first argument are concatenated. Argument 0 is the log-level, matching
427 static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
430 naRuntimeError(c, "no prioirty argument to logprint()");
432 naRef priority = args[0];
435 for(int i=1; i<n; i++) {
436 naRef s = naStringValue(c, args[i]);
437 if(naIsNil(s)) continue;
438 buf += naStr_data(s);
440 // use the nasal source file and line for the message location, since
441 // that's more useful than the location here!
442 sglog().log(SG_NASAL, (sgDebugPriority)(int) priority.num,
443 naStr_data(naGetSourceFile(c, 0)),
444 naGetLine(c, 0), buf);
445 return naNum(buf.length());
449 // fgcommand() extension function. Executes a named command via the
450 // FlightGear command manager. Takes a single property node name as
452 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
454 naRef cmd = argc > 0 ? args[0] : naNil();
455 naRef props = argc > 1 ? args[1] : naNil();
456 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
457 naRuntimeError(c, "bad arguments to fgcommand()");
458 SGPropertyNode_ptr tmp, *node;
460 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
462 tmp = new SGPropertyNode();
465 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
468 // settimer(func, dt, simtime) extension function. Falls through to
469 // FGNasalSys::setTimer(). See there for docs.
470 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
472 nasalSys->setTimer(c, argc, args);
476 static naRef f_makeTimer(naContext c, naRef me, int argc, naRef* args)
478 if (!naIsNum(args[0])) {
479 naRuntimeError(c, "bad interval argument to maketimer");
482 naRef func, self = naNil();
483 if (naIsFunc(args[1])) {
485 } else if ((argc == 3) && naIsFunc(args[2])) {
490 TimerObj* timerObj = new TimerObj(nasalSys, func, self, args[0].num);
491 return nasal::to_nasal(c, timerObj);
494 // setlistener(func, property, bool) extension function. Falls through to
495 // FGNasalSys::setListener(). See there for docs.
496 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
498 return nasalSys->setListener(c, argc, args);
501 // removelistener(int) extension function. Falls through to
502 // FGNasalSys::removeListener(). See there for docs.
503 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
505 return nasalSys->removeListener(c, argc, args);
508 // Returns a ghost handle to the argument to the currently executing
510 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
512 return nasalSys->cmdArgGhost();
515 // Sets up a property interpolation. The first argument is either a
516 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
517 // interpolate. The second argument is a vector of pairs of
518 // value/delta numbers.
519 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
521 SGPropertyNode* node;
522 naRef prop = argc > 0 ? args[0] : naNil();
523 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
524 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
527 naRef curve = argc > 1 ? args[1] : naNil();
528 if(!naIsVector(curve)) return naNil();
529 int nPoints = naVec_size(curve) / 2;
531 simgear::PropertyList value_nodes;
532 value_nodes.reserve(nPoints);
534 deltas.reserve(nPoints);
536 for( int i = 0; i < nPoints; ++i )
538 SGPropertyNode* val = new SGPropertyNode;
539 val->setDoubleValue(naNumValue(naVec_get(curve, 2*i)).num);
540 value_nodes.push_back(val);
541 deltas.push_back(naNumValue(naVec_get(curve, 2*i+1)).num);
544 node->interpolate("numeric", value_nodes, deltas, "linear");
548 // This is a better RNG than the one in the default Nasal distribution
549 // (which is based on the C library rand() implementation). It will
551 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
553 return naNum(sg_random());
556 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
562 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
568 // Return an array listing of all files in a directory
569 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
571 if(argc != 1 || !naIsString(args[0]))
572 naRuntimeError(c, "bad arguments to directory()");
574 simgear::Dir d(SGPath(naStr_data(args[0])));
575 if(!d.exists()) return naNil();
576 naRef result = naNewVector(c);
578 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
579 for (unsigned int i=0; i<paths.size(); ++i) {
580 std::string p = paths[i].file();
581 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
588 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
590 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
592 if(argc != 1 || !naIsString(args[0]))
593 naRuntimeError(c, "bad arguments to resolveDataPath()");
595 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
596 const char* pdata = p.c_str();
597 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
600 static naRef f_findDataDir(naContext c, naRef me, int argc, naRef* args)
602 if(argc != 1 || !naIsString(args[0]))
603 naRuntimeError(c, "bad arguments to findDataDir()");
605 SGPath p = globals->find_data_dir(naStr_data(args[0]));
606 const char* pdata = p.c_str();
607 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
610 class NasalCommand : public SGCommandMgr::Command
613 NasalCommand(FGNasalSys* sys, naRef f, const std::string& name) :
618 globals->get_commands()->addCommandObject(_name, this);
619 _gcRoot = sys->gcSave(f);
622 virtual ~NasalCommand()
624 _sys->gcRelease(_gcRoot);
627 virtual bool operator()(const SGPropertyNode* aNode)
629 _sys->setCmdArg(const_cast<SGPropertyNode*>(aNode));
631 args[0] = _sys->wrappedPropsNode(const_cast<SGPropertyNode*>(aNode));
633 _sys->callMethod(_func, naNil(), 1, args, naNil() /* locals */);
645 static naRef f_addCommand(naContext c, naRef me, int argc, naRef* args)
647 if(argc != 2 || !naIsString(args[0]) || !naIsFunc(args[1]))
648 naRuntimeError(c, "bad arguments to addcommand()");
650 nasalSys->addCommand(args[1], naStr_data(args[0]));
654 static naRef f_removeCommand(naContext c, naRef me, int argc, naRef* args)
656 if ((argc < 1) || !naIsString(args[0]))
657 naRuntimeError(c, "bad argument to removecommand()");
659 globals->get_commands()->removeCommand(naStr_data(args[0]));
664 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
666 // <path> ... absolute path to an XML file
667 // <start-tag> ... callback function with two args: tag name, attribute hash
668 // <end-tag> ... callback function with one arg: tag name
669 // <data> ... callback function with one arg: data
670 // <pi> ... callback function with two args: target, data
671 // (pi = "processing instruction")
672 // All four callback functions are optional and default to nil.
673 // The function returns nil on error, or the validated file name otherwise.
674 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
676 if(argc < 1 || !naIsString(args[0]))
677 naRuntimeError(c, "parsexml(): path argument missing or not a string");
678 if(argc > 5) argc = 5;
679 for(int i=1; i<argc; i++)
680 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
681 naRuntimeError(c, "parsexml(): callback argument not a function");
683 const char* file = fgValidatePath(naStr_data(args[0]), false);
685 naRuntimeError(c, "parsexml(): reading '%s' denied "
686 "(unauthorized access)", naStr_data(args[0]));
689 std::ifstream input(file);
690 NasalXMLVisitor visitor(c, argc, args);
692 readXML(input, visitor);
693 } catch (const sg_exception& e) {
694 naRuntimeError(c, "parsexml(): file '%s' %s",
695 file, e.getFormattedMessage().c_str());
698 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
702 * Parse very simple and small subset of markdown
704 * parse_markdown(src)
706 static naRef f_parse_markdown(naContext c, naRef me, int argc, naRef* args)
708 nasal::CallContext ctx(c, argc, args);
710 simgear::SimpleMarkdown::parse(ctx.requireArg<std::string>(0))
714 // Return UNIX epoch time in seconds.
715 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
719 GetSystemTimeAsFileTime(&ft);
720 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
721 // Converts from 100ns units in 1601 epoch to unix epoch in sec
722 return naNum((t * 1e-7) - 11644473600.0);
725 gettimeofday(&td, 0);
726 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
730 // Table of extension functions. Terminate with zeros.
731 static struct { const char* name; naCFunction func; } funcs[] = {
732 { "getprop", f_getprop },
733 { "setprop", f_setprop },
734 { "print", f_print },
735 { "logprint", f_logprint },
736 { "_fgcommand", f_fgcommand },
737 { "settimer", f_settimer },
738 { "maketimer", f_makeTimer },
739 { "_setlistener", f_setlistener },
740 { "removelistener", f_removelistener },
741 { "addcommand", f_addCommand },
742 { "removecommand", f_removeCommand },
743 { "_cmdarg", f_cmdarg },
744 { "_interpolate", f_interpolate },
746 { "srand", f_srand },
747 { "abort", f_abort },
748 { "directory", f_directory },
749 { "resolvepath", f_resolveDataPath },
750 { "finddata", f_findDataDir },
751 { "parsexml", f_parsexml },
752 { "parse_markdown", f_parse_markdown },
753 { "systime", f_systime },
757 naRef FGNasalSys::cmdArgGhost()
759 return propNodeGhost(_cmdArg);
762 void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
767 void FGNasalSys::init()
770 SG_LOG(SG_GENERAL, SG_ALERT, "duplicate init of Nasal");
774 _context = naNewContext();
776 // Start with globals. Add it to itself as a recursive
777 // sub-reference under the name "globals". This gives client-code
778 // write access to the namespace if someone wants to do something
780 _globals = naInit_std(_context);
781 naSave(_context, _globals);
782 hashset(_globals, "globals", _globals);
784 hashset(_globals, "math", naInit_math(_context));
785 hashset(_globals, "bits", naInit_bits(_context));
786 hashset(_globals, "io", naInit_io(_context));
787 hashset(_globals, "thread", naInit_thread(_context));
788 hashset(_globals, "utf8", naInit_utf8(_context));
790 // Add our custom extension functions:
791 for(i=0; funcs[i].name; i++)
792 hashset(_globals, funcs[i].name,
793 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
795 // And our SGPropertyNode wrapper
796 hashset(_globals, "props", genPropsModule());
798 // Add string methods
799 _string = naInit_string(_context);
800 naSave(_context, _string);
801 initNasalString(_globals, _string, _context);
803 initNasalPositioned(_globals, _context);
804 initNasalPositioned_cppbind(_globals, _context);
805 initNasalAircraft(_globals, _context);
806 NasalClipboard::init(this);
807 initNasalCanvas(_globals, _context);
808 initNasalCondition(_globals, _context);
809 initNasalHTTP(_globals, _context);
810 initNasalSGPath(_globals, _context);
812 NasalTimerObj::init("Timer")
813 .method("start", &TimerObj::start)
814 .method("stop", &TimerObj::stop)
815 .method("restart", &TimerObj::restart)
816 .member("singleShot", &TimerObj::isSingleShot, &TimerObj::setSingleShot)
817 .member("isRunning", &TimerObj::isRunning);
819 // Now load the various source files in the Nasal directory
820 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
821 loadScriptDirectory(nasalDir);
823 // Add modules in Nasal subdirectories to property tree
824 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
825 simgear::Dir::NO_DOT_OR_DOTDOT, "");
826 for (unsigned int i=0; i<directories.size(); ++i) {
827 simgear::Dir dir(directories[i]);
828 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
829 addModule(directories[i].file(), scripts);
832 // set signal and remove node to avoid restoring at reinit
833 const char *s = "nasal-dir-initialized";
834 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
835 signal->setBoolValue(s, true);
836 signal->removeChildren(s);
838 // Pull scripts out of the property tree, too
839 loadPropertyScripts();
841 // now Nasal modules are loaded, we can do some delayed work
842 postinitNasalPositioned(_globals, _context);
843 postinitNasalGUI(_globals, _context);
848 void FGNasalSys::shutdown()
854 shutdownNasalPositioned();
856 map<int, FGNasalListener *>::iterator it, end = _listener.end();
857 for(it = _listener.begin(); it != end; ++it)
861 NasalCommandDict::iterator j = _commands.begin();
862 for (; j != _commands.end(); ++j) {
863 globals->get_commands()->removeCommand(j->first);
867 std::vector<FGNasalModuleListener*>::iterator k = _moduleListeners.begin();
868 for(; k!= _moduleListeners.end(); ++k)
870 _moduleListeners.clear();
874 _string = naNil(); // will be freed by _context
875 naFreeContext(_context);
877 //setWatchedRef(_globals);
879 // remove the recursive reference in globals
880 hashset(_globals, "globals", naNil());
887 naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps)
889 if (naIsNil(_wrappedNodeFunc)) {
890 nasal::Hash props = getGlobals().get<nasal::Hash>("props");
891 _wrappedNodeFunc = props.get("wrapNode");
895 args[0] = propNodeGhost(aProps);
896 naContext ctx = naNewContext();
897 naRef wrapped = naCall(ctx, _wrappedNodeFunc, 1, args, naNil(), naNil());
902 void FGNasalSys::update(double)
904 if( NasalClipboard::getInstance() )
905 NasalClipboard::getInstance()->update();
907 if(!_dead_listener.empty()) {
908 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
909 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
910 _dead_listener.clear();
913 if (!_loadList.empty())
918 // process Nasal load hook (only one per update loop to avoid excessive lags)
919 _loadList.pop()->load();
922 if (!_unloadList.empty())
924 // process pending Nasal unload hooks after _all_ load hooks were processed
925 // (only unload one per update loop to avoid excessive lags)
926 _unloadList.pop()->unload();
929 // The global context is a legacy thing. We use dynamically
930 // created contexts for naCall() now, so that we can call them
931 // recursively. But there are still spots that want to use it for
932 // naNew*() calls, which end up leaking memory because the context
933 // only clears out its temporary vector when it's *used*. So just
934 // junk it and fetch a new/reinitialized one every frame. This is
935 // clumsy: the right solution would use the dynamic context in all
936 // cases and eliminate _context entirely. But that's more work,
937 // and this works fine (yes, they say "New" and "Free", but
938 // they're very fast, just trust me). -Andy
939 naFreeContext(_context);
940 _context = naNewContext();
943 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
945 return p1.file() < p2.file();
948 // Loads all scripts in given directory
949 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
951 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
952 // Note: simgear::Dir already reports file entries in a deterministic order,
953 // so a fixed loading sequence is guaranteed (same for every user)
954 for (unsigned int i=0; i<scripts.size(); ++i) {
955 SGPath fullpath(scripts[i]);
956 SGPath file = fullpath.file();
957 loadModule(fullpath, file.base().c_str());
961 // Create module with list of scripts
962 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
964 if (! scripts.empty())
966 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
967 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
968 for (unsigned int i=0; i<scripts.size(); ++i) {
969 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
970 pFileNode->setStringValue(scripts[i].c_str());
972 if (!module_node->hasChild("enabled",0))
974 SGPropertyNode* node = module_node->getChild("enabled",0,true);
975 node->setBoolValue(true);
976 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
981 // Loads the scripts found under /nasal in the global tree
982 void FGNasalSys::loadPropertyScripts()
984 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
987 for(int i=0; i<nasal->nChildren(); i++)
989 SGPropertyNode* n = nasal->getChild(i);
990 loadPropertyScripts(n);
994 // Loads the scripts found under /nasal in the global tree
995 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
997 bool is_loaded = false;
999 const char* module = n->getName();
1000 if(n->hasChild("module"))
1001 module = n->getStringValue("module");
1002 if (n->getBoolValue("enabled",true))
1004 // allow multiple files to be specified within a single
1008 bool file_specified = false;
1010 while((fn = n->getChild("file", j)) != NULL) {
1011 file_specified = true;
1012 const char* file = fn->getStringValue();
1014 if (!p.isAbsolute() || !p.exists())
1016 p = globals->resolve_maybe_aircraft_path(file);
1019 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
1020 file << "' for module '" << module << "'.");
1023 ok &= p.isNull() ? false : loadModule(p, module);
1027 const char* src = n->getStringValue("script");
1028 if(!n->hasChild("script")) src = 0; // Hrm...
1030 createModule(module, n->getPath().c_str(), src, strlen(src));
1032 if(!file_specified && !src)
1034 // module no longer exists - clear the archived "enable" flag
1035 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
1036 SGPropertyNode* node = n->getChild("enabled",0,false);
1038 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
1040 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
1041 "no <file> or <script> defined in " <<
1042 "/nasal/" << module);
1049 SGPropertyNode* enable = n->getChild("enabled");
1052 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
1053 _moduleListeners.push_back(listener);
1054 enable->addChangeListener(listener, false);
1057 SGPropertyNode* loaded = n->getChild("loaded",0,true);
1058 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
1059 loaded->setBoolValue(is_loaded);
1062 // Logs a runtime error, with stack trace, to the FlightGear log stream
1063 void FGNasalSys::logError(naContext context)
1065 SG_LOG(SG_NASAL, SG_ALERT, "Nasal runtime error: " << naGetError(context));
1066 int stack_depth = naStackDepth(context);
1067 if( stack_depth < 1 )
1069 SG_LOG(SG_NASAL, SG_ALERT,
1070 " at " << naStr_data(naGetSourceFile(context, 0)) <<
1071 ", line " << naGetLine(context, 0));
1072 for(int i=1; i<stack_depth; i++)
1073 SG_LOG(SG_NASAL, SG_ALERT,
1074 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
1075 ", line " << naGetLine(context, i));
1078 // Reads a script file, executes it, and places the resulting
1079 // namespace into the global namespace under the specified module
1081 bool FGNasalSys::loadModule(SGPath file, const char* module)
1084 char* buf = readfile(file.c_str(), &len);
1086 SG_LOG(SG_NASAL, SG_ALERT,
1087 "Nasal error: could not read script file " << file.c_str()
1088 << " into module " << module);
1092 bool ok = createModule(module, file.c_str(), buf, len);
1097 // Parse and run. Save the local variables namespace, as it will
1098 // become a sub-object of globals. The optional "arg" argument can be
1099 // used to pass an associated property node to the module, which can then
1100 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
1101 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1102 const char* src, int len,
1103 const SGPropertyNode* cmdarg,
1104 int argc, naRef* args)
1106 naContext ctx = naNewContext();
1107 naRef code = parse(ctx, fileName, src, len);
1114 // See if we already have a module hash to use. This allows the
1115 // user to, for example, add functions to the built-in math
1116 // module. Make a new one if necessary.
1118 naRef modname = naNewString(ctx);
1119 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1120 if(!naHash_get(_globals, modname, &locals))
1121 locals = naNewHash(ctx);
1123 _cmdArg = (SGPropertyNode*)cmdarg;
1125 callWithContext(ctx, code, argc, args, locals);
1126 hashset(_globals, moduleName, locals);
1132 void FGNasalSys::deleteModule(const char* moduleName)
1135 // can occur on shutdown due to us being shutdown first, but other
1136 // subsystems having Nasal objects.
1140 naContext ctx = naNewContext();
1141 naRef modname = naNewString(ctx);
1142 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1143 naHash_delete(_globals, modname);
1147 naRef FGNasalSys::parse(naContext ctx, const char* filename, const char* buf, int len)
1150 naRef srcfile = naNewString(ctx);
1151 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1152 naRef code = naParseCode(ctx, srcfile, 1, (char*)buf, len, &errLine);
1154 SG_LOG(SG_NASAL, SG_ALERT,
1155 "Nasal parse error: " << naGetError(ctx) <<
1156 " in "<< filename <<", line " << errLine);
1160 // Bind to the global namespace before returning
1161 return naBindFunction(ctx, code, _globals);
1164 bool FGNasalSys::handleCommand( const char* moduleName,
1165 const char* fileName,
1167 const SGPropertyNode* arg )
1169 naContext ctx = naNewContext();
1170 naRef code = parse(ctx, fileName, src, strlen(src));
1176 // Commands can be run "in" a module. Make sure that module
1177 // exists, and set it up as the local variables hash for the
1179 naRef locals = naNil();
1181 naRef modname = naNewString(ctx);
1182 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1183 if(!naHash_get(_globals, modname, &locals)) {
1184 locals = naNewHash(ctx);
1185 naHash_set(_globals, modname, locals);
1189 // Cache this command's argument for inspection via cmdarg(). For
1190 // performance reasons, we won't bother with it if the invoked
1191 // code doesn't need it.
1192 _cmdArg = (SGPropertyNode*)arg;
1194 callWithContext(ctx, code, 0, 0, locals);
1199 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1201 const char* src = arg->getStringValue("script");
1202 const char* moduleName = arg->getStringValue("module");
1204 return handleCommand( moduleName,
1205 arg->getPath(true).c_str(),
1210 // settimer(func, dt, simtime) extension function. The first argument
1211 // is a Nasal function to call, the second is a delta time (from now),
1212 // in seconds. The third, if present, is a boolean value indicating
1213 // that "real world" time (rather than simulator time) is to be used.
1215 // Implementation note: the FGTimer objects don't live inside the
1216 // garbage collector, so the Nasal handler functions have to be
1217 // "saved" somehow lest they be inadvertently cleaned. In this case,
1218 // they are inserted into a globals.__gcsave hash and removed on
1220 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1222 // Extract the handler, delta, and simtime arguments:
1223 naRef handler = argc > 0 ? args[0] : naNil();
1224 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1225 naRuntimeError(c, "settimer() with invalid function argument");
1229 naRef delta = argc > 1 ? args[1] : naNil();
1230 if(naIsNil(delta)) {
1231 naRuntimeError(c, "settimer() with invalid time argument");
1235 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1237 // Generate and register a C++ timer handler
1238 NasalTimer* t = new NasalTimer;
1239 t->handler = handler;
1240 t->gcKey = gcSave(handler);
1243 globals->get_event_mgr()->addEvent("NasalTimer",
1244 t, &NasalTimer::timerExpired,
1245 delta.num, simtime);
1248 void FGNasalSys::handleTimer(NasalTimer* t)
1250 call(t->handler, 0, 0, naNil());
1251 gcRelease(t->gcKey);
1254 int FGNasalSys::gcSave(naRef r)
1259 void FGNasalSys::gcRelease(int key)
1264 void FGNasalSys::NasalTimer::timerExpired()
1266 nasal->handleTimer(this);
1270 int FGNasalSys::_listenerId = 0;
1272 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1273 // Attaches a callback function to a property (specified as a global
1274 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1275 // optional argument (default=0) is set to 1, then the function is also
1276 // called initially. If the fourth, optional argument is set to 0, then the
1277 // function is only called when the property node value actually changes.
1278 // Otherwise it's called independent of the value whenever the node is
1279 // written to (default). The setlistener() function returns a unique
1280 // id number, which is to be used as argument to the removelistener()
1282 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1284 SGPropertyNode_ptr node;
1285 naRef prop = argc > 0 ? args[0] : naNil();
1286 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1287 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1289 naRuntimeError(c, "setlistener() with invalid property argument");
1294 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1297 naRef code = argc > 1 ? args[1] : naNil();
1298 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1299 naRuntimeError(c, "setlistener() with invalid function argument");
1303 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1304 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1305 FGNasalListener *nl = new FGNasalListener(node, code, this,
1306 gcSave(code), _listenerId, init, type);
1308 node->addChangeListener(nl, init != 0);
1310 _listener[_listenerId] = nl;
1311 return naNum(_listenerId++);
1314 // removelistener(int) extension function. The argument is the id of
1315 // a listener as returned by the setlistener() function.
1316 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1318 naRef id = argc > 0 ? args[0] : naNil();
1319 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1321 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1322 naRuntimeError(c, "removelistener() with invalid listener id");
1326 it->second->_dead = true;
1327 _dead_listener.push_back(it->second);
1328 _listener.erase(it);
1329 return naNum(_listener.size());
1332 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1334 if( _loadList.empty() )
1336 _loadList.push(data);
1339 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1341 _unloadList.push(data);
1344 void FGNasalSys::addCommand(naRef func, const std::string& name)
1346 if (_commands.find(name) != _commands.end()) {
1347 SG_LOG(SG_NASAL, SG_WARN, "duplicate add of command:" << name);
1351 NasalCommand* cmd = new NasalCommand(this, func, name);
1352 _commands[name] = cmd;
1355 void FGNasalSys::removeCommand(const std::string& name)
1357 NasalCommandDict::iterator it = _commands.find(name);
1358 if (it == _commands.end()) {
1359 SG_LOG(SG_NASAL, SG_WARN, "remove of unknwon command:" << name);
1363 // will delete the NasalCommand instance
1364 globals->get_commands()->removeCommand(name);
1365 _commands.erase(it);
1368 //////////////////////////////////////////////////////////////////////////
1369 // FGNasalListener class.
1371 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1372 FGNasalSys* nasal, int key, int id,
1373 int init, int type) :
1386 if(_type == 0 && !_init)
1390 FGNasalListener::~FGNasalListener()
1392 _node->removeChangeListener(this);
1393 _nas->gcRelease(_gcKey);
1396 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1398 if(_active || _dead) return;
1401 arg[0] = _nas->propNodeGhost(which);
1402 arg[1] = _nas->propNodeGhost(_node);
1403 arg[2] = mode; // value changed, child added/removed
1404 arg[3] = naNum(_node != which); // child event?
1405 _nas->call(_code, 4, arg, naNil());
1409 void FGNasalListener::valueChanged(SGPropertyNode* node)
1411 if(_type < 2 && node != _node) return; // skip child events
1412 if(_type > 0 || changed(_node) || _init)
1413 call(node, naNum(0));
1418 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1420 if(_type == 2) call(child, naNum(1));
1423 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1425 if(_type == 2) call(child, naNum(-1));
1428 bool FGNasalListener::changed(SGPropertyNode* node)
1430 using namespace simgear;
1431 props::Type type = node->getType();
1432 if(type == props::NONE) return false;
1433 if(type == props::UNSPECIFIED) return true;
1441 long l = node->getLongValue();
1442 result = l != _last_int;
1449 double d = node->getDoubleValue();
1450 result = d != _last_float;
1456 string s = node->getStringValue();
1457 result = s != _last_string;
1464 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1466 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1467 _c(naSubContext(c)),
1468 _start_element(argc > 1 ? args[1] : naNil()),
1469 _end_element(argc > 2 ? args[2] : naNil()),
1470 _data(argc > 3 ? args[3] : naNil()),
1471 _pi(argc > 4 ? args[4] : naNil())
1475 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1477 if(naIsNil(_start_element)) return;
1478 naRef attr = naNewHash(_c);
1479 for(int i=0; i<a.size(); i++) {
1480 naRef name = make_string(a.getName(i));
1481 naRef value = make_string(a.getValue(i));
1482 naHash_set(attr, name, value);
1484 call(_start_element, 2, make_string(tag), attr);
1487 void NasalXMLVisitor::endElement(const char* tag)
1489 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1492 void NasalXMLVisitor::data(const char* str, int len)
1494 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1497 void NasalXMLVisitor::pi(const char* target, const char* data)
1499 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1502 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1507 naCall(_c, func, num, args, naNil(), naNil());
1512 naRef NasalXMLVisitor::make_string(const char* s, int n)
1514 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1515 n < 0 ? strlen(s) : n);