console.cpp 54 KB

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