console.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "platform/platformTLS.h"
  24. #include "platform/threads/thread.h"
  25. #include "console/console.h"
  26. #include "console/consoleInternal.h"
  27. #include "console/consoleObject.h"
  28. #include "console/consoleParser.h"
  29. #include "core/stream/fileStream.h"
  30. #include "console/ast.h"
  31. #include "core/tAlgorithm.h"
  32. #include "console/consoleTypes.h"
  33. #include "console/telnetDebugger.h"
  34. #include "console/simBase.h"
  35. #include "console/compiler.h"
  36. #include "console/stringStack.h"
  37. #include "console/ICallMethod.h"
  38. #include "console/engineAPI.h"
  39. #include <stdarg.h>
  40. #include "platform/threads/mutex.h"
  41. extern StringStack STR;
  42. extern ConsoleValueStack CSTK;
  43. ConsoleDocFragment* ConsoleDocFragment::smFirst;
  44. ExprEvalState gEvalState;
  45. StmtNode *gStatementList;
  46. StmtNode *gAnonFunctionList;
  47. U32 gAnonFunctionID = 0;
  48. ConsoleConstructor *ConsoleConstructor::first = NULL;
  49. bool gWarnUndefinedScriptVariables;
  50. static char scratchBuffer[4096];
  51. CON_DECLARE_PARSER(CMD);
  52. static const char * prependDollar ( const char * name )
  53. {
  54. if(name[0] != '$')
  55. {
  56. S32 len = dStrlen(name);
  57. AssertFatal(len < sizeof(scratchBuffer)-2, "CONSOLE: name too long");
  58. scratchBuffer[0] = '$';
  59. dMemcpy(scratchBuffer + 1, name, len + 1);
  60. name = scratchBuffer;
  61. }
  62. return name;
  63. }
  64. static const char * prependPercent ( const char * name )
  65. {
  66. if(name[0] != '%')
  67. {
  68. S32 len = dStrlen(name);
  69. AssertFatal(len < sizeof(scratchBuffer)-2, "CONSOLE: name too long");
  70. scratchBuffer[0] = '%';
  71. dMemcpy(scratchBuffer + 1, name, len + 1);
  72. name = scratchBuffer;
  73. }
  74. return name;
  75. }
  76. //--------------------------------------
  77. void ConsoleConstructor::init( const char *cName, const char *fName, const char *usg, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  78. {
  79. mina = minArgs;
  80. maxa = maxArgs;
  81. funcName = fName;
  82. usage = usg;
  83. className = cName;
  84. sc = 0; fc = 0; vc = 0; bc = 0; ic = 0;
  85. callback = group = false;
  86. next = first;
  87. ns = false;
  88. first = this;
  89. toolOnly = isToolOnly;
  90. this->header = header;
  91. }
  92. void ConsoleConstructor::setup()
  93. {
  94. for(ConsoleConstructor *walk = first; walk; walk = walk->next)
  95. {
  96. #ifdef TORQUE_DEBUG
  97. walk->validate();
  98. #endif
  99. if( walk->sc )
  100. Con::addCommand( walk->className, walk->funcName, walk->sc, walk->usage, walk->mina, walk->maxa, walk->toolOnly, walk->header );
  101. else if( walk->ic )
  102. Con::addCommand( walk->className, walk->funcName, walk->ic, walk->usage, walk->mina, walk->maxa, walk->toolOnly, walk->header );
  103. else if( walk->fc )
  104. Con::addCommand( walk->className, walk->funcName, walk->fc, walk->usage, walk->mina, walk->maxa, walk->toolOnly, walk->header );
  105. else if( walk->vc )
  106. Con::addCommand( walk->className, walk->funcName, walk->vc, walk->usage, walk->mina, walk->maxa, walk->toolOnly, walk->header );
  107. else if( walk->bc )
  108. Con::addCommand( walk->className, walk->funcName, walk->bc, walk->usage, walk->mina, walk->maxa, walk->toolOnly, walk->header );
  109. else if( walk->group )
  110. Con::markCommandGroup( walk->className, walk->funcName, walk->usage );
  111. else if( walk->callback )
  112. Con::noteScriptCallback( walk->className, walk->funcName, walk->usage, walk->header );
  113. else if( walk->ns )
  114. {
  115. Namespace* ns = Namespace::find( StringTable->insert( walk->className ) );
  116. if( ns )
  117. ns->mUsage = walk->usage;
  118. }
  119. else
  120. {
  121. AssertISV( false, "Found a ConsoleConstructor with an indeterminate type!" );
  122. }
  123. }
  124. }
  125. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, StringCallback sfunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  126. {
  127. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  128. sc = sfunc;
  129. }
  130. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, IntCallback ifunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  131. {
  132. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  133. ic = ifunc;
  134. }
  135. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, FloatCallback ffunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  136. {
  137. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  138. fc = ffunc;
  139. }
  140. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, VoidCallback vfunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  141. {
  142. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  143. vc = vfunc;
  144. }
  145. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, BoolCallback bfunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  146. {
  147. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  148. bc = bfunc;
  149. }
  150. ConsoleConstructor::ConsoleConstructor(const char* className, const char* groupName, const char* aUsage)
  151. {
  152. init(className, groupName, usage, -1, -2);
  153. group = true;
  154. // Somewhere, the entry list is getting flipped, partially.
  155. // so we have to do tricks to deal with making sure usage
  156. // is properly populated.
  157. // This is probably redundant.
  158. static char * lastUsage = NULL;
  159. if(aUsage)
  160. lastUsage = (char *)aUsage;
  161. usage = lastUsage;
  162. }
  163. ConsoleConstructor::ConsoleConstructor(const char *className, const char *callbackName, const char *usage, ConsoleFunctionHeader* header )
  164. {
  165. init( className, callbackName, usage, -2, -3, false, header );
  166. callback = true;
  167. ns = true;
  168. }
  169. void ConsoleConstructor::validate()
  170. {
  171. #ifdef TORQUE_DEBUG
  172. // Don't do the following check if we're not a method/func.
  173. if(this->group)
  174. return;
  175. // In debug, walk the list and make sure this isn't a duplicate.
  176. for(ConsoleConstructor *walk = first; walk; walk = walk->next)
  177. {
  178. // Skip mismatching func/method names.
  179. if(dStricmp(walk->funcName, this->funcName))
  180. continue;
  181. // Don't compare functions with methods or vice versa.
  182. if(bool(this->className) != bool(walk->className))
  183. continue;
  184. // Skip mismatching classnames, if they're present.
  185. if(this->className && walk->className && dStricmp(walk->className, this->className))
  186. continue;
  187. // If we encounter ourselves, stop searching; this prevents duplicate
  188. // firing of the assert, instead only firing for the latter encountered
  189. // entry.
  190. if(this == walk)
  191. break;
  192. // Match!
  193. if(this->className)
  194. {
  195. AssertISV(false, avar("ConsoleConstructor::setup - ConsoleMethod '%s::%s' collides with another of the same name.", this->className, this->funcName));
  196. }
  197. else
  198. {
  199. AssertISV(false, avar("ConsoleConstructor::setup - ConsoleFunction '%s' collides with another of the same name.", this->funcName));
  200. }
  201. }
  202. #endif
  203. }
  204. // We comment out the implementation of the Con namespace when doxygenizing because
  205. // otherwise Doxygen decides to ignore our docs in console.h
  206. #ifndef DOXYGENIZING
  207. namespace Con
  208. {
  209. static Vector<ConsumerCallback> gConsumers(__FILE__, __LINE__);
  210. static Vector< String > sInstantGroupStack( __FILE__, __LINE__ );
  211. static DataChunker consoleLogChunker;
  212. static Vector<ConsoleLogEntry> consoleLog(__FILE__, __LINE__);
  213. static bool consoleLogLocked;
  214. static bool logBufferEnabled=true;
  215. static S32 printLevel = 10;
  216. static FileStream consoleLogFile;
  217. static const char *defLogFileName = "console.log";
  218. static S32 consoleLogMode = 0;
  219. static bool active = false;
  220. static bool newLogFile;
  221. static const char *logFileName;
  222. static const S32 MaxCompletionBufferSize = 4096;
  223. static char completionBuffer[MaxCompletionBufferSize];
  224. static char tabBuffer[MaxCompletionBufferSize] = {0};
  225. static SimObjectPtr<SimObject> tabObject;
  226. static U32 completionBaseStart;
  227. static U32 completionBaseLen;
  228. String gInstantGroup;
  229. Con::ConsoleInputEvent smConsoleInput;
  230. /// Current script file name and root, these are registered as
  231. /// console variables.
  232. /// @{
  233. ///
  234. StringTableEntry gCurrentFile;
  235. StringTableEntry gCurrentRoot;
  236. /// @}
  237. S32 gObjectCopyFailures = -1;
  238. bool alwaysUseDebugOutput = true;
  239. bool useTimestamp = false;
  240. ConsoleFunctionGroupBegin( Clipboard, "Miscellaneous functions to control the clipboard and clear the console.");
  241. DefineConsoleFunction( cls, void, (), , "()"
  242. "@brief Clears the console output.\n\n"
  243. "@ingroup Console")
  244. {
  245. if(consoleLogLocked)
  246. return;
  247. consoleLogChunker.freeBlocks();
  248. consoleLog.setSize(0);
  249. };
  250. DefineConsoleFunction( getClipboard, const char*, (), , "()"
  251. "@brief Get text from the clipboard.\n\n"
  252. "@internal")
  253. {
  254. return Platform::getClipboard();
  255. };
  256. DefineConsoleFunction( setClipboard, bool, (const char* text), , "(string text)"
  257. "@brief Set the system clipboard.\n\n"
  258. "@internal")
  259. {
  260. return Platform::setClipboard(text);
  261. };
  262. ConsoleFunctionGroupEnd( Clipboard );
  263. void postConsoleInput( RawData data );
  264. void init()
  265. {
  266. AssertFatal(active == false, "Con::init should only be called once.");
  267. // Set up general init values.
  268. active = true;
  269. logFileName = NULL;
  270. newLogFile = true;
  271. gWarnUndefinedScriptVariables = false;
  272. // Initialize subsystems.
  273. Namespace::init();
  274. ConsoleConstructor::setup();
  275. // Set up the parser(s)
  276. CON_ADD_PARSER(CMD, "cs", true); // TorqueScript
  277. // Setup the console types.
  278. ConsoleBaseType::initialize();
  279. // And finally, the ACR...
  280. AbstractClassRep::initialize();
  281. // Variables
  282. setVariable("Con::prompt", "% ");
  283. addVariable("Con::logBufferEnabled", TypeBool, &logBufferEnabled, "If true, the log buffer will be enabled.\n"
  284. "@ingroup Console\n");
  285. addVariable("Con::printLevel", TypeS32, &printLevel,
  286. "@brief This is deprecated.\n\n"
  287. "It is no longer in use and does nothing.\n"
  288. "@ingroup Console\n");
  289. addVariable("Con::warnUndefinedVariables", TypeBool, &gWarnUndefinedScriptVariables, "If true, a warning will be displayed in the console whenever a undefined variable is used in script.\n"
  290. "@ingroup Console\n");
  291. addVariable( "instantGroup", TypeRealString, &gInstantGroup, "The group that objects will be added to when they are created.\n"
  292. "@ingroup Console\n");
  293. addVariable("Con::objectCopyFailures", TypeS32, &gObjectCopyFailures, "If greater than zero then it counts the number of object creation "
  294. "failures based on a missing copy object and does not report an error..\n"
  295. "@ingroup Console\n");
  296. // Current script file name and root
  297. addVariable( "Con::File", TypeString, &gCurrentFile, "The currently executing script file.\n"
  298. "@ingroup FileSystem\n");
  299. addVariable( "Con::Root", TypeString, &gCurrentRoot, "The mod folder for the currently executing script file.\n"
  300. "@ingroup FileSystem\n" );
  301. // alwaysUseDebugOutput determines whether to send output to the platform's
  302. // "debug" system. see winConsole for an example.
  303. // in ship builds we don't expose this variable to script
  304. // and we set it to false by default (don't want to provide more information
  305. // to potential hackers). platform code should also ifdef out the code that
  306. // pays attention to this in ship builds (see winConsole.cpp)
  307. // note that enabling this can slow down your game
  308. // if you are running from the debugger and printing a lot of console messages.
  309. #ifndef TORQUE_SHIPPING
  310. addVariable("Con::alwaysUseDebugOutput", TypeBool, &alwaysUseDebugOutput,
  311. "@brief Determines whether to send output to the platform's \"debug\" system.\n\n"
  312. "@note This is disabled in shipping builds.\n"
  313. "@ingroup Console");
  314. #else
  315. alwaysUseDebugOutput = false;
  316. #endif
  317. // controls whether a timestamp is prepended to every console message
  318. addVariable("Con::useTimestamp", TypeBool, &useTimestamp, "If true a timestamp is prepended to every console message.\n"
  319. "@ingroup Console\n");
  320. // Plug us into the journaled console input signal.
  321. smConsoleInput.notify(postConsoleInput);
  322. }
  323. //--------------------------------------
  324. void shutdown()
  325. {
  326. AssertFatal(active == true, "Con::shutdown should only be called once.");
  327. active = false;
  328. smConsoleInput.remove(postConsoleInput);
  329. consoleLogFile.close();
  330. Namespace::shutdown();
  331. AbstractClassRep::shutdown();
  332. Compiler::freeConsoleParserList();
  333. }
  334. bool isActive()
  335. {
  336. return active;
  337. }
  338. bool isMainThread()
  339. {
  340. #ifdef TORQUE_MULTITHREAD
  341. return ThreadManager::isMainThread();
  342. #else
  343. // If we're single threaded we're always in the main thread.
  344. return true;
  345. #endif
  346. }
  347. //--------------------------------------
  348. void getLockLog(ConsoleLogEntry *&log, U32 &size)
  349. {
  350. consoleLogLocked = true;
  351. log = consoleLog.address();
  352. size = consoleLog.size();
  353. }
  354. void unlockLog()
  355. {
  356. consoleLogLocked = false;
  357. }
  358. U32 tabComplete(char* inputBuffer, U32 cursorPos, U32 maxResultLength, bool forwardTab)
  359. {
  360. // Check for null input.
  361. if (!inputBuffer[0])
  362. {
  363. return cursorPos;
  364. }
  365. // Cap the max result length.
  366. if (maxResultLength > MaxCompletionBufferSize)
  367. {
  368. maxResultLength = MaxCompletionBufferSize;
  369. }
  370. // See if this is the same partial text as last checked.
  371. if (dStrcmp(tabBuffer, inputBuffer))
  372. {
  373. // If not...
  374. // Save it for checking next time.
  375. dStrcpy(tabBuffer, inputBuffer);
  376. // Scan backward from the cursor position to find the base to complete from.
  377. S32 p = cursorPos;
  378. while ((p > 0) && (inputBuffer[p - 1] != ' ') && (inputBuffer[p - 1] != '.') && (inputBuffer[p - 1] != '('))
  379. {
  380. p--;
  381. }
  382. completionBaseStart = p;
  383. completionBaseLen = cursorPos - p;
  384. // Is this function being invoked on an object?
  385. if (inputBuffer[p - 1] == '.')
  386. {
  387. // If so...
  388. if (p <= 1)
  389. {
  390. // Bail if no object identifier.
  391. return cursorPos;
  392. }
  393. // Find the object identifier.
  394. S32 objLast = --p;
  395. while ((p > 0) && (inputBuffer[p - 1] != ' ') && (inputBuffer[p - 1] != '('))
  396. {
  397. p--;
  398. }
  399. if (objLast == p)
  400. {
  401. // Bail if no object identifier.
  402. return cursorPos;
  403. }
  404. // Look up the object identifier.
  405. dStrncpy(completionBuffer, inputBuffer + p, objLast - p);
  406. completionBuffer[objLast - p] = 0;
  407. tabObject = Sim::findObject(completionBuffer);
  408. if (tabObject == NULL)
  409. {
  410. // Bail if not found.
  411. return cursorPos;
  412. }
  413. }
  414. else
  415. {
  416. // Not invoked on an object; we'll use the global namespace.
  417. tabObject = 0;
  418. }
  419. }
  420. // Chop off the input text at the cursor position.
  421. inputBuffer[cursorPos] = 0;
  422. // Try to find a completion in the appropriate namespace.
  423. const char *newText;
  424. if (tabObject != 0)
  425. {
  426. newText = tabObject->tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  427. }
  428. else
  429. {
  430. // In the global namespace, we can complete on global vars as well as functions.
  431. if (inputBuffer[completionBaseStart] == '$')
  432. {
  433. newText = gEvalState.globalVars.tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  434. }
  435. else
  436. {
  437. newText = Namespace::global()->tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  438. }
  439. }
  440. if (newText)
  441. {
  442. // If we got something, append it to the input text.
  443. S32 len = dStrlen(newText);
  444. if (len + completionBaseStart > maxResultLength)
  445. {
  446. len = maxResultLength - completionBaseStart;
  447. }
  448. dStrncpy(inputBuffer + completionBaseStart, newText, len);
  449. inputBuffer[completionBaseStart + len] = 0;
  450. // And set the cursor after it.
  451. cursorPos = completionBaseStart + len;
  452. }
  453. // Save the modified input buffer for checking next time.
  454. dStrcpy(tabBuffer, inputBuffer);
  455. // Return the new (maybe) cursor position.
  456. return cursorPos;
  457. }
  458. //------------------------------------------------------------------------------
  459. static void log(const char *string)
  460. {
  461. // Bail if we ain't logging.
  462. if (!consoleLogMode)
  463. {
  464. return;
  465. }
  466. // In mode 1, we open, append, close on each log write.
  467. if ((consoleLogMode & 0x3) == 1)
  468. {
  469. consoleLogFile.open(defLogFileName, Torque::FS::File::ReadWrite);
  470. }
  471. // Write to the log if its status is hunky-dory.
  472. if ((consoleLogFile.getStatus() == Stream::Ok) || (consoleLogFile.getStatus() == Stream::EOS))
  473. {
  474. consoleLogFile.setPosition(consoleLogFile.getStreamSize());
  475. // If this is the first write...
  476. if (newLogFile)
  477. {
  478. // Make a header.
  479. Platform::LocalTime lt;
  480. Platform::getLocalTime(lt);
  481. char buffer[128];
  482. dSprintf(buffer, sizeof(buffer), "//-------------------------- %d/%d/%d -- %02d:%02d:%02d -----\r\n",
  483. lt.month + 1,
  484. lt.monthday,
  485. lt.year + 1900,
  486. lt.hour,
  487. lt.min,
  488. lt.sec);
  489. consoleLogFile.write(dStrlen(buffer), buffer);
  490. newLogFile = false;
  491. if (consoleLogMode & 0x4)
  492. {
  493. // Dump anything that has been printed to the console so far.
  494. consoleLogMode -= 0x4;
  495. U32 size, line;
  496. ConsoleLogEntry *log;
  497. getLockLog(log, size);
  498. for (line = 0; line < size; line++)
  499. {
  500. consoleLogFile.write(dStrlen(log[line].mString), log[line].mString);
  501. consoleLogFile.write(2, "\r\n");
  502. }
  503. unlockLog();
  504. }
  505. }
  506. // Now write what we came here to write.
  507. consoleLogFile.write(dStrlen(string), string);
  508. consoleLogFile.write(2, "\r\n");
  509. }
  510. if ((consoleLogMode & 0x3) == 1)
  511. {
  512. consoleLogFile.close();
  513. }
  514. }
  515. //------------------------------------------------------------------------------
  516. static void _printf(ConsoleLogEntry::Level level, ConsoleLogEntry::Type type, const char* fmt, va_list argptr)
  517. {
  518. if (!active)
  519. return;
  520. Con::active = false;
  521. char buffer[8192];
  522. U32 offset = 0;
  523. if( gEvalState.traceOn && gEvalState.getStackDepth() > 0 )
  524. {
  525. offset = gEvalState.getStackDepth() * 3;
  526. for(U32 i = 0; i < offset; i++)
  527. buffer[i] = ' ';
  528. }
  529. if (useTimestamp)
  530. {
  531. static U32 startTime = Platform::getRealMilliseconds();
  532. U32 curTime = Platform::getRealMilliseconds() - startTime;
  533. offset += dSprintf(buffer + offset, sizeof(buffer) - offset, "[+%4d.%03d]", U32(curTime * 0.001), curTime % 1000);
  534. }
  535. dVsprintf(buffer + offset, sizeof(buffer) - offset, fmt, argptr);
  536. for(S32 i = 0; i < gConsumers.size(); i++)
  537. gConsumers[i](level, buffer);
  538. if(logBufferEnabled || consoleLogMode)
  539. {
  540. char *pos = buffer;
  541. while(*pos)
  542. {
  543. if(*pos == '\t')
  544. *pos = '^';
  545. pos++;
  546. }
  547. pos = buffer;
  548. for(;;)
  549. {
  550. char *eofPos = dStrchr(pos, '\n');
  551. if(eofPos)
  552. *eofPos = 0;
  553. log(pos);
  554. if(logBufferEnabled && !consoleLogLocked)
  555. {
  556. ConsoleLogEntry entry;
  557. entry.mLevel = level;
  558. entry.mType = type;
  559. #ifndef TORQUE_SHIPPING // this is equivalent to a memory leak, turn it off in ship build
  560. entry.mString = (const char *)consoleLogChunker.alloc(dStrlen(pos) + 1);
  561. dStrcpy(const_cast<char*>(entry.mString), pos);
  562. // This prevents infinite recursion if the console itself needs to
  563. // re-allocate memory to accommodate the new console log entry, and
  564. // LOG_PAGE_ALLOCS is defined. It is kind of a dirty hack, but the
  565. // uses for LOG_PAGE_ALLOCS are limited, and it is not worth writing
  566. // a lot of special case code to support this situation. -patw
  567. const bool save = Con::active;
  568. Con::active = false;
  569. consoleLog.push_back(entry);
  570. Con::active = save;
  571. #endif
  572. }
  573. if(!eofPos)
  574. break;
  575. pos = eofPos + 1;
  576. }
  577. }
  578. Con::active = true;
  579. }
  580. //------------------------------------------------------------------------------
  581. void printf(const char* fmt,...)
  582. {
  583. va_list argptr;
  584. va_start(argptr, fmt);
  585. _printf(ConsoleLogEntry::Normal, ConsoleLogEntry::General, fmt, argptr);
  586. va_end(argptr);
  587. }
  588. void warnf(ConsoleLogEntry::Type type, const char* fmt,...)
  589. {
  590. va_list argptr;
  591. va_start(argptr, fmt);
  592. _printf(ConsoleLogEntry::Warning, type, fmt, argptr);
  593. va_end(argptr);
  594. }
  595. void errorf(ConsoleLogEntry::Type type, const char* fmt,...)
  596. {
  597. va_list argptr;
  598. va_start(argptr, fmt);
  599. _printf(ConsoleLogEntry::Error, type, fmt, argptr);
  600. va_end(argptr);
  601. }
  602. void warnf(const char* fmt,...)
  603. {
  604. va_list argptr;
  605. va_start(argptr, fmt);
  606. _printf(ConsoleLogEntry::Warning, ConsoleLogEntry::General, fmt, argptr);
  607. va_end(argptr);
  608. }
  609. void errorf(const char* fmt,...)
  610. {
  611. va_list argptr;
  612. va_start(argptr, fmt);
  613. _printf(ConsoleLogEntry::Error, ConsoleLogEntry::General, fmt, argptr);
  614. va_end(argptr);
  615. }
  616. //---------------------------------------------------------------------------
  617. bool getVariableObjectField(const char *name, SimObject **object, const char **field)
  618. {
  619. // get the field info from the object..
  620. const char *dot = dStrchr(name, '.');
  621. if(name[0] != '$' && dot)
  622. {
  623. S32 len = dStrlen(name);
  624. AssertFatal(len < sizeof(scratchBuffer)-1, "Sim::getVariable - name too long");
  625. dMemcpy(scratchBuffer, name, len+1);
  626. char * token = dStrtok(scratchBuffer, ".");
  627. SimObject * obj = Sim::findObject(token);
  628. if(!obj)
  629. return false;
  630. token = dStrtok(0, ".\0");
  631. if(!token)
  632. return false;
  633. while(token != NULL)
  634. {
  635. const char * val = obj->getDataField(StringTable->insert(token), 0);
  636. if(!val)
  637. return false;
  638. char *fieldToken = token;
  639. token = dStrtok(0, ".\0");
  640. if(token)
  641. {
  642. obj = Sim::findObject(token);
  643. if(!obj)
  644. return false;
  645. }
  646. else
  647. {
  648. *object = obj;
  649. *field = fieldToken;
  650. return true;
  651. }
  652. }
  653. }
  654. return false;
  655. }
  656. Dictionary::Entry *getLocalVariableEntry(const char *name)
  657. {
  658. name = prependPercent(name);
  659. return gEvalState.getCurrentFrame().lookup(StringTable->insert(name));
  660. }
  661. Dictionary::Entry *getVariableEntry(const char *name)
  662. {
  663. name = prependDollar(name);
  664. return gEvalState.globalVars.lookup(StringTable->insert(name));
  665. }
  666. Dictionary::Entry *addVariableEntry(const char *name)
  667. {
  668. name = prependDollar(name);
  669. return gEvalState.globalVars.add(StringTable->insert(name));
  670. }
  671. Dictionary::Entry *getAddVariableEntry(const char *name)
  672. {
  673. name = prependDollar(name);
  674. StringTableEntry stName = StringTable->insert(name);
  675. Dictionary::Entry *entry = gEvalState.globalVars.lookup(stName);
  676. if (!entry)
  677. entry = gEvalState.globalVars.add(stName);
  678. return entry;
  679. }
  680. Dictionary::Entry *getAddLocalVariableEntry(const char *name)
  681. {
  682. name = prependPercent(name);
  683. StringTableEntry stName = StringTable->insert(name);
  684. Dictionary::Entry *entry = gEvalState.getCurrentFrame().lookup(stName);
  685. if (!entry)
  686. entry = gEvalState.getCurrentFrame().add(stName);
  687. return entry;
  688. }
  689. void setVariable(const char *name, const char *value)
  690. {
  691. SimObject *obj = NULL;
  692. const char *objField = NULL;
  693. if (getVariableObjectField(name, &obj, &objField))
  694. {
  695. obj->setDataField(StringTable->insert(objField), 0, value);
  696. }
  697. else
  698. {
  699. name = prependDollar(name);
  700. gEvalState.globalVars.setVariable(StringTable->insert(name), value);
  701. }
  702. }
  703. void setLocalVariable(const char *name, const char *value)
  704. {
  705. name = prependPercent(name);
  706. gEvalState.getCurrentFrame().setVariable(StringTable->insert(name), value);
  707. }
  708. void setBoolVariable(const char *varName, bool value)
  709. {
  710. SimObject *obj = NULL;
  711. const char *objField = NULL;
  712. if (getVariableObjectField(varName, &obj, &objField))
  713. {
  714. obj->setDataField(StringTable->insert(objField), 0, value ? "1" : "0");
  715. }
  716. else
  717. {
  718. varName = prependDollar(varName);
  719. Dictionary::Entry *entry = getAddVariableEntry(varName);
  720. entry->setStringValue(value ? "1" : "0");
  721. }
  722. }
  723. void setIntVariable(const char *varName, S32 value)
  724. {
  725. SimObject *obj = NULL;
  726. const char *objField = NULL;
  727. if (getVariableObjectField(varName, &obj, &objField))
  728. {
  729. char scratchBuffer[32];
  730. dSprintf(scratchBuffer, sizeof(scratchBuffer), "%d", value);
  731. obj->setDataField(StringTable->insert(objField), 0, scratchBuffer);
  732. }
  733. else
  734. {
  735. varName = prependDollar(varName);
  736. Dictionary::Entry *entry = getAddVariableEntry(varName);
  737. entry->setIntValue(value);
  738. }
  739. }
  740. void setFloatVariable(const char *varName, F32 value)
  741. {
  742. SimObject *obj = NULL;
  743. const char *objField = NULL;
  744. if (getVariableObjectField(varName, &obj, &objField))
  745. {
  746. char scratchBuffer[32];
  747. dSprintf(scratchBuffer, sizeof(scratchBuffer), "%g", value);
  748. obj->setDataField(StringTable->insert(objField), 0, scratchBuffer);
  749. }
  750. else
  751. {
  752. varName = prependDollar(varName);
  753. Dictionary::Entry *entry = getAddVariableEntry(varName);
  754. entry->setFloatValue(value);
  755. }
  756. }
  757. //---------------------------------------------------------------------------
  758. void addConsumer(ConsumerCallback consumer)
  759. {
  760. gConsumers.push_back(consumer);
  761. }
  762. // dhc - found this empty -- trying what I think is a reasonable impl.
  763. void removeConsumer(ConsumerCallback consumer)
  764. {
  765. for(S32 i = 0; i < gConsumers.size(); i++)
  766. {
  767. if (gConsumers[i] == consumer)
  768. {
  769. // remove it from the list.
  770. gConsumers.erase(i);
  771. break;
  772. }
  773. }
  774. }
  775. void stripColorChars(char* line)
  776. {
  777. char* c = line;
  778. char cp = *c;
  779. while (cp)
  780. {
  781. if (cp < 18)
  782. {
  783. // Could be a color control character; let's take a closer look.
  784. if ((cp != 8) && (cp != 9) && (cp != 10) && (cp != 13))
  785. {
  786. // Yep... copy following chars forward over this.
  787. char* cprime = c;
  788. char cpp;
  789. do
  790. {
  791. cpp = *++cprime;
  792. *(cprime - 1) = cpp;
  793. }
  794. while (cpp);
  795. // Back up 1 so we'll check this position again post-copy.
  796. c--;
  797. }
  798. }
  799. cp = *++c;
  800. }
  801. }
  802. //
  803. const char *getObjectTokenField(const char *name)
  804. {
  805. const char *dot = dStrchr(name, '.');
  806. if(name[0] != '$' && dot)
  807. {
  808. S32 len = dStrlen(name);
  809. AssertFatal(len < sizeof(scratchBuffer)-1, "Sim::getVariable - object name too long");
  810. dMemcpy(scratchBuffer, name, len+1);
  811. char * token = dStrtok(scratchBuffer, ".");
  812. SimObject * obj = Sim::findObject(token);
  813. if(!obj)
  814. return("");
  815. token = dStrtok(0, ".\0");
  816. if(!token)
  817. return("");
  818. while(token != NULL)
  819. {
  820. const char * val = obj->getDataField(StringTable->insert(token), 0);
  821. if(!val)
  822. return("");
  823. token = dStrtok(0, ".\0");
  824. if(token)
  825. {
  826. obj = Sim::findObject(token);
  827. if(!obj)
  828. return("");
  829. }
  830. else
  831. return(val);
  832. }
  833. }
  834. return NULL;
  835. }
  836. const char *getVariable(const char *name)
  837. {
  838. const char *objField = getObjectTokenField(name);
  839. if (objField)
  840. {
  841. return objField;
  842. }
  843. else
  844. {
  845. Dictionary::Entry *entry = getVariableEntry(name);
  846. return entry ? entry->getStringValue() : "";
  847. }
  848. }
  849. const char *getLocalVariable(const char *name)
  850. {
  851. name = prependPercent(name);
  852. return gEvalState.getCurrentFrame().getVariable(StringTable->insert(name));
  853. }
  854. bool getBoolVariable(const char *varName, bool def)
  855. {
  856. const char *objField = getObjectTokenField(varName);
  857. if (objField)
  858. {
  859. return *objField ? dAtob(objField) : def;
  860. }
  861. else
  862. {
  863. Dictionary::Entry *entry = getVariableEntry(varName);
  864. objField = entry ? entry->getStringValue() : "";
  865. return *objField ? dAtob(objField) : def;
  866. }
  867. }
  868. S32 getIntVariable(const char *varName, S32 def)
  869. {
  870. const char *objField = getObjectTokenField(varName);
  871. if (objField)
  872. {
  873. return *objField ? dAtoi(objField) : def;
  874. }
  875. else
  876. {
  877. Dictionary::Entry *entry = getVariableEntry(varName);
  878. return entry ? entry->getIntValue() : def;
  879. }
  880. }
  881. F32 getFloatVariable(const char *varName, F32 def)
  882. {
  883. const char *objField = getObjectTokenField(varName);
  884. if (objField)
  885. {
  886. return *objField ? dAtof(objField) : def;
  887. }
  888. else
  889. {
  890. Dictionary::Entry *entry = getVariableEntry(varName);
  891. return entry ? entry->getFloatValue() : def;
  892. }
  893. }
  894. //---------------------------------------------------------------------------
  895. void addVariable( const char *name,
  896. S32 type,
  897. void *dptr,
  898. const char* usage )
  899. {
  900. gEvalState.globalVars.addVariable( name, type, dptr, usage );
  901. }
  902. void addConstant( const char *name,
  903. S32 type,
  904. const void *dptr,
  905. const char* usage )
  906. {
  907. Dictionary::Entry* entry = gEvalState.globalVars.addVariable( name, type, const_cast< void* >( dptr ), usage );
  908. entry->mIsConstant = true;
  909. }
  910. bool removeVariable(const char *name)
  911. {
  912. name = StringTable->lookup(prependDollar(name));
  913. return name!=0 && gEvalState.globalVars.removeVariable(name);
  914. }
  915. void addVariableNotify( const char *name, const NotifyDelegate &callback )
  916. {
  917. gEvalState.globalVars.addVariableNotify( name, callback );
  918. }
  919. void removeVariableNotify( const char *name, const NotifyDelegate &callback )
  920. {
  921. gEvalState.globalVars.removeVariableNotify( name, callback );
  922. }
  923. //---------------------------------------------------------------------------
  924. void addCommand( const char *nsName, const char *name,StringCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  925. {
  926. Namespace *ns = lookupNamespace(nsName);
  927. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  928. }
  929. void addCommand( const char *nsName, const char *name,VoidCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  930. {
  931. Namespace *ns = lookupNamespace(nsName);
  932. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  933. }
  934. void addCommand( const char *nsName, const char *name,IntCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  935. {
  936. Namespace *ns = lookupNamespace(nsName);
  937. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  938. }
  939. void addCommand( const char *nsName, const char *name,FloatCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  940. {
  941. Namespace *ns = lookupNamespace(nsName);
  942. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  943. }
  944. void addCommand( const char *nsName, const char *name,BoolCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  945. {
  946. Namespace *ns = lookupNamespace(nsName);
  947. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  948. }
  949. void noteScriptCallback( const char *className, const char *funcName, const char *usage, ConsoleFunctionHeader* header )
  950. {
  951. Namespace *ns = lookupNamespace(className);
  952. ns->addScriptCallback( StringTable->insert(funcName), usage, header );
  953. }
  954. void markCommandGroup(const char * nsName, const char *name, const char* usage)
  955. {
  956. Namespace *ns = lookupNamespace(nsName);
  957. ns->markGroup(name,usage);
  958. }
  959. void beginCommandGroup(const char * nsName, const char *name, const char* usage)
  960. {
  961. markCommandGroup(nsName, name, usage);
  962. }
  963. void endCommandGroup(const char * nsName, const char *name)
  964. {
  965. markCommandGroup(nsName, name, NULL);
  966. }
  967. void addCommand( const char *name,StringCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  968. {
  969. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  970. }
  971. void addCommand( const char *name,VoidCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  972. {
  973. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  974. }
  975. void addCommand( const char *name,IntCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  976. {
  977. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  978. }
  979. void addCommand( const char *name,FloatCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  980. {
  981. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  982. }
  983. void addCommand( const char *name,BoolCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  984. {
  985. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  986. }
  987. ConsoleValueRef evaluate(const char* string, bool echo, const char *fileName)
  988. {
  989. ConsoleStackFrameSaver stackSaver;
  990. stackSaver.save();
  991. if (echo)
  992. {
  993. if (string[0] == '%')
  994. Con::printf("%s", string);
  995. else
  996. Con::printf("%s%s", getVariable( "$Con::Prompt" ), string);
  997. }
  998. if(fileName)
  999. fileName = StringTable->insert(fileName);
  1000. CodeBlock *newCodeBlock = new CodeBlock();
  1001. return newCodeBlock->compileExec(fileName, string, false, fileName ? -1 : 0);
  1002. }
  1003. //------------------------------------------------------------------------------
  1004. ConsoleValueRef evaluatef(const char* string, ...)
  1005. {
  1006. ConsoleStackFrameSaver stackSaver;
  1007. stackSaver.save();
  1008. char buffer[4096];
  1009. va_list args;
  1010. va_start(args, string);
  1011. dVsprintf(buffer, sizeof(buffer), string, args);
  1012. va_end(args);
  1013. CodeBlock *newCodeBlock = new CodeBlock();
  1014. return newCodeBlock->compileExec(NULL, buffer, false, 0);
  1015. }
  1016. //------------------------------------------------------------------------------
  1017. // Internal execute for global function which does not save the stack
  1018. ConsoleValueRef _internalExecute(S32 argc, ConsoleValueRef argv[])
  1019. {
  1020. Namespace::Entry *ent;
  1021. StringTableEntry funcName = StringTable->insert(argv[0]);
  1022. ent = Namespace::global()->lookup(funcName);
  1023. if(!ent)
  1024. {
  1025. warnf(ConsoleLogEntry::Script, "%s: Unknown command.", (const char*)argv[0]);
  1026. STR.clearFunctionOffset();
  1027. return ConsoleValueRef();
  1028. }
  1029. return ent->execute(argc, argv, &gEvalState);
  1030. }
  1031. ConsoleValueRef execute(S32 argc, ConsoleValueRef argv[])
  1032. {
  1033. #ifdef TORQUE_MULTITHREAD
  1034. if(isMainThread())
  1035. {
  1036. #endif
  1037. ConsoleStackFrameSaver stackSaver;
  1038. stackSaver.save();
  1039. return _internalExecute(argc, argv);
  1040. #ifdef TORQUE_MULTITHREAD
  1041. }
  1042. else
  1043. {
  1044. SimConsoleThreadExecCallback cb;
  1045. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, false, &cb);
  1046. Sim::postEvent(Sim::getRootGroup(), evt, Sim::getCurrentTime());
  1047. return cb.waitForResult();
  1048. }
  1049. #endif
  1050. }
  1051. ConsoleValueRef execute(S32 argc, const char *argv[])
  1052. {
  1053. ConsoleStackFrameSaver stackSaver;
  1054. stackSaver.save();
  1055. StringStackConsoleWrapper args(argc, argv);
  1056. return execute(args.count(), args);
  1057. }
  1058. //------------------------------------------------------------------------------
  1059. // Internal execute for object method which does not save the stack
  1060. ConsoleValueRef _internalExecute(SimObject *object, S32 argc, ConsoleValueRef argv[], bool thisCallOnly)
  1061. {
  1062. if(argc < 2)
  1063. {
  1064. STR.clearFunctionOffset();
  1065. return ConsoleValueRef();
  1066. }
  1067. // [neo, 10/05/2007 - #3010]
  1068. // Make sure we don't get recursive calls, respect the flag!
  1069. // Should we be calling handlesMethod() first?
  1070. if( !thisCallOnly )
  1071. {
  1072. ICallMethod *com = dynamic_cast<ICallMethod *>(object);
  1073. if(com)
  1074. {
  1075. STR.pushFrame();
  1076. CSTK.pushFrame();
  1077. com->callMethodArgList(argc, argv, false);
  1078. STR.popFrame();
  1079. CSTK.popFrame();
  1080. }
  1081. }
  1082. if(object->getNamespace())
  1083. {
  1084. U32 ident = object->getId();
  1085. ConsoleValueRef oldIdent(argv[1]);
  1086. StringTableEntry funcName = StringTable->insert(argv[0]);
  1087. Namespace::Entry *ent = object->getNamespace()->lookup(funcName);
  1088. if(ent == NULL)
  1089. {
  1090. //warnf(ConsoleLogEntry::Script, "%s: undefined for object '%s' - id %d", funcName, object->getName(), object->getId());
  1091. STR.clearFunctionOffset();
  1092. return ConsoleValueRef();
  1093. }
  1094. // Twiddle %this argument
  1095. ConsoleValue func_ident;
  1096. func_ident.setIntValue((S32)ident);
  1097. argv[1] = ConsoleValueRef::fromValue(&func_ident);
  1098. SimObject *save = gEvalState.thisObject;
  1099. gEvalState.thisObject = object;
  1100. ConsoleValueRef ret = ent->execute(argc, argv, &gEvalState);
  1101. gEvalState.thisObject = save;
  1102. // Twiddle it back
  1103. argv[1] = oldIdent;
  1104. return ret;
  1105. }
  1106. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), (const char*)argv[0]);
  1107. STR.clearFunctionOffset();
  1108. return ConsoleValueRef();
  1109. }
  1110. ConsoleValueRef execute(SimObject *object, S32 argc, ConsoleValueRef argv[], bool thisCallOnly)
  1111. {
  1112. if(argc < 2)
  1113. {
  1114. STR.clearFunctionOffset();
  1115. return ConsoleValueRef();
  1116. }
  1117. ConsoleStackFrameSaver stackSaver;
  1118. stackSaver.save();
  1119. if (object->getNamespace() || !thisCallOnly)
  1120. {
  1121. if (isMainThread())
  1122. {
  1123. return _internalExecute(object, argc, argv, thisCallOnly);
  1124. }
  1125. else
  1126. {
  1127. SimConsoleThreadExecCallback cb;
  1128. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, true, &cb);
  1129. Sim::postEvent(object, evt, Sim::getCurrentTime());
  1130. }
  1131. }
  1132. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), (const char*)argv[0]);
  1133. STR.clearFunctionOffset();
  1134. return ConsoleValueRef();
  1135. }
  1136. ConsoleValueRef execute(SimObject *object, S32 argc, const char *argv[], bool thisCallOnly)
  1137. {
  1138. ConsoleStackFrameSaver stackSaver;
  1139. stackSaver.save();
  1140. StringStackConsoleWrapper args(argc, argv);
  1141. return execute(object, args.count(), args, thisCallOnly);
  1142. }
  1143. inline ConsoleValueRef _executef(SimObject *obj, S32 checkArgc, S32 argc, ConsoleValueRef *argv)
  1144. {
  1145. const U32 maxArg = 12;
  1146. AssertWarn(checkArgc == argc, "Incorrect arg count passed to Con::executef(SimObject*)");
  1147. AssertFatal(argc <= maxArg - 1, "Too many args passed to Con::_executef(SimObject*). Please update the function to handle more.");
  1148. return execute(obj, argc, argv);
  1149. }
  1150. //------------------------------------------------------------------------------
  1151. inline ConsoleValueRef _executef(S32 checkArgc, S32 argc, ConsoleValueRef *argv)
  1152. {
  1153. const U32 maxArg = 10;
  1154. AssertFatal(checkArgc == argc, "Incorrect arg count passed to Con::executef()");
  1155. AssertFatal(argc <= maxArg, "Too many args passed to Con::_executef(). Please update the function to handle more.");
  1156. return execute(argc, argv);
  1157. }
  1158. //------------------------------------------------------------------------------
  1159. bool isFunction(const char *fn)
  1160. {
  1161. const char *string = StringTable->lookup(fn);
  1162. if(!string)
  1163. return false;
  1164. else
  1165. return Namespace::global()->lookup(string) != NULL;
  1166. }
  1167. //------------------------------------------------------------------------------
  1168. void setLogMode(S32 newMode)
  1169. {
  1170. if ((newMode & 0x3) != (consoleLogMode & 0x3)) {
  1171. if (newMode && !consoleLogMode) {
  1172. // Enabling logging when it was previously disabled.
  1173. newLogFile = true;
  1174. }
  1175. if ((consoleLogMode & 0x3) == 2) {
  1176. // Changing away from mode 2, must close logfile.
  1177. consoleLogFile.close();
  1178. }
  1179. else if ((newMode & 0x3) == 2) {
  1180. #ifdef _XBOX
  1181. // Xbox is not going to support logging to a file. Use the OutputDebugStr
  1182. // log consumer
  1183. Platform::debugBreak();
  1184. #endif
  1185. // Starting mode 2, must open logfile.
  1186. consoleLogFile.open(defLogFileName, Torque::FS::File::Write);
  1187. }
  1188. consoleLogMode = newMode;
  1189. }
  1190. }
  1191. Namespace *lookupNamespace(const char *ns)
  1192. {
  1193. if(!ns)
  1194. return Namespace::global();
  1195. return Namespace::find(StringTable->insert(ns));
  1196. }
  1197. bool linkNamespaces(const char *parent, const char *child)
  1198. {
  1199. Namespace *pns = lookupNamespace(parent);
  1200. Namespace *cns = lookupNamespace(child);
  1201. if(pns && cns)
  1202. return cns->classLinkTo(pns);
  1203. return false;
  1204. }
  1205. bool unlinkNamespaces(const char *parent, const char *child)
  1206. {
  1207. Namespace *pns = lookupNamespace(parent);
  1208. Namespace *cns = lookupNamespace(child);
  1209. if(pns == cns)
  1210. {
  1211. Con::warnf("Con::unlinkNamespaces - trying to unlink '%s' from itself, aborting.", parent);
  1212. return false;
  1213. }
  1214. if(pns && cns)
  1215. return cns->unlinkClass(pns);
  1216. return false;
  1217. }
  1218. bool classLinkNamespaces(Namespace *parent, Namespace *child)
  1219. {
  1220. if(parent && child)
  1221. return child->classLinkTo(parent);
  1222. return false;
  1223. }
  1224. void setData(S32 type, void *dptr, S32 index, S32 argc, const char **argv, const EnumTable *tbl, BitSet32 flag)
  1225. {
  1226. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1227. AssertFatal(cbt, "Con::setData - could not resolve type ID!");
  1228. cbt->setData((void *) (((const char *)dptr) + index * cbt->getTypeSize()),argc, argv, tbl, flag);
  1229. }
  1230. const char *getData(S32 type, void *dptr, S32 index, const EnumTable *tbl, BitSet32 flag)
  1231. {
  1232. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1233. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1234. return cbt->getData((void *) (((const char *)dptr) + index * cbt->getTypeSize()), tbl, flag);
  1235. }
  1236. const char *getFormattedData(S32 type, const char *data, const EnumTable *tbl, BitSet32 flag)
  1237. {
  1238. ConsoleBaseType *cbt = ConsoleBaseType::getType( type );
  1239. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1240. // Datablock types are just a datablock
  1241. // name and don't ever need formatting.
  1242. if ( cbt->isDatablock() )
  1243. return data;
  1244. bool currWarn = gWarnUndefinedScriptVariables;
  1245. gWarnUndefinedScriptVariables = false;
  1246. const char* globalValue = Con::getVariable(data);
  1247. gWarnUndefinedScriptVariables = currWarn;
  1248. if (dStrlen(globalValue) > 0)
  1249. return globalValue;
  1250. void* variable = cbt->getNativeVariable();
  1251. if (variable)
  1252. {
  1253. Con::setData(type, variable, 0, 1, &data, tbl, flag);
  1254. const char* formattedVal = Con::getData(type, variable, 0, tbl, flag);
  1255. static const U32 bufSize = 2048;
  1256. char* returnBuffer = Con::getReturnBuffer(bufSize);
  1257. dSprintf(returnBuffer, bufSize, "%s\0", formattedVal );
  1258. cbt->deleteNativeVariable(variable);
  1259. return returnBuffer;
  1260. }
  1261. else
  1262. return data;
  1263. }
  1264. //------------------------------------------------------------------------------
  1265. bool isCurrentScriptToolScript()
  1266. {
  1267. // With a player build we ALWAYS return false
  1268. #ifndef TORQUE_TOOLS
  1269. return false;
  1270. #else
  1271. const StringTableEntry cbFullPath = CodeBlock::getCurrentCodeBlockFullPath();
  1272. if(cbFullPath == NULL)
  1273. return false;
  1274. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1275. return dStrnicmp(exePath, cbFullPath, dStrlen(exePath)) == 0;
  1276. #endif
  1277. }
  1278. //------------------------------------------------------------------------------
  1279. StringTableEntry getModNameFromPath(const char *path)
  1280. {
  1281. if(path == NULL || *path == 0)
  1282. return NULL;
  1283. char buf[1024];
  1284. buf[0] = 0;
  1285. if(path[0] == '/' || path[1] == ':')
  1286. {
  1287. // It's an absolute path
  1288. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1289. U32 len = dStrlen(exePath);
  1290. if(dStrnicmp(exePath, path, len) == 0)
  1291. {
  1292. const char *ptr = path + len + 1;
  1293. const char *slash = dStrchr(ptr, '/');
  1294. if(slash)
  1295. {
  1296. dStrncpy(buf, ptr, slash - ptr);
  1297. buf[slash - ptr] = 0;
  1298. }
  1299. else
  1300. return NULL;
  1301. }
  1302. else
  1303. return NULL;
  1304. }
  1305. else
  1306. {
  1307. const char *slash = dStrchr(path, '/');
  1308. if(slash)
  1309. {
  1310. dStrncpy(buf, path, slash - path);
  1311. buf[slash - path] = 0;
  1312. }
  1313. else
  1314. return NULL;
  1315. }
  1316. return StringTable->insert(buf);
  1317. }
  1318. void postConsoleInput( RawData data )
  1319. {
  1320. // Schedule this to happen at the next time event.
  1321. ConsoleValue values[2];
  1322. ConsoleValueRef argv[2];
  1323. values[0].init();
  1324. values[0].setStringValue("eval");
  1325. values[1].init();
  1326. values[1].setStringValue((const char*)data.data);
  1327. argv[0].value = &values[0];
  1328. argv[1].value = &values[1];
  1329. Sim::postCurrentEvent(Sim::getRootGroup(), new SimConsoleEvent(2, argv, false));
  1330. }
  1331. //------------------------------------------------------------------------------
  1332. void pushInstantGroup( String name )
  1333. {
  1334. sInstantGroupStack.push_back( gInstantGroup );
  1335. gInstantGroup = name;
  1336. }
  1337. void popInstantGroup()
  1338. {
  1339. if( sInstantGroupStack.empty() )
  1340. gInstantGroup = String::EmptyString;
  1341. else
  1342. {
  1343. gInstantGroup = sInstantGroupStack.last();
  1344. sInstantGroupStack.pop_back();
  1345. }
  1346. }
  1347. typedef HashMap<StringTableEntry, StringTableEntry> typePathExpandoMap;
  1348. static typePathExpandoMap PathExpandos;
  1349. //-----------------------------------------------------------------------------
  1350. void addPathExpando(const char* pExpandoName, const char* pPath)
  1351. {
  1352. // Sanity!
  1353. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1354. AssertFatal(pPath != NULL, "Expando path cannot be NULL.");
  1355. // Fetch expando name.
  1356. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1357. // Fetch the length of the path.
  1358. S32 pathLength = dStrlen(pPath);
  1359. char pathBuffer[1024];
  1360. // Sanity!
  1361. if (pathLength == 0 || pathLength >= sizeof(pathBuffer))
  1362. {
  1363. Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
  1364. return;
  1365. }
  1366. // Strip repeat slashes.
  1367. if (!Con::stripRepeatSlashes(pathBuffer, pPath, sizeof(pathBuffer)))
  1368. {
  1369. Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
  1370. return;
  1371. }
  1372. // Fetch new path length.
  1373. pathLength = dStrlen(pathBuffer);
  1374. // Sanity!
  1375. if (pathLength == 0)
  1376. {
  1377. Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
  1378. return;
  1379. }
  1380. // Remove any terminating slash.
  1381. if (pathBuffer[pathLength - 1] == '/')
  1382. pathBuffer[pathLength - 1] = 0;
  1383. // Fetch expanded path.
  1384. StringTableEntry expandedPath = StringTable->insert(pathBuffer);
  1385. // Info.
  1386. #if defined(TORQUE_DEBUG)
  1387. Con::printf("Adding path expando of '%s' as '%s'.", expandoName, expandedPath);
  1388. #endif
  1389. // Find any existing path expando.
  1390. typePathExpandoMap::iterator expandoItr = PathExpandos.find(pExpandoName);
  1391. // Does the expando exist?
  1392. if (expandoItr != PathExpandos.end())
  1393. {
  1394. // Yes, so modify the path.
  1395. expandoItr->value = expandedPath;
  1396. return;
  1397. }
  1398. // Insert expando.
  1399. PathExpandos.insert(expandoName, expandedPath);
  1400. }
  1401. //-----------------------------------------------------------------------------
  1402. StringTableEntry getPathExpando(const char* pExpandoName)
  1403. {
  1404. // Sanity!
  1405. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1406. // Fetch expando name.
  1407. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1408. // Find any existing path expando.
  1409. typePathExpandoMap::iterator expandoItr = PathExpandos.find(expandoName);
  1410. // Does the expando exist?
  1411. if (expandoItr != PathExpandos.end())
  1412. {
  1413. // Yes, so return it.
  1414. return expandoItr->value;
  1415. }
  1416. // Not found.
  1417. return NULL;
  1418. }
  1419. //-----------------------------------------------------------------------------
  1420. void removePathExpando(const char* pExpandoName)
  1421. {
  1422. // Sanity!
  1423. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1424. // Fetch expando name.
  1425. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1426. // Find any existing path expando.
  1427. typePathExpandoMap::iterator expandoItr = PathExpandos.find(expandoName);
  1428. // Does the expando exist?
  1429. if (expandoItr == PathExpandos.end())
  1430. {
  1431. // No, so warn.
  1432. #if defined(TORQUE_DEBUG)
  1433. Con::warnf("Removing path expando of '%s' but it does not exist.", expandoName);
  1434. #endif
  1435. return;
  1436. }
  1437. // Info.
  1438. #if defined(TORQUE_DEBUG)
  1439. Con::printf("Removing path expando of '%s' as '%s'.", expandoName, expandoItr->value);
  1440. #endif
  1441. // Remove expando.
  1442. PathExpandos.erase(expandoItr);
  1443. }
  1444. //-----------------------------------------------------------------------------
  1445. bool isPathExpando(const char* pExpandoName)
  1446. {
  1447. // Sanity!
  1448. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1449. // Fetch expando name.
  1450. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1451. return PathExpandos.contains(expandoName);
  1452. }
  1453. //-----------------------------------------------------------------------------
  1454. U32 getPathExpandoCount(void)
  1455. {
  1456. return PathExpandos.size();
  1457. }
  1458. //-----------------------------------------------------------------------------
  1459. StringTableEntry getPathExpandoKey(U32 expandoIndex)
  1460. {
  1461. // Finish if index is out of range.
  1462. if (expandoIndex >= PathExpandos.size())
  1463. return NULL;
  1464. // Find indexed iterator.
  1465. typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
  1466. while (expandoIndex > 0) { ++expandoItr; --expandoIndex; }
  1467. return expandoItr->key;
  1468. }
  1469. //-----------------------------------------------------------------------------
  1470. StringTableEntry getPathExpandoValue(U32 expandoIndex)
  1471. {
  1472. // Finish if index is out of range.
  1473. if (expandoIndex >= PathExpandos.size())
  1474. return NULL;
  1475. // Find indexed iterator.
  1476. typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
  1477. while (expandoIndex > 0) { ++expandoItr; --expandoIndex; }
  1478. return expandoItr->value;
  1479. }
  1480. //-----------------------------------------------------------------------------
  1481. bool expandPath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint, const bool ensureTrailingSlash)
  1482. {
  1483. char pathBuffer[2048];
  1484. const char* pSrc = pSrcPath;
  1485. char* pSlash;
  1486. // Fetch leading character.
  1487. const char leadingToken = *pSrc;
  1488. // Fetch following token.
  1489. const char followingToken = leadingToken != 0 ? pSrc[1] : 0;
  1490. // Expando.
  1491. if (leadingToken == '^')
  1492. {
  1493. // Initial prefix search.
  1494. const char* pPrefixSrc = pSrc + 1;
  1495. char* pPrefixDst = pathBuffer;
  1496. // Search for end of expando.
  1497. while (*pPrefixSrc != '/' && *pPrefixSrc != 0)
  1498. {
  1499. // Copy prefix character.
  1500. *pPrefixDst++ = *pPrefixSrc++;
  1501. }
  1502. // Yes, so terminate the expando string.
  1503. *pPrefixDst = 0;
  1504. // Fetch the expando path.
  1505. StringTableEntry expandoPath = getPathExpando(pathBuffer);
  1506. // Does the expando exist?
  1507. if (expandoPath == NULL)
  1508. {
  1509. // No, so error.
  1510. Con::errorf("expandPath() : Could not find path expando '%s' for path '%s'.", pathBuffer, pSrcPath);
  1511. // Are we ensuring the trailing slash?
  1512. if (ensureTrailingSlash)
  1513. {
  1514. // Yes, so ensure it.
  1515. Con::ensureTrailingSlash(pDstPath, pSrcPath);
  1516. }
  1517. else
  1518. {
  1519. // No, so just use the source path.
  1520. dStrcpy(pDstPath, pSrcPath);
  1521. }
  1522. return false;
  1523. }
  1524. // Skip the expando and the following slash.
  1525. pSrc += dStrlen(pathBuffer) + 1;
  1526. // Format the output path.
  1527. dSprintf(pathBuffer, sizeof(pathBuffer), "%s/%s", expandoPath, pSrc);
  1528. // Are we ensuring the trailing slash?
  1529. if (ensureTrailingSlash)
  1530. {
  1531. // Yes, so ensure it.
  1532. Con::ensureTrailingSlash(pathBuffer, pathBuffer);
  1533. }
  1534. // Strip repeat slashes.
  1535. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1536. return true;
  1537. }
  1538. // Script-Relative.
  1539. if (leadingToken == '.')
  1540. {
  1541. // Fetch the code-block file-path.
  1542. const StringTableEntry codeblockFullPath = CodeBlock::getCurrentCodeBlockFullPath();
  1543. // Do we have a code block full path?
  1544. if (codeblockFullPath == NULL)
  1545. {
  1546. // No, so error.
  1547. Con::errorf("expandPath() : Could not find relative path from code-block for path '%s'.", pSrcPath);
  1548. // Are we ensuring the trailing slash?
  1549. if (ensureTrailingSlash)
  1550. {
  1551. // Yes, so ensure it.
  1552. Con::ensureTrailingSlash(pDstPath, pSrcPath);
  1553. }
  1554. else
  1555. {
  1556. // No, so just use the source path.
  1557. dStrcpy(pDstPath, pSrcPath);
  1558. }
  1559. return false;
  1560. }
  1561. // Yes, so use it as the prefix.
  1562. dStrncpy(pathBuffer, codeblockFullPath, sizeof(pathBuffer) - 1);
  1563. // Find the final slash in the code-block.
  1564. pSlash = dStrrchr(pathBuffer, '/');
  1565. // Is this a parent directory token?
  1566. if (followingToken == '.')
  1567. {
  1568. // Yes, so terminate after the slash so we include it.
  1569. pSlash[1] = 0;
  1570. }
  1571. else
  1572. {
  1573. // No, it's a current directory token so terminate at the slash so we don't include it.
  1574. pSlash[0] = 0;
  1575. // Skip the current directory token.
  1576. pSrc++;
  1577. }
  1578. // Format the output path.
  1579. dStrncat(pathBuffer, "/", sizeof(pathBuffer) - 1 - strlen(pathBuffer));
  1580. dStrncat(pathBuffer, pSrc, sizeof(pathBuffer) - 1 - strlen(pathBuffer));
  1581. // Are we ensuring the trailing slash?
  1582. if (ensureTrailingSlash)
  1583. {
  1584. // Yes, so ensure it.
  1585. Con::ensureTrailingSlash(pathBuffer, pathBuffer);
  1586. }
  1587. // Strip repeat slashes.
  1588. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1589. return true;
  1590. }
  1591. // All else.
  1592. //Using a special case here because the code below barfs on trying to build a full path for apk reading
  1593. #ifdef TORQUE_OS_ANDROID
  1594. if (leadingToken == '/' || strstr(pSrcPath, "/") == NULL)
  1595. Platform::makeFullPathName(pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint);
  1596. else
  1597. dSprintf(pathBuffer, sizeof(pathBuffer), "/%s", pSrcPath);
  1598. #else
  1599. Platform::makeFullPathName(pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint);
  1600. #endif
  1601. // Are we ensuring the trailing slash?
  1602. if (ensureTrailingSlash)
  1603. {
  1604. // Yes, so ensure it.
  1605. Con::ensureTrailingSlash(pathBuffer, pathBuffer);
  1606. }
  1607. // Strip repeat slashes.
  1608. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1609. return true;
  1610. }
  1611. //-----------------------------------------------------------------------------
  1612. bool isBasePath(const char* SrcPath, const char* pBasePath)
  1613. {
  1614. char expandBuffer[1024];
  1615. Con::expandPath(expandBuffer, sizeof(expandBuffer), SrcPath);
  1616. return dStrnicmp(pBasePath, expandBuffer, dStrlen(pBasePath)) == 0;
  1617. }
  1618. //-----------------------------------------------------------------------------
  1619. void collapsePath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint)
  1620. {
  1621. // Check path against expandos. If there are multiple matches, choose the
  1622. // expando that produces the shortest relative path.
  1623. char pathBuffer[2048];
  1624. // Fetch expando count.
  1625. const U32 expandoCount = getPathExpandoCount();
  1626. // Iterate expandos.
  1627. U32 expandoRelativePathLength = U32_MAX;
  1628. for (U32 expandoIndex = 0; expandoIndex < expandoCount; ++expandoIndex)
  1629. {
  1630. // Fetch expando value (path).
  1631. StringTableEntry expandoValue = getPathExpandoValue(expandoIndex);
  1632. // Skip if not the base path.
  1633. if (!isBasePath(pSrcPath, expandoValue))
  1634. continue;
  1635. // Fetch path relative to expando path.
  1636. StringTableEntry relativePath = Platform::makeRelativePathName(pSrcPath, expandoValue);
  1637. // If the relative path is simply a period
  1638. if (relativePath[0] == '.')
  1639. relativePath++;
  1640. if (dStrlen(relativePath) > expandoRelativePathLength)
  1641. {
  1642. // This expando covers less of the path than any previous one found.
  1643. // We will keep the previous one.
  1644. continue;
  1645. }
  1646. // Keep track of the relative path length
  1647. expandoRelativePathLength = dStrlen(relativePath);
  1648. // Fetch expando key (name).
  1649. StringTableEntry expandoName = getPathExpandoKey(expandoIndex);
  1650. // Format against expando.
  1651. dSprintf(pathBuffer, sizeof(pathBuffer), "^%s/%s", expandoName, relativePath);
  1652. }
  1653. // Check if we've found a suitable expando
  1654. if (expandoRelativePathLength != U32_MAX)
  1655. {
  1656. // Strip repeat slashes.
  1657. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1658. return;
  1659. }
  1660. // Fetch the working directory.
  1661. StringTableEntry workingDirectory = pWorkingDirectoryHint != NULL ? pWorkingDirectoryHint : Platform::getCurrentDirectory();
  1662. // Fetch path relative to current directory.
  1663. StringTableEntry relativePath = Platform::makeRelativePathName(pSrcPath, workingDirectory);
  1664. // If the relative path is simply a period
  1665. if (relativePath[0] == '.' && relativePath[1] != '.')
  1666. relativePath++;
  1667. // Format against expando.
  1668. dSprintf(pathBuffer, sizeof(pathBuffer), "%s/%s", workingDirectory, relativePath);
  1669. // Strip repeat slashes.
  1670. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1671. }
  1672. void ensureTrailingSlash(char* pDstPath, const char* pSrcPath)
  1673. {
  1674. // Copy to target.
  1675. dStrcpy(pDstPath, pSrcPath);
  1676. // Find trailing character index.
  1677. S32 trailIndex = dStrlen(pDstPath);
  1678. // Ignore if empty string.
  1679. if (trailIndex == 0)
  1680. return;
  1681. // Finish if the trailing slash already exists.
  1682. if (pDstPath[trailIndex - 1] == '/')
  1683. return;
  1684. // Add trailing slash.
  1685. pDstPath[trailIndex++] = '/';
  1686. pDstPath[trailIndex] = 0;
  1687. }
  1688. //-----------------------------------------------------------------------------
  1689. bool stripRepeatSlashes(char* pDstPath, const char* pSrcPath, S32 dstSize)
  1690. {
  1691. // Note original destination.
  1692. char* pOriginalDst = pDstPath;
  1693. // Reset last source character.
  1694. char lastSrcChar = 0;
  1695. // Search source...
  1696. while (dstSize > 0)
  1697. {
  1698. // Fetch characters.
  1699. const char srcChar = *pSrcPath++;
  1700. // Do we have a repeat slash?
  1701. if (srcChar == '/' && lastSrcChar == '/')
  1702. {
  1703. // Yes, so skip it.
  1704. continue;
  1705. }
  1706. // No, so copy character.
  1707. *pDstPath++ = srcChar;
  1708. // Finish if end of source.
  1709. if (srcChar == 0)
  1710. return true;
  1711. // Reduce room left in destination.
  1712. dstSize--;
  1713. // Set last character.
  1714. lastSrcChar = srcChar;
  1715. }
  1716. // Terminate the destination string as we ran out of room.
  1717. *pOriginalDst = 0;
  1718. // Fail!
  1719. return false;
  1720. }
  1721. } // end of Console namespace
  1722. #endif
  1723. //=============================================================================
  1724. // API.
  1725. //=============================================================================
  1726. // MARK: ---- API ----
  1727. //-----------------------------------------------------------------------------
  1728. DefineEngineFunction( log, void, ( const char* message ),,
  1729. "@brief Logs a message to the console.\n\n"
  1730. "@param message The message text.\n"
  1731. "@note By default, messages will appear white in the console.\n"
  1732. "@ingroup Logging")
  1733. {
  1734. Con::printf( "%s", message );
  1735. }
  1736. //-----------------------------------------------------------------------------
  1737. DefineEngineFunction( logError, void, ( const char* message ),,
  1738. "@brief Logs an error message to the console.\n\n"
  1739. "@param message The message text.\n"
  1740. "@note By default, errors will appear red in the console.\n"
  1741. "@ingroup Logging")
  1742. {
  1743. Con::errorf( "%s", message );
  1744. }
  1745. //-----------------------------------------------------------------------------
  1746. DefineEngineFunction( logWarning, void, ( const char* message ),,
  1747. "@brief Logs a warning message to the console.\n\n"
  1748. "@param message The message text.\n\n"
  1749. "@note By default, warnings will appear turquoise in the console.\n"
  1750. "@ingroup Logging")
  1751. {
  1752. Con::warnf( "%s", message );
  1753. }
  1754. //------------------------------------------------------------------------------
  1755. extern ConsoleValueStack CSTK;
  1756. ConsoleValueRef::ConsoleValueRef(const ConsoleValueRef &ref)
  1757. {
  1758. value = ref.value;
  1759. }
  1760. ConsoleValueRef& ConsoleValueRef::operator=(const ConsoleValueRef &newValue)
  1761. {
  1762. value = newValue.value;
  1763. return *this;
  1764. }
  1765. ConsoleValueRef& ConsoleValueRef::operator=(const char *newValue)
  1766. {
  1767. AssertFatal(value, "value should not be NULL");
  1768. value->setStringValue(newValue);
  1769. return *this;
  1770. }
  1771. ConsoleValueRef& ConsoleValueRef::operator=(S32 newValue)
  1772. {
  1773. AssertFatal(value, "value should not be NULL");
  1774. value->setIntValue(newValue);
  1775. return *this;
  1776. }
  1777. ConsoleValueRef& ConsoleValueRef::operator=(U32 newValue)
  1778. {
  1779. AssertFatal(value, "value should not be NULL");
  1780. value->setIntValue(newValue);
  1781. return *this;
  1782. }
  1783. ConsoleValueRef& ConsoleValueRef::operator=(F32 newValue)
  1784. {
  1785. AssertFatal(value, "value should not be NULL");
  1786. value->setFloatValue(newValue);
  1787. return *this;
  1788. }
  1789. ConsoleValueRef& ConsoleValueRef::operator=(F64 newValue)
  1790. {
  1791. AssertFatal(value, "value should not be NULL");
  1792. value->setFloatValue(newValue);
  1793. return *this;
  1794. }
  1795. //------------------------------------------------------------------------------
  1796. StringStackWrapper::StringStackWrapper(int targc, ConsoleValueRef targv[])
  1797. {
  1798. argv = new const char*[targc];
  1799. argc = targc;
  1800. for (int i=0; i<targc; i++)
  1801. {
  1802. argv[i] = dStrdup(targv[i]);
  1803. }
  1804. }
  1805. StringStackWrapper::~StringStackWrapper()
  1806. {
  1807. for (int i=0; i<argc; i++)
  1808. {
  1809. dFree(argv[i]);
  1810. }
  1811. delete[] argv;
  1812. }
  1813. StringStackConsoleWrapper::StringStackConsoleWrapper(int targc, const char** targ)
  1814. {
  1815. argv = new ConsoleValueRef[targc];
  1816. argvValue = new ConsoleValue[targc];
  1817. argc = targc;
  1818. for (int i=0; i<targc; i++) {
  1819. argvValue[i].init();
  1820. argv[i].value = &argvValue[i];
  1821. argvValue[i].setStackStringValue(targ[i]);
  1822. }
  1823. }
  1824. StringStackConsoleWrapper::~StringStackConsoleWrapper()
  1825. {
  1826. for (int i=0; i<argc; i++)
  1827. {
  1828. argv[i] = 0;
  1829. }
  1830. delete[] argv;
  1831. delete[] argvValue;
  1832. }
  1833. //------------------------------------------------------------------------------
  1834. S32 ConsoleValue::getSignedIntValue()
  1835. {
  1836. if(type <= TypeInternalString)
  1837. return (S32)fval;
  1838. else
  1839. return dAtoi(Con::getData(type, dataPtr, 0, enumTable));
  1840. }
  1841. U32 ConsoleValue::getIntValue()
  1842. {
  1843. if(type <= TypeInternalString)
  1844. return ival;
  1845. else
  1846. return dAtoi(Con::getData(type, dataPtr, 0, enumTable));
  1847. }
  1848. F32 ConsoleValue::getFloatValue()
  1849. {
  1850. if(type <= TypeInternalString)
  1851. return fval;
  1852. else
  1853. return dAtof(Con::getData(type, dataPtr, 0, enumTable));
  1854. }
  1855. const char *ConsoleValue::getStringValue()
  1856. {
  1857. if(type == TypeInternalString || type == TypeInternalStackString)
  1858. return sval;
  1859. else if (type == TypeInternalStringStackPtr)
  1860. return STR.mBuffer + (uintptr_t)sval;
  1861. else
  1862. {
  1863. // We need a string representation, so lets create one
  1864. const char *internalValue = NULL;
  1865. if(type == TypeInternalFloat)
  1866. internalValue = Con::getData(TypeF32, &fval, 0);
  1867. else if(type == TypeInternalInt)
  1868. internalValue = Con::getData(TypeS32, &ival, 0);
  1869. else
  1870. return Con::getData(type, dataPtr, 0, enumTable); // We can't save sval here since it is the same as dataPtr
  1871. if (!internalValue)
  1872. return "";
  1873. U32 stringLen = dStrlen(internalValue);
  1874. U32 newLen = ((stringLen + 1) + 15) & ~15; // pad upto next cache line
  1875. if (bufferLen == 0)
  1876. sval = (char *) dMalloc(newLen);
  1877. else if(newLen > bufferLen)
  1878. sval = (char *) dRealloc(sval, newLen);
  1879. dStrcpy(sval, internalValue);
  1880. bufferLen = newLen;
  1881. return sval;
  1882. }
  1883. }
  1884. StringStackPtr ConsoleValue::getStringStackPtr()
  1885. {
  1886. if (type == TypeInternalStringStackPtr)
  1887. return (uintptr_t)sval;
  1888. else
  1889. return (uintptr_t)-1;
  1890. }
  1891. bool ConsoleValue::getBoolValue()
  1892. {
  1893. if(type == TypeInternalString || type == TypeInternalStackString || type == TypeInternalStringStackPtr)
  1894. return dAtob(getStringValue());
  1895. if(type == TypeInternalFloat)
  1896. return fval > 0;
  1897. else if(type == TypeInternalInt)
  1898. return ival > 0;
  1899. else {
  1900. const char *value = Con::getData(type, dataPtr, 0, enumTable);
  1901. return dAtob(value);
  1902. }
  1903. }
  1904. void ConsoleValue::setIntValue(S32 val)
  1905. {
  1906. setFloatValue(val);
  1907. }
  1908. void ConsoleValue::setIntValue(U32 val)
  1909. {
  1910. if(type <= TypeInternalString)
  1911. {
  1912. fval = (F32)val;
  1913. ival = val;
  1914. if(bufferLen > 0)
  1915. {
  1916. dFree(sval);
  1917. bufferLen = 0;
  1918. }
  1919. sval = typeValueEmpty;
  1920. type = TypeInternalInt;
  1921. }
  1922. else
  1923. {
  1924. const char *dptr = Con::getData(TypeS32, &val, 0);
  1925. Con::setData(type, dataPtr, 0, 1, &dptr, enumTable);
  1926. }
  1927. }
  1928. void ConsoleValue::setBoolValue(bool val)
  1929. {
  1930. return setIntValue(val ? 1 : 0);
  1931. }
  1932. void ConsoleValue::setFloatValue(F32 val)
  1933. {
  1934. if(type <= TypeInternalString)
  1935. {
  1936. fval = val;
  1937. ival = static_cast<U32>(val);
  1938. if(bufferLen > 0)
  1939. {
  1940. dFree(sval);
  1941. bufferLen = 0;
  1942. }
  1943. sval = typeValueEmpty;
  1944. type = TypeInternalFloat;
  1945. }
  1946. else
  1947. {
  1948. const char *dptr = Con::getData(TypeF32, &val, 0);
  1949. Con::setData(type, dataPtr, 0, 1, &dptr, enumTable);
  1950. }
  1951. }
  1952. //------------------------------------------------------------------------------
  1953. ConsoleValueRef _BaseEngineConsoleCallbackHelper::_exec()
  1954. {
  1955. ConsoleValueRef returnValue;
  1956. if( mThis )
  1957. {
  1958. // Cannot invoke callback until object has been registered
  1959. if (mThis->isProperlyAdded()) {
  1960. returnValue = Con::_internalExecute( mThis, mArgc, mArgv, false );
  1961. } else {
  1962. STR.clearFunctionOffset();
  1963. returnValue = ConsoleValueRef();
  1964. }
  1965. }
  1966. else
  1967. returnValue = Con::_internalExecute( mArgc, mArgv );
  1968. mArgc = mInitialArgc; // reset args
  1969. return returnValue;
  1970. }
  1971. ConsoleValueRef _BaseEngineConsoleCallbackHelper::_execLater(SimConsoleThreadExecEvent *evt)
  1972. {
  1973. mArgc = mInitialArgc; // reset args
  1974. Sim::postEvent((SimObject*)Sim::getRootGroup(), evt, Sim::getCurrentTime());
  1975. return evt->getCB().waitForResult();
  1976. }
  1977. //------------------------------------------------------------------------------
  1978. void ConsoleStackFrameSaver::save()
  1979. {
  1980. CSTK.pushFrame();
  1981. STR.pushFrame();
  1982. mSaved = true;
  1983. }
  1984. void ConsoleStackFrameSaver::restore()
  1985. {
  1986. if (mSaved)
  1987. {
  1988. CSTK.popFrame();
  1989. STR.popFrame();
  1990. }
  1991. }