2
0

console.cpp 68 KB

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