console.cpp 54 KB

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