console.cpp 53 KB

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