console.cpp 68 KB

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