console.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886
  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. CodeBlock *newCodeBlock = new CodeBlock();
  1013. return newCodeBlock->compileExec(NULL, buffer, false, 0);
  1014. }
  1015. //------------------------------------------------------------------------------
  1016. // Internal execute for global function which does not save the stack
  1017. ConsoleValueRef _internalExecute(S32 argc, ConsoleValueRef argv[])
  1018. {
  1019. Namespace::Entry *ent;
  1020. StringTableEntry funcName = StringTable->insert(argv[0]);
  1021. ent = Namespace::global()->lookup(funcName);
  1022. if(!ent)
  1023. {
  1024. warnf(ConsoleLogEntry::Script, "%s: Unknown command.", (const char*)argv[0]);
  1025. STR.clearFunctionOffset();
  1026. return ConsoleValueRef();
  1027. }
  1028. return ent->execute(argc, argv, &gEvalState);
  1029. }
  1030. ConsoleValueRef execute(S32 argc, ConsoleValueRef argv[])
  1031. {
  1032. #ifdef TORQUE_MULTITHREAD
  1033. if(isMainThread())
  1034. {
  1035. #endif
  1036. ConsoleStackFrameSaver stackSaver;
  1037. stackSaver.save();
  1038. return _internalExecute(argc, argv);
  1039. #ifdef TORQUE_MULTITHREAD
  1040. }
  1041. else
  1042. {
  1043. SimConsoleThreadExecCallback cb;
  1044. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, false, &cb);
  1045. Sim::postEvent(Sim::getRootGroup(), evt, Sim::getCurrentTime());
  1046. return cb.waitForResult();
  1047. }
  1048. #endif
  1049. }
  1050. ConsoleValueRef execute(S32 argc, const char *argv[])
  1051. {
  1052. ConsoleStackFrameSaver stackSaver;
  1053. stackSaver.save();
  1054. StringStackConsoleWrapper args(argc, argv);
  1055. return execute(args.count(), args);
  1056. }
  1057. //------------------------------------------------------------------------------
  1058. // Internal execute for object method which does not save the stack
  1059. ConsoleValueRef _internalExecute(SimObject *object, S32 argc, ConsoleValueRef argv[], bool thisCallOnly)
  1060. {
  1061. if(argc < 2)
  1062. {
  1063. STR.clearFunctionOffset();
  1064. return ConsoleValueRef();
  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. STR.pushFrame();
  1075. CSTK.pushFrame();
  1076. com->callMethodArgList(argc, argv, false);
  1077. STR.popFrame();
  1078. CSTK.popFrame();
  1079. }
  1080. }
  1081. if(object->getNamespace())
  1082. {
  1083. U32 ident = object->getId();
  1084. ConsoleValueRef oldIdent = argv[1];
  1085. StringTableEntry funcName = StringTable->insert(argv[0]);
  1086. Namespace::Entry *ent = object->getNamespace()->lookup(funcName);
  1087. if(ent == NULL)
  1088. {
  1089. //warnf(ConsoleLogEntry::Script, "%s: undefined for object '%s' - id %d", funcName, object->getName(), object->getId());
  1090. STR.clearFunctionOffset();
  1091. return ConsoleValueRef();
  1092. }
  1093. // Twiddle %this argument
  1094. argv[1] = (S32)ident;
  1095. SimObject *save = gEvalState.thisObject;
  1096. gEvalState.thisObject = object;
  1097. ConsoleValueRef ret = ent->execute(argc, argv, &gEvalState);
  1098. gEvalState.thisObject = save;
  1099. // Twiddle it back
  1100. argv[1] = oldIdent;
  1101. return ret;
  1102. }
  1103. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), (const char*)argv[0]);
  1104. STR.clearFunctionOffset();
  1105. return ConsoleValueRef();
  1106. }
  1107. ConsoleValueRef execute(SimObject *object, S32 argc, ConsoleValueRef argv[], bool thisCallOnly)
  1108. {
  1109. if(argc < 2)
  1110. {
  1111. STR.clearFunctionOffset();
  1112. return ConsoleValueRef();
  1113. }
  1114. ConsoleStackFrameSaver stackSaver;
  1115. stackSaver.save();
  1116. if (object->getNamespace() || !thisCallOnly)
  1117. {
  1118. if (isMainThread())
  1119. {
  1120. return _internalExecute(object, argc, argv, thisCallOnly);
  1121. }
  1122. else
  1123. {
  1124. SimConsoleThreadExecCallback cb;
  1125. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, true, &cb);
  1126. Sim::postEvent(object, evt, Sim::getCurrentTime());
  1127. }
  1128. }
  1129. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), (const char*)argv[0]);
  1130. STR.clearFunctionOffset();
  1131. return ConsoleValueRef();
  1132. }
  1133. ConsoleValueRef execute(SimObject *object, S32 argc, const char *argv[], bool thisCallOnly)
  1134. {
  1135. ConsoleStackFrameSaver stackSaver;
  1136. stackSaver.save();
  1137. StringStackConsoleWrapper args(argc, argv);
  1138. return execute(object, args.count(), args, thisCallOnly);
  1139. }
  1140. inline ConsoleValueRef _executef(SimObject *obj, S32 checkArgc, S32 argc, ConsoleValueRef *argv)
  1141. {
  1142. const U32 maxArg = 12;
  1143. AssertWarn(checkArgc == argc, "Incorrect arg count passed to Con::executef(SimObject*)");
  1144. AssertFatal(argc <= maxArg - 1, "Too many args passed to Con::_executef(SimObject*). Please update the function to handle more.");
  1145. return execute(obj, argc, argv);
  1146. }
  1147. //------------------------------------------------------------------------------
  1148. inline ConsoleValueRef _executef(S32 checkArgc, S32 argc, ConsoleValueRef *argv)
  1149. {
  1150. const U32 maxArg = 10;
  1151. AssertFatal(checkArgc == argc, "Incorrect arg count passed to Con::executef()");
  1152. AssertFatal(argc <= maxArg, "Too many args passed to Con::_executef(). Please update the function to handle more.");
  1153. return execute(argc, argv);
  1154. }
  1155. //------------------------------------------------------------------------------
  1156. bool isFunction(const char *fn)
  1157. {
  1158. const char *string = StringTable->lookup(fn);
  1159. if(!string)
  1160. return false;
  1161. else
  1162. return Namespace::global()->lookup(string) != NULL;
  1163. }
  1164. //------------------------------------------------------------------------------
  1165. void setLogMode(S32 newMode)
  1166. {
  1167. if ((newMode & 0x3) != (consoleLogMode & 0x3)) {
  1168. if (newMode && !consoleLogMode) {
  1169. // Enabling logging when it was previously disabled.
  1170. newLogFile = true;
  1171. }
  1172. if ((consoleLogMode & 0x3) == 2) {
  1173. // Changing away from mode 2, must close logfile.
  1174. consoleLogFile.close();
  1175. }
  1176. else if ((newMode & 0x3) == 2) {
  1177. #ifdef _XBOX
  1178. // Xbox is not going to support logging to a file. Use the OutputDebugStr
  1179. // log consumer
  1180. Platform::debugBreak();
  1181. #endif
  1182. // Starting mode 2, must open logfile.
  1183. consoleLogFile.open(defLogFileName, Torque::FS::File::Write);
  1184. }
  1185. consoleLogMode = newMode;
  1186. }
  1187. }
  1188. Namespace *lookupNamespace(const char *ns)
  1189. {
  1190. if(!ns)
  1191. return Namespace::global();
  1192. return Namespace::find(StringTable->insert(ns));
  1193. }
  1194. bool linkNamespaces(const char *parent, const char *child)
  1195. {
  1196. Namespace *pns = lookupNamespace(parent);
  1197. Namespace *cns = lookupNamespace(child);
  1198. if(pns && cns)
  1199. return cns->classLinkTo(pns);
  1200. return false;
  1201. }
  1202. bool unlinkNamespaces(const char *parent, const char *child)
  1203. {
  1204. Namespace *pns = lookupNamespace(parent);
  1205. Namespace *cns = lookupNamespace(child);
  1206. if(pns == cns)
  1207. {
  1208. Con::warnf("Con::unlinkNamespaces - trying to unlink '%s' from itself, aborting.", parent);
  1209. return false;
  1210. }
  1211. if(pns && cns)
  1212. return cns->unlinkClass(pns);
  1213. return false;
  1214. }
  1215. bool classLinkNamespaces(Namespace *parent, Namespace *child)
  1216. {
  1217. if(parent && child)
  1218. return child->classLinkTo(parent);
  1219. return false;
  1220. }
  1221. void setData(S32 type, void *dptr, S32 index, S32 argc, const char **argv, const EnumTable *tbl, BitSet32 flag)
  1222. {
  1223. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1224. AssertFatal(cbt, "Con::setData - could not resolve type ID!");
  1225. cbt->setData((void *) (((const char *)dptr) + index * cbt->getTypeSize()),argc, argv, tbl, flag);
  1226. }
  1227. const char *getData(S32 type, void *dptr, S32 index, const EnumTable *tbl, BitSet32 flag)
  1228. {
  1229. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1230. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1231. return cbt->getData((void *) (((const char *)dptr) + index * cbt->getTypeSize()), tbl, flag);
  1232. }
  1233. const char *getFormattedData(S32 type, const char *data, const EnumTable *tbl, BitSet32 flag)
  1234. {
  1235. ConsoleBaseType *cbt = ConsoleBaseType::getType( type );
  1236. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1237. // Datablock types are just a datablock
  1238. // name and don't ever need formatting.
  1239. if ( cbt->isDatablock() )
  1240. return data;
  1241. bool currWarn = gWarnUndefinedScriptVariables;
  1242. gWarnUndefinedScriptVariables = false;
  1243. const char* globalValue = Con::getVariable(data);
  1244. gWarnUndefinedScriptVariables = currWarn;
  1245. if (dStrlen(globalValue) > 0)
  1246. return globalValue;
  1247. void* variable = cbt->getNativeVariable();
  1248. if (variable)
  1249. {
  1250. Con::setData(type, variable, 0, 1, &data, tbl, flag);
  1251. const char* formattedVal = Con::getData(type, variable, 0, tbl, flag);
  1252. static const U32 bufSize = 2048;
  1253. char* returnBuffer = Con::getReturnBuffer(bufSize);
  1254. dSprintf(returnBuffer, bufSize, "%s\0", formattedVal );
  1255. cbt->deleteNativeVariable(variable);
  1256. return returnBuffer;
  1257. }
  1258. else
  1259. return data;
  1260. }
  1261. //------------------------------------------------------------------------------
  1262. bool isCurrentScriptToolScript()
  1263. {
  1264. // With a player build we ALWAYS return false
  1265. #ifndef TORQUE_TOOLS
  1266. return false;
  1267. #else
  1268. const StringTableEntry cbFullPath = CodeBlock::getCurrentCodeBlockFullPath();
  1269. if(cbFullPath == NULL)
  1270. return false;
  1271. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1272. return dStrnicmp(exePath, cbFullPath, dStrlen(exePath)) == 0;
  1273. #endif
  1274. }
  1275. //------------------------------------------------------------------------------
  1276. StringTableEntry getModNameFromPath(const char *path)
  1277. {
  1278. if(path == NULL || *path == 0)
  1279. return NULL;
  1280. char buf[1024];
  1281. buf[0] = 0;
  1282. if(path[0] == '/' || path[1] == ':')
  1283. {
  1284. // It's an absolute path
  1285. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1286. U32 len = dStrlen(exePath);
  1287. if(dStrnicmp(exePath, path, len) == 0)
  1288. {
  1289. const char *ptr = path + len + 1;
  1290. const char *slash = dStrchr(ptr, '/');
  1291. if(slash)
  1292. {
  1293. dStrncpy(buf, ptr, slash - ptr);
  1294. buf[slash - ptr] = 0;
  1295. }
  1296. else
  1297. return NULL;
  1298. }
  1299. else
  1300. return NULL;
  1301. }
  1302. else
  1303. {
  1304. const char *slash = dStrchr(path, '/');
  1305. if(slash)
  1306. {
  1307. dStrncpy(buf, path, slash - path);
  1308. buf[slash - path] = 0;
  1309. }
  1310. else
  1311. return NULL;
  1312. }
  1313. return StringTable->insert(buf);
  1314. }
  1315. void postConsoleInput( RawData data )
  1316. {
  1317. // Schedule this to happen at the next time event.
  1318. ConsoleValueRef argv[2];
  1319. argv[0] = "eval";
  1320. argv[1] = ( const char* ) data.data;
  1321. Sim::postCurrentEvent(Sim::getRootGroup(), new SimConsoleEvent(2, argv, false));
  1322. }
  1323. //------------------------------------------------------------------------------
  1324. void pushInstantGroup( String name )
  1325. {
  1326. sInstantGroupStack.push_back( gInstantGroup );
  1327. gInstantGroup = name;
  1328. }
  1329. void popInstantGroup()
  1330. {
  1331. if( sInstantGroupStack.empty() )
  1332. gInstantGroup = String::EmptyString;
  1333. else
  1334. {
  1335. gInstantGroup = sInstantGroupStack.last();
  1336. sInstantGroupStack.pop_back();
  1337. }
  1338. }
  1339. } // end of Console namespace
  1340. #endif
  1341. //=============================================================================
  1342. // API.
  1343. //=============================================================================
  1344. // MARK: ---- API ----
  1345. //-----------------------------------------------------------------------------
  1346. DefineEngineFunction( log, void, ( const char* message ),,
  1347. "@brief Logs a message to the console.\n\n"
  1348. "@param message The message text.\n"
  1349. "@note By default, messages will appear white in the console.\n"
  1350. "@ingroup Logging")
  1351. {
  1352. Con::printf( "%s", message );
  1353. }
  1354. //-----------------------------------------------------------------------------
  1355. DefineEngineFunction( logError, void, ( const char* message ),,
  1356. "@brief Logs an error message to the console.\n\n"
  1357. "@param message The message text.\n"
  1358. "@note By default, errors will appear red in the console.\n"
  1359. "@ingroup Logging")
  1360. {
  1361. Con::errorf( "%s", message );
  1362. }
  1363. //-----------------------------------------------------------------------------
  1364. DefineEngineFunction( logWarning, void, ( const char* message ),,
  1365. "@brief Logs a warning message to the console.\n\n"
  1366. "@param message The message text.\n\n"
  1367. "@note By default, warnings will appear turquoise in the console.\n"
  1368. "@ingroup Logging")
  1369. {
  1370. Con::warnf( "%s", message );
  1371. }
  1372. //------------------------------------------------------------------------------
  1373. extern ConsoleValueStack CSTK;
  1374. ConsoleValueRef::ConsoleValueRef(const ConsoleValueRef &ref)
  1375. {
  1376. value = ref.value;
  1377. }
  1378. ConsoleValueRef::ConsoleValueRef(const char *newValue) : value(NULL)
  1379. {
  1380. *this = newValue;
  1381. }
  1382. ConsoleValueRef::ConsoleValueRef(const String &newValue) : value(NULL)
  1383. {
  1384. *this = (const char*)(newValue.utf8());
  1385. }
  1386. ConsoleValueRef::ConsoleValueRef(U32 newValue) : value(NULL)
  1387. {
  1388. *this = newValue;
  1389. }
  1390. ConsoleValueRef::ConsoleValueRef(S32 newValue) : value(NULL)
  1391. {
  1392. *this = newValue;
  1393. }
  1394. ConsoleValueRef::ConsoleValueRef(F32 newValue) : value(NULL)
  1395. {
  1396. *this = newValue;
  1397. }
  1398. ConsoleValueRef::ConsoleValueRef(F64 newValue) : value(NULL)
  1399. {
  1400. *this = newValue;
  1401. }
  1402. ConsoleValueRef& ConsoleValueRef::operator=(const ConsoleValueRef &newValue)
  1403. {
  1404. value = newValue.value;
  1405. return *this;
  1406. }
  1407. ConsoleValueRef& ConsoleValueRef::operator=(const char *newValue)
  1408. {
  1409. AssertFatal(value, "value should not be NULL");
  1410. value->setStringValue(newValue);
  1411. return *this;
  1412. }
  1413. ConsoleValueRef& ConsoleValueRef::operator=(S32 newValue)
  1414. {
  1415. AssertFatal(value, "value should not be NULL");
  1416. value->setIntValue(newValue);
  1417. return *this;
  1418. }
  1419. ConsoleValueRef& ConsoleValueRef::operator=(U32 newValue)
  1420. {
  1421. AssertFatal(value, "value should not be NULL");
  1422. value->setIntValue(newValue);
  1423. return *this;
  1424. }
  1425. ConsoleValueRef& ConsoleValueRef::operator=(F32 newValue)
  1426. {
  1427. AssertFatal(value, "value should not be NULL");
  1428. value->setFloatValue(newValue);
  1429. return *this;
  1430. }
  1431. ConsoleValueRef& ConsoleValueRef::operator=(F64 newValue)
  1432. {
  1433. AssertFatal(value, "value should not be NULL");
  1434. value->setFloatValue(newValue);
  1435. return *this;
  1436. }
  1437. //------------------------------------------------------------------------------
  1438. StringStackWrapper::StringStackWrapper(int targc, ConsoleValueRef targv[])
  1439. {
  1440. argv = new const char*[targc];
  1441. argc = targc;
  1442. for (int i=0; i<targc; i++)
  1443. {
  1444. argv[i] = dStrdup(targv[i]);
  1445. }
  1446. }
  1447. StringStackWrapper::~StringStackWrapper()
  1448. {
  1449. for (int i=0; i<argc; i++)
  1450. {
  1451. dFree(argv[i]);
  1452. }
  1453. delete[] argv;
  1454. }
  1455. StringStackConsoleWrapper::StringStackConsoleWrapper(int targc, const char** targ)
  1456. {
  1457. argv = new ConsoleValueRef[targc];
  1458. argvValue = new ConsoleValue[targc];
  1459. argc = targc;
  1460. for (int i=0; i<targc; i++) {
  1461. argvValue[i].init();
  1462. argv[i].value = &argvValue[i];
  1463. argvValue[i].setStackStringValue(targ[i]);
  1464. }
  1465. }
  1466. StringStackConsoleWrapper::~StringStackConsoleWrapper()
  1467. {
  1468. for (int i=0; i<argc; i++)
  1469. {
  1470. argv[i] = 0;
  1471. }
  1472. delete[] argv;
  1473. delete[] argvValue;
  1474. }
  1475. //------------------------------------------------------------------------------
  1476. S32 ConsoleValue::getSignedIntValue()
  1477. {
  1478. if(type <= TypeInternalString)
  1479. return (S32)fval;
  1480. else
  1481. return dAtoi(Con::getData(type, dataPtr, 0, enumTable));
  1482. }
  1483. U32 ConsoleValue::getIntValue()
  1484. {
  1485. if(type <= TypeInternalString)
  1486. return ival;
  1487. else
  1488. return dAtoi(Con::getData(type, dataPtr, 0, enumTable));
  1489. }
  1490. F32 ConsoleValue::getFloatValue()
  1491. {
  1492. if(type <= TypeInternalString)
  1493. return fval;
  1494. else
  1495. return dAtof(Con::getData(type, dataPtr, 0, enumTable));
  1496. }
  1497. const char *ConsoleValue::getStringValue()
  1498. {
  1499. if(type == TypeInternalString || type == TypeInternalStackString)
  1500. return sval;
  1501. else if (type == TypeInternalStringStackPtr)
  1502. return STR.mBuffer + (U32)sval;
  1503. if(type == TypeInternalFloat)
  1504. return Con::getData(TypeF32, &fval, 0);
  1505. else if(type == TypeInternalInt)
  1506. return Con::getData(TypeS32, &ival, 0);
  1507. else
  1508. return Con::getData(type, dataPtr, 0, enumTable);
  1509. }
  1510. StringStackPtr ConsoleValue::getStringStackPtr()
  1511. {
  1512. if (type == TypeInternalStringStackPtr)
  1513. return (U32)sval;
  1514. else
  1515. return (U32)-1;
  1516. }
  1517. bool ConsoleValue::getBoolValue()
  1518. {
  1519. if(type == TypeInternalString || type == TypeInternalStackString || type == TypeInternalStringStackPtr)
  1520. return dAtob(getStringValue());
  1521. if(type == TypeInternalFloat)
  1522. return fval > 0;
  1523. else if(type == TypeInternalInt)
  1524. return ival > 0;
  1525. else {
  1526. const char *value = Con::getData(type, dataPtr, 0, enumTable);
  1527. return dAtob(value);
  1528. }
  1529. }
  1530. void ConsoleValue::setIntValue(S32 val)
  1531. {
  1532. setFloatValue(val);
  1533. }
  1534. void ConsoleValue::setIntValue(U32 val)
  1535. {
  1536. if(type <= TypeInternalString)
  1537. {
  1538. fval = (F32)val;
  1539. ival = val;
  1540. if(sval != typeValueEmpty)
  1541. {
  1542. if (type != TypeInternalStackString && type != TypeInternalStringStackPtr) dFree(sval);
  1543. sval = typeValueEmpty;
  1544. }
  1545. type = TypeInternalInt;
  1546. }
  1547. else
  1548. {
  1549. const char *dptr = Con::getData(TypeS32, &val, 0);
  1550. Con::setData(type, dataPtr, 0, 1, &dptr, enumTable);
  1551. }
  1552. }
  1553. void ConsoleValue::setBoolValue(bool val)
  1554. {
  1555. return setIntValue(val ? 1 : 0);
  1556. }
  1557. void ConsoleValue::setFloatValue(F32 val)
  1558. {
  1559. if(type <= TypeInternalString)
  1560. {
  1561. fval = val;
  1562. ival = static_cast<U32>(val);
  1563. if(sval != typeValueEmpty)
  1564. {
  1565. if (type != TypeInternalStackString && type != TypeInternalStringStackPtr) dFree(sval);
  1566. sval = typeValueEmpty;
  1567. }
  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. }