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))
715 * Create md5 hash from given string
719 static naRef f_md5(naContext c, naRef me, int argc, naRef* args)
721 if( argc != 1 || !naIsString(args[0]) )
722 naRuntimeError(c, "md5(): wrong type or number of arguments");
724 return nasal::to_nasal(
726 simgear::strutils::md5(naStr_data(args[0]), naStr_len(args[0]))
730 // Return UNIX epoch time in seconds.
731 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
735 GetSystemTimeAsFileTime(&ft);
736 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
737 // Converts from 100ns units in 1601 epoch to unix epoch in sec
738 return naNum((t * 1e-7) - 11644473600.0);
741 gettimeofday(&td, 0);
742 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
746 // Table of extension functions. Terminate with zeros.
747 static struct { const char* name; naCFunction func; } funcs[] = {
748 { "getprop", f_getprop },
749 { "setprop", f_setprop },
750 { "print", f_print },
751 { "logprint", f_logprint },
752 { "_fgcommand", f_fgcommand },
753 { "settimer", f_settimer },
754 { "maketimer", f_makeTimer },
755 { "_setlistener", f_setlistener },
756 { "removelistener", f_removelistener },
757 { "addcommand", f_addCommand },
758 { "removecommand", f_removeCommand },
759 { "_cmdarg", f_cmdarg },
760 { "_interpolate", f_interpolate },
762 { "srand", f_srand },
763 { "abort", f_abort },
764 { "directory", f_directory },
765 { "resolvepath", f_resolveDataPath },
766 { "finddata", f_findDataDir },
767 { "parsexml", f_parsexml },
768 { "parse_markdown", f_parse_markdown },
770 { "systime", f_systime },
774 naRef FGNasalSys::cmdArgGhost()
776 return propNodeGhost(_cmdArg);
779 void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
784 void FGNasalSys::init()
787 SG_LOG(SG_GENERAL, SG_ALERT, "duplicate init of Nasal");
791 _context = naNewContext();
793 // Start with globals. Add it to itself as a recursive
794 // sub-reference under the name "globals". This gives client-code
795 // write access to the namespace if someone wants to do something
797 _globals = naInit_std(_context);
798 naSave(_context, _globals);
799 hashset(_globals, "globals", _globals);
801 hashset(_globals, "math", naInit_math(_context));
802 hashset(_globals, "bits", naInit_bits(_context));
803 hashset(_globals, "io", naInit_io(_context));
804 hashset(_globals, "thread", naInit_thread(_context));
805 hashset(_globals, "utf8", naInit_utf8(_context));
807 // Add our custom extension functions:
808 for(i=0; funcs[i].name; i++)
809 hashset(_globals, funcs[i].name,
810 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
812 // And our SGPropertyNode wrapper
813 hashset(_globals, "props", genPropsModule());
815 // Add string methods
816 _string = naInit_string(_context);
817 naSave(_context, _string);
818 initNasalString(_globals, _string, _context);
820 initNasalPositioned(_globals, _context);
821 initNasalPositioned_cppbind(_globals, _context);
822 initNasalAircraft(_globals, _context);
823 NasalClipboard::init(this);
824 initNasalCanvas(_globals, _context);
825 initNasalCondition(_globals, _context);
826 initNasalHTTP(_globals, _context);
827 initNasalSGPath(_globals, _context);
829 NasalTimerObj::init("Timer")
830 .method("start", &TimerObj::start)
831 .method("stop", &TimerObj::stop)
832 .method("restart", &TimerObj::restart)
833 .member("singleShot", &TimerObj::isSingleShot, &TimerObj::setSingleShot)
834 .member("isRunning", &TimerObj::isRunning);
836 // Now load the various source files in the Nasal directory
837 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
838 loadScriptDirectory(nasalDir);
840 // Add modules in Nasal subdirectories to property tree
841 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
842 simgear::Dir::NO_DOT_OR_DOTDOT, "");
843 for (unsigned int i=0; i<directories.size(); ++i) {
844 simgear::Dir dir(directories[i]);
845 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
846 addModule(directories[i].file(), scripts);
849 // set signal and remove node to avoid restoring at reinit
850 const char *s = "nasal-dir-initialized";
851 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
852 signal->setBoolValue(s, true);
853 signal->removeChildren(s);
855 // Pull scripts out of the property tree, too
856 loadPropertyScripts();
858 // now Nasal modules are loaded, we can do some delayed work
859 postinitNasalPositioned(_globals, _context);
860 postinitNasalGUI(_globals, _context);
865 void FGNasalSys::shutdown()
871 shutdownNasalPositioned();
873 map<int, FGNasalListener *>::iterator it, end = _listener.end();
874 for(it = _listener.begin(); it != end; ++it)
878 NasalCommandDict::iterator j = _commands.begin();
879 for (; j != _commands.end(); ++j) {
880 globals->get_commands()->removeCommand(j->first);
884 std::vector<FGNasalModuleListener*>::iterator k = _moduleListeners.begin();
885 for(; k!= _moduleListeners.end(); ++k)
887 _moduleListeners.clear();
891 _string = naNil(); // will be freed by _context
892 naFreeContext(_context);
894 //setWatchedRef(_globals);
896 // remove the recursive reference in globals
897 hashset(_globals, "globals", naNil());
904 naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps)
906 if (naIsNil(_wrappedNodeFunc)) {
907 nasal::Hash props = getGlobals().get<nasal::Hash>("props");
908 _wrappedNodeFunc = props.get("wrapNode");
912 args[0] = propNodeGhost(aProps);
913 naContext ctx = naNewContext();
914 naRef wrapped = naCall(ctx, _wrappedNodeFunc, 1, args, naNil(), naNil());
919 void FGNasalSys::update(double)
921 if( NasalClipboard::getInstance() )
922 NasalClipboard::getInstance()->update();
924 if(!_dead_listener.empty()) {
925 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
926 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
927 _dead_listener.clear();
930 if (!_loadList.empty())
935 // process Nasal load hook (only one per update loop to avoid excessive lags)
936 _loadList.pop()->load();
939 if (!_unloadList.empty())
941 // process pending Nasal unload hooks after _all_ load hooks were processed
942 // (only unload one per update loop to avoid excessive lags)
943 _unloadList.pop()->unload();
946 // Destroy all queued ghosts
947 nasal::ghostProcessDestroyList();
949 // The global context is a legacy thing. We use dynamically
950 // created contexts for naCall() now, so that we can call them
951 // recursively. But there are still spots that want to use it for
952 // naNew*() calls, which end up leaking memory because the context
953 // only clears out its temporary vector when it's *used*. So just
954 // junk it and fetch a new/reinitialized one every frame. This is
955 // clumsy: the right solution would use the dynamic context in all
956 // cases and eliminate _context entirely. But that's more work,
957 // and this works fine (yes, they say "New" and "Free", but
958 // they're very fast, just trust me). -Andy
959 naFreeContext(_context);
960 _context = naNewContext();
963 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
965 return p1.file() < p2.file();
968 // Loads all scripts in given directory
969 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
971 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
972 // Note: simgear::Dir already reports file entries in a deterministic order,
973 // so a fixed loading sequence is guaranteed (same for every user)
974 for (unsigned int i=0; i<scripts.size(); ++i) {
975 SGPath fullpath(scripts[i]);
976 SGPath file = fullpath.file();
977 loadModule(fullpath, file.base().c_str());
981 // Create module with list of scripts
982 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
984 if (! scripts.empty())
986 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
987 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
988 for (unsigned int i=0; i<scripts.size(); ++i) {
989 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
990 pFileNode->setStringValue(scripts[i].c_str());
992 if (!module_node->hasChild("enabled",0))
994 SGPropertyNode* node = module_node->getChild("enabled",0,true);
995 node->setBoolValue(true);
996 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
1001 // Loads the scripts found under /nasal in the global tree
1002 void FGNasalSys::loadPropertyScripts()
1004 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
1007 for(int i=0; i<nasal->nChildren(); i++)
1009 SGPropertyNode* n = nasal->getChild(i);
1010 loadPropertyScripts(n);
1014 // Loads the scripts found under /nasal in the global tree
1015 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
1017 bool is_loaded = false;
1019 const char* module = n->getName();
1020 if(n->hasChild("module"))
1021 module = n->getStringValue("module");
1022 if (n->getBoolValue("enabled",true))
1024 // allow multiple files to be specified within a single
1028 bool file_specified = false;
1030 while((fn = n->getChild("file", j)) != NULL) {
1031 file_specified = true;
1032 const char* file = fn->getStringValue();
1034 if (!p.isAbsolute() || !p.exists())
1036 p = globals->resolve_maybe_aircraft_path(file);
1039 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
1040 file << "' for module '" << module << "'.");
1043 ok &= p.isNull() ? false : loadModule(p, module);
1047 const char* src = n->getStringValue("script");
1048 if(!n->hasChild("script")) src = 0; // Hrm...
1050 createModule(module, n->getPath().c_str(), src, strlen(src));
1052 if(!file_specified && !src)
1054 // module no longer exists - clear the archived "enable" flag
1055 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
1056 SGPropertyNode* node = n->getChild("enabled",0,false);
1058 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
1060 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
1061 "no <file> or <script> defined in " <<
1062 "/nasal/" << module);
1069 SGPropertyNode* enable = n->getChild("enabled");
1072 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
1073 _moduleListeners.push_back(listener);
1074 enable->addChangeListener(listener, false);
1077 SGPropertyNode* loaded = n->getChild("loaded",0,true);
1078 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
1079 loaded->setBoolValue(is_loaded);
1082 // Logs a runtime error, with stack trace, to the FlightGear log stream
1083 void FGNasalSys::logError(naContext context)
1085 SG_LOG(SG_NASAL, SG_ALERT, "Nasal runtime error: " << naGetError(context));
1086 int stack_depth = naStackDepth(context);
1087 if( stack_depth < 1 )
1089 SG_LOG(SG_NASAL, SG_ALERT,
1090 " at " << naStr_data(naGetSourceFile(context, 0)) <<
1091 ", line " << naGetLine(context, 0));
1092 for(int i=1; i<stack_depth; i++)
1093 SG_LOG(SG_NASAL, SG_ALERT,
1094 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
1095 ", line " << naGetLine(context, i));
1098 // Reads a script file, executes it, and places the resulting
1099 // namespace into the global namespace under the specified module
1101 bool FGNasalSys::loadModule(SGPath file, const char* module)
1104 char* buf = readfile(file.c_str(), &len);
1106 SG_LOG(SG_NASAL, SG_ALERT,
1107 "Nasal error: could not read script file " << file.c_str()
1108 << " into module " << module);
1112 bool ok = createModule(module, file.c_str(), buf, len);
1117 // Parse and run. Save the local variables namespace, as it will
1118 // become a sub-object of globals. The optional "arg" argument can be
1119 // used to pass an associated property node to the module, which can then
1120 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
1121 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1122 const char* src, int len,
1123 const SGPropertyNode* cmdarg,
1124 int argc, naRef* args)
1126 naContext ctx = naNewContext();
1127 naRef code = parse(ctx, fileName, src, len);
1134 // See if we already have a module hash to use. This allows the
1135 // user to, for example, add functions to the built-in math
1136 // module. Make a new one if necessary.
1138 naRef modname = naNewString(ctx);
1139 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1140 if(!naHash_get(_globals, modname, &locals))
1141 locals = naNewHash(ctx);
1143 _cmdArg = (SGPropertyNode*)cmdarg;
1145 callWithContext(ctx, code, argc, args, locals);
1146 hashset(_globals, moduleName, locals);
1152 void FGNasalSys::deleteModule(const char* moduleName)
1155 // can occur on shutdown due to us being shutdown first, but other
1156 // subsystems having Nasal objects.
1160 naContext ctx = naNewContext();
1161 naRef modname = naNewString(ctx);
1162 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1163 naHash_delete(_globals, modname);
1167 naRef FGNasalSys::parse(naContext ctx, const char* filename, const char* buf, int len)
1170 naRef srcfile = naNewString(ctx);
1171 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1172 naRef code = naParseCode(ctx, srcfile, 1, (char*)buf, len, &errLine);
1174 SG_LOG(SG_NASAL, SG_ALERT,
1175 "Nasal parse error: " << naGetError(ctx) <<
1176 " in "<< filename <<", line " << errLine);
1180 // Bind to the global namespace before returning
1181 return naBindFunction(ctx, code, _globals);
1184 bool FGNasalSys::handleCommand( const char* moduleName,
1185 const char* fileName,
1187 const SGPropertyNode* arg )
1189 naContext ctx = naNewContext();
1190 naRef code = parse(ctx, fileName, src, strlen(src));
1196 // Commands can be run "in" a module. Make sure that module
1197 // exists, and set it up as the local variables hash for the
1199 naRef locals = naNil();
1201 naRef modname = naNewString(ctx);
1202 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1203 if(!naHash_get(_globals, modname, &locals)) {
1204 locals = naNewHash(ctx);
1205 naHash_set(_globals, modname, locals);
1209 // Cache this command's argument for inspection via cmdarg(). For
1210 // performance reasons, we won't bother with it if the invoked
1211 // code doesn't need it.
1212 _cmdArg = (SGPropertyNode*)arg;
1214 callWithContext(ctx, code, 0, 0, locals);
1219 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1221 const char* src = arg->getStringValue("script");
1222 const char* moduleName = arg->getStringValue("module");
1224 return handleCommand( moduleName,
1225 arg->getPath(true).c_str(),
1230 // settimer(func, dt, simtime) extension function. The first argument
1231 // is a Nasal function to call, the second is a delta time (from now),
1232 // in seconds. The third, if present, is a boolean value indicating
1233 // that "real world" time (rather than simulator time) is to be used.
1235 // Implementation note: the FGTimer objects don't live inside the
1236 // garbage collector, so the Nasal handler functions have to be
1237 // "saved" somehow lest they be inadvertently cleaned. In this case,
1238 // they are inserted into a globals.__gcsave hash and removed on
1240 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1242 // Extract the handler, delta, and simtime arguments:
1243 naRef handler = argc > 0 ? args[0] : naNil();
1244 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1245 naRuntimeError(c, "settimer() with invalid function argument");
1249 naRef delta = argc > 1 ? args[1] : naNil();
1250 if(naIsNil(delta)) {
1251 naRuntimeError(c, "settimer() with invalid time argument");
1255 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1257 // Generate and register a C++ timer handler
1258 NasalTimer* t = new NasalTimer;
1259 t->handler = handler;
1260 t->gcKey = gcSave(handler);
1263 globals->get_event_mgr()->addEvent("NasalTimer",
1264 t, &NasalTimer::timerExpired,
1265 delta.num, simtime);
1268 void FGNasalSys::handleTimer(NasalTimer* t)
1270 call(t->handler, 0, 0, naNil());
1271 gcRelease(t->gcKey);
1274 int FGNasalSys::gcSave(naRef r)
1279 void FGNasalSys::gcRelease(int key)
1284 void FGNasalSys::NasalTimer::timerExpired()
1286 nasal->handleTimer(this);
1290 int FGNasalSys::_listenerId = 0;
1292 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1293 // Attaches a callback function to a property (specified as a global
1294 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1295 // optional argument (default=0) is set to 1, then the function is also
1296 // called initially. If the fourth, optional argument is set to 0, then the
1297 // function is only called when the property node value actually changes.
1298 // Otherwise it's called independent of the value whenever the node is
1299 // written to (default). The setlistener() function returns a unique
1300 // id number, which is to be used as argument to the removelistener()
1302 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1304 SGPropertyNode_ptr node;
1305 naRef prop = argc > 0 ? args[0] : naNil();
1306 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1307 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1309 naRuntimeError(c, "setlistener() with invalid property argument");
1314 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1317 naRef code = argc > 1 ? args[1] : naNil();
1318 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1319 naRuntimeError(c, "setlistener() with invalid function argument");
1323 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1324 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1325 FGNasalListener *nl = new FGNasalListener(node, code, this,
1326 gcSave(code), _listenerId, init, type);
1328 node->addChangeListener(nl, init != 0);
1330 _listener[_listenerId] = nl;
1331 return naNum(_listenerId++);
1334 // removelistener(int) extension function. The argument is the id of
1335 // a listener as returned by the setlistener() function.
1336 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1338 naRef id = argc > 0 ? args[0] : naNil();
1339 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1341 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1342 naRuntimeError(c, "removelistener() with invalid listener id");
1346 it->second->_dead = true;
1347 _dead_listener.push_back(it->second);
1348 _listener.erase(it);
1349 return naNum(_listener.size());
1352 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1354 if( _loadList.empty() )
1356 _loadList.push(data);
1359 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1361 _unloadList.push(data);
1364 void FGNasalSys::addCommand(naRef func, const std::string& name)
1366 if (_commands.find(name) != _commands.end()) {
1367 SG_LOG(SG_NASAL, SG_WARN, "duplicate add of command:" << name);
1371 NasalCommand* cmd = new NasalCommand(this, func, name);
1372 _commands[name] = cmd;
1375 void FGNasalSys::removeCommand(const std::string& name)
1377 NasalCommandDict::iterator it = _commands.find(name);
1378 if (it == _commands.end()) {
1379 SG_LOG(SG_NASAL, SG_WARN, "remove of unknwon command:" << name);
1383 // will delete the NasalCommand instance
1384 globals->get_commands()->removeCommand(name);
1385 _commands.erase(it);
1388 //////////////////////////////////////////////////////////////////////////
1389 // FGNasalListener class.
1391 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1392 FGNasalSys* nasal, int key, int id,
1393 int init, int type) :
1406 if(_type == 0 && !_init)
1410 FGNasalListener::~FGNasalListener()
1412 _node->removeChangeListener(this);
1413 _nas->gcRelease(_gcKey);
1416 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1418 if(_active || _dead) return;
1421 arg[0] = _nas->propNodeGhost(which);
1422 arg[1] = _nas->propNodeGhost(_node);
1423 arg[2] = mode; // value changed, child added/removed
1424 arg[3] = naNum(_node != which); // child event?
1425 _nas->call(_code, 4, arg, naNil());
1429 void FGNasalListener::valueChanged(SGPropertyNode* node)
1431 if(_type < 2 && node != _node) return; // skip child events
1432 if(_type > 0 || changed(_node) || _init)
1433 call(node, naNum(0));
1438 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1440 if(_type == 2) call(child, naNum(1));
1443 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1445 if(_type == 2) call(child, naNum(-1));
1448 bool FGNasalListener::changed(SGPropertyNode* node)
1450 using namespace simgear;
1451 props::Type type = node->getType();
1452 if(type == props::NONE) return false;
1453 if(type == props::UNSPECIFIED) return true;
1461 long l = node->getLongValue();
1462 result = l != _last_int;
1469 double d = node->getDoubleValue();
1470 result = d != _last_float;
1476 string s = node->getStringValue();
1477 result = s != _last_string;
1484 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1486 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1487 _c(naSubContext(c)),
1488 _start_element(argc > 1 ? args[1] : naNil()),
1489 _end_element(argc > 2 ? args[2] : naNil()),
1490 _data(argc > 3 ? args[3] : naNil()),
1491 _pi(argc > 4 ? args[4] : naNil())
1495 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1497 if(naIsNil(_start_element)) return;
1498 naRef attr = naNewHash(_c);
1499 for(int i=0; i<a.size(); i++) {
1500 naRef name = make_string(a.getName(i));
1501 naRef value = make_string(a.getValue(i));
1502 naHash_set(attr, name, value);
1504 call(_start_element, 2, make_string(tag), attr);
1507 void NasalXMLVisitor::endElement(const char* tag)
1509 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1512 void NasalXMLVisitor::data(const char* str, int len)
1514 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1517 void NasalXMLVisitor::pi(const char* target, const char* data)
1519 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1522 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1527 naCall(_c, func, num, args, naNil(), naNil());
1532 naRef NasalXMLVisitor::make_string(const char* s, int n)
1534 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1535 n < 0 ? strlen(s) : n);