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. gGlobalVars.reset();
  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. Namespace::Entry *ent;
  1031. ent = Namespace::global()->lookup(funcName);
  1032. if(!ent)
  1033. {
  1034. warnf(ConsoleLogEntry::Script, "%s: Unknown command.", funcName);
  1035. STR.clearFunctionOffset();
  1036. return std::move(ConsoleValue());
  1037. }
  1038. return std::move(ent->execute(argc, argv, NULL));
  1039. }
  1040. ConsoleValue execute(S32 argc, ConsoleValue argv[])
  1041. {
  1042. #ifdef TORQUE_MULTITHREAD
  1043. if(isMainThread())
  1044. {
  1045. #endif
  1046. ConsoleStackFrameSaver stackSaver;
  1047. stackSaver.save();
  1048. return _internalExecute(argc, argv);
  1049. #ifdef TORQUE_MULTITHREAD
  1050. }
  1051. else
  1052. {
  1053. SimConsoleThreadExecCallback cb;
  1054. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, false, &cb);
  1055. Sim::postEvent(Sim::getRootGroup(), evt, Sim::getCurrentTime());
  1056. return cb.waitForResult();
  1057. }
  1058. #endif
  1059. }
  1060. ConsoleValue execute(S32 argc, const char *argv[])
  1061. {
  1062. ConsoleStackFrameSaver stackSaver;
  1063. stackSaver.save();
  1064. StringArrayToConsoleValueWrapper args(argc, argv);
  1065. return std::move(execute(args.count(), args));
  1066. }
  1067. //------------------------------------------------------------------------------
  1068. // Internal execute for object method which does not save the stack
  1069. static ConsoleValue _internalExecute(SimObject *object, S32 argc, ConsoleValue argv[], bool thisCallOnly)
  1070. {
  1071. if (object == NULL)
  1072. return std::move(ConsoleValue());
  1073. if(argc < 2)
  1074. {
  1075. STR.clearFunctionOffset();
  1076. return std::move(ConsoleValue());
  1077. }
  1078. // [neo, 10/05/2007 - #3010]
  1079. // Make sure we don't get recursive calls, respect the flag!
  1080. // Should we be calling handlesMethod() first?
  1081. if( !thisCallOnly )
  1082. {
  1083. ICallMethod *com = dynamic_cast<ICallMethod *>(object);
  1084. if(com)
  1085. {
  1086. ConsoleStackFrameSaver saver;
  1087. saver.save();
  1088. com->callMethodArgList(argc, argv, false);
  1089. }
  1090. }
  1091. StringTableEntry funcName = StringTable->insert(argv[0].getString());
  1092. if(object->getNamespace())
  1093. {
  1094. U32 ident = object->getId();
  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. const char* oldIdent = dStrdup(argv[1].getString());
  1103. // Twiddle %this argument
  1104. argv[1].setInt(ident);
  1105. ConsoleValue ret = std::move(ent->execute(argc, argv, object));
  1106. // Twiddle it back
  1107. argv[1].setString(oldIdent);
  1108. dFree(oldIdent);
  1109. return ret;
  1110. }
  1111. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), funcName);
  1112. STR.clearFunctionOffset();
  1113. return std::move(ConsoleValue());
  1114. }
  1115. ConsoleValue execute(SimObject *object, S32 argc, ConsoleValue argv[], bool thisCallOnly)
  1116. {
  1117. if(argc < 2)
  1118. {
  1119. STR.clearFunctionOffset();
  1120. return std::move(ConsoleValue());
  1121. }
  1122. ConsoleStackFrameSaver stackSaver;
  1123. stackSaver.save();
  1124. if (object->getNamespace() || !thisCallOnly)
  1125. {
  1126. if (isMainThread())
  1127. {
  1128. return std::move(_internalExecute(object, argc, argv, thisCallOnly));
  1129. }
  1130. else
  1131. {
  1132. SimConsoleThreadExecCallback cb;
  1133. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, true, &cb);
  1134. Sim::postEvent(object, evt, Sim::getCurrentTime());
  1135. }
  1136. }
  1137. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), argv[0].getString());
  1138. STR.clearFunctionOffset();
  1139. return std::move(ConsoleValue());
  1140. }
  1141. ConsoleValue execute(SimObject *object, S32 argc, const char *argv[], bool thisCallOnly)
  1142. {
  1143. ConsoleStackFrameSaver stackSaver;
  1144. stackSaver.save();
  1145. StringArrayToConsoleValueWrapper args(argc, argv);
  1146. return std::move(execute(object, args.count(), args, thisCallOnly));
  1147. }
  1148. inline ConsoleValue _executef(SimObject *obj, S32 checkArgc, S32 argc, ConsoleValue *argv)
  1149. {
  1150. const U32 maxArg = 12;
  1151. AssertFatal(checkArgc == argc, "Incorrect arg count passed to Con::executef(SimObject*)");
  1152. AssertFatal(argc <= maxArg - 1, "Too many args passed to Con::_executef(SimObject*). Please update the function to handle more.");
  1153. return std::move(execute(obj, argc, argv));
  1154. }
  1155. //------------------------------------------------------------------------------
  1156. inline ConsoleValue _executef(S32 checkArgc, S32 argc, ConsoleValue *argv)
  1157. {
  1158. const U32 maxArg = 10;
  1159. AssertFatal(checkArgc == argc, "Incorrect arg count passed to Con::executef()");
  1160. AssertFatal(argc <= maxArg, "Too many args passed to Con::_executef(). Please update the function to handle more.");
  1161. return std::move(execute(argc, argv));
  1162. }
  1163. //------------------------------------------------------------------------------
  1164. bool isFunction(const char *fn)
  1165. {
  1166. const char *string = StringTable->lookup(fn);
  1167. if(!string)
  1168. return false;
  1169. else
  1170. return Namespace::global()->lookup(string) != NULL;
  1171. }
  1172. //------------------------------------------------------------------------------
  1173. void setLogMode(S32 newMode)
  1174. {
  1175. if ((newMode & 0x3) != (consoleLogMode & 0x3)) {
  1176. if (newMode && !consoleLogMode) {
  1177. // Enabling logging when it was previously disabled.
  1178. newLogFile = true;
  1179. }
  1180. if ((consoleLogMode & 0x3) == 2) {
  1181. // Changing away from mode 2, must close logfile.
  1182. consoleLogFile.close();
  1183. }
  1184. else if ((newMode & 0x3) == 2) {
  1185. #ifdef _XBOX
  1186. // Xbox is not going to support logging to a file. Use the OutputDebugStr
  1187. // log consumer
  1188. Platform::debugBreak();
  1189. #endif
  1190. // Starting mode 2, must open logfile.
  1191. consoleLogFile.open(defLogFileName, Torque::FS::File::Write);
  1192. }
  1193. consoleLogMode = newMode;
  1194. }
  1195. }
  1196. //------------------------------------------------------------------------------
  1197. ReturnBuffer retBuffer;
  1198. char* getReturnBuffer(U32 bufferSize)
  1199. {
  1200. return retBuffer.getBuffer(bufferSize);
  1201. }
  1202. char* getReturnBuffer(const char* stringToCopy)
  1203. {
  1204. U32 len = dStrlen(stringToCopy) + 1;
  1205. char* ret = retBuffer.getBuffer(len);
  1206. dMemcpy(ret, stringToCopy, len);
  1207. return ret;
  1208. }
  1209. char* getReturnBuffer(const String& str)
  1210. {
  1211. const U32 size = str.size();
  1212. char* ret = retBuffer.getBuffer(size);
  1213. dMemcpy(ret, str.c_str(), size);
  1214. return ret;
  1215. }
  1216. char* getReturnBuffer(const StringBuilder& str)
  1217. {
  1218. char* buffer = Con::getReturnBuffer(str.length() + 1);
  1219. str.copy(buffer);
  1220. buffer[str.length()] = '\0';
  1221. return buffer;
  1222. }
  1223. char* getArgBuffer(U32 bufferSize)
  1224. {
  1225. return STR.getArgBuffer(bufferSize);
  1226. }
  1227. char* getFloatArg(F64 arg)
  1228. {
  1229. char* ret = STR.getArgBuffer(32);
  1230. dSprintf(ret, 32, "%g", arg);
  1231. return ret;
  1232. }
  1233. char* getIntArg(S32 arg)
  1234. {
  1235. char* ret = STR.getArgBuffer(32);
  1236. dSprintf(ret, 32, "%d", arg);
  1237. return ret;
  1238. }
  1239. char* getBoolArg(bool arg)
  1240. {
  1241. char* ret = STR.getArgBuffer(32);
  1242. dSprintf(ret, 32, "%d", arg);
  1243. return ret;
  1244. }
  1245. char* getStringArg(const char* arg)
  1246. {
  1247. U32 len = dStrlen(arg) + 1;
  1248. char* ret = STR.getArgBuffer(len);
  1249. dMemcpy(ret, arg, len);
  1250. return ret;
  1251. }
  1252. char* getStringArg(const String& arg)
  1253. {
  1254. const U32 size = arg.size();
  1255. char* ret = STR.getArgBuffer(size);
  1256. dMemcpy(ret, arg.c_str(), size);
  1257. return ret;
  1258. }
  1259. //------------------------------------------------------------------------------
  1260. Namespace *lookupNamespace(const char *ns)
  1261. {
  1262. if(!ns)
  1263. return Namespace::global();
  1264. return Namespace::find(StringTable->insert(ns));
  1265. }
  1266. bool linkNamespaces(const char *parent, const char *child)
  1267. {
  1268. Namespace *pns = lookupNamespace(parent);
  1269. Namespace *cns = lookupNamespace(child);
  1270. if(pns && cns)
  1271. return cns->classLinkTo(pns);
  1272. return false;
  1273. }
  1274. bool unlinkNamespaces(const char *parent, const char *child)
  1275. {
  1276. Namespace *pns = lookupNamespace(parent);
  1277. Namespace *cns = lookupNamespace(child);
  1278. if(pns == cns)
  1279. {
  1280. Con::warnf("Con::unlinkNamespaces - trying to unlink '%s' from itself, aborting.", parent);
  1281. return false;
  1282. }
  1283. if(pns && cns)
  1284. return cns->unlinkClass(pns);
  1285. return false;
  1286. }
  1287. bool classLinkNamespaces(Namespace *parent, Namespace *child)
  1288. {
  1289. if(parent && child)
  1290. return child->classLinkTo(parent);
  1291. return false;
  1292. }
  1293. void setData(S32 type, void *dptr, S32 index, S32 argc, const char **argv, const EnumTable *tbl, BitSet32 flag)
  1294. {
  1295. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1296. AssertFatal(cbt, "Con::setData - could not resolve type ID!");
  1297. cbt->setData((void *) (((const char *)dptr) + index * cbt->getTypeSize()),argc, argv, tbl, flag);
  1298. }
  1299. const char *getData(S32 type, void *dptr, S32 index, const EnumTable *tbl, BitSet32 flag)
  1300. {
  1301. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1302. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1303. return cbt->getData((void *) (((const char *)dptr) + index * cbt->getTypeSize()), tbl, flag);
  1304. }
  1305. const char *getFormattedData(S32 type, const char *data, const EnumTable *tbl, BitSet32 flag)
  1306. {
  1307. ConsoleBaseType *cbt = ConsoleBaseType::getType( type );
  1308. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1309. // Datablock types are just a datablock
  1310. // name and don't ever need formatting.
  1311. if ( cbt->isDatablock() )
  1312. return data;
  1313. bool currWarn = gWarnUndefinedScriptVariables;
  1314. gWarnUndefinedScriptVariables = false;
  1315. const char* globalValue = Con::getVariable(data);
  1316. gWarnUndefinedScriptVariables = currWarn;
  1317. if (dStrlen(globalValue) > 0)
  1318. return globalValue;
  1319. void* variable = cbt->getNativeVariable();
  1320. if (variable)
  1321. {
  1322. Con::setData(type, variable, 0, 1, &data, tbl, flag);
  1323. const char* formattedVal = Con::getData(type, variable, 0, tbl, flag);
  1324. static const U32 bufSize = 2048;
  1325. char* returnBuffer = Con::getReturnBuffer(bufSize);
  1326. dSprintf(returnBuffer, bufSize, "%s\0", formattedVal );
  1327. cbt->deleteNativeVariable(variable);
  1328. return returnBuffer;
  1329. }
  1330. else
  1331. return data;
  1332. }
  1333. //------------------------------------------------------------------------------
  1334. bool isCurrentScriptToolScript()
  1335. {
  1336. // With a player build we ALWAYS return false
  1337. #ifndef TORQUE_TOOLS
  1338. return false;
  1339. #else
  1340. const StringTableEntry cbFullPath = getCurrentScriptModulePath();
  1341. if(cbFullPath == NULL)
  1342. return false;
  1343. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1344. return dStrnicmp(exePath, cbFullPath, dStrlen(exePath)) == 0;
  1345. #endif
  1346. }
  1347. //------------------------------------------------------------------------------
  1348. bool isScriptFile(const char* pFilePath)
  1349. {
  1350. return (Torque::FS::IsFile(pFilePath)
  1351. || Torque::FS::IsFile(pFilePath + String(".dso"))
  1352. || Torque::FS::IsFile(pFilePath + String(".mis"))
  1353. || Torque::FS::IsFile(pFilePath + String(".mis.dso"))
  1354. || Torque::FS::IsFile(pFilePath + String(".gui"))
  1355. || Torque::FS::IsFile(pFilePath + String(".gui.dso"))
  1356. || Torque::FS::IsFile(pFilePath + String("." TORQUE_SCRIPT_EXTENSION))
  1357. || Torque::FS::IsFile(pFilePath + String("." TORQUE_SCRIPT_EXTENSION) + String(".dso")));
  1358. }
  1359. //------------------------------------------------------------------------------
  1360. StringTableEntry getModNameFromPath(const char *path)
  1361. {
  1362. if(path == NULL || *path == 0)
  1363. return NULL;
  1364. char buf[1024] = {};
  1365. buf[0] = 0;
  1366. if(path[0] == '/' || path[1] == ':')
  1367. {
  1368. // It's an absolute path
  1369. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1370. U32 len = dStrlen(exePath);
  1371. if(dStrnicmp(exePath, path, len) == 0)
  1372. {
  1373. const char *ptr = path + len + 1;
  1374. const char *slash = dStrchr(ptr, '/');
  1375. if(slash)
  1376. {
  1377. dStrncpy(buf, ptr, slash - ptr);
  1378. buf[slash - ptr] = 0;
  1379. }
  1380. else
  1381. return NULL;
  1382. }
  1383. else
  1384. return NULL;
  1385. }
  1386. else
  1387. {
  1388. const char *slash = dStrchr(path, '/');
  1389. if(slash)
  1390. {
  1391. dStrncpy(buf, path, slash - path);
  1392. buf[slash - path] = 0;
  1393. }
  1394. else
  1395. return NULL;
  1396. }
  1397. return StringTable->insert(buf);
  1398. }
  1399. void postConsoleInput( RawData data )
  1400. {
  1401. // Schedule this to happen at the next time event.
  1402. ConsoleValue argv[2];
  1403. argv[0].setString("eval");
  1404. argv[1].setString(reinterpret_cast<const char*>(data.data));
  1405. Sim::postCurrentEvent(Sim::getRootGroup(), new SimConsoleEvent(2, argv, false));
  1406. }
  1407. //------------------------------------------------------------------------------
  1408. void pushInstantGroup( String name )
  1409. {
  1410. sInstantGroupStack.push_back( gInstantGroup );
  1411. gInstantGroup = name;
  1412. }
  1413. void popInstantGroup()
  1414. {
  1415. if( sInstantGroupStack.empty() )
  1416. gInstantGroup = String::EmptyString;
  1417. else
  1418. {
  1419. gInstantGroup = sInstantGroupStack.last();
  1420. sInstantGroupStack.pop_back();
  1421. }
  1422. }
  1423. typedef HashMap<StringTableEntry, StringTableEntry> typePathExpandoMap;
  1424. static typePathExpandoMap PathExpandos;
  1425. //-----------------------------------------------------------------------------
  1426. void addPathExpando(const char* pExpandoName, const char* pPath)
  1427. {
  1428. // Sanity!
  1429. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1430. AssertFatal(pPath != NULL, "Expando path cannot be NULL.");
  1431. // Fetch expando name.
  1432. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1433. // Fetch the length of the path.
  1434. S32 pathLength = dStrlen(pPath);
  1435. char pathBuffer[1024];
  1436. // Sanity!
  1437. if (pathLength == 0 || pathLength >= sizeof(pathBuffer))
  1438. {
  1439. Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
  1440. return;
  1441. }
  1442. // Strip repeat slashes.
  1443. if (!Con::stripRepeatSlashes(pathBuffer, pPath, sizeof(pathBuffer)))
  1444. {
  1445. Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
  1446. return;
  1447. }
  1448. // Fetch new path length.
  1449. pathLength = dStrlen(pathBuffer);
  1450. // Sanity!
  1451. if (pathLength == 0)
  1452. {
  1453. Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
  1454. return;
  1455. }
  1456. // Remove any terminating slash.
  1457. if (pathBuffer[pathLength - 1] == '/')
  1458. pathBuffer[pathLength - 1] = 0;
  1459. // Fetch expanded path.
  1460. StringTableEntry expandedPath = StringTable->insert(pathBuffer);
  1461. // Info.
  1462. #if defined(TORQUE_DEBUG)
  1463. Con::printf("Adding path expando of '%s' as '%s'.", expandoName, expandedPath);
  1464. #endif
  1465. // Find any existing path expando.
  1466. typePathExpandoMap::iterator expandoItr = PathExpandos.find(pExpandoName);
  1467. // Does the expando exist?
  1468. if (expandoItr != PathExpandos.end())
  1469. {
  1470. // Yes, so modify the path.
  1471. expandoItr->value = expandedPath;
  1472. return;
  1473. }
  1474. // Insert expando.
  1475. PathExpandos.insert(expandoName, expandedPath);
  1476. }
  1477. //-----------------------------------------------------------------------------
  1478. StringTableEntry getPathExpando(const char* pExpandoName)
  1479. {
  1480. // Sanity!
  1481. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1482. // Fetch expando name.
  1483. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1484. // Find any existing path expando.
  1485. typePathExpandoMap::iterator expandoItr = PathExpandos.find(expandoName);
  1486. // Does the expando exist?
  1487. if (expandoItr != PathExpandos.end())
  1488. {
  1489. // Yes, so return it.
  1490. return expandoItr->value;
  1491. }
  1492. // Not found.
  1493. return NULL;
  1494. }
  1495. //-----------------------------------------------------------------------------
  1496. void removePathExpando(const char* pExpandoName)
  1497. {
  1498. // Sanity!
  1499. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1500. // Fetch expando name.
  1501. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1502. // Find any existing path expando.
  1503. typePathExpandoMap::iterator expandoItr = PathExpandos.find(expandoName);
  1504. // Does the expando exist?
  1505. if (expandoItr == PathExpandos.end())
  1506. {
  1507. // No, so warn.
  1508. #if defined(TORQUE_DEBUG)
  1509. Con::warnf("Removing path expando of '%s' but it does not exist.", expandoName);
  1510. #endif
  1511. return;
  1512. }
  1513. // Info.
  1514. #if defined(TORQUE_DEBUG)
  1515. Con::printf("Removing path expando of '%s' as '%s'.", expandoName, expandoItr->value);
  1516. #endif
  1517. // Remove expando.
  1518. PathExpandos.erase(expandoItr);
  1519. }
  1520. //-----------------------------------------------------------------------------
  1521. bool isPathExpando(const char* pExpandoName)
  1522. {
  1523. // Sanity!
  1524. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1525. // Fetch expando name.
  1526. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1527. return PathExpandos.contains(expandoName);
  1528. }
  1529. //-----------------------------------------------------------------------------
  1530. U32 getPathExpandoCount(void)
  1531. {
  1532. return PathExpandos.size();
  1533. }
  1534. //-----------------------------------------------------------------------------
  1535. StringTableEntry getPathExpandoKey(U32 expandoIndex)
  1536. {
  1537. // Finish if index is out of range.
  1538. if (expandoIndex >= PathExpandos.size())
  1539. return NULL;
  1540. // Find indexed iterator.
  1541. typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
  1542. while (expandoIndex > 0) { ++expandoItr; --expandoIndex; }
  1543. return expandoItr->key;
  1544. }
  1545. //-----------------------------------------------------------------------------
  1546. StringTableEntry getPathExpandoValue(U32 expandoIndex)
  1547. {
  1548. // Finish if index is out of range.
  1549. if (expandoIndex >= PathExpandos.size())
  1550. return NULL;
  1551. // Find indexed iterator.
  1552. typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
  1553. while (expandoIndex > 0) { ++expandoItr; --expandoIndex; }
  1554. return expandoItr->value;
  1555. }
  1556. //-----------------------------------------------------------------------------
  1557. bool expandPath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint, const bool ensureTrailingSlash)
  1558. {
  1559. char pathBuffer[2048] = {};
  1560. const char* pSrc = pSrcPath;
  1561. char* pSlash;
  1562. // Fetch leading character.
  1563. const char leadingToken = *pSrc;
  1564. // Fetch following token.
  1565. const char followingToken = leadingToken != 0 ? pSrc[1] : 0;
  1566. // Expando.
  1567. if (leadingToken == '^')
  1568. {
  1569. // Initial prefix search.
  1570. const char* pPrefixSrc = pSrc + 1;
  1571. char* pPrefixDst = pathBuffer;
  1572. // Search for end of expando.
  1573. while (*pPrefixSrc != '/' && *pPrefixSrc != 0)
  1574. {
  1575. // Copy prefix character.
  1576. *pPrefixDst++ = *pPrefixSrc++;
  1577. }
  1578. // Yes, so terminate the expando string.
  1579. *pPrefixDst = 0;
  1580. // Fetch the expando path.
  1581. StringTableEntry expandoPath = getPathExpando(pathBuffer);
  1582. // Does the expando exist?
  1583. if (expandoPath == NULL)
  1584. {
  1585. // No, so error.
  1586. Con::errorf("expandPath() : Could not find path expando '%s' for path '%s'.", pathBuffer, pSrcPath);
  1587. // Are we ensuring the trailing slash?
  1588. if (ensureTrailingSlash)
  1589. {
  1590. // Yes, so ensure it.
  1591. Con::ensureTrailingSlash(pDstPath, pSrcPath, size);
  1592. }
  1593. else
  1594. {
  1595. // No, so just use the source path.
  1596. dStrcpy(pDstPath, pSrcPath, size);
  1597. }
  1598. return false;
  1599. }
  1600. // Skip the expando and the following slash.
  1601. pSrc += dStrlen(pathBuffer) + 1;
  1602. // Format the output path.
  1603. dSprintf(pathBuffer, sizeof(pathBuffer), "%s/%s", expandoPath, pSrc);
  1604. // Are we ensuring the trailing slash?
  1605. if (ensureTrailingSlash)
  1606. {
  1607. // Yes, so ensure it.
  1608. Con::ensureTrailingSlash(pathBuffer, pathBuffer, size);
  1609. }
  1610. // Strip repeat slashes.
  1611. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1612. return true;
  1613. }
  1614. // Script-Relative.
  1615. if (leadingToken == '.')
  1616. {
  1617. // Fetch the code-block file-path.
  1618. const StringTableEntry codeblockFullPath = getCurrentScriptModulePath();
  1619. // Do we have a code block full path?
  1620. if (codeblockFullPath == NULL)
  1621. {
  1622. // No, so error.
  1623. Con::errorf("expandPath() : Could not find relative path from code-block for path '%s'.", pSrcPath);
  1624. // Are we ensuring the trailing slash?
  1625. if (ensureTrailingSlash)
  1626. {
  1627. // Yes, so ensure it.
  1628. Con::ensureTrailingSlash(pDstPath, pSrcPath, size);
  1629. }
  1630. else
  1631. {
  1632. // No, so just use the source path.
  1633. dStrcpy(pDstPath, pSrcPath, size);
  1634. }
  1635. return false;
  1636. }
  1637. // Yes, so use it as the prefix.
  1638. dStrncpy(pathBuffer, codeblockFullPath, sizeof(pathBuffer) - 1);
  1639. // Find the final slash in the code-block.
  1640. pSlash = dStrrchr(pathBuffer, '/');
  1641. // Is this a parent directory token?
  1642. if (followingToken == '.')
  1643. {
  1644. // Yes, so terminate after the slash so we include it.
  1645. pSlash[1] = 0;
  1646. }
  1647. else
  1648. {
  1649. // No, it's a current directory token so terminate at the slash so we don't include it.
  1650. pSlash[0] = 0;
  1651. // Skip the current directory token.
  1652. pSrc++;
  1653. }
  1654. // Format the output path.
  1655. dStrncat(pathBuffer, "/", sizeof(pathBuffer) - 1 - strlen(pathBuffer));
  1656. dStrncat(pathBuffer, pSrc, sizeof(pathBuffer) - 1 - strlen(pathBuffer));
  1657. // Are we ensuring the trailing slash?
  1658. if (ensureTrailingSlash)
  1659. {
  1660. // Yes, so ensure it.
  1661. Con::ensureTrailingSlash(pathBuffer, pathBuffer, size);
  1662. }
  1663. // Strip repeat slashes.
  1664. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1665. return true;
  1666. }
  1667. // All else.
  1668. //Using a special case here because the code below barfs on trying to build a full path for apk reading
  1669. #ifdef TORQUE_OS_ANDROID
  1670. if (leadingToken == '/' || strstr(pSrcPath, "/") == NULL)
  1671. Platform::makeFullPathName(pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint);
  1672. else
  1673. dSprintf(pathBuffer, sizeof(pathBuffer), "/%s", pSrcPath);
  1674. #else
  1675. Platform::makeFullPathName(pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint);
  1676. #endif
  1677. // Are we ensuring the trailing slash?
  1678. if (ensureTrailingSlash)
  1679. {
  1680. // Yes, so ensure it.
  1681. Con::ensureTrailingSlash(pathBuffer, pathBuffer, size);
  1682. }
  1683. // Strip repeat slashes.
  1684. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1685. return true;
  1686. }
  1687. //-----------------------------------------------------------------------------
  1688. bool isBasePath(const char* SrcPath, const char* pBasePath)
  1689. {
  1690. char expandBuffer[1024], expandBaseBuffer[1024];
  1691. Con::expandPath(expandBuffer, sizeof(expandBuffer), SrcPath);
  1692. Con::expandPath(expandBaseBuffer, sizeof(expandBaseBuffer), pBasePath);
  1693. return dStrnicmp(expandBaseBuffer, expandBuffer, dStrlen(expandBaseBuffer)) == 0;
  1694. }
  1695. //-----------------------------------------------------------------------------
  1696. void collapsePath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint)
  1697. {
  1698. // Check path against expandos. If there are multiple matches, choose the
  1699. // expando that produces the shortest relative path.
  1700. char pathBuffer[2048];
  1701. // Fetch expando count.
  1702. const U32 expandoCount = getPathExpandoCount();
  1703. // Iterate expandos.
  1704. U32 expandoRelativePathLength = U32_MAX;
  1705. for (U32 expandoIndex = 0; expandoIndex < expandoCount; ++expandoIndex)
  1706. {
  1707. // Fetch expando value (path).
  1708. StringTableEntry expandoValue = getPathExpandoValue(expandoIndex);
  1709. // Skip if not the base path.
  1710. if (!isBasePath(pSrcPath, expandoValue))
  1711. continue;
  1712. // Fetch path relative to expando path.
  1713. StringTableEntry relativePath = Platform::makeRelativePathName(pSrcPath, expandoValue);
  1714. // If the relative path is simply a period
  1715. if (relativePath[0] == '.')
  1716. relativePath++;
  1717. if (dStrlen(relativePath) > expandoRelativePathLength)
  1718. {
  1719. // This expando covers less of the path than any previous one found.
  1720. // We will keep the previous one.
  1721. continue;
  1722. }
  1723. // Keep track of the relative path length
  1724. expandoRelativePathLength = dStrlen(relativePath);
  1725. // Fetch expando key (name).
  1726. StringTableEntry expandoName = getPathExpandoKey(expandoIndex);
  1727. // Format against expando.
  1728. dSprintf(pathBuffer, sizeof(pathBuffer), "^%s/%s", expandoName, relativePath);
  1729. }
  1730. // Check if we've found a suitable expando
  1731. if (expandoRelativePathLength != U32_MAX)
  1732. {
  1733. // Strip repeat slashes.
  1734. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1735. return;
  1736. }
  1737. // Fetch the working directory.
  1738. StringTableEntry workingDirectory = pWorkingDirectoryHint != NULL ? pWorkingDirectoryHint : Platform::getCurrentDirectory();
  1739. // Fetch path relative to current directory.
  1740. StringTableEntry relativePath = Platform::makeRelativePathName(pSrcPath, workingDirectory);
  1741. // If the relative path is simply a period
  1742. if (relativePath[0] == '.' && relativePath[1] != '.')
  1743. relativePath++;
  1744. // Format against expando.
  1745. dSprintf(pathBuffer, sizeof(pathBuffer), "%s/%s", workingDirectory, relativePath);
  1746. // Strip repeat slashes.
  1747. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1748. }
  1749. void ensureTrailingSlash(char* pDstPath, const char* pSrcPath, S32 dstSize)
  1750. {
  1751. // Copy to target.
  1752. dStrcpy(pDstPath, pSrcPath, dstSize);
  1753. // Find trailing character index.
  1754. S32 trailIndex = dStrlen(pDstPath);
  1755. // Ignore if empty string.
  1756. if (trailIndex == 0)
  1757. return;
  1758. // Finish if the trailing slash already exists.
  1759. if (pDstPath[trailIndex - 1] == '/')
  1760. return;
  1761. // Add trailing slash.
  1762. pDstPath[trailIndex++] = '/';
  1763. pDstPath[trailIndex] = 0;
  1764. }
  1765. //-----------------------------------------------------------------------------
  1766. StringTableEntry getDSOPath(const char *scriptPath)
  1767. {
  1768. #ifndef TORQUE2D_TOOLS_FIXME
  1769. // [tom, 11/17/2006] Force old behavior for the player. May not want to do this.
  1770. const char *slash = dStrrchr(scriptPath, '/');
  1771. if (slash != NULL)
  1772. return StringTable->insertn(scriptPath, slash - scriptPath, true);
  1773. slash = dStrrchr(scriptPath, ':');
  1774. if (slash != NULL)
  1775. return StringTable->insertn(scriptPath, (slash - scriptPath) + 1, true);
  1776. return "";
  1777. #else
  1778. char relPath[1024], dsoPath[1024];
  1779. bool isPrefs = false;
  1780. // [tom, 11/17/2006] Prefs are handled slightly differently to avoid dso name clashes
  1781. StringTableEntry prefsPath = Platform::getPrefsPath();
  1782. if (dStrnicmp(scriptPath, prefsPath, dStrlen(prefsPath)) == 0)
  1783. {
  1784. relPath[0] = 0;
  1785. isPrefs = true;
  1786. }
  1787. else
  1788. {
  1789. StringTableEntry strippedPath = Platform::stripBasePath(scriptPath);
  1790. dStrcpy(relPath, strippedPath, 1024);
  1791. char *slash = dStrrchr(relPath, '/');
  1792. if (slash)
  1793. *slash = 0;
  1794. }
  1795. const char *overridePath;
  1796. if (!isPrefs)
  1797. overridePath = Con::getVariable("$Scripts::OverrideDSOPath");
  1798. else
  1799. overridePath = prefsPath;
  1800. if (overridePath && *overridePath)
  1801. Platform::makeFullPathName(relPath, dsoPath, sizeof(dsoPath), overridePath);
  1802. else
  1803. {
  1804. char t[1024];
  1805. dSprintf(t, sizeof(t), "compiledScripts/%s", relPath);
  1806. Platform::makeFullPathName(t, dsoPath, sizeof(dsoPath), Platform::getPrefsPath());
  1807. }
  1808. return StringTable->insert(dsoPath);
  1809. #endif
  1810. }
  1811. //-----------------------------------------------------------------------------
  1812. bool stripRepeatSlashes(char* pDstPath, const char* pSrcPath, S32 dstSize)
  1813. {
  1814. // Note original destination.
  1815. char* pOriginalDst = pDstPath;
  1816. // Reset last source character.
  1817. char lastSrcChar = 0;
  1818. // Search source...
  1819. while (dstSize > 0)
  1820. {
  1821. // Fetch characters.
  1822. const char srcChar = *pSrcPath++;
  1823. // Do we have a repeat slash?
  1824. if (srcChar == '/' && lastSrcChar == '/')
  1825. {
  1826. // Yes, so skip it.
  1827. continue;
  1828. }
  1829. // No, so copy character.
  1830. *pDstPath++ = srcChar;
  1831. // Finish if end of source.
  1832. if (srcChar == 0)
  1833. return true;
  1834. // Reduce room left in destination.
  1835. dstSize--;
  1836. // Set last character.
  1837. lastSrcChar = srcChar;
  1838. }
  1839. // Terminate the destination string as we ran out of room.
  1840. *pOriginalDst = 0;
  1841. // Fail!
  1842. return false;
  1843. }
  1844. } // end of Console namespace
  1845. #endif
  1846. //=============================================================================
  1847. // API.
  1848. //=============================================================================
  1849. // MARK: ---- API ----
  1850. //-----------------------------------------------------------------------------
  1851. DefineEngineFunction( log, void, ( const char* message ),,
  1852. "@brief Logs a message to the console.\n\n"
  1853. "@param message The message text.\n"
  1854. "@note By default, messages will appear white in the console.\n"
  1855. "@ingroup Logging")
  1856. {
  1857. Con::printf( "%s", message );
  1858. }
  1859. //-----------------------------------------------------------------------------
  1860. DefineEngineFunction( logError, void, ( const char* message ),,
  1861. "@brief Logs an error message to the console.\n\n"
  1862. "@param message The message text.\n"
  1863. "@note By default, errors will appear red in the console.\n"
  1864. "@ingroup Logging")
  1865. {
  1866. Con::errorf( "%s", message );
  1867. }
  1868. //-----------------------------------------------------------------------------
  1869. DefineEngineFunction( logWarning, void, ( const char* message ),,
  1870. "@brief Logs a warning message to the console.\n\n"
  1871. "@param message The message text.\n\n"
  1872. "@note By default, warnings will appear turquoise in the console.\n"
  1873. "@ingroup Logging")
  1874. {
  1875. Con::warnf( "%s", message );
  1876. }
  1877. //------------------------------------------------------------------------------
  1878. ConsoleValueToStringArrayWrapper::ConsoleValueToStringArrayWrapper(int targc, ConsoleValue *targv)
  1879. {
  1880. argv = new const char*[targc];
  1881. argc = targc;
  1882. for (S32 i = 0; i < targc; i++)
  1883. {
  1884. argv[i] = dStrdup(targv[i].getString());
  1885. }
  1886. }
  1887. ConsoleValueToStringArrayWrapper::~ConsoleValueToStringArrayWrapper()
  1888. {
  1889. for (S32 i = 0; i< argc; i++)
  1890. {
  1891. dFree(argv[i]);
  1892. }
  1893. delete[] argv;
  1894. }
  1895. StringArrayToConsoleValueWrapper::StringArrayToConsoleValueWrapper(int targc, const char** targv)
  1896. {
  1897. argv = new ConsoleValue[targc]();
  1898. argc = targc;
  1899. for (int i=0; i<targc; i++)
  1900. {
  1901. argv[i].setString(targv[i]);
  1902. }
  1903. }
  1904. StringArrayToConsoleValueWrapper::~StringArrayToConsoleValueWrapper()
  1905. {
  1906. delete[] argv;
  1907. }
  1908. //------------------------------------------------------------------------------
  1909. ConsoleValue _BaseEngineConsoleCallbackHelper::_exec()
  1910. {
  1911. if( mThis )
  1912. {
  1913. // Cannot invoke callback until object has been registered
  1914. if (mThis->isProperlyAdded())
  1915. {
  1916. ConsoleValue returnValue = Con::_internalExecute( mThis, mArgc, mArgv, false );
  1917. mArgc = mInitialArgc; // reset
  1918. return returnValue;
  1919. }
  1920. STR.clearFunctionOffset();
  1921. mArgc = mInitialArgc; // reset
  1922. return std::move(ConsoleValue());
  1923. }
  1924. ConsoleValue returnValue = std::move(Con::_internalExecute( mArgc, mArgv ));
  1925. mArgc = mInitialArgc; // reset args
  1926. return returnValue;
  1927. }
  1928. ConsoleValue _BaseEngineConsoleCallbackHelper::_execLater(SimConsoleThreadExecEvent *evt)
  1929. {
  1930. mArgc = mInitialArgc; // reset args
  1931. Sim::postEvent((SimObject*)Sim::getRootGroup(), evt, Sim::getCurrentTime());
  1932. return std::move(evt->getCB().waitForResult());
  1933. }
  1934. //------------------------------------------------------------------------------
  1935. void ConsoleStackFrameSaver::save()
  1936. {
  1937. gCallStack.pushFrame(0);
  1938. mSaved = true;
  1939. }
  1940. void ConsoleStackFrameSaver::restore()
  1941. {
  1942. if (mSaved)
  1943. {
  1944. gCallStack.popFrame();
  1945. }
  1946. }
  1947. //------------------------------------------------------------------------------