console.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889
  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 "console/ast.h"
  31. #include "core/tAlgorithm.h"
  32. #include "console/consoleTypes.h"
  33. #include "console/telnetDebugger.h"
  34. #include "console/simBase.h"
  35. #include "console/compiler.h"
  36. #include "console/stringStack.h"
  37. #include "console/ICallMethod.h"
  38. #include "console/engineAPI.h"
  39. #include <stdarg.h>
  40. #include "platform/threads/mutex.h"
  41. extern StringStack STR;
  42. extern ConsoleValueStack CSTK;
  43. ConsoleDocFragment* ConsoleDocFragment::smFirst;
  44. ExprEvalState gEvalState;
  45. StmtNode *gStatementList;
  46. StmtNode *gAnonFunctionList;
  47. U32 gAnonFunctionID = 0;
  48. ConsoleConstructor *ConsoleConstructor::first = NULL;
  49. bool gWarnUndefinedScriptVariables;
  50. static char scratchBuffer[4096];
  51. CON_DECLARE_PARSER(CMD);
  52. static const char * prependDollar ( const char * name )
  53. {
  54. if(name[0] != '$')
  55. {
  56. S32 len = dStrlen(name);
  57. AssertFatal(len < sizeof(scratchBuffer)-2, "CONSOLE: name too long");
  58. scratchBuffer[0] = '$';
  59. dMemcpy(scratchBuffer + 1, name, len + 1);
  60. name = scratchBuffer;
  61. }
  62. return name;
  63. }
  64. static const char * prependPercent ( const char * name )
  65. {
  66. if(name[0] != '%')
  67. {
  68. S32 len = dStrlen(name);
  69. AssertFatal(len < sizeof(scratchBuffer)-2, "CONSOLE: name too long");
  70. scratchBuffer[0] = '%';
  71. dMemcpy(scratchBuffer + 1, name, len + 1);
  72. name = scratchBuffer;
  73. }
  74. return name;
  75. }
  76. //--------------------------------------
  77. void ConsoleConstructor::init( const char *cName, const char *fName, const char *usg, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  78. {
  79. mina = minArgs;
  80. maxa = maxArgs;
  81. funcName = fName;
  82. usage = usg;
  83. className = cName;
  84. sc = 0; fc = 0; vc = 0; bc = 0; ic = 0;
  85. callback = group = false;
  86. next = first;
  87. ns = false;
  88. first = this;
  89. toolOnly = isToolOnly;
  90. this->header = header;
  91. }
  92. void ConsoleConstructor::setup()
  93. {
  94. for(ConsoleConstructor *walk = first; walk; walk = walk->next)
  95. {
  96. #ifdef TORQUE_DEBUG
  97. walk->validate();
  98. #endif
  99. if( walk->sc )
  100. Con::addCommand( walk->className, walk->funcName, walk->sc, walk->usage, walk->mina, walk->maxa, walk->toolOnly, walk->header );
  101. else if( walk->ic )
  102. Con::addCommand( walk->className, walk->funcName, walk->ic, walk->usage, walk->mina, walk->maxa, walk->toolOnly, walk->header );
  103. else if( walk->fc )
  104. Con::addCommand( walk->className, walk->funcName, walk->fc, walk->usage, walk->mina, walk->maxa, walk->toolOnly, walk->header );
  105. else if( walk->vc )
  106. Con::addCommand( walk->className, walk->funcName, walk->vc, walk->usage, walk->mina, walk->maxa, walk->toolOnly, walk->header );
  107. else if( walk->bc )
  108. Con::addCommand( walk->className, walk->funcName, walk->bc, walk->usage, walk->mina, walk->maxa, walk->toolOnly, walk->header );
  109. else if( walk->group )
  110. Con::markCommandGroup( walk->className, walk->funcName, walk->usage );
  111. else if( walk->callback )
  112. Con::noteScriptCallback( walk->className, walk->funcName, walk->usage, walk->header );
  113. else if( walk->ns )
  114. {
  115. Namespace* ns = Namespace::find( StringTable->insert( walk->className ) );
  116. if( ns )
  117. ns->mUsage = walk->usage;
  118. }
  119. else
  120. {
  121. AssertISV( false, "Found a ConsoleConstructor with an indeterminate type!" );
  122. }
  123. }
  124. }
  125. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, StringCallback sfunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  126. {
  127. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  128. sc = sfunc;
  129. }
  130. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, IntCallback ifunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  131. {
  132. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  133. ic = ifunc;
  134. }
  135. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, FloatCallback ffunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  136. {
  137. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  138. fc = ffunc;
  139. }
  140. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, VoidCallback vfunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  141. {
  142. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  143. vc = vfunc;
  144. }
  145. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, BoolCallback bfunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  146. {
  147. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  148. bc = bfunc;
  149. }
  150. ConsoleConstructor::ConsoleConstructor(const char* className, const char* groupName, const char* aUsage)
  151. {
  152. init(className, groupName, usage, -1, -2);
  153. group = true;
  154. // Somewhere, the entry list is getting flipped, partially.
  155. // so we have to do tricks to deal with making sure usage
  156. // is properly populated.
  157. // This is probably redundant.
  158. static char * lastUsage = NULL;
  159. if(aUsage)
  160. lastUsage = (char *)aUsage;
  161. usage = lastUsage;
  162. }
  163. ConsoleConstructor::ConsoleConstructor(const char *className, const char *callbackName, const char *usage, ConsoleFunctionHeader* header )
  164. {
  165. init( className, callbackName, usage, -2, -3, false, header );
  166. callback = true;
  167. ns = true;
  168. }
  169. void ConsoleConstructor::validate()
  170. {
  171. #ifdef TORQUE_DEBUG
  172. // Don't do the following check if we're not a method/func.
  173. if(this->group)
  174. return;
  175. // In debug, walk the list and make sure this isn't a duplicate.
  176. for(ConsoleConstructor *walk = first; walk; walk = walk->next)
  177. {
  178. // Skip mismatching func/method names.
  179. if(dStricmp(walk->funcName, this->funcName))
  180. continue;
  181. // Don't compare functions with methods or vice versa.
  182. if(bool(this->className) != bool(walk->className))
  183. continue;
  184. // Skip mismatching classnames, if they're present.
  185. if(this->className && walk->className && dStricmp(walk->className, this->className))
  186. continue;
  187. // If we encounter ourselves, stop searching; this prevents duplicate
  188. // firing of the assert, instead only firing for the latter encountered
  189. // entry.
  190. if(this == walk)
  191. break;
  192. // Match!
  193. if(this->className)
  194. {
  195. AssertISV(false, avar("ConsoleConstructor::setup - ConsoleMethod '%s::%s' collides with another of the same name.", this->className, this->funcName));
  196. }
  197. else
  198. {
  199. AssertISV(false, avar("ConsoleConstructor::setup - ConsoleFunction '%s' collides with another of the same name.", this->funcName));
  200. }
  201. }
  202. #endif
  203. }
  204. // We comment out the implementation of the Con namespace when doxygenizing because
  205. // otherwise Doxygen decides to ignore our docs in console.h
  206. #ifndef DOXYGENIZING
  207. namespace Con
  208. {
  209. static Vector<ConsumerCallback> gConsumers(__FILE__, __LINE__);
  210. static Vector< String > sInstantGroupStack( __FILE__, __LINE__ );
  211. static DataChunker consoleLogChunker;
  212. static Vector<ConsoleLogEntry> consoleLog(__FILE__, __LINE__);
  213. static bool consoleLogLocked;
  214. static bool logBufferEnabled=true;
  215. static S32 printLevel = 10;
  216. static FileStream consoleLogFile;
  217. static const char *defLogFileName = "console.log";
  218. static S32 consoleLogMode = 0;
  219. static bool active = false;
  220. static bool newLogFile;
  221. static const char *logFileName;
  222. static const S32 MaxCompletionBufferSize = 4096;
  223. static char completionBuffer[MaxCompletionBufferSize];
  224. static char tabBuffer[MaxCompletionBufferSize] = {0};
  225. static SimObjectPtr<SimObject> tabObject;
  226. static U32 completionBaseStart;
  227. static U32 completionBaseLen;
  228. String gInstantGroup;
  229. Con::ConsoleInputEvent smConsoleInput;
  230. /// Current script file name and root, these are registered as
  231. /// console variables.
  232. /// @{
  233. ///
  234. StringTableEntry gCurrentFile;
  235. StringTableEntry gCurrentRoot;
  236. /// @}
  237. S32 gObjectCopyFailures = -1;
  238. bool alwaysUseDebugOutput = true;
  239. bool useTimestamp = false;
  240. ConsoleFunctionGroupBegin( Clipboard, "Miscellaneous functions to control the clipboard and clear the console.");
  241. DefineConsoleFunction( cls, void, (), , "()"
  242. "@brief Clears the console output.\n\n"
  243. "@ingroup Console")
  244. {
  245. if(consoleLogLocked)
  246. return;
  247. consoleLogChunker.freeBlocks();
  248. consoleLog.setSize(0);
  249. };
  250. DefineConsoleFunction( getClipboard, const char*, (), , "()"
  251. "@brief Get text from the clipboard.\n\n"
  252. "@internal")
  253. {
  254. return Platform::getClipboard();
  255. };
  256. DefineConsoleFunction( setClipboard, bool, (const char* text), , "(string text)"
  257. "@brief Set the system clipboard.\n\n"
  258. "@internal")
  259. {
  260. return Platform::setClipboard(text);
  261. };
  262. ConsoleFunctionGroupEnd( Clipboard );
  263. void postConsoleInput( RawData data );
  264. void init()
  265. {
  266. AssertFatal(active == false, "Con::init should only be called once.");
  267. // Set up general init values.
  268. active = true;
  269. logFileName = NULL;
  270. newLogFile = true;
  271. gWarnUndefinedScriptVariables = false;
  272. // Initialize subsystems.
  273. Namespace::init();
  274. ConsoleConstructor::setup();
  275. // Set up the parser(s)
  276. CON_ADD_PARSER(CMD, "cs", true); // TorqueScript
  277. // Setup the console types.
  278. ConsoleBaseType::initialize();
  279. // And finally, the ACR...
  280. AbstractClassRep::initialize();
  281. // Variables
  282. setVariable("Con::prompt", "% ");
  283. addVariable("Con::logBufferEnabled", TypeBool, &logBufferEnabled, "If true, the log buffer will be enabled.\n"
  284. "@ingroup Console\n");
  285. addVariable("Con::printLevel", TypeS32, &printLevel,
  286. "@brief This is deprecated.\n\n"
  287. "It is no longer in use and does nothing.\n"
  288. "@ingroup Console\n");
  289. addVariable("Con::warnUndefinedVariables", TypeBool, &gWarnUndefinedScriptVariables, "If true, a warning will be displayed in the console whenever a undefined variable is used in script.\n"
  290. "@ingroup Console\n");
  291. addVariable( "instantGroup", TypeRealString, &gInstantGroup, "The group that objects will be added to when they are created.\n"
  292. "@ingroup Console\n");
  293. addVariable("Con::objectCopyFailures", TypeS32, &gObjectCopyFailures, "If greater than zero then it counts the number of object creation "
  294. "failures based on a missing copy object and does not report an error..\n"
  295. "@ingroup Console\n");
  296. // Current script file name and root
  297. addVariable( "Con::File", TypeString, &gCurrentFile, "The currently executing script file.\n"
  298. "@ingroup FileSystem\n");
  299. addVariable( "Con::Root", TypeString, &gCurrentRoot, "The mod folder for the currently executing script file.\n"
  300. "@ingroup FileSystem\n" );
  301. // alwaysUseDebugOutput determines whether to send output to the platform's
  302. // "debug" system. see winConsole for an example.
  303. // in ship builds we don't expose this variable to script
  304. // and we set it to false by default (don't want to provide more information
  305. // to potential hackers). platform code should also ifdef out the code that
  306. // pays attention to this in ship builds (see winConsole.cpp)
  307. // note that enabling this can slow down your game
  308. // if you are running from the debugger and printing a lot of console messages.
  309. #ifndef TORQUE_SHIPPING
  310. addVariable("Con::alwaysUseDebugOutput", TypeBool, &alwaysUseDebugOutput,
  311. "@brief Determines whether to send output to the platform's \"debug\" system.\n\n"
  312. "@note This is disabled in shipping builds.\n"
  313. "@ingroup Console");
  314. #else
  315. alwaysUseDebugOutput = false;
  316. #endif
  317. // controls whether a timestamp is prepended to every console message
  318. addVariable("Con::useTimestamp", TypeBool, &useTimestamp, "If true a timestamp is prepended to every console message.\n"
  319. "@ingroup Console\n");
  320. // Plug us into the journaled console input signal.
  321. smConsoleInput.notify(postConsoleInput);
  322. }
  323. //--------------------------------------
  324. void shutdown()
  325. {
  326. AssertFatal(active == true, "Con::shutdown should only be called once.");
  327. active = false;
  328. smConsoleInput.remove(postConsoleInput);
  329. consoleLogFile.close();
  330. Namespace::shutdown();
  331. AbstractClassRep::shutdown();
  332. Compiler::freeConsoleParserList();
  333. }
  334. bool isActive()
  335. {
  336. return active;
  337. }
  338. bool isMainThread()
  339. {
  340. #ifdef TORQUE_MULTITHREAD
  341. return ThreadManager::isMainThread();
  342. #else
  343. // If we're single threaded we're always in the main thread.
  344. return true;
  345. #endif
  346. }
  347. //--------------------------------------
  348. void getLockLog(ConsoleLogEntry *&log, U32 &size)
  349. {
  350. consoleLogLocked = true;
  351. log = consoleLog.address();
  352. size = consoleLog.size();
  353. }
  354. void unlockLog()
  355. {
  356. consoleLogLocked = false;
  357. }
  358. U32 tabComplete(char* inputBuffer, U32 cursorPos, U32 maxResultLength, bool forwardTab)
  359. {
  360. // Check for null input.
  361. if (!inputBuffer[0])
  362. {
  363. return cursorPos;
  364. }
  365. // Cap the max result length.
  366. if (maxResultLength > MaxCompletionBufferSize)
  367. {
  368. maxResultLength = MaxCompletionBufferSize;
  369. }
  370. // See if this is the same partial text as last checked.
  371. if (dStrcmp(tabBuffer, inputBuffer))
  372. {
  373. // If not...
  374. // Save it for checking next time.
  375. dStrcpy(tabBuffer, inputBuffer);
  376. // Scan backward from the cursor position to find the base to complete from.
  377. S32 p = cursorPos;
  378. while ((p > 0) && (inputBuffer[p - 1] != ' ') && (inputBuffer[p - 1] != '.') && (inputBuffer[p - 1] != '('))
  379. {
  380. p--;
  381. }
  382. completionBaseStart = p;
  383. completionBaseLen = cursorPos - p;
  384. // Is this function being invoked on an object?
  385. if (inputBuffer[p - 1] == '.')
  386. {
  387. // If so...
  388. if (p <= 1)
  389. {
  390. // Bail if no object identifier.
  391. return cursorPos;
  392. }
  393. // Find the object identifier.
  394. S32 objLast = --p;
  395. while ((p > 0) && (inputBuffer[p - 1] != ' ') && (inputBuffer[p - 1] != '('))
  396. {
  397. p--;
  398. }
  399. if (objLast == p)
  400. {
  401. // Bail if no object identifier.
  402. return cursorPos;
  403. }
  404. // Look up the object identifier.
  405. dStrncpy(completionBuffer, inputBuffer + p, objLast - p);
  406. completionBuffer[objLast - p] = 0;
  407. tabObject = Sim::findObject(completionBuffer);
  408. if (tabObject == NULL)
  409. {
  410. // Bail if not found.
  411. return cursorPos;
  412. }
  413. }
  414. else
  415. {
  416. // Not invoked on an object; we'll use the global namespace.
  417. tabObject = 0;
  418. }
  419. }
  420. // Chop off the input text at the cursor position.
  421. inputBuffer[cursorPos] = 0;
  422. // Try to find a completion in the appropriate namespace.
  423. const char *newText;
  424. if (tabObject != 0)
  425. {
  426. newText = tabObject->tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  427. }
  428. else
  429. {
  430. // In the global namespace, we can complete on global vars as well as functions.
  431. if (inputBuffer[completionBaseStart] == '$')
  432. {
  433. newText = gEvalState.globalVars.tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  434. }
  435. else
  436. {
  437. newText = Namespace::global()->tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  438. }
  439. }
  440. if (newText)
  441. {
  442. // If we got something, append it to the input text.
  443. S32 len = dStrlen(newText);
  444. if (len + completionBaseStart > maxResultLength)
  445. {
  446. len = maxResultLength - completionBaseStart;
  447. }
  448. dStrncpy(inputBuffer + completionBaseStart, newText, len);
  449. inputBuffer[completionBaseStart + len] = 0;
  450. // And set the cursor after it.
  451. cursorPos = completionBaseStart + len;
  452. }
  453. // Save the modified input buffer for checking next time.
  454. dStrcpy(tabBuffer, inputBuffer);
  455. // Return the new (maybe) cursor position.
  456. return cursorPos;
  457. }
  458. //------------------------------------------------------------------------------
  459. static void log(const char *string)
  460. {
  461. // Bail if we ain't logging.
  462. if (!consoleLogMode)
  463. {
  464. return;
  465. }
  466. // In mode 1, we open, append, close on each log write.
  467. if ((consoleLogMode & 0x3) == 1)
  468. {
  469. consoleLogFile.open(defLogFileName, Torque::FS::File::ReadWrite);
  470. }
  471. // Write to the log if its status is hunky-dory.
  472. if ((consoleLogFile.getStatus() == Stream::Ok) || (consoleLogFile.getStatus() == Stream::EOS))
  473. {
  474. consoleLogFile.setPosition(consoleLogFile.getStreamSize());
  475. // If this is the first write...
  476. if (newLogFile)
  477. {
  478. // Make a header.
  479. Platform::LocalTime lt;
  480. Platform::getLocalTime(lt);
  481. char buffer[128];
  482. dSprintf(buffer, sizeof(buffer), "//-------------------------- %d/%d/%d -- %02d:%02d:%02d -----\r\n",
  483. lt.month + 1,
  484. lt.monthday,
  485. lt.year + 1900,
  486. lt.hour,
  487. lt.min,
  488. lt.sec);
  489. consoleLogFile.write(dStrlen(buffer), buffer);
  490. newLogFile = false;
  491. if (consoleLogMode & 0x4)
  492. {
  493. // Dump anything that has been printed to the console so far.
  494. consoleLogMode -= 0x4;
  495. U32 size, line;
  496. ConsoleLogEntry *log;
  497. getLockLog(log, size);
  498. for (line = 0; line < size; line++)
  499. {
  500. consoleLogFile.write(dStrlen(log[line].mString), log[line].mString);
  501. consoleLogFile.write(2, "\r\n");
  502. }
  503. unlockLog();
  504. }
  505. }
  506. // Now write what we came here to write.
  507. consoleLogFile.write(dStrlen(string), string);
  508. consoleLogFile.write(2, "\r\n");
  509. }
  510. if ((consoleLogMode & 0x3) == 1)
  511. {
  512. consoleLogFile.close();
  513. }
  514. }
  515. //------------------------------------------------------------------------------
  516. static void _printf(ConsoleLogEntry::Level level, ConsoleLogEntry::Type type, const char* fmt, va_list argptr)
  517. {
  518. if (!active)
  519. return;
  520. Con::active = false;
  521. char buffer[8192];
  522. U32 offset = 0;
  523. if( gEvalState.traceOn && gEvalState.getStackDepth() > 0 )
  524. {
  525. offset = gEvalState.getStackDepth() * 3;
  526. for(U32 i = 0; i < offset; i++)
  527. buffer[i] = ' ';
  528. }
  529. if (useTimestamp)
  530. {
  531. static U32 startTime = Platform::getRealMilliseconds();
  532. U32 curTime = Platform::getRealMilliseconds() - startTime;
  533. offset += dSprintf(buffer + offset, sizeof(buffer) - offset, "[+%4d.%03d]", U32(curTime * 0.001), curTime % 1000);
  534. }
  535. dVsprintf(buffer + offset, sizeof(buffer) - offset, fmt, argptr);
  536. for(S32 i = 0; i < gConsumers.size(); i++)
  537. gConsumers[i](level, buffer);
  538. if(logBufferEnabled || consoleLogMode)
  539. {
  540. char *pos = buffer;
  541. while(*pos)
  542. {
  543. if(*pos == '\t')
  544. *pos = '^';
  545. pos++;
  546. }
  547. pos = buffer;
  548. for(;;)
  549. {
  550. char *eofPos = dStrchr(pos, '\n');
  551. if(eofPos)
  552. *eofPos = 0;
  553. log(pos);
  554. if(logBufferEnabled && !consoleLogLocked)
  555. {
  556. ConsoleLogEntry entry;
  557. entry.mLevel = level;
  558. entry.mType = type;
  559. #ifndef TORQUE_SHIPPING // this is equivalent to a memory leak, turn it off in ship build
  560. entry.mString = (const char *)consoleLogChunker.alloc(dStrlen(pos) + 1);
  561. dStrcpy(const_cast<char*>(entry.mString), pos);
  562. // This prevents infinite recursion if the console itself needs to
  563. // re-allocate memory to accommodate the new console log entry, and
  564. // LOG_PAGE_ALLOCS is defined. It is kind of a dirty hack, but the
  565. // uses for LOG_PAGE_ALLOCS are limited, and it is not worth writing
  566. // a lot of special case code to support this situation. -patw
  567. const bool save = Con::active;
  568. Con::active = false;
  569. consoleLog.push_back(entry);
  570. Con::active = save;
  571. #endif
  572. }
  573. if(!eofPos)
  574. break;
  575. pos = eofPos + 1;
  576. }
  577. }
  578. Con::active = true;
  579. }
  580. //------------------------------------------------------------------------------
  581. void printf(const char* fmt,...)
  582. {
  583. va_list argptr;
  584. va_start(argptr, fmt);
  585. _printf(ConsoleLogEntry::Normal, ConsoleLogEntry::General, fmt, argptr);
  586. va_end(argptr);
  587. }
  588. void warnf(ConsoleLogEntry::Type type, const char* fmt,...)
  589. {
  590. va_list argptr;
  591. va_start(argptr, fmt);
  592. _printf(ConsoleLogEntry::Warning, type, fmt, argptr);
  593. va_end(argptr);
  594. }
  595. void errorf(ConsoleLogEntry::Type type, const char* fmt,...)
  596. {
  597. va_list argptr;
  598. va_start(argptr, fmt);
  599. _printf(ConsoleLogEntry::Error, type, fmt, argptr);
  600. va_end(argptr);
  601. }
  602. void warnf(const char* fmt,...)
  603. {
  604. va_list argptr;
  605. va_start(argptr, fmt);
  606. _printf(ConsoleLogEntry::Warning, ConsoleLogEntry::General, fmt, argptr);
  607. va_end(argptr);
  608. }
  609. void errorf(const char* fmt,...)
  610. {
  611. va_list argptr;
  612. va_start(argptr, fmt);
  613. _printf(ConsoleLogEntry::Error, ConsoleLogEntry::General, fmt, argptr);
  614. va_end(argptr);
  615. }
  616. //---------------------------------------------------------------------------
  617. bool getVariableObjectField(const char *name, SimObject **object, const char **field)
  618. {
  619. // get the field info from the object..
  620. const char *dot = dStrchr(name, '.');
  621. if(name[0] != '$' && dot)
  622. {
  623. S32 len = dStrlen(name);
  624. AssertFatal(len < sizeof(scratchBuffer)-1, "Sim::getVariable - name too long");
  625. dMemcpy(scratchBuffer, name, len+1);
  626. char * token = dStrtok(scratchBuffer, ".");
  627. SimObject * obj = Sim::findObject(token);
  628. if(!obj)
  629. return false;
  630. token = dStrtok(0, ".\0");
  631. if(!token)
  632. return false;
  633. while(token != NULL)
  634. {
  635. const char * val = obj->getDataField(StringTable->insert(token), 0);
  636. if(!val)
  637. return false;
  638. char *fieldToken = token;
  639. token = dStrtok(0, ".\0");
  640. if(token)
  641. {
  642. obj = Sim::findObject(token);
  643. if(!obj)
  644. return false;
  645. }
  646. else
  647. {
  648. *object = obj;
  649. *field = fieldToken;
  650. return true;
  651. }
  652. }
  653. }
  654. return false;
  655. }
  656. Dictionary::Entry *getLocalVariableEntry(const char *name)
  657. {
  658. name = prependPercent(name);
  659. return gEvalState.getCurrentFrame().lookup(StringTable->insert(name));
  660. }
  661. Dictionary::Entry *getVariableEntry(const char *name)
  662. {
  663. name = prependDollar(name);
  664. return gEvalState.globalVars.lookup(StringTable->insert(name));
  665. }
  666. Dictionary::Entry *addVariableEntry(const char *name)
  667. {
  668. name = prependDollar(name);
  669. return gEvalState.globalVars.add(StringTable->insert(name));
  670. }
  671. Dictionary::Entry *getAddVariableEntry(const char *name)
  672. {
  673. name = prependDollar(name);
  674. StringTableEntry stName = StringTable->insert(name);
  675. Dictionary::Entry *entry = gEvalState.globalVars.lookup(stName);
  676. if (!entry)
  677. entry = gEvalState.globalVars.add(stName);
  678. return entry;
  679. }
  680. Dictionary::Entry *getAddLocalVariableEntry(const char *name)
  681. {
  682. name = prependPercent(name);
  683. StringTableEntry stName = StringTable->insert(name);
  684. Dictionary::Entry *entry = gEvalState.getCurrentFrame().lookup(stName);
  685. if (!entry)
  686. entry = gEvalState.getCurrentFrame().add(stName);
  687. return entry;
  688. }
  689. void setVariable(const char *name, const char *value)
  690. {
  691. SimObject *obj = NULL;
  692. const char *objField = NULL;
  693. if (getVariableObjectField(name, &obj, &objField))
  694. {
  695. obj->setDataField(StringTable->insert(objField), 0, value);
  696. }
  697. else
  698. {
  699. name = prependDollar(name);
  700. gEvalState.globalVars.setVariable(StringTable->insert(name), value);
  701. }
  702. }
  703. void setLocalVariable(const char *name, const char *value)
  704. {
  705. name = prependPercent(name);
  706. gEvalState.getCurrentFrame().setVariable(StringTable->insert(name), value);
  707. }
  708. void setBoolVariable(const char *varName, bool value)
  709. {
  710. SimObject *obj = NULL;
  711. const char *objField = NULL;
  712. if (getVariableObjectField(varName, &obj, &objField))
  713. {
  714. obj->setDataField(StringTable->insert(objField), 0, value ? "1" : "0");
  715. }
  716. else
  717. {
  718. varName = prependDollar(varName);
  719. Dictionary::Entry *entry = getAddVariableEntry(varName);
  720. entry->setStringValue(value ? "1" : "0");
  721. }
  722. }
  723. void setIntVariable(const char *varName, S32 value)
  724. {
  725. SimObject *obj = NULL;
  726. const char *objField = NULL;
  727. if (getVariableObjectField(varName, &obj, &objField))
  728. {
  729. char scratchBuffer[32];
  730. dSprintf(scratchBuffer, sizeof(scratchBuffer), "%d", value);
  731. obj->setDataField(StringTable->insert(objField), 0, scratchBuffer);
  732. }
  733. else
  734. {
  735. varName = prependDollar(varName);
  736. Dictionary::Entry *entry = getAddVariableEntry(varName);
  737. entry->setIntValue(value);
  738. }
  739. }
  740. void setFloatVariable(const char *varName, F32 value)
  741. {
  742. SimObject *obj = NULL;
  743. const char *objField = NULL;
  744. if (getVariableObjectField(varName, &obj, &objField))
  745. {
  746. char scratchBuffer[32];
  747. dSprintf(scratchBuffer, sizeof(scratchBuffer), "%g", value);
  748. obj->setDataField(StringTable->insert(objField), 0, scratchBuffer);
  749. }
  750. else
  751. {
  752. varName = prependDollar(varName);
  753. Dictionary::Entry *entry = getAddVariableEntry(varName);
  754. entry->setFloatValue(value);
  755. }
  756. }
  757. //---------------------------------------------------------------------------
  758. void addConsumer(ConsumerCallback consumer)
  759. {
  760. gConsumers.push_back(consumer);
  761. }
  762. // dhc - found this empty -- trying what I think is a reasonable impl.
  763. void removeConsumer(ConsumerCallback consumer)
  764. {
  765. for(S32 i = 0; i < gConsumers.size(); i++)
  766. {
  767. if (gConsumers[i] == consumer)
  768. {
  769. // remove it from the list.
  770. gConsumers.erase(i);
  771. break;
  772. }
  773. }
  774. }
  775. void stripColorChars(char* line)
  776. {
  777. char* c = line;
  778. char cp = *c;
  779. while (cp)
  780. {
  781. if (cp < 18)
  782. {
  783. // Could be a color control character; let's take a closer look.
  784. if ((cp != 8) && (cp != 9) && (cp != 10) && (cp != 13))
  785. {
  786. // Yep... copy following chars forward over this.
  787. char* cprime = c;
  788. char cpp;
  789. do
  790. {
  791. cpp = *++cprime;
  792. *(cprime - 1) = cpp;
  793. }
  794. while (cpp);
  795. // Back up 1 so we'll check this position again post-copy.
  796. c--;
  797. }
  798. }
  799. cp = *++c;
  800. }
  801. }
  802. //
  803. const char *getObjectTokenField(const char *name)
  804. {
  805. const char *dot = dStrchr(name, '.');
  806. if(name[0] != '$' && dot)
  807. {
  808. S32 len = dStrlen(name);
  809. AssertFatal(len < sizeof(scratchBuffer)-1, "Sim::getVariable - object name too long");
  810. dMemcpy(scratchBuffer, name, len+1);
  811. char * token = dStrtok(scratchBuffer, ".");
  812. SimObject * obj = Sim::findObject(token);
  813. if(!obj)
  814. return("");
  815. token = dStrtok(0, ".\0");
  816. if(!token)
  817. return("");
  818. while(token != NULL)
  819. {
  820. const char * val = obj->getDataField(StringTable->insert(token), 0);
  821. if(!val)
  822. return("");
  823. token = dStrtok(0, ".\0");
  824. if(token)
  825. {
  826. obj = Sim::findObject(token);
  827. if(!obj)
  828. return("");
  829. }
  830. else
  831. return(val);
  832. }
  833. }
  834. return NULL;
  835. }
  836. const char *getVariable(const char *name)
  837. {
  838. const char *objField = getObjectTokenField(name);
  839. if (objField)
  840. {
  841. return objField;
  842. }
  843. else
  844. {
  845. Dictionary::Entry *entry = getVariableEntry(name);
  846. return entry ? entry->getStringValue() : "";
  847. }
  848. }
  849. const char *getLocalVariable(const char *name)
  850. {
  851. name = prependPercent(name);
  852. return gEvalState.getCurrentFrame().getVariable(StringTable->insert(name));
  853. }
  854. bool getBoolVariable(const char *varName, bool def)
  855. {
  856. const char *objField = getObjectTokenField(varName);
  857. if (objField)
  858. {
  859. return *objField ? dAtob(objField) : def;
  860. }
  861. else
  862. {
  863. Dictionary::Entry *entry = getVariableEntry(varName);
  864. objField = entry ? entry->getStringValue() : "";
  865. return *objField ? dAtob(objField) : def;
  866. }
  867. }
  868. S32 getIntVariable(const char *varName, S32 def)
  869. {
  870. const char *objField = getObjectTokenField(varName);
  871. if (objField)
  872. {
  873. return *objField ? dAtoi(objField) : def;
  874. }
  875. else
  876. {
  877. Dictionary::Entry *entry = getVariableEntry(varName);
  878. return entry ? entry->getIntValue() : def;
  879. }
  880. }
  881. F32 getFloatVariable(const char *varName, F32 def)
  882. {
  883. const char *objField = getObjectTokenField(varName);
  884. if (objField)
  885. {
  886. return *objField ? dAtof(objField) : def;
  887. }
  888. else
  889. {
  890. Dictionary::Entry *entry = getVariableEntry(varName);
  891. return entry ? entry->getFloatValue() : def;
  892. }
  893. }
  894. //---------------------------------------------------------------------------
  895. void addVariable( const char *name,
  896. S32 type,
  897. void *dptr,
  898. const char* usage )
  899. {
  900. gEvalState.globalVars.addVariable( name, type, dptr, usage );
  901. }
  902. void addConstant( const char *name,
  903. S32 type,
  904. const void *dptr,
  905. const char* usage )
  906. {
  907. Dictionary::Entry* entry = gEvalState.globalVars.addVariable( name, type, const_cast< void* >( dptr ), usage );
  908. entry->mIsConstant = true;
  909. }
  910. bool removeVariable(const char *name)
  911. {
  912. name = StringTable->lookup(prependDollar(name));
  913. return name!=0 && gEvalState.globalVars.removeVariable(name);
  914. }
  915. void addVariableNotify( const char *name, const NotifyDelegate &callback )
  916. {
  917. gEvalState.globalVars.addVariableNotify( name, callback );
  918. }
  919. void removeVariableNotify( const char *name, const NotifyDelegate &callback )
  920. {
  921. gEvalState.globalVars.removeVariableNotify( name, callback );
  922. }
  923. //---------------------------------------------------------------------------
  924. void addCommand( const char *nsName, const char *name,StringCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  925. {
  926. Namespace *ns = lookupNamespace(nsName);
  927. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  928. }
  929. void addCommand( const char *nsName, const char *name,VoidCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  930. {
  931. Namespace *ns = lookupNamespace(nsName);
  932. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  933. }
  934. void addCommand( const char *nsName, const char *name,IntCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  935. {
  936. Namespace *ns = lookupNamespace(nsName);
  937. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  938. }
  939. void addCommand( const char *nsName, const char *name,FloatCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  940. {
  941. Namespace *ns = lookupNamespace(nsName);
  942. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  943. }
  944. void addCommand( const char *nsName, const char *name,BoolCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  945. {
  946. Namespace *ns = lookupNamespace(nsName);
  947. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  948. }
  949. void noteScriptCallback( const char *className, const char *funcName, const char *usage, ConsoleFunctionHeader* header )
  950. {
  951. Namespace *ns = lookupNamespace(className);
  952. ns->addScriptCallback( StringTable->insert(funcName), usage, header );
  953. }
  954. void markCommandGroup(const char * nsName, const char *name, const char* usage)
  955. {
  956. Namespace *ns = lookupNamespace(nsName);
  957. ns->markGroup(name,usage);
  958. }
  959. void beginCommandGroup(const char * nsName, const char *name, const char* usage)
  960. {
  961. markCommandGroup(nsName, name, usage);
  962. }
  963. void endCommandGroup(const char * nsName, const char *name)
  964. {
  965. markCommandGroup(nsName, name, NULL);
  966. }
  967. void addCommand( const char *name,StringCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  968. {
  969. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  970. }
  971. void addCommand( const char *name,VoidCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  972. {
  973. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  974. }
  975. void addCommand( const char *name,IntCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  976. {
  977. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  978. }
  979. void addCommand( const char *name,FloatCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  980. {
  981. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  982. }
  983. void addCommand( const char *name,BoolCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  984. {
  985. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  986. }
  987. ConsoleValueRef evaluate(const char* string, bool echo, const char *fileName)
  988. {
  989. ConsoleStackFrameSaver stackSaver;
  990. stackSaver.save();
  991. if (echo)
  992. {
  993. if (string[0] == '%')
  994. Con::printf("%s", string);
  995. else
  996. Con::printf("%s%s", getVariable( "$Con::Prompt" ), string);
  997. }
  998. if(fileName)
  999. fileName = StringTable->insert(fileName);
  1000. CodeBlock *newCodeBlock = new CodeBlock();
  1001. return newCodeBlock->compileExec(fileName, string, false, fileName ? -1 : 0);
  1002. }
  1003. //------------------------------------------------------------------------------
  1004. ConsoleValueRef evaluatef(const char* string, ...)
  1005. {
  1006. ConsoleStackFrameSaver stackSaver;
  1007. stackSaver.save();
  1008. char buffer[4096];
  1009. va_list args;
  1010. va_start(args, string);
  1011. dVsprintf(buffer, sizeof(buffer), string, args);
  1012. va_end(args);
  1013. CodeBlock *newCodeBlock = new CodeBlock();
  1014. return newCodeBlock->compileExec(NULL, buffer, false, 0);
  1015. }
  1016. //------------------------------------------------------------------------------
  1017. // Internal execute for global function which does not save the stack
  1018. ConsoleValueRef _internalExecute(S32 argc, ConsoleValueRef argv[])
  1019. {
  1020. Namespace::Entry *ent;
  1021. StringTableEntry funcName = StringTable->insert(argv[0]);
  1022. ent = Namespace::global()->lookup(funcName);
  1023. if(!ent)
  1024. {
  1025. warnf(ConsoleLogEntry::Script, "%s: Unknown command.", (const char*)argv[0]);
  1026. STR.clearFunctionOffset();
  1027. return ConsoleValueRef();
  1028. }
  1029. return ent->execute(argc, argv, &gEvalState);
  1030. }
  1031. ConsoleValueRef execute(S32 argc, ConsoleValueRef argv[])
  1032. {
  1033. #ifdef TORQUE_MULTITHREAD
  1034. if(isMainThread())
  1035. {
  1036. #endif
  1037. ConsoleStackFrameSaver stackSaver;
  1038. stackSaver.save();
  1039. return _internalExecute(argc, argv);
  1040. #ifdef TORQUE_MULTITHREAD
  1041. }
  1042. else
  1043. {
  1044. SimConsoleThreadExecCallback cb;
  1045. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, false, &cb);
  1046. Sim::postEvent(Sim::getRootGroup(), evt, Sim::getCurrentTime());
  1047. return cb.waitForResult();
  1048. }
  1049. #endif
  1050. }
  1051. ConsoleValueRef execute(S32 argc, const char *argv[])
  1052. {
  1053. ConsoleStackFrameSaver stackSaver;
  1054. stackSaver.save();
  1055. StringStackConsoleWrapper args(argc, argv);
  1056. return execute(args.count(), args);
  1057. }
  1058. //------------------------------------------------------------------------------
  1059. // Internal execute for object method which does not save the stack
  1060. ConsoleValueRef _internalExecute(SimObject *object, S32 argc, ConsoleValueRef argv[], bool thisCallOnly)
  1061. {
  1062. if(argc < 2)
  1063. {
  1064. STR.clearFunctionOffset();
  1065. return ConsoleValueRef();
  1066. }
  1067. // [neo, 10/05/2007 - #3010]
  1068. // Make sure we don't get recursive calls, respect the flag!
  1069. // Should we be calling handlesMethod() first?
  1070. if( !thisCallOnly )
  1071. {
  1072. ICallMethod *com = dynamic_cast<ICallMethod *>(object);
  1073. if(com)
  1074. {
  1075. STR.pushFrame();
  1076. CSTK.pushFrame();
  1077. com->callMethodArgList(argc, argv, false);
  1078. STR.popFrame();
  1079. CSTK.popFrame();
  1080. }
  1081. }
  1082. if(object->getNamespace())
  1083. {
  1084. U32 ident = object->getId();
  1085. ConsoleValueRef oldIdent = argv[1];
  1086. StringTableEntry funcName = StringTable->insert(argv[0]);
  1087. Namespace::Entry *ent = object->getNamespace()->lookup(funcName);
  1088. if(ent == NULL)
  1089. {
  1090. //warnf(ConsoleLogEntry::Script, "%s: undefined for object '%s' - id %d", funcName, object->getName(), object->getId());
  1091. STR.clearFunctionOffset();
  1092. return ConsoleValueRef();
  1093. }
  1094. // Twiddle %this argument
  1095. argv[1] = (S32)ident;
  1096. SimObject *save = gEvalState.thisObject;
  1097. gEvalState.thisObject = object;
  1098. ConsoleValueRef ret = ent->execute(argc, argv, &gEvalState);
  1099. gEvalState.thisObject = save;
  1100. // Twiddle it back
  1101. argv[1] = oldIdent;
  1102. return ret;
  1103. }
  1104. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), (const char*)argv[0]);
  1105. STR.clearFunctionOffset();
  1106. return ConsoleValueRef();
  1107. }
  1108. ConsoleValueRef execute(SimObject *object, S32 argc, ConsoleValueRef argv[], bool thisCallOnly)
  1109. {
  1110. if(argc < 2)
  1111. {
  1112. STR.clearFunctionOffset();
  1113. return ConsoleValueRef();
  1114. }
  1115. ConsoleStackFrameSaver stackSaver;
  1116. stackSaver.save();
  1117. if (object->getNamespace() || !thisCallOnly)
  1118. {
  1119. if (isMainThread())
  1120. {
  1121. return _internalExecute(object, argc, argv, thisCallOnly);
  1122. }
  1123. else
  1124. {
  1125. SimConsoleThreadExecCallback cb;
  1126. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, true, &cb);
  1127. Sim::postEvent(object, evt, Sim::getCurrentTime());
  1128. }
  1129. }
  1130. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), (const char*)argv[0]);
  1131. STR.clearFunctionOffset();
  1132. return ConsoleValueRef();
  1133. }
  1134. ConsoleValueRef execute(SimObject *object, S32 argc, const char *argv[], bool thisCallOnly)
  1135. {
  1136. ConsoleStackFrameSaver stackSaver;
  1137. stackSaver.save();
  1138. StringStackConsoleWrapper args(argc, argv);
  1139. return execute(object, args.count(), args, thisCallOnly);
  1140. }
  1141. inline ConsoleValueRef _executef(SimObject *obj, S32 checkArgc, S32 argc, ConsoleValueRef *argv)
  1142. {
  1143. const U32 maxArg = 12;
  1144. AssertWarn(checkArgc == argc, "Incorrect arg count passed to Con::executef(SimObject*)");
  1145. AssertFatal(argc <= maxArg - 1, "Too many args passed to Con::_executef(SimObject*). Please update the function to handle more.");
  1146. return execute(obj, argc, argv);
  1147. }
  1148. //------------------------------------------------------------------------------
  1149. inline ConsoleValueRef _executef(S32 checkArgc, S32 argc, ConsoleValueRef *argv)
  1150. {
  1151. const U32 maxArg = 10;
  1152. AssertFatal(checkArgc == argc, "Incorrect arg count passed to Con::executef()");
  1153. AssertFatal(argc <= maxArg, "Too many args passed to Con::_executef(). Please update the function to handle more.");
  1154. return execute(argc, argv);
  1155. }
  1156. //------------------------------------------------------------------------------
  1157. bool isFunction(const char *fn)
  1158. {
  1159. const char *string = StringTable->lookup(fn);
  1160. if(!string)
  1161. return false;
  1162. else
  1163. return Namespace::global()->lookup(string) != NULL;
  1164. }
  1165. //------------------------------------------------------------------------------
  1166. void setLogMode(S32 newMode)
  1167. {
  1168. if ((newMode & 0x3) != (consoleLogMode & 0x3)) {
  1169. if (newMode && !consoleLogMode) {
  1170. // Enabling logging when it was previously disabled.
  1171. newLogFile = true;
  1172. }
  1173. if ((consoleLogMode & 0x3) == 2) {
  1174. // Changing away from mode 2, must close logfile.
  1175. consoleLogFile.close();
  1176. }
  1177. else if ((newMode & 0x3) == 2) {
  1178. #ifdef _XBOX
  1179. // Xbox is not going to support logging to a file. Use the OutputDebugStr
  1180. // log consumer
  1181. Platform::debugBreak();
  1182. #endif
  1183. // Starting mode 2, must open logfile.
  1184. consoleLogFile.open(defLogFileName, Torque::FS::File::Write);
  1185. }
  1186. consoleLogMode = newMode;
  1187. }
  1188. }
  1189. Namespace *lookupNamespace(const char *ns)
  1190. {
  1191. if(!ns)
  1192. return Namespace::global();
  1193. return Namespace::find(StringTable->insert(ns));
  1194. }
  1195. bool linkNamespaces(const char *parent, const char *child)
  1196. {
  1197. Namespace *pns = lookupNamespace(parent);
  1198. Namespace *cns = lookupNamespace(child);
  1199. if(pns && cns)
  1200. return cns->classLinkTo(pns);
  1201. return false;
  1202. }
  1203. bool unlinkNamespaces(const char *parent, const char *child)
  1204. {
  1205. Namespace *pns = lookupNamespace(parent);
  1206. Namespace *cns = lookupNamespace(child);
  1207. if(pns == cns)
  1208. {
  1209. Con::warnf("Con::unlinkNamespaces - trying to unlink '%s' from itself, aborting.", parent);
  1210. return false;
  1211. }
  1212. if(pns && cns)
  1213. return cns->unlinkClass(pns);
  1214. return false;
  1215. }
  1216. bool classLinkNamespaces(Namespace *parent, Namespace *child)
  1217. {
  1218. if(parent && child)
  1219. return child->classLinkTo(parent);
  1220. return false;
  1221. }
  1222. void setData(S32 type, void *dptr, S32 index, S32 argc, const char **argv, const EnumTable *tbl, BitSet32 flag)
  1223. {
  1224. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1225. AssertFatal(cbt, "Con::setData - could not resolve type ID!");
  1226. cbt->setData((void *) (((const char *)dptr) + index * cbt->getTypeSize()),argc, argv, tbl, flag);
  1227. }
  1228. const char *getData(S32 type, void *dptr, S32 index, const EnumTable *tbl, BitSet32 flag)
  1229. {
  1230. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1231. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1232. return cbt->getData((void *) (((const char *)dptr) + index * cbt->getTypeSize()), tbl, flag);
  1233. }
  1234. const char *getFormattedData(S32 type, const char *data, const EnumTable *tbl, BitSet32 flag)
  1235. {
  1236. ConsoleBaseType *cbt = ConsoleBaseType::getType( type );
  1237. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1238. // Datablock types are just a datablock
  1239. // name and don't ever need formatting.
  1240. if ( cbt->isDatablock() )
  1241. return data;
  1242. bool currWarn = gWarnUndefinedScriptVariables;
  1243. gWarnUndefinedScriptVariables = false;
  1244. const char* globalValue = Con::getVariable(data);
  1245. gWarnUndefinedScriptVariables = currWarn;
  1246. if (dStrlen(globalValue) > 0)
  1247. return globalValue;
  1248. void* variable = cbt->getNativeVariable();
  1249. if (variable)
  1250. {
  1251. Con::setData(type, variable, 0, 1, &data, tbl, flag);
  1252. const char* formattedVal = Con::getData(type, variable, 0, tbl, flag);
  1253. static const U32 bufSize = 2048;
  1254. char* returnBuffer = Con::getReturnBuffer(bufSize);
  1255. dSprintf(returnBuffer, bufSize, "%s\0", formattedVal );
  1256. cbt->deleteNativeVariable(variable);
  1257. return returnBuffer;
  1258. }
  1259. else
  1260. return data;
  1261. }
  1262. //------------------------------------------------------------------------------
  1263. bool isCurrentScriptToolScript()
  1264. {
  1265. // With a player build we ALWAYS return false
  1266. #ifndef TORQUE_TOOLS
  1267. return false;
  1268. #else
  1269. const StringTableEntry cbFullPath = CodeBlock::getCurrentCodeBlockFullPath();
  1270. if(cbFullPath == NULL)
  1271. return false;
  1272. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1273. return dStrnicmp(exePath, cbFullPath, dStrlen(exePath)) == 0;
  1274. #endif
  1275. }
  1276. //------------------------------------------------------------------------------
  1277. StringTableEntry getModNameFromPath(const char *path)
  1278. {
  1279. if(path == NULL || *path == 0)
  1280. return NULL;
  1281. char buf[1024];
  1282. buf[0] = 0;
  1283. if(path[0] == '/' || path[1] == ':')
  1284. {
  1285. // It's an absolute path
  1286. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1287. U32 len = dStrlen(exePath);
  1288. if(dStrnicmp(exePath, path, len) == 0)
  1289. {
  1290. const char *ptr = path + len + 1;
  1291. const char *slash = dStrchr(ptr, '/');
  1292. if(slash)
  1293. {
  1294. dStrncpy(buf, ptr, slash - ptr);
  1295. buf[slash - ptr] = 0;
  1296. }
  1297. else
  1298. return NULL;
  1299. }
  1300. else
  1301. return NULL;
  1302. }
  1303. else
  1304. {
  1305. const char *slash = dStrchr(path, '/');
  1306. if(slash)
  1307. {
  1308. dStrncpy(buf, path, slash - path);
  1309. buf[slash - path] = 0;
  1310. }
  1311. else
  1312. return NULL;
  1313. }
  1314. return StringTable->insert(buf);
  1315. }
  1316. void postConsoleInput( RawData data )
  1317. {
  1318. // Schedule this to happen at the next time event.
  1319. ConsoleValue values[2];
  1320. ConsoleValueRef argv[2];
  1321. values[0].init();
  1322. values[0].setStringValue("eval");
  1323. values[1].init();
  1324. values[1].setStringValue((const char*)data.data);
  1325. argv[0].value = &values[0];
  1326. argv[1].value = &values[1];
  1327. Sim::postCurrentEvent(Sim::getRootGroup(), new SimConsoleEvent(2, argv, false));
  1328. }
  1329. //------------------------------------------------------------------------------
  1330. void pushInstantGroup( String name )
  1331. {
  1332. sInstantGroupStack.push_back( gInstantGroup );
  1333. gInstantGroup = name;
  1334. }
  1335. void popInstantGroup()
  1336. {
  1337. if( sInstantGroupStack.empty() )
  1338. gInstantGroup = String::EmptyString;
  1339. else
  1340. {
  1341. gInstantGroup = sInstantGroupStack.last();
  1342. sInstantGroupStack.pop_back();
  1343. }
  1344. }
  1345. } // end of Console namespace
  1346. #endif
  1347. //=============================================================================
  1348. // API.
  1349. //=============================================================================
  1350. // MARK: ---- API ----
  1351. //-----------------------------------------------------------------------------
  1352. DefineEngineFunction( log, void, ( const char* message ),,
  1353. "@brief Logs a message to the console.\n\n"
  1354. "@param message The message text.\n"
  1355. "@note By default, messages will appear white in the console.\n"
  1356. "@ingroup Logging")
  1357. {
  1358. Con::printf( "%s", message );
  1359. }
  1360. //-----------------------------------------------------------------------------
  1361. DefineEngineFunction( logError, void, ( const char* message ),,
  1362. "@brief Logs an error message to the console.\n\n"
  1363. "@param message The message text.\n"
  1364. "@note By default, errors will appear red in the console.\n"
  1365. "@ingroup Logging")
  1366. {
  1367. Con::errorf( "%s", message );
  1368. }
  1369. //-----------------------------------------------------------------------------
  1370. DefineEngineFunction( logWarning, void, ( const char* message ),,
  1371. "@brief Logs a warning message to the console.\n\n"
  1372. "@param message The message text.\n\n"
  1373. "@note By default, warnings will appear turquoise in the console.\n"
  1374. "@ingroup Logging")
  1375. {
  1376. Con::warnf( "%s", message );
  1377. }
  1378. //------------------------------------------------------------------------------
  1379. extern ConsoleValueStack CSTK;
  1380. ConsoleValueRef::ConsoleValueRef(const ConsoleValueRef &ref)
  1381. {
  1382. value = ref.value;
  1383. }
  1384. ConsoleValueRef& ConsoleValueRef::operator=(const ConsoleValueRef &newValue)
  1385. {
  1386. value = newValue.value;
  1387. return *this;
  1388. }
  1389. ConsoleValueRef& ConsoleValueRef::operator=(const char *newValue)
  1390. {
  1391. AssertFatal(value, "value should not be NULL");
  1392. value->setStringValue(newValue);
  1393. return *this;
  1394. }
  1395. ConsoleValueRef& ConsoleValueRef::operator=(S32 newValue)
  1396. {
  1397. AssertFatal(value, "value should not be NULL");
  1398. value->setIntValue(newValue);
  1399. return *this;
  1400. }
  1401. ConsoleValueRef& ConsoleValueRef::operator=(U32 newValue)
  1402. {
  1403. AssertFatal(value, "value should not be NULL");
  1404. value->setIntValue(newValue);
  1405. return *this;
  1406. }
  1407. ConsoleValueRef& ConsoleValueRef::operator=(F32 newValue)
  1408. {
  1409. AssertFatal(value, "value should not be NULL");
  1410. value->setFloatValue(newValue);
  1411. return *this;
  1412. }
  1413. ConsoleValueRef& ConsoleValueRef::operator=(F64 newValue)
  1414. {
  1415. AssertFatal(value, "value should not be NULL");
  1416. value->setFloatValue(newValue);
  1417. return *this;
  1418. }
  1419. //------------------------------------------------------------------------------
  1420. StringStackWrapper::StringStackWrapper(int targc, ConsoleValueRef targv[])
  1421. {
  1422. argv = new const char*[targc];
  1423. argc = targc;
  1424. for (int i=0; i<targc; i++)
  1425. {
  1426. argv[i] = dStrdup(targv[i]);
  1427. }
  1428. }
  1429. StringStackWrapper::~StringStackWrapper()
  1430. {
  1431. for (int i=0; i<argc; i++)
  1432. {
  1433. dFree(argv[i]);
  1434. }
  1435. delete[] argv;
  1436. }
  1437. StringStackConsoleWrapper::StringStackConsoleWrapper(int targc, const char** targ)
  1438. {
  1439. argv = new ConsoleValueRef[targc];
  1440. argvValue = new ConsoleValue[targc];
  1441. argc = targc;
  1442. for (int i=0; i<targc; i++) {
  1443. argvValue[i].init();
  1444. argv[i].value = &argvValue[i];
  1445. argvValue[i].setStackStringValue(targ[i]);
  1446. }
  1447. }
  1448. StringStackConsoleWrapper::~StringStackConsoleWrapper()
  1449. {
  1450. for (int i=0; i<argc; i++)
  1451. {
  1452. argv[i] = 0;
  1453. }
  1454. delete[] argv;
  1455. delete[] argvValue;
  1456. }
  1457. //------------------------------------------------------------------------------
  1458. S32 ConsoleValue::getSignedIntValue()
  1459. {
  1460. if(type <= TypeInternalString)
  1461. return (S32)fval;
  1462. else
  1463. return dAtoi(Con::getData(type, dataPtr, 0, enumTable));
  1464. }
  1465. U32 ConsoleValue::getIntValue()
  1466. {
  1467. if(type <= TypeInternalString)
  1468. return ival;
  1469. else
  1470. return dAtoi(Con::getData(type, dataPtr, 0, enumTable));
  1471. }
  1472. F32 ConsoleValue::getFloatValue()
  1473. {
  1474. if(type <= TypeInternalString)
  1475. return fval;
  1476. else
  1477. return dAtof(Con::getData(type, dataPtr, 0, enumTable));
  1478. }
  1479. const char *ConsoleValue::getStringValue()
  1480. {
  1481. if(type == TypeInternalString || type == TypeInternalStackString)
  1482. return sval;
  1483. else if (type == TypeInternalStringStackPtr)
  1484. return STR.mBuffer + (uintptr_t)sval;
  1485. else
  1486. {
  1487. // We need a string representation, so lets create one
  1488. const char *internalValue = NULL;
  1489. if(type == TypeInternalFloat)
  1490. internalValue = Con::getData(TypeF32, &fval, 0);
  1491. else if(type == TypeInternalInt)
  1492. internalValue = Con::getData(TypeS32, &ival, 0);
  1493. else
  1494. return Con::getData(type, dataPtr, 0, enumTable); // We can't save sval here since it is the same as dataPtr
  1495. if (!internalValue)
  1496. return "";
  1497. U32 stringLen = dStrlen(internalValue);
  1498. U32 newLen = ((stringLen + 1) + 15) & ~15; // pad upto next cache line
  1499. if (bufferLen == 0)
  1500. sval = (char *) dMalloc(newLen);
  1501. else if(newLen > bufferLen)
  1502. sval = (char *) dRealloc(sval, newLen);
  1503. dStrcpy(sval, internalValue);
  1504. bufferLen = newLen;
  1505. return sval;
  1506. }
  1507. }
  1508. StringStackPtr ConsoleValue::getStringStackPtr()
  1509. {
  1510. if (type == TypeInternalStringStackPtr)
  1511. return (uintptr_t)sval;
  1512. else
  1513. return (uintptr_t)-1;
  1514. }
  1515. bool ConsoleValue::getBoolValue()
  1516. {
  1517. if(type == TypeInternalString || type == TypeInternalStackString || type == TypeInternalStringStackPtr)
  1518. return dAtob(getStringValue());
  1519. if(type == TypeInternalFloat)
  1520. return fval > 0;
  1521. else if(type == TypeInternalInt)
  1522. return ival > 0;
  1523. else {
  1524. const char *value = Con::getData(type, dataPtr, 0, enumTable);
  1525. return dAtob(value);
  1526. }
  1527. }
  1528. void ConsoleValue::setIntValue(S32 val)
  1529. {
  1530. setFloatValue(val);
  1531. }
  1532. void ConsoleValue::setIntValue(U32 val)
  1533. {
  1534. if(type <= TypeInternalString)
  1535. {
  1536. fval = (F32)val;
  1537. ival = val;
  1538. if(bufferLen > 0)
  1539. {
  1540. dFree(sval);
  1541. bufferLen = 0;
  1542. }
  1543. sval = typeValueEmpty;
  1544. type = TypeInternalInt;
  1545. }
  1546. else
  1547. {
  1548. const char *dptr = Con::getData(TypeS32, &val, 0);
  1549. Con::setData(type, dataPtr, 0, 1, &dptr, enumTable);
  1550. }
  1551. }
  1552. void ConsoleValue::setBoolValue(bool val)
  1553. {
  1554. return setIntValue(val ? 1 : 0);
  1555. }
  1556. void ConsoleValue::setFloatValue(F32 val)
  1557. {
  1558. if(type <= TypeInternalString)
  1559. {
  1560. fval = val;
  1561. ival = static_cast<U32>(val);
  1562. if(bufferLen > 0)
  1563. {
  1564. dFree(sval);
  1565. bufferLen = 0;
  1566. }
  1567. sval = typeValueEmpty;
  1568. type = TypeInternalFloat;
  1569. }
  1570. else
  1571. {
  1572. const char *dptr = Con::getData(TypeF32, &val, 0);
  1573. Con::setData(type, dataPtr, 0, 1, &dptr, enumTable);
  1574. }
  1575. }
  1576. //------------------------------------------------------------------------------
  1577. ConsoleValueRef _BaseEngineConsoleCallbackHelper::_exec()
  1578. {
  1579. ConsoleValueRef returnValue;
  1580. if( mThis )
  1581. {
  1582. // Cannot invoke callback until object has been registered
  1583. if (mThis->isProperlyAdded()) {
  1584. returnValue = Con::_internalExecute( mThis, mArgc, mArgv, false );
  1585. } else {
  1586. STR.clearFunctionOffset();
  1587. returnValue = ConsoleValueRef();
  1588. }
  1589. }
  1590. else
  1591. returnValue = Con::_internalExecute( mArgc, mArgv );
  1592. mArgc = mInitialArgc; // reset args
  1593. return returnValue;
  1594. }
  1595. ConsoleValueRef _BaseEngineConsoleCallbackHelper::_execLater(SimConsoleThreadExecEvent *evt)
  1596. {
  1597. mArgc = mInitialArgc; // reset args
  1598. Sim::postEvent((SimObject*)Sim::getRootGroup(), evt, Sim::getCurrentTime());
  1599. return evt->getCB().waitForResult();
  1600. }
  1601. //------------------------------------------------------------------------------
  1602. void ConsoleStackFrameSaver::save()
  1603. {
  1604. CSTK.pushFrame();
  1605. STR.pushFrame();
  1606. mSaved = true;
  1607. }
  1608. void ConsoleStackFrameSaver::restore()
  1609. {
  1610. if (mSaved)
  1611. {
  1612. CSTK.popFrame();
  1613. STR.popFrame();
  1614. }
  1615. }