10 #ifdef HAVE_SYS_TIME_H
11 # include <sys/time.h> // gettimeofday
17 #include <sys/types.h>
22 #include <simgear/nasal/nasal.h>
23 #include <simgear/nasal/iolib.h>
24 #include <simgear/props/props.hxx>
25 #include <simgear/math/sg_random.h>
26 #include <simgear/misc/sg_path.hxx>
27 #include <simgear/misc/sg_dir.hxx>
28 #include <simgear/misc/SimpleMarkdown.hxx>
29 #include <simgear/structure/commands.hxx>
30 #include <simgear/math/sg_geodesy.hxx>
31 #include <simgear/structure/event_mgr.hxx>
32 #include <simgear/debug/BufferedLogCallback.hxx>
34 #include <simgear/nasal/cppbind/from_nasal.hxx>
35 #include <simgear/nasal/cppbind/to_nasal.hxx>
36 #include <simgear/nasal/cppbind/Ghost.hxx>
37 #include <simgear/nasal/cppbind/NasalHash.hxx>
39 #include "NasalSGPath.hxx"
40 #include "NasalSys.hxx"
41 #include "NasalSys_private.hxx"
42 #include "NasalAircraft.hxx"
43 #include "NasalModelData.hxx"
44 #include "NasalPositioned.hxx"
45 #include "NasalCanvas.hxx"
46 #include "NasalClipboard.hxx"
47 #include "NasalCondition.hxx"
48 #include "NasalHTTP.hxx"
49 #include "NasalString.hxx"
51 #include <Main/globals.hxx>
52 #include <Main/util.hxx>
53 #include <Main/fg_props.hxx>
59 void postinitNasalGUI(naRef globals, naContext c);
61 static FGNasalSys* nasalSys = 0;
63 // Listener class for loading Nasal modules on demand
64 class FGNasalModuleListener : public SGPropertyChangeListener
67 FGNasalModuleListener(SGPropertyNode* node);
69 virtual void valueChanged(SGPropertyNode* node);
72 SGPropertyNode_ptr _node;
75 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
79 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
81 if (_node->getBoolValue("enabled",false)&&
82 !_node->getBoolValue("loaded",true))
84 nasalSys->loadPropertyScripts(_node);
88 //////////////////////////////////////////////////////////////////////////
91 class TimerObj : public SGReferenced
94 TimerObj(FGNasalSys* sys, naRef f, naRef self, double interval) :
103 snprintf(nm, 128, "nasal-timer-%p", this);
105 _gcRoot = sys->gcSave(f);
106 _gcSelf = sys->gcSave(self);
112 _sys->gcRelease(_gcRoot);
113 _sys->gcRelease(_gcSelf);
116 bool isRunning() const { return _isRunning; }
121 globals->get_event_mgr()->removeTask(_name);
134 globals->get_event_mgr()->addEvent(_name, this, &TimerObj::invoke, _interval);
136 globals->get_event_mgr()->addTask(_name, this, &TimerObj::invoke,
137 _interval, _interval /* delay */);
141 // stop and then start -
142 void restart(double newInterval)
144 _interval = newInterval;
152 // Callback may restart the timer, so update status before callback is
153 // called (Prevent warnings of deleting not existing tasks from the
158 _sys->callMethod(_func, _self, 0, args, naNil() /* locals */);
161 void setSingleShot(bool aSingleShot)
163 _singleShot = aSingleShot;
166 bool isSingleShot() const
167 { return _singleShot; }
172 int _gcRoot, _gcSelf;
178 typedef SGSharedPtr<TimerObj> TimerObjRef;
179 typedef nasal::Ghost<TimerObjRef> NasalTimerObj;
181 ///////////////////////////////////////////////////////////////////////////
183 // Read and return file contents in a single buffer. Note use of
184 // stat() to get the file size. This is a win32 function, believe it
185 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
186 // Text mode brain damage will kill us if we're trying to do bytewise
188 static char* readfile(const char* file, int* lenOut)
191 if(stat(file, &data) != 0) return 0;
192 FILE* f = fopen(file, "rb");
194 char* buf = new char[data.st_size];
195 *lenOut = fread(buf, 1, data.st_size, f);
197 if(*lenOut != data.st_size) {
198 // Shouldn't happen, but warn anyway since it represents a
199 // platform bug and not a typical runtime error (missing file,
201 SG_LOG(SG_NASAL, SG_ALERT,
202 "ERROR in Nasal initialization: " <<
203 "short count returned from fread() of " << file <<
204 ". Check your C library!");
211 FGNasalSys::FGNasalSys() :
218 _wrappedNodeFunc = naNil();
220 _log = new simgear::BufferedLogCallback(SG_NASAL, SG_INFO);
221 _log->truncateAt(255);
222 sglog().addCallback(_log);
224 naSetErrorHandler(&logError);
227 // Utility. Sets a named key in a hash by C string, rather than nasal
229 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
231 naRef s = naNewString(_context);
232 naStr_fromdata(s, (char*)key, strlen(key));
233 naHash_set(hash, s, val);
236 void FGNasalSys::globalsSet(const char* key, naRef val)
238 hashset(_globals, key, val);
241 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
243 return callMethod(code, naNil(), argc, args, locals);
246 naRef FGNasalSys::callWithContext(naContext ctx, naRef code, int argc, naRef* args, naRef locals)
248 return callMethodWithContext(ctx, code, naNil(), argc, args, locals);
251 // Does a naCall() in a new context. Wrapped here to make lock
252 // tracking easier. Extension functions are called with the lock, but
253 // we have to release it before making a new naCall(). So rather than
254 // drop the lock in every extension function that might call back into
255 // Nasal, we keep a stack depth counter here and only unlock/lock
256 // around the naCall if it isn't the first one.
258 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
260 return naCallMethod(code, self, argc, args, locals);
263 naRef FGNasalSys::callMethodWithContext(naContext ctx, naRef code, naRef self, int argc, naRef* args, naRef locals)
265 return naCallMethodCtx(ctx, code, self, argc, args, locals);
268 FGNasalSys::~FGNasalSys()
271 SG_LOG(SG_GENERAL, SG_ALERT, "Nasal was not shutdown");
276 bool FGNasalSys::parseAndRun(const char* sourceCode)
278 naContext ctx = naNewContext();
279 naRef code = parse(ctx, "FGNasalSys::parseAndRun()", sourceCode,
285 callWithContext(ctx, code, 0, 0, naNil());
291 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
293 FGNasalScript* script = new FGNasalScript();
294 script->_gcKey = -1; // important, if we delete it on a parse
295 script->_nas = this; // error, don't clobber a real handle!
299 sprintf(buf, "FGNasalScript@%p", (void *)script);
303 script->_code = parse(name, src, strlen(src));
304 if(naIsNil(script->_code)) {
309 script->_gcKey = gcSave(script->_code);
314 // The get/setprop functions accept a *list* of strings and walk
315 // through the property tree with them to find the appropriate node.
316 // This allows a Nasal object to hold onto a property path and use it
317 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
318 // is the utility function that walks the property tree.
319 static SGPropertyNode* findnode(naContext c, naRef* vec, int len, bool create=false)
321 SGPropertyNode* p = globals->get_props();
323 for(int i=0; i<len; i++) {
326 naRuntimeError(c, "bad argument to setprop/getprop path: expected a string");
328 naRef b = i < len-1 ? naNumValue(vec[i+1]) : naNil();
330 p = p->getNode(naStr_data(a), (int)b.num, create);
333 p = p->getNode(naStr_data(a), create);
337 } catch (const string& err) {
338 naRuntimeError(c, (char *)err.c_str());
343 // getprop() extension function. Concatenates its string arguments as
344 // property names and returns the value of the specified property. Or
345 // nil if it doesn't exist.
346 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
348 using namespace simgear;
350 naRuntimeError(c, "getprop() expects at least 1 argument");
352 const SGPropertyNode* p = findnode(c, args, argc, false);
353 if(!p) return naNil();
355 switch(p->getType()) {
356 case props::BOOL: case props::INT:
357 case props::LONG: case props::FLOAT:
360 double dv = p->getDoubleValue();
361 if (SGMisc<double>::isNaN(dv)) {
362 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
370 case props::UNSPECIFIED:
372 naRef nastr = naNewString(c);
373 const char* val = p->getStringValue();
374 naStr_fromdata(nastr, (char*)val, strlen(val));
377 case props::ALIAS: // <--- FIXME, recurse?
383 // setprop() extension function. Concatenates its string arguments as
384 // property names and sets the value of the specified property to the
386 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
389 naRuntimeError(c, "setprop() expects at least 2 arguments");
391 naRef val = args[argc - 1];
392 SGPropertyNode* p = findnode(c, args, argc-1, true);
396 if(naIsString(val)) result = p->setStringValue(naStr_data(val));
399 naRuntimeError(c, "setprop() value is not string or number");
401 if (SGMisc<double>::isNaN(val.num)) {
402 naRuntimeError(c, "setprop() passed a NaN");
405 result = p->setDoubleValue(val.num);
407 } catch (const string& err) {
408 naRuntimeError(c, (char *)err.c_str());
410 return naNum(result);
413 // print() extension function. Concatenates and prints its arguments
414 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
415 // make sure it appears. Is there better way to do this?
416 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
420 for(int i=0; i<n; i++) {
421 naRef s = naStringValue(c, args[i]);
422 if(naIsNil(s)) continue;
423 buf += naStr_data(s);
425 SG_LOG(SG_NASAL, SG_ALERT, buf);
426 return naNum(buf.length());
429 // logprint() extension function. Same as above, all arguments after the
430 // first argument are concatenated. Argument 0 is the log-level, matching
432 static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
435 naRuntimeError(c, "no prioirty argument to logprint()");
437 naRef priority = args[0];
440 for(int i=1; i<n; i++) {
441 naRef s = naStringValue(c, args[i]);
442 if(naIsNil(s)) continue;
443 buf += naStr_data(s);
445 // use the nasal source file and line for the message location, since
446 // that's more useful than the location here!
447 sglog().log(SG_NASAL, (sgDebugPriority)(int) priority.num,
448 naStr_data(naGetSourceFile(c, 0)),
449 naGetLine(c, 0), buf);
450 return naNum(buf.length());
454 // fgcommand() extension function. Executes a named command via the
455 // FlightGear command manager. Takes a single property node name as
457 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
459 naRef cmd = argc > 0 ? args[0] : naNil();
460 naRef props = argc > 1 ? args[1] : naNil();
461 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
462 naRuntimeError(c, "bad arguments to fgcommand()");
463 SGPropertyNode_ptr node;
465 node = static_cast<SGPropertyNode*>(naGhost_ptr(props));
467 node = new SGPropertyNode;
469 return naNum(globals->get_commands()->execute(naStr_data(cmd), node));
472 // settimer(func, dt, simtime) extension function. Falls through to
473 // FGNasalSys::setTimer(). See there for docs.
474 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
476 nasalSys->setTimer(c, argc, args);
480 static naRef f_makeTimer(naContext c, naRef me, int argc, naRef* args)
482 if (!naIsNum(args[0])) {
483 naRuntimeError(c, "bad interval argument to maketimer");
486 naRef func, self = naNil();
487 if (naIsFunc(args[1])) {
489 } else if ((argc == 3) && naIsFunc(args[2])) {
494 TimerObj* timerObj = new TimerObj(nasalSys, func, self, args[0].num);
495 return nasal::to_nasal(c, timerObj);
498 // setlistener(func, property, bool) extension function. Falls through to
499 // FGNasalSys::setListener(). See there for docs.
500 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
502 return nasalSys->setListener(c, argc, args);
505 // removelistener(int) extension function. Falls through to
506 // FGNasalSys::removeListener(). See there for docs.
507 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
509 return nasalSys->removeListener(c, argc, args);
512 // Returns a ghost handle to the argument to the currently executing
514 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
516 return nasalSys->cmdArgGhost();
519 // Sets up a property interpolation. The first argument is either a
520 // ghost (SGPropertyNode*) or a string (global property path) to
521 // interpolate. The second argument is a vector of pairs of
522 // value/delta numbers.
523 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
525 SGPropertyNode* node;
526 naRef prop = argc > 0 ? args[0] : naNil();
527 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
528 else if(naIsGhost(prop)) node = static_cast<SGPropertyNode*>(naGhost_ptr(prop));
531 naRef curve = argc > 1 ? args[1] : naNil();
532 if(!naIsVector(curve)) return naNil();
533 int nPoints = naVec_size(curve) / 2;
535 simgear::PropertyList value_nodes;
536 value_nodes.reserve(nPoints);
538 deltas.reserve(nPoints);
540 for( int i = 0; i < nPoints; ++i )
542 SGPropertyNode* val = new SGPropertyNode;
543 val->setDoubleValue(naNumValue(naVec_get(curve, 2*i)).num);
544 value_nodes.push_back(val);
545 deltas.push_back(naNumValue(naVec_get(curve, 2*i+1)).num);
548 node->interpolate("numeric", value_nodes, deltas, "linear");
552 // This is a better RNG than the one in the default Nasal distribution
553 // (which is based on the C library rand() implementation). It will
555 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
557 return naNum(sg_random());
560 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
566 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
572 // Return an array listing of all files in a directory
573 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
575 if(argc != 1 || !naIsString(args[0]))
576 naRuntimeError(c, "bad arguments to directory()");
578 simgear::Dir d(SGPath(naStr_data(args[0])));
579 if(!d.exists()) return naNil();
580 naRef result = naNewVector(c);
582 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
583 for (unsigned int i=0; i<paths.size(); ++i) {
584 std::string p = paths[i].file();
585 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
592 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
594 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
596 if(argc != 1 || !naIsString(args[0]))
597 naRuntimeError(c, "bad arguments to resolveDataPath()");
599 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
600 const char* pdata = p.c_str();
601 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
604 static naRef f_findDataDir(naContext c, naRef me, int argc, naRef* args)
606 if(argc != 1 || !naIsString(args[0]))
607 naRuntimeError(c, "bad arguments to findDataDir()");
609 SGPath p = globals->find_data_dir(naStr_data(args[0]));
610 const char* pdata = p.c_str();
611 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
614 class NasalCommand : public SGCommandMgr::Command
617 NasalCommand(FGNasalSys* sys, naRef f, const std::string& name) :
622 globals->get_commands()->addCommandObject(_name, this);
623 _gcRoot = sys->gcSave(f);
626 virtual ~NasalCommand()
628 _sys->gcRelease(_gcRoot);
631 virtual bool operator()(const SGPropertyNode* aNode)
633 _sys->setCmdArg(const_cast<SGPropertyNode*>(aNode));
635 args[0] = _sys->wrappedPropsNode(const_cast<SGPropertyNode*>(aNode));
637 _sys->callMethod(_func, naNil(), 1, args, naNil() /* locals */);
649 static naRef f_addCommand(naContext c, naRef me, int argc, naRef* args)
651 if(argc != 2 || !naIsString(args[0]) || !naIsFunc(args[1]))
652 naRuntimeError(c, "bad arguments to addcommand()");
654 nasalSys->addCommand(args[1], naStr_data(args[0]));
658 static naRef f_removeCommand(naContext c, naRef me, int argc, naRef* args)
660 if ((argc < 1) || !naIsString(args[0]))
661 naRuntimeError(c, "bad argument to removecommand()");
663 globals->get_commands()->removeCommand(naStr_data(args[0]));
667 static naRef f_open(naContext c, naRef me, int argc, naRef* args)
670 naRef file = argc > 0 ? naStringValue(c, args[0]) : naNil();
671 naRef mode = argc > 1 ? naStringValue(c, args[1]) : naNil();
672 if(!naStr_data(file)) naRuntimeError(c, "bad argument to open()");
673 const char* modestr = naStr_data(mode) ? naStr_data(mode) : "rb";
674 std::string filename = fgValidatePath(naStr_data(file),
675 strcmp(modestr, "rb") && strcmp(modestr, "r"));
676 if(filename.empty()) {
677 naRuntimeError(c, "open(): reading/writing '%s' denied "
678 "(unauthorized access)", naStr_data(file));
681 f = fopen(filename.c_str(), modestr);
682 if(!f) naRuntimeError(c, strerror(errno));
683 return naIOGhost(c, f);
687 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
689 // <path> ... absolute path to an XML file
690 // <start-tag> ... callback function with two args: tag name, attribute hash
691 // <end-tag> ... callback function with one arg: tag name
692 // <data> ... callback function with one arg: data
693 // <pi> ... callback function with two args: target, data
694 // (pi = "processing instruction")
695 // All four callback functions are optional and default to nil.
696 // The function returns nil on error, or the validated file name otherwise.
697 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
699 if(argc < 1 || !naIsString(args[0]))
700 naRuntimeError(c, "parsexml(): path argument missing or not a string");
701 if(argc > 5) argc = 5;
702 for(int i=1; i<argc; i++)
703 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
704 naRuntimeError(c, "parsexml(): callback argument not a function");
706 const char* file = fgValidatePath(naStr_data(args[0]), false);
708 naRuntimeError(c, "parsexml(): reading '%s' denied "
709 "(unauthorized access)", naStr_data(args[0]));
712 std::ifstream input(file);
713 NasalXMLVisitor visitor(c, argc, args);
715 readXML(input, visitor);
716 } catch (const sg_exception& e) {
717 naRuntimeError(c, "parsexml(): file '%s' %s",
718 file, e.getFormattedMessage().c_str());
721 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
725 * Parse very simple and small subset of markdown
727 * parse_markdown(src)
729 static naRef f_parse_markdown(naContext c, naRef me, int argc, naRef* args)
731 nasal::CallContext ctx(c, me, argc, args);
733 simgear::SimpleMarkdown::parse(ctx.requireArg<std::string>(0))
738 * Create md5 hash from given string
742 static naRef f_md5(naContext c, naRef me, int argc, naRef* args)
744 if( argc != 1 || !naIsString(args[0]) )
745 naRuntimeError(c, "md5(): wrong type or number of arguments");
747 return nasal::to_nasal(
749 simgear::strutils::md5(naStr_data(args[0]), naStr_len(args[0]))
753 // Return UNIX epoch time in seconds.
754 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
758 GetSystemTimeAsFileTime(&ft);
759 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
760 // Converts from 100ns units in 1601 epoch to unix epoch in sec
761 return naNum((t * 1e-7) - 11644473600.0);
764 gettimeofday(&td, 0);
765 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
769 // Table of extension functions. Terminate with zeros.
770 static struct { const char* name; naCFunction func; } funcs[] = {
771 { "getprop", f_getprop },
772 { "setprop", f_setprop },
773 { "print", f_print },
774 { "logprint", f_logprint },
775 { "_fgcommand", f_fgcommand },
776 { "settimer", f_settimer },
777 { "maketimer", f_makeTimer },
778 { "_setlistener", f_setlistener },
779 { "removelistener", f_removelistener },
780 { "addcommand", f_addCommand },
781 { "removecommand", f_removeCommand },
782 { "_cmdarg", f_cmdarg },
783 { "_interpolate", f_interpolate },
785 { "srand", f_srand },
786 { "abort", f_abort },
787 { "directory", f_directory },
788 { "resolvepath", f_resolveDataPath },
789 { "finddata", f_findDataDir },
790 { "parsexml", f_parsexml },
791 { "parse_markdown", f_parse_markdown },
793 { "systime", f_systime },
797 naRef FGNasalSys::cmdArgGhost()
799 return propNodeGhost(_cmdArg);
802 void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
807 void FGNasalSys::init()
810 SG_LOG(SG_GENERAL, SG_ALERT, "duplicate init of Nasal");
814 _context = naNewContext();
816 // Start with globals. Add it to itself as a recursive
817 // sub-reference under the name "globals". This gives client-code
818 // write access to the namespace if someone wants to do something
820 _globals = naInit_std(_context);
821 naSave(_context, _globals);
822 hashset(_globals, "globals", _globals);
824 hashset(_globals, "math", naInit_math(_context));
825 hashset(_globals, "bits", naInit_bits(_context));
826 hashset(_globals, "io", naInit_io(_context));
827 hashset(_globals, "thread", naInit_thread(_context));
828 hashset(_globals, "utf8", naInit_utf8(_context));
830 // Add our custom extension functions:
831 for(i=0; funcs[i].name; i++)
832 hashset(_globals, funcs[i].name,
833 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
834 nasal::Hash io_module = nasal::Hash(_globals, _context).get<nasal::Hash>("io");
835 io_module.set("open", f_open);
837 // And our SGPropertyNode wrapper
838 hashset(_globals, "props", genPropsModule());
840 // Add string methods
841 _string = naInit_string(_context);
842 naSave(_context, _string);
843 initNasalString(_globals, _string, _context);
845 initNasalPositioned(_globals, _context);
846 initNasalPositioned_cppbind(_globals, _context);
847 initNasalAircraft(_globals, _context);
848 NasalClipboard::init(this);
849 initNasalCanvas(_globals, _context);
850 initNasalCondition(_globals, _context);
851 initNasalHTTP(_globals, _context);
852 initNasalSGPath(_globals, _context);
854 NasalTimerObj::init("Timer")
855 .method("start", &TimerObj::start)
856 .method("stop", &TimerObj::stop)
857 .method("restart", &TimerObj::restart)
858 .member("singleShot", &TimerObj::isSingleShot, &TimerObj::setSingleShot)
859 .member("isRunning", &TimerObj::isRunning);
861 // Set allowed paths for Nasal I/O
862 fgInitAllowedPaths();
864 // Now load the various source files in the Nasal directory
865 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
866 loadScriptDirectory(nasalDir);
868 // Add modules in Nasal subdirectories to property tree
869 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
870 simgear::Dir::NO_DOT_OR_DOTDOT, "");
871 for (unsigned int i=0; i<directories.size(); ++i) {
872 simgear::Dir dir(directories[i]);
873 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
874 addModule(directories[i].file(), scripts);
877 // set signal and remove node to avoid restoring at reinit
878 const char *s = "nasal-dir-initialized";
879 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
880 signal->setBoolValue(s, true);
881 signal->removeChildren(s);
883 if( !checkIOrules() )
885 SG_LOG(SG_NASAL, SG_ALERT, "Required IOrules check failed.");
889 // Pull scripts out of the property tree, too
890 loadPropertyScripts();
892 // now Nasal modules are loaded, we can do some delayed work
893 postinitNasalPositioned(_globals, _context);
894 postinitNasalGUI(_globals, _context);
899 void FGNasalSys::shutdown()
905 shutdownNasalPositioned();
907 map<int, FGNasalListener *>::iterator it, end = _listener.end();
908 for(it = _listener.begin(); it != end; ++it)
912 NasalCommandDict::iterator j = _commands.begin();
913 for (; j != _commands.end(); ++j) {
914 globals->get_commands()->removeCommand(j->first);
918 std::vector<FGNasalModuleListener*>::iterator k = _moduleListeners.begin();
919 for(; k!= _moduleListeners.end(); ++k)
921 _moduleListeners.clear();
925 _string = naNil(); // will be freed by _context
926 naFreeContext(_context);
928 //setWatchedRef(_globals);
930 // remove the recursive reference in globals
931 hashset(_globals, "globals", naNil());
938 naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps)
940 if (naIsNil(_wrappedNodeFunc)) {
941 nasal::Hash props = getGlobals().get<nasal::Hash>("props");
942 _wrappedNodeFunc = props.get("wrapNode");
946 args[0] = propNodeGhost(aProps);
947 naContext ctx = naNewContext();
948 naRef wrapped = naCallMethodCtx(ctx, _wrappedNodeFunc, naNil(), 1, args, naNil());
953 void FGNasalSys::update(double)
955 if( NasalClipboard::getInstance() )
956 NasalClipboard::getInstance()->update();
958 if(!_dead_listener.empty()) {
959 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
960 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
961 _dead_listener.clear();
964 if (!_loadList.empty())
969 // process Nasal load hook (only one per update loop to avoid excessive lags)
970 _loadList.pop()->load();
973 if (!_unloadList.empty())
975 // process pending Nasal unload hooks after _all_ load hooks were processed
976 // (only unload one per update loop to avoid excessive lags)
977 _unloadList.pop()->unload();
980 // Destroy all queued ghosts
981 nasal::ghostProcessDestroyList();
983 // The global context is a legacy thing. We use dynamically
984 // created contexts for naCall() now, so that we can call them
985 // recursively. But there are still spots that want to use it for
986 // naNew*() calls, which end up leaking memory because the context
987 // only clears out its temporary vector when it's *used*. So just
988 // junk it and fetch a new/reinitialized one every frame. This is
989 // clumsy: the right solution would use the dynamic context in all
990 // cases and eliminate _context entirely. But that's more work,
991 // and this works fine (yes, they say "New" and "Free", but
992 // they're very fast, just trust me). -Andy
993 naFreeContext(_context);
994 _context = naNewContext();
997 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
999 return p1.file() < p2.file();
1002 // Loads all scripts in given directory
1003 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
1005 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
1006 // Note: simgear::Dir already reports file entries in a deterministic order,
1007 // so a fixed loading sequence is guaranteed (same for every user)
1008 for (unsigned int i=0; i<scripts.size(); ++i) {
1009 SGPath fullpath(scripts[i]);
1010 SGPath file = fullpath.file();
1011 loadModule(fullpath, file.base().c_str());
1015 // Create module with list of scripts
1016 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
1018 if (! scripts.empty())
1020 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
1021 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
1022 for (unsigned int i=0; i<scripts.size(); ++i) {
1023 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
1024 pFileNode->setStringValue(scripts[i].c_str());
1026 if (!module_node->hasChild("enabled",0))
1028 SGPropertyNode* node = module_node->getChild("enabled",0,true);
1029 node->setBoolValue(true);
1030 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
1035 // Loads the scripts found under /nasal in the global tree
1036 void FGNasalSys::loadPropertyScripts()
1038 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
1041 for(int i=0; i<nasal->nChildren(); i++)
1043 SGPropertyNode* n = nasal->getChild(i);
1044 loadPropertyScripts(n);
1048 // Loads the scripts found under /nasal in the global tree
1049 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
1051 bool is_loaded = false;
1053 const char* module = n->getName();
1054 if(n->hasChild("module"))
1055 module = n->getStringValue("module");
1056 if (n->getBoolValue("enabled",true))
1058 // allow multiple files to be specified within a single
1062 bool file_specified = false;
1064 while((fn = n->getChild("file", j)) != NULL) {
1065 file_specified = true;
1066 const char* file = fn->getStringValue();
1068 if (!p.isAbsolute() || !p.exists())
1070 p = globals->resolve_maybe_aircraft_path(file);
1073 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
1074 file << "' for module '" << module << "'.");
1077 ok &= p.isNull() ? false : loadModule(p, module);
1081 const char* src = n->getStringValue("script");
1082 if(!n->hasChild("script")) src = 0; // Hrm...
1084 createModule(module, n->getPath().c_str(), src, strlen(src));
1086 if(!file_specified && !src)
1088 // module no longer exists - clear the archived "enable" flag
1089 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
1090 SGPropertyNode* node = n->getChild("enabled",0,false);
1092 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
1094 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
1095 "no <file> or <script> defined in " <<
1096 "/nasal/" << module);
1103 SGPropertyNode* enable = n->getChild("enabled");
1106 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
1107 _moduleListeners.push_back(listener);
1108 enable->addChangeListener(listener, false);
1111 SGPropertyNode* loaded = n->getChild("loaded",0,true);
1112 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
1113 loaded->setBoolValue(is_loaded);
1116 // Logs a runtime error, with stack trace, to the FlightGear log stream
1117 void FGNasalSys::logError(naContext context)
1119 SG_LOG(SG_NASAL, SG_ALERT, "Nasal runtime error: " << naGetError(context));
1120 int stack_depth = naStackDepth(context);
1121 if( stack_depth < 1 )
1123 SG_LOG(SG_NASAL, SG_ALERT,
1124 " at " << naStr_data(naGetSourceFile(context, 0)) <<
1125 ", line " << naGetLine(context, 0));
1126 for(int i=1; i<stack_depth; i++)
1127 SG_LOG(SG_NASAL, SG_ALERT,
1128 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
1129 ", line " << naGetLine(context, i));
1132 // Reads a script file, executes it, and places the resulting
1133 // namespace into the global namespace under the specified module
1135 bool FGNasalSys::loadModule(SGPath file, const char* module)
1138 char* buf = readfile(file.c_str(), &len);
1140 SG_LOG(SG_NASAL, SG_ALERT,
1141 "Nasal error: could not read script file " << file.c_str()
1142 << " into module " << module);
1146 bool ok = createModule(module, file.c_str(), buf, len);
1151 // Parse and run. Save the local variables namespace, as it will
1152 // become a sub-object of globals. The optional "arg" argument can be
1153 // used to pass an associated property node to the module, which can then
1154 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
1155 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1156 const char* src, int len,
1157 const SGPropertyNode* cmdarg,
1158 int argc, naRef* args)
1160 naContext ctx = naNewContext();
1161 naRef code = parse(ctx, fileName, src, len);
1168 // See if we already have a module hash to use. This allows the
1169 // user to, for example, add functions to the built-in math
1170 // module. Make a new one if necessary.
1172 naRef modname = naNewString(ctx);
1173 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1174 if(!naHash_get(_globals, modname, &locals))
1175 locals = naNewHash(ctx);
1177 _cmdArg = (SGPropertyNode*)cmdarg;
1179 callWithContext(ctx, code, argc, args, locals);
1180 hashset(_globals, moduleName, locals);
1186 void FGNasalSys::deleteModule(const char* moduleName)
1189 // can occur on shutdown due to us being shutdown first, but other
1190 // subsystems having Nasal objects.
1194 naContext ctx = naNewContext();
1195 naRef modname = naNewString(ctx);
1196 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1197 naHash_delete(_globals, modname);
1201 naRef FGNasalSys::parse(naContext ctx, const char* filename, const char* buf, int len)
1204 naRef srcfile = naNewString(ctx);
1205 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1206 naRef code = naParseCode(ctx, srcfile, 1, (char*)buf, len, &errLine);
1208 SG_LOG(SG_NASAL, SG_ALERT,
1209 "Nasal parse error: " << naGetError(ctx) <<
1210 " in "<< filename <<", line " << errLine);
1214 // Bind to the global namespace before returning
1215 return naBindFunction(ctx, code, _globals);
1218 bool FGNasalSys::handleCommand( const char* moduleName,
1219 const char* fileName,
1221 const SGPropertyNode* arg )
1223 naContext ctx = naNewContext();
1224 naRef code = parse(ctx, fileName, src, strlen(src));
1230 // Commands can be run "in" a module. Make sure that module
1231 // exists, and set it up as the local variables hash for the
1233 naRef locals = naNil();
1235 naRef modname = naNewString(ctx);
1236 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1237 if(!naHash_get(_globals, modname, &locals)) {
1238 locals = naNewHash(ctx);
1239 naHash_set(_globals, modname, locals);
1243 // Cache this command's argument for inspection via cmdarg(). For
1244 // performance reasons, we won't bother with it if the invoked
1245 // code doesn't need it.
1246 _cmdArg = (SGPropertyNode*)arg;
1248 callWithContext(ctx, code, 0, 0, locals);
1253 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1255 const char* src = arg->getStringValue("script");
1256 const char* moduleName = arg->getStringValue("module");
1258 return handleCommand( moduleName,
1259 arg->getPath(true).c_str(),
1264 // settimer(func, dt, simtime) extension function. The first argument
1265 // is a Nasal function to call, the second is a delta time (from now),
1266 // in seconds. The third, if present, is a boolean value indicating
1267 // that "real world" time (rather than simulator time) is to be used.
1269 // Implementation note: the FGTimer objects don't live inside the
1270 // garbage collector, so the Nasal handler functions have to be
1271 // "saved" somehow lest they be inadvertently cleaned. In this case,
1272 // they are inserted into a globals.__gcsave hash and removed on
1274 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1276 // Extract the handler, delta, and simtime arguments:
1277 naRef handler = argc > 0 ? args[0] : naNil();
1278 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1279 naRuntimeError(c, "settimer() with invalid function argument");
1283 naRef delta = argc > 1 ? args[1] : naNil();
1284 if(naIsNil(delta)) {
1285 naRuntimeError(c, "settimer() with invalid time argument");
1289 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1291 // Generate and register a C++ timer handler
1292 NasalTimer* t = new NasalTimer;
1293 t->handler = handler;
1294 t->gcKey = gcSave(handler);
1297 globals->get_event_mgr()->addEvent("NasalTimer",
1298 t, &NasalTimer::timerExpired,
1299 delta.num, simtime);
1302 void FGNasalSys::handleTimer(NasalTimer* t)
1304 call(t->handler, 0, 0, naNil());
1305 gcRelease(t->gcKey);
1308 int FGNasalSys::gcSave(naRef r)
1313 void FGNasalSys::gcRelease(int key)
1318 //------------------------------------------------------------------------------
1319 bool FGNasalSys::checkIOrules()
1321 // Ensure IOrules and path validation are working properly by trying to
1322 // access a folder/file which should never be accessible.
1323 const char* no_access_path =
1329 bool success = true;
1332 if( fgValidatePath(no_access_path, true) )
1339 "Check your IOrules! (write to '" << no_access_path << "' is allowed)"
1344 if( fgValidatePath(no_access_path, false) )
1351 "Check your IOrules! (read from '" << no_access_path << "' is allowed)"
1358 //------------------------------------------------------------------------------
1359 void FGNasalSys::NasalTimer::timerExpired()
1361 nasal->handleTimer(this);
1365 int FGNasalSys::_listenerId = 0;
1367 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1368 // Attaches a callback function to a property (specified as a global
1369 // property path string or a SGPropertyNode* ghost). If the third,
1370 // optional argument (default=0) is set to 1, then the function is also
1371 // called initially. If the fourth, optional argument is set to 0, then the
1372 // function is only called when the property node value actually changes.
1373 // Otherwise it's called independent of the value whenever the node is
1374 // written to (default). The setlistener() function returns a unique
1375 // id number, which is to be used as argument to the removelistener()
1377 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1379 SGPropertyNode_ptr node;
1380 naRef prop = argc > 0 ? args[0] : naNil();
1381 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1382 else if(naIsGhost(prop)) node = static_cast<SGPropertyNode*>(naGhost_ptr(prop));
1384 naRuntimeError(c, "setlistener() with invalid property argument");
1389 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1392 naRef code = argc > 1 ? args[1] : naNil();
1393 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1394 naRuntimeError(c, "setlistener() with invalid function argument");
1398 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1399 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1400 FGNasalListener *nl = new FGNasalListener(node, code, this,
1401 gcSave(code), _listenerId, init, type);
1403 node->addChangeListener(nl, init != 0);
1405 _listener[_listenerId] = nl;
1406 return naNum(_listenerId++);
1409 // removelistener(int) extension function. The argument is the id of
1410 // a listener as returned by the setlistener() function.
1411 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1413 naRef id = argc > 0 ? args[0] : naNil();
1414 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1416 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1417 naRuntimeError(c, "removelistener() with invalid listener id");
1421 it->second->_dead = true;
1422 _dead_listener.push_back(it->second);
1423 _listener.erase(it);
1424 return naNum(_listener.size());
1427 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1429 if( _loadList.empty() )
1431 _loadList.push(data);
1434 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1436 _unloadList.push(data);
1439 void FGNasalSys::addCommand(naRef func, const std::string& name)
1441 if (_commands.find(name) != _commands.end()) {
1442 SG_LOG(SG_NASAL, SG_WARN, "duplicate add of command:" << name);
1446 NasalCommand* cmd = new NasalCommand(this, func, name);
1447 _commands[name] = cmd;
1450 void FGNasalSys::removeCommand(const std::string& name)
1452 NasalCommandDict::iterator it = _commands.find(name);
1453 if (it == _commands.end()) {
1454 SG_LOG(SG_NASAL, SG_WARN, "remove of unknwon command:" << name);
1458 // will delete the NasalCommand instance
1459 globals->get_commands()->removeCommand(name);
1460 _commands.erase(it);
1463 //////////////////////////////////////////////////////////////////////////
1464 // FGNasalListener class.
1466 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1467 FGNasalSys* nasal, int key, int id,
1468 int init, int type) :
1481 if(_type == 0 && !_init)
1485 FGNasalListener::~FGNasalListener()
1487 _node->removeChangeListener(this);
1488 _nas->gcRelease(_gcKey);
1491 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1493 if(_active || _dead) return;
1496 arg[0] = _nas->propNodeGhost(which);
1497 arg[1] = _nas->propNodeGhost(_node);
1498 arg[2] = mode; // value changed, child added/removed
1499 arg[3] = naNum(_node != which); // child event?
1500 _nas->call(_code, 4, arg, naNil());
1504 void FGNasalListener::valueChanged(SGPropertyNode* node)
1506 if(_type < 2 && node != _node) return; // skip child events
1507 if(_type > 0 || changed(_node) || _init)
1508 call(node, naNum(0));
1513 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1515 if(_type == 2) call(child, naNum(1));
1518 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1520 if(_type == 2) call(child, naNum(-1));
1523 bool FGNasalListener::changed(SGPropertyNode* node)
1525 using namespace simgear;
1526 props::Type type = node->getType();
1527 if(type == props::NONE) return false;
1528 if(type == props::UNSPECIFIED) return true;
1536 long l = node->getLongValue();
1537 result = l != _last_int;
1544 double d = node->getDoubleValue();
1545 result = d != _last_float;
1551 string s = node->getStringValue();
1552 result = s != _last_string;
1559 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1561 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1562 _c(naSubContext(c)),
1563 _start_element(argc > 1 ? args[1] : naNil()),
1564 _end_element(argc > 2 ? args[2] : naNil()),
1565 _data(argc > 3 ? args[3] : naNil()),
1566 _pi(argc > 4 ? args[4] : naNil())
1570 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1572 if(naIsNil(_start_element)) return;
1573 naRef attr = naNewHash(_c);
1574 for(int i=0; i<a.size(); i++) {
1575 naRef name = make_string(a.getName(i));
1576 naRef value = make_string(a.getValue(i));
1577 naHash_set(attr, name, value);
1579 call(_start_element, 2, make_string(tag), attr);
1582 void NasalXMLVisitor::endElement(const char* tag)
1584 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1587 void NasalXMLVisitor::data(const char* str, int len)
1589 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1592 void NasalXMLVisitor::pi(const char* target, const char* data)
1594 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1597 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1602 naCall(_c, func, num, args, naNil(), naNil());
1607 naRef NasalXMLVisitor::make_string(const char* s, int n)
1609 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1610 n < 0 ? strlen(s) : n);