console.cpp 67 KB

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