console.cpp 67 KB

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