console.cpp 45 KB

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