console.cpp 53 KB

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