console.cc 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 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 "io/fileStream.h"
  29. #include "io/resource/resourceManager.h"
  30. #include "console/ast.h"
  31. #include "collection/findIterator.h"
  32. #include "console/consoleTypes.h"
  33. #include "debug/telnetDebugger.h"
  34. #include "sim/simBase.h"
  35. #include "console/compiler.h"
  36. #include "string/stringStack.h"
  37. #include "component/dynamicConsoleMethodComponent.h"
  38. #include "memory/safeDelete.h"
  39. #include <stdarg.h>
  40. #include "output_ScriptBinding.h"
  41. #include "expando_ScriptBinding.h"
  42. #ifndef _HASHTABLE_H_
  43. #include "collection/hashTable.h"
  44. #endif
  45. static Mutex* sLogMutex;
  46. extern StringStack STR;
  47. ExprEvalState gEvalState;
  48. StmtNode *statementList;
  49. ConsoleConstructor *ConsoleConstructor::first = NULL;
  50. bool gWarnUndefinedScriptVariables;
  51. static char scratchBuffer[4096];
  52. CON_DECLARE_PARSER(CMD);
  53. // TO-DO: Console debugger stuff to be cleaned up later
  54. static S32 dbgGetCurrentFrame(void)
  55. {
  56. return gEvalState.stack.size() - 1;
  57. }
  58. static const char * prependDollar ( const char * name )
  59. {
  60. if(name[0] != '$')
  61. {
  62. S32 len = dStrlen(name);
  63. AssertFatal(len < sizeof(scratchBuffer)-2, "CONSOLE: name too long");
  64. scratchBuffer[0] = '$';
  65. dMemcpy(scratchBuffer + 1, name, len + 1);
  66. name = scratchBuffer;
  67. }
  68. return name;
  69. }
  70. static const char * prependPercent ( const char * name )
  71. {
  72. if(name[0] != '%')
  73. {
  74. S32 len = dStrlen(name);
  75. AssertFatal(len < sizeof(scratchBuffer)-2, "CONSOLE: name too long");
  76. scratchBuffer[0] = '%';
  77. dMemcpy(scratchBuffer + 1, name, len + 1);
  78. name = scratchBuffer;
  79. }
  80. return name;
  81. }
  82. //--------------------------------------
  83. void ConsoleConstructor::init(const char *cName, const char *fName, const char *usg, S32 minArgs, S32 maxArgs)
  84. {
  85. mina = minArgs;
  86. maxa = maxArgs;
  87. funcName = fName;
  88. usage = usg;
  89. className = cName;
  90. sc = 0; fc = 0; vc = 0; bc = 0; ic = 0;
  91. group = false;
  92. next = first;
  93. ns = false;
  94. first = this;
  95. }
  96. void ConsoleConstructor::setup()
  97. {
  98. for(ConsoleConstructor *walk = first; walk; walk = walk->next)
  99. {
  100. if(walk->sc)
  101. Con::addCommand(walk->className, walk->funcName, walk->sc, walk->usage, walk->mina, walk->maxa);
  102. else if(walk->ic)
  103. Con::addCommand(walk->className, walk->funcName, walk->ic, walk->usage, walk->mina, walk->maxa);
  104. else if(walk->fc)
  105. Con::addCommand(walk->className, walk->funcName, walk->fc, walk->usage, walk->mina, walk->maxa);
  106. else if(walk->vc)
  107. Con::addCommand(walk->className, walk->funcName, walk->vc, walk->usage, walk->mina, walk->maxa);
  108. else if(walk->bc)
  109. Con::addCommand(walk->className, walk->funcName, walk->bc, walk->usage, walk->mina, walk->maxa);
  110. else if(walk->group)
  111. Con::markCommandGroup(walk->className, walk->funcName, walk->usage);
  112. else if(walk->overload)
  113. Con::addOverload(walk->className, walk->funcName, walk->usage);
  114. else if(walk->ns)
  115. {
  116. Namespace* ns = Namespace::find(StringTable->insert(walk->className));
  117. if( ns )
  118. ns->mUsage = walk->usage;
  119. }
  120. else
  121. AssertFatal(false, "Found a ConsoleConstructor with an indeterminate type!");
  122. }
  123. }
  124. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, StringCallback sfunc, const char *usage, S32 minArgs, S32 maxArgs)
  125. {
  126. init(className, funcName, usage, minArgs, maxArgs);
  127. sc = sfunc;
  128. }
  129. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, IntCallback ifunc, const char *usage, S32 minArgs, S32 maxArgs)
  130. {
  131. init(className, funcName, usage, minArgs, maxArgs);
  132. ic = ifunc;
  133. }
  134. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, FloatCallback ffunc, const char *usage, S32 minArgs, S32 maxArgs)
  135. {
  136. init(className, funcName, usage, minArgs, maxArgs);
  137. fc = ffunc;
  138. }
  139. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, VoidCallback vfunc, const char *usage, S32 minArgs, S32 maxArgs)
  140. {
  141. init(className, funcName, usage, minArgs, maxArgs);
  142. vc = vfunc;
  143. }
  144. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, BoolCallback bfunc, const char *usage, S32 minArgs, S32 maxArgs)
  145. {
  146. init(className, funcName, usage, minArgs, maxArgs);
  147. bc = bfunc;
  148. }
  149. ConsoleConstructor::ConsoleConstructor(const char* className, const char* groupName, const char* aUsage)
  150. {
  151. init(className, groupName, usage, -1, -2);
  152. group = true;
  153. // Somewhere, the entry list is getting flipped, partially.
  154. // so we have to do tricks to deal with making sure usage
  155. // is properly populated.
  156. // This is probably redundant.
  157. static char * lastUsage = NULL;
  158. if(aUsage)
  159. lastUsage = (char *)aUsage;
  160. usage = lastUsage;
  161. }
  162. ConsoleConstructor::ConsoleConstructor(const char* className, const char* usage)
  163. {
  164. init(className, NULL, usage, -1, -2);
  165. ns = true;
  166. }
  167. namespace Con
  168. {
  169. static Vector<ConsumerCallback> gConsumers(__FILE__, __LINE__);
  170. static DataChunker consoleLogChunker;
  171. static Vector<ConsoleLogEntry> consoleLog(__FILE__, __LINE__);
  172. static bool consoleLogLocked;
  173. static bool logBufferEnabled=true;
  174. static S32 printLevel = 10;
  175. static FileStream consoleLogFile;
  176. static const char *defLogFileName = "console.log";
  177. static S32 consoleLogMode = 0;
  178. static bool active = false;
  179. static bool newLogFile;
  180. static const char *logFileName;
  181. static const int MaxCompletionBufferSize = 4096;
  182. static char completionBuffer[MaxCompletionBufferSize];
  183. static char tabBuffer[MaxCompletionBufferSize] = {0};
  184. static SimObjectPtr<SimObject> tabObject;
  185. static U32 completionBaseStart;
  186. static U32 completionBaseLen;
  187. #ifdef TORQUE_MULTITHREAD
  188. static ThreadIdent gMainThreadID = -1;
  189. #endif
  190. /// Current script file name and root, these are registered as
  191. /// console variables.
  192. /// @{
  193. ///
  194. StringTableEntry gCurrentFile;
  195. StringTableEntry gCurrentRoot;
  196. /// @}
  197. void init()
  198. {
  199. AssertFatal(active == false, "Con::init should only be called once.");
  200. // Set up general init values.
  201. active = true;
  202. logFileName = NULL;
  203. newLogFile = true;
  204. gWarnUndefinedScriptVariables = false;
  205. sLogMutex = new Mutex;
  206. #ifdef TORQUE_MULTITHREAD
  207. // Note the main thread ID.
  208. gMainThreadID = ThreadManager::getCurrentThreadId();
  209. #endif
  210. // Initialize subsystems.
  211. Namespace::init();
  212. ConsoleConstructor::setup();
  213. // Set up the parser(s)
  214. CON_ADD_PARSER(CMD, "cs", true); // TorqueScript
  215. // Variables
  216. setVariable("Con::prompt", "% ");
  217. addVariable("Con::logBufferEnabled", TypeBool, &logBufferEnabled);
  218. addVariable("Con::printLevel", TypeS32, &printLevel);
  219. addVariable("Con::warnUndefinedVariables", TypeBool, &gWarnUndefinedScriptVariables);
  220. // Current script file name and root
  221. Con::addVariable( "Con::File", TypeString, &gCurrentFile );
  222. Con::addVariable( "Con::Root", TypeString, &gCurrentRoot );
  223. // Setup the console types.
  224. ConsoleBaseType::initialize();
  225. // And finally, the ACR...
  226. AbstractClassRep::initialize();
  227. }
  228. //--------------------------------------
  229. void shutdown()
  230. {
  231. AssertFatal(active == true, "Con::shutdown should only be called once.");
  232. active = false;
  233. consoleLogFile.close();
  234. Namespace::shutdown();
  235. SAFE_DELETE( sLogMutex );
  236. }
  237. bool isActive()
  238. {
  239. return active;
  240. }
  241. bool isMainThread()
  242. {
  243. #ifdef TORQUE_MULTITHREAD
  244. return ThreadManager::isCurrentThread(gMainThreadID);
  245. #else
  246. // If we're single threaded we're always in the main thread.
  247. return true;
  248. #endif
  249. }
  250. //--------------------------------------
  251. void getLockLog(ConsoleLogEntry *&log, U32 &size)
  252. {
  253. consoleLogLocked = true;
  254. log = consoleLog.address();
  255. size = consoleLog.size();
  256. }
  257. void unlockLog()
  258. {
  259. consoleLogLocked = false;
  260. }
  261. U32 tabComplete(char* inputBuffer, U32 cursorPos, U32 maxResultLength, bool forwardTab)
  262. {
  263. // Check for null input.
  264. if (!inputBuffer[0])
  265. {
  266. return cursorPos;
  267. }
  268. // Cap the max result length.
  269. if (maxResultLength > MaxCompletionBufferSize)
  270. {
  271. maxResultLength = MaxCompletionBufferSize;
  272. }
  273. // See if this is the same partial text as last checked.
  274. if (dStrcmp(tabBuffer, inputBuffer))
  275. {
  276. // If not...
  277. // Save it for checking next time.
  278. dStrcpy(tabBuffer, inputBuffer);
  279. // Scan backward from the cursor position to find the base to complete from.
  280. S32 p = cursorPos;
  281. while ((p > 0) && (inputBuffer[p - 1] != ' ') && (inputBuffer[p - 1] != '.') && (inputBuffer[p - 1] != '('))
  282. {
  283. p--;
  284. }
  285. completionBaseStart = p;
  286. completionBaseLen = cursorPos - p;
  287. // Is this function being invoked on an object?
  288. if (inputBuffer[p - 1] == '.')
  289. {
  290. // If so...
  291. if (p <= 1)
  292. {
  293. // Bail if no object identifier.
  294. return cursorPos;
  295. }
  296. // Find the object identifier.
  297. S32 objLast = --p;
  298. while ((p > 0) && (inputBuffer[p - 1] != ' ') && (inputBuffer[p - 1] != '('))
  299. {
  300. p--;
  301. }
  302. if (objLast == p)
  303. {
  304. // Bail if no object identifier.
  305. return cursorPos;
  306. }
  307. // Look up the object identifier.
  308. dStrncpy(completionBuffer, inputBuffer + p, objLast - p);
  309. completionBuffer[objLast - p] = 0;
  310. tabObject = Sim::findObject(completionBuffer);
  311. if (!bool(tabObject))
  312. {
  313. // Bail if not found.
  314. return cursorPos;
  315. }
  316. }
  317. else
  318. {
  319. // Not invoked on an object; we'll use the global namespace.
  320. tabObject = 0;
  321. }
  322. }
  323. // Chop off the input text at the cursor position.
  324. inputBuffer[cursorPos] = 0;
  325. // Try to find a completion in the appropriate namespace.
  326. const char *newText;
  327. if (bool(tabObject))
  328. {
  329. newText = tabObject->tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  330. }
  331. else
  332. {
  333. // In the global namespace, we can complete on global vars as well as functions.
  334. if (inputBuffer[completionBaseStart] == '$')
  335. {
  336. newText = gEvalState.globalVars.tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  337. }
  338. else
  339. {
  340. newText = Namespace::global()->tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  341. }
  342. }
  343. if (newText)
  344. {
  345. // If we got something, append it to the input text.
  346. S32 len = dStrlen(newText);
  347. if (len + completionBaseStart > maxResultLength)
  348. {
  349. len = maxResultLength - completionBaseStart;
  350. }
  351. dStrncpy(inputBuffer + completionBaseStart, newText, len);
  352. inputBuffer[completionBaseStart + len] = 0;
  353. // And set the cursor after it.
  354. cursorPos = completionBaseStart + len;
  355. }
  356. // Save the modified input buffer for checking next time.
  357. dStrcpy(tabBuffer, inputBuffer);
  358. // Return the new (maybe) cursor position.
  359. return cursorPos;
  360. }
  361. //------------------------------------------------------------------------------
  362. static void log(const char *string)
  363. {
  364. // Lock.
  365. MutexHandle mutex;
  366. if( sLogMutex )
  367. mutex.lock( sLogMutex, true );
  368. // Bail if we ain't logging.
  369. if (!consoleLogMode)
  370. {
  371. return;
  372. }
  373. // In mode 1, we open, append, close on each log write.
  374. if ((consoleLogMode & 0x3) == 1)
  375. {
  376. consoleLogFile.open(defLogFileName, FileStream::ReadWrite);
  377. }
  378. // Write to the log if its status is hunky-dory.
  379. if ((consoleLogFile.getStatus() == Stream::Ok) || (consoleLogFile.getStatus() == Stream::EOS))
  380. {
  381. consoleLogFile.setPosition(consoleLogFile.getStreamSize());
  382. // If this is the first write...
  383. if (newLogFile)
  384. {
  385. // Make a header.
  386. Platform::LocalTime lt;
  387. Platform::getLocalTime(lt);
  388. char buffer[128];
  389. dSprintf(buffer, sizeof(buffer), "//-------------------------- %d/%d/%d -- %02d:%02d:%02d -----\r\n",
  390. lt.month + 1,
  391. lt.monthday,
  392. lt.year + 1900,
  393. lt.hour,
  394. lt.min,
  395. lt.sec);
  396. consoleLogFile.write(dStrlen(buffer), buffer);
  397. newLogFile = false;
  398. if (consoleLogMode & 0x4)
  399. {
  400. // Dump anything that has been printed to the console so far.
  401. consoleLogMode -= 0x4;
  402. U32 size, line;
  403. ConsoleLogEntry *log;
  404. getLockLog(log, size);
  405. for (line = 0; line < size; line++)
  406. {
  407. consoleLogFile.write(dStrlen(log[line].mString), log[line].mString);
  408. consoleLogFile.write(2, "\r\n");
  409. }
  410. unlockLog();
  411. }
  412. }
  413. // Now write what we came here to write.
  414. consoleLogFile.write(dStrlen(string), string);
  415. consoleLogFile.write(2, "\r\n");
  416. }
  417. if ((consoleLogMode & 0x3) == 1)
  418. {
  419. consoleLogFile.close();
  420. }
  421. }
  422. //------------------------------------------------------------------------------
  423. void cls( void )
  424. {
  425. if(consoleLogLocked)
  426. return;
  427. consoleLogChunker.freeBlocks();
  428. consoleLog.setSize(0);
  429. };
  430. //------------------------------------------------------------------------------
  431. #if defined( _MSC_VER )
  432. #include <windows.h>
  433. static void _outputDebugString(char* pString)
  434. {
  435. // Format string.
  436. char* pBuffer = pString;
  437. S32 stringLength = dStrlen(pString);
  438. pBuffer += stringLength;
  439. *pBuffer++ = '\r';
  440. *pBuffer++ = '\n';
  441. *pBuffer = '\0';
  442. stringLength = strlen(pString) + 1;
  443. wchar_t *wstr = new wchar_t[stringLength];
  444. dMemset( wstr, 0, stringLength );
  445. // Convert to wide string.
  446. Con::MultiByteToWideChar( CP_ACP, NULL, pString, -1, wstr, stringLength );
  447. // Output string.
  448. Con::OutputDebugStringW( wstr );
  449. delete [] wstr;
  450. }
  451. #endif
  452. //------------------------------------------------------------------------------
  453. static void _printf(ConsoleLogEntry::Level level, ConsoleLogEntry::Type type, const char* fmt)
  454. {
  455. Con::active = false;
  456. char buffer[4096];
  457. U32 offset = 0;
  458. if(gEvalState.traceOn && gEvalState.stack.size())
  459. {
  460. offset = gEvalState.stack.size() * 3;
  461. for(U32 i = 0; i < offset; i++)
  462. buffer[i] = ' ';
  463. }
  464. dSprintf(buffer + offset, sizeof(buffer) - offset, "%s", fmt);
  465. for(U32 i = 0; i < (U32)gConsumers.size(); i++)
  466. gConsumers[i](level, buffer);
  467. Platform::cprintf(buffer);
  468. if(logBufferEnabled || consoleLogMode)
  469. {
  470. char *pos = buffer;
  471. while(*pos)
  472. {
  473. if(*pos == '\t')
  474. *pos = '^';
  475. pos++;
  476. }
  477. pos = buffer;
  478. for(;;)
  479. {
  480. char *eofPos = dStrchr(pos, '\n');
  481. if(eofPos)
  482. *eofPos = 0;
  483. log(pos);
  484. if(logBufferEnabled && !consoleLogLocked)
  485. {
  486. ConsoleLogEntry entry;
  487. entry.mLevel = level;
  488. entry.mType = type;
  489. entry.mString = (const char *)consoleLogChunker.alloc(dStrlen(pos) + 1);
  490. dStrcpy(const_cast<char*>(entry.mString), pos);
  491. consoleLog.push_back(entry);
  492. }
  493. if(!eofPos)
  494. break;
  495. pos = eofPos + 1;
  496. }
  497. }
  498. Con::active = true;
  499. #if defined( _MSC_VER )
  500. _outputDebugString( buffer );
  501. #endif
  502. }
  503. //------------------------------------------------------------------------------
  504. class ConPrinfThreadedEvent : public SimEvent
  505. {
  506. ConsoleLogEntry::Level mLevel;
  507. ConsoleLogEntry::Type mType;
  508. char *mBuf;
  509. public:
  510. ConPrinfThreadedEvent(ConsoleLogEntry::Level level = ConsoleLogEntry::Normal, ConsoleLogEntry::Type type = ConsoleLogEntry::General, const char *buf = NULL)
  511. {
  512. mLevel = level;
  513. mType = type;
  514. if(buf)
  515. {
  516. mBuf = (char*)dMalloc(dStrlen(buf)+1);
  517. dMemcpy((void*)mBuf, (void*)buf, dStrlen(buf));
  518. mBuf[dStrlen(buf)] = 0;
  519. }
  520. else
  521. mBuf = NULL;
  522. }
  523. ~ConPrinfThreadedEvent()
  524. {
  525. SAFE_FREE(mBuf);
  526. }
  527. virtual void process(SimObject *object)
  528. {
  529. if(mBuf)
  530. {
  531. switch(mLevel)
  532. {
  533. case ConsoleLogEntry::Normal :
  534. Con::printf(mBuf);
  535. break;
  536. case ConsoleLogEntry::Warning :
  537. Con::warnf(mType, mBuf);
  538. break;
  539. case ConsoleLogEntry::Error :
  540. Con::errorf(mType, mBuf);
  541. break;
  542. case ConsoleLogEntry::NUM_CLASS :
  543. Con::errorf("Unhandled case NUM_CLASS");
  544. break;
  545. }
  546. }
  547. }
  548. };
  549. //------------------------------------------------------------------------------
  550. void printf(const char* fmt,...)
  551. {
  552. va_list argptr;
  553. va_start(argptr, fmt);
  554. char buf[8192];
  555. dVsprintf(buf, sizeof(buf), fmt, argptr);
  556. if(!isMainThread())
  557. Sim::postEvent(Sim::getRootGroup(), new ConPrinfThreadedEvent(ConsoleLogEntry::Normal, ConsoleLogEntry::General, buf), Sim::getTargetTime());
  558. else
  559. _printf(ConsoleLogEntry::Normal, ConsoleLogEntry::General, buf);
  560. va_end(argptr);
  561. }
  562. void warnf(ConsoleLogEntry::Type type, const char* fmt,...)
  563. {
  564. va_list argptr;
  565. va_start(argptr, fmt);
  566. char buf[8192];
  567. dVsprintf(buf, sizeof(buf), fmt, argptr);
  568. if(!isMainThread())
  569. Sim::postEvent(Sim::getRootGroup(), new ConPrinfThreadedEvent(ConsoleLogEntry::Warning, type, buf), Sim::getTargetTime());
  570. else
  571. _printf(ConsoleLogEntry::Warning, type, buf);
  572. va_end(argptr);
  573. }
  574. void errorf(ConsoleLogEntry::Type type, const char* fmt,...)
  575. {
  576. va_list argptr;
  577. va_start(argptr, fmt);
  578. char buf[8192];
  579. dVsprintf(buf, sizeof(buf), fmt, argptr);
  580. if(!isMainThread())
  581. Sim::postEvent(Sim::getRootGroup(), new ConPrinfThreadedEvent(ConsoleLogEntry::Error, type, buf), Sim::getTargetTime());
  582. else
  583. _printf(ConsoleLogEntry::Error, type, buf);
  584. va_end(argptr);
  585. }
  586. void warnf(const char* fmt,...)
  587. {
  588. va_list argptr;
  589. va_start(argptr, fmt);
  590. char buf[8192];
  591. dVsprintf(buf, sizeof(buf), fmt, argptr);
  592. if(!isMainThread())
  593. Sim::postEvent(Sim::getRootGroup(), new ConPrinfThreadedEvent(ConsoleLogEntry::Warning, ConsoleLogEntry::General, buf), Sim::getTargetTime());
  594. else
  595. _printf(ConsoleLogEntry::Warning, ConsoleLogEntry::General, buf);
  596. va_end(argptr);
  597. }
  598. void errorf(const char* fmt,...)
  599. {
  600. va_list argptr;
  601. va_start(argptr, fmt);
  602. char buf[8192];
  603. dVsprintf(buf, sizeof(buf), fmt, argptr);
  604. if(!isMainThread())
  605. Sim::postEvent(Sim::getRootGroup(), new ConPrinfThreadedEvent(ConsoleLogEntry::Error, ConsoleLogEntry::General, buf), Sim::getTargetTime());
  606. else
  607. _printf(ConsoleLogEntry::Error, ConsoleLogEntry::General, buf);
  608. va_end(argptr);
  609. }
  610. //---------------------------------------------------------------------------
  611. void setVariable(const char *name, const char *value)
  612. {
  613. name = prependDollar(name);
  614. gEvalState.globalVars.setVariable(StringTable->insert(name), value);
  615. }
  616. void setLocalVariable(const char *name, const char *value)
  617. {
  618. name = prependPercent(name);
  619. gEvalState.stack.last()->setVariable(StringTable->insert(name), value);
  620. }
  621. void setBoolVariable(const char *varName, bool value)
  622. {
  623. setVariable(varName, value ? "1" : "0");
  624. }
  625. void setIntVariable(const char *varName, S32 value)
  626. {
  627. char scratchBuffer[32];
  628. dSprintf(scratchBuffer, sizeof(scratchBuffer), "%d", value);
  629. setVariable(varName, scratchBuffer);
  630. }
  631. void setFloatVariable(const char *varName, F32 value)
  632. {
  633. char scratchBuffer[32];
  634. dSprintf(scratchBuffer, sizeof(scratchBuffer), "%.9g", value);
  635. setVariable(varName, scratchBuffer);
  636. }
  637. //---------------------------------------------------------------------------
  638. void addConsumer(ConsumerCallback consumer)
  639. {
  640. gConsumers.push_back(consumer);
  641. }
  642. // dhc - found this empty -- trying what I think is a reasonable impl.
  643. void removeConsumer(ConsumerCallback consumer)
  644. {
  645. for(U32 i = 0; i < (U32)gConsumers.size(); i++)
  646. if (gConsumers[i] == consumer)
  647. { // remove it from the list.
  648. gConsumers.erase(i);
  649. break;
  650. }
  651. }
  652. void stripColorChars(char* line)
  653. {
  654. char* c = line;
  655. char cp = *c;
  656. while (cp)
  657. {
  658. if (cp < 18)
  659. {
  660. // Could be a color control character; let's take a closer look.
  661. if ((cp != 8) && (cp != 9) && (cp != 10) && (cp != 13))
  662. {
  663. // Yep... copy following chars forward over this.
  664. char* cprime = c;
  665. char cpp;
  666. do
  667. {
  668. cpp = *++cprime;
  669. *(cprime - 1) = cpp;
  670. }
  671. while (cpp);
  672. // Back up 1 so we'll check this position again post-copy.
  673. c--;
  674. }
  675. }
  676. cp = *++c;
  677. }
  678. }
  679. const char *getVariable(const char *name)
  680. {
  681. // get the field info from the object..
  682. if(name[0] != '$' && dStrchr(name, '.') && !isFunction(name))
  683. {
  684. S32 len = dStrlen(name);
  685. AssertFatal(len < sizeof(scratchBuffer)-1, "Sim::getVariable - name too long");
  686. dMemcpy(scratchBuffer, name, len+1);
  687. char * token = dStrtok(scratchBuffer, ".");
  688. SimObject * obj = Sim::findObject(token);
  689. if(!obj)
  690. return("");
  691. token = dStrtok(0, ".\0");
  692. if(!token)
  693. return("");
  694. while(token != NULL)
  695. {
  696. const char * val = obj->getDataField(StringTable->insert(token), 0);
  697. if(!val)
  698. return("");
  699. token = dStrtok(0, ".\0");
  700. if(token)
  701. {
  702. obj = Sim::findObject(token);
  703. if(!obj)
  704. return("");
  705. }
  706. else
  707. return(val);
  708. }
  709. }
  710. name = prependDollar(name);
  711. return gEvalState.globalVars.getVariable(StringTable->insert(name));
  712. }
  713. const char *getLocalVariable(const char *name)
  714. {
  715. name = prependPercent(name);
  716. return gEvalState.stack.last()->getVariable(StringTable->insert(name));
  717. }
  718. bool getBoolVariable(const char *varName, bool def)
  719. {
  720. const char *value = getVariable(varName);
  721. return *value ? dAtob(value) : def;
  722. }
  723. S32 getIntVariable(const char *varName, S32 def)
  724. {
  725. const char *value = getVariable(varName);
  726. return *value ? dAtoi(value) : def;
  727. }
  728. F32 getFloatVariable(const char *varName, F32 def)
  729. {
  730. const char *value = getVariable(varName);
  731. return *value ? dAtof(value) : def;
  732. }
  733. //---------------------------------------------------------------------------
  734. bool addVariable(const char *name, S32 t, void *dp)
  735. {
  736. gEvalState.globalVars.addVariable(name, t, dp);
  737. return true;
  738. }
  739. bool removeVariable(const char *name)
  740. {
  741. name = StringTable->lookup(prependDollar(name));
  742. return name!=0 && gEvalState.globalVars.removeVariable(name);
  743. }
  744. //---------------------------------------------------------------------------
  745. void addCommand(const char *nsName, const char *name,StringCallback cb, const char *usage, S32 minArgs, S32 maxArgs)
  746. {
  747. Namespace *ns = lookupNamespace(nsName);
  748. ns->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
  749. }
  750. void addCommand(const char *nsName, const char *name,VoidCallback cb, const char *usage, S32 minArgs, S32 maxArgs)
  751. {
  752. Namespace *ns = lookupNamespace(nsName);
  753. ns->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
  754. }
  755. void addCommand(const char *nsName, const char *name,IntCallback cb, const char *usage, S32 minArgs, S32 maxArgs)
  756. {
  757. Namespace *ns = lookupNamespace(nsName);
  758. ns->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
  759. }
  760. void addCommand(const char *nsName, const char *name,FloatCallback cb, const char *usage, S32 minArgs, S32 maxArgs)
  761. {
  762. Namespace *ns = lookupNamespace(nsName);
  763. ns->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
  764. }
  765. void addCommand(const char *nsName, const char *name,BoolCallback cb, const char *usage, S32 minArgs, S32 maxArgs)
  766. {
  767. Namespace *ns = lookupNamespace(nsName);
  768. ns->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
  769. }
  770. void markCommandGroup(const char * nsName, const char *name, const char* usage)
  771. {
  772. Namespace *ns = lookupNamespace(nsName);
  773. ns->markGroup(name,usage);
  774. }
  775. void beginCommandGroup(const char * nsName, const char *name, const char* usage)
  776. {
  777. markCommandGroup(nsName, name, usage);
  778. }
  779. void endCommandGroup(const char * nsName, const char *name)
  780. {
  781. markCommandGroup(nsName, name, NULL);
  782. }
  783. void addOverload(const char * nsName, const char * name, const char * altUsage)
  784. {
  785. Namespace *ns = lookupNamespace(nsName);
  786. ns->addOverload(name,altUsage);
  787. }
  788. void addCommand(const char *name,StringCallback cb,const char *usage, S32 minArgs, S32 maxArgs)
  789. {
  790. Namespace::global()->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
  791. }
  792. void addCommand(const char *name,VoidCallback cb,const char *usage, S32 minArgs, S32 maxArgs)
  793. {
  794. Namespace::global()->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
  795. }
  796. void addCommand(const char *name,IntCallback cb,const char *usage, S32 minArgs, S32 maxArgs)
  797. {
  798. Namespace::global()->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
  799. }
  800. void addCommand(const char *name,FloatCallback cb,const char *usage, S32 minArgs, S32 maxArgs)
  801. {
  802. Namespace::global()->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
  803. }
  804. void addCommand(const char *name,BoolCallback cb,const char *usage, S32 minArgs, S32 maxArgs)
  805. {
  806. Namespace::global()->addCommand(StringTable->insert(name), cb, usage, minArgs, maxArgs);
  807. }
  808. const char *evaluate(const char* string, bool echo, const char *fileName)
  809. {
  810. if (echo)
  811. Con::printf("%s%s", getVariable( "$Con::Prompt" ), string);
  812. if(fileName)
  813. fileName = StringTable->insert(fileName);
  814. CodeBlock *newCodeBlock = new CodeBlock();
  815. return newCodeBlock->compileExec(fileName, string, false, fileName ? -1 : 0);
  816. }
  817. //------------------------------------------------------------------------------
  818. const char *evaluatef(const char* string, ...)
  819. {
  820. const char * result = NULL;
  821. char * buffer = new char[4096];
  822. if (buffer != NULL)
  823. {
  824. va_list args;
  825. va_start(args, string);
  826. dVsprintf(buffer, 4096, string, args);
  827. va_end (args);
  828. CodeBlock *newCodeBlock = new CodeBlock();
  829. result = newCodeBlock->compileExec(NULL, buffer, false, 0);
  830. delete [] buffer;
  831. buffer = NULL;
  832. }
  833. return result;
  834. }
  835. const char *execute(S32 argc, const char *argv[])
  836. {
  837. #ifdef TORQUE_MULTITHREAD
  838. if(isMainThread())
  839. {
  840. #endif
  841. Namespace::Entry *ent;
  842. StringTableEntry funcName = StringTable->insert(argv[0]);
  843. ent = Namespace::global()->lookup(funcName);
  844. if(!ent)
  845. {
  846. warnf(ConsoleLogEntry::Script, "%s: Unknown command.", argv[0]);
  847. // Clean up arg buffers, if any.
  848. STR.clearFunctionOffset();
  849. return "";
  850. }
  851. const char *ret = ent->execute(argc, argv, &gEvalState);
  852. // Reset the function offset so the stack
  853. // doesn't continue to grow unnecessarily
  854. STR.clearFunctionOffset();
  855. return ret;
  856. #ifdef TORQUE_MULTITHREAD
  857. }
  858. else
  859. {
  860. SimConsoleThreadExecCallback cb;
  861. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, false, &cb);
  862. Sim::postEvent(Sim::getRootGroup(), evt, Sim::getCurrentTime());
  863. return cb.waitForResult();
  864. }
  865. #endif
  866. }
  867. //------------------------------------------------------------------------------
  868. const char *execute(SimObject *object, S32 argc, const char *argv[],bool thisCallOnly)
  869. {
  870. static char idBuf[16];
  871. if(argc < 2)
  872. return "";
  873. // [neo, 10/05/2007 - #3010]
  874. // Make sure we don't get recursive calls, respect the flag!
  875. // Should we be calling handlesMethod() first?
  876. if( !thisCallOnly )
  877. {
  878. DynamicConsoleMethodComponent *com = dynamic_cast<DynamicConsoleMethodComponent *>(object);
  879. if(com)
  880. com->callMethodArgList(argc, argv, false);
  881. }
  882. if(object->getNamespace())
  883. {
  884. StringTableEntry funcName = StringTable->insert(argv[0]);
  885. Namespace::Entry *ent = object->getNamespace()->lookup(funcName);
  886. if(ent == NULL)
  887. {
  888. //warnf(ConsoleLogEntry::Script, "%s: undefined for object '%s' - id %d", funcName, object->getName(), object->getId());
  889. // Clean up arg buffers, if any.
  890. STR.clearFunctionOffset();
  891. return "";
  892. }
  893. // Twiddle %this argument
  894. const char *oldArg1 = argv[1];
  895. dSprintf(idBuf, sizeof(idBuf), "%d", object->getId());
  896. argv[1] = idBuf;
  897. object->pushScriptCallbackGuard();
  898. SimObject *save = gEvalState.thisObject;
  899. gEvalState.thisObject = object;
  900. const char *ret = ent->execute(argc, argv, &gEvalState);
  901. gEvalState.thisObject = save;
  902. object->popScriptCallbackGuard();
  903. // Twiddle it back
  904. argv[1] = oldArg1;
  905. // Reset the function offset so the stack
  906. // doesn't continue to grow unnecessarily
  907. STR.clearFunctionOffset();
  908. return ret;
  909. }
  910. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), argv[0]);
  911. return "";
  912. }
  913. const char *executef(SimObject *object, S32 argc, ...)
  914. {
  915. const char *argv[128];
  916. va_list args;
  917. va_start(args, argc);
  918. for(S32 i = 0; i < argc; i++)
  919. argv[i+1] = va_arg(args, const char *);
  920. va_end(args);
  921. argv[0] = argv[1];
  922. argc++;
  923. return execute(object, argc, argv);
  924. }
  925. //------------------------------------------------------------------------------
  926. const char *executef(S32 argc, ...)
  927. {
  928. const char *argv[128];
  929. va_list args;
  930. va_start(args, argc);
  931. for(S32 i = 0; i < argc; i++)
  932. argv[i] = va_arg(args, const char *);
  933. va_end(args);
  934. return execute(argc, argv);
  935. }
  936. //------------------------------------------------------------------------------
  937. bool isFunction(const char *fn)
  938. {
  939. const char *string = StringTable->lookup(fn);
  940. if(!string)
  941. return false;
  942. else
  943. return Namespace::global()->lookup(string) != NULL;
  944. }
  945. //------------------------------------------------------------------------------
  946. void setLogMode(S32 newMode)
  947. {
  948. if ((newMode & 0x3) != (consoleLogMode & 0x3))
  949. {
  950. if (newMode && !consoleLogMode)
  951. {
  952. // Enabling logging when it was previously disabled.
  953. newLogFile = true;
  954. }
  955. if ((consoleLogMode & 0x3) == 2)
  956. {
  957. // Changing away from mode 2, must close logfile.
  958. consoleLogFile.close();
  959. }
  960. else if ((newMode & 0x3) == 2)
  961. {
  962. // Starting mode 2, must open logfile.
  963. consoleLogFile.open(defLogFileName, FileStream::Write);
  964. }
  965. consoleLogMode = newMode;
  966. }
  967. }
  968. Namespace *lookupNamespace(const char *ns)
  969. {
  970. if(!ns)
  971. return Namespace::global();
  972. return Namespace::find(StringTable->insert(ns));
  973. }
  974. bool linkNamespaces(const char *parent, const char *child)
  975. {
  976. Namespace *pns = lookupNamespace(parent);
  977. Namespace *cns = lookupNamespace(child);
  978. if(pns && cns)
  979. return cns->classLinkTo(pns);
  980. return false;
  981. }
  982. bool unlinkNamespaces(const char *parent, const char *child)
  983. {
  984. Namespace *pns = lookupNamespace(parent);
  985. Namespace *cns = lookupNamespace(child);
  986. if(pns && cns)
  987. return cns->unlinkClass(pns);
  988. return false;
  989. }
  990. bool classLinkNamespaces(Namespace *parent, Namespace *child)
  991. {
  992. if(parent && child)
  993. return child->classLinkTo(parent);
  994. return false;
  995. }
  996. void setData(S32 type, void *dptr, S32 index, S32 argc, const char **argv, EnumTable *tbl, BitSet32 flag)
  997. {
  998. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  999. AssertFatal(cbt, "Con::setData - could not resolve type ID!");
  1000. cbt->setData((void *) (((const char *)dptr) + index * cbt->getTypeSize()),argc, argv, tbl, flag);
  1001. }
  1002. const char *getData(S32 type, void *dptr, S32 index, EnumTable *tbl, BitSet32 flag)
  1003. {
  1004. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1005. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1006. return cbt->getData((void *) (((const char *)dptr) + index * cbt->getTypeSize()), tbl, flag);
  1007. }
  1008. //------------------------------------------------------------------------------
  1009. StringTableEntry getModNameFromPath(const char *path)
  1010. {
  1011. if(path == NULL || *path == 0)
  1012. return NULL;
  1013. char buf[1024];
  1014. buf[0] = 0;
  1015. if(path[0] == '/' || path[1] == ':')
  1016. {
  1017. // It's an absolute path
  1018. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1019. U32 len = dStrlen(exePath);
  1020. if(dStrnicmp(exePath, path, len) == 0)
  1021. {
  1022. const char *ptr = path + len + 1;
  1023. const char *slash = dStrchr(ptr, '/');
  1024. if(slash)
  1025. {
  1026. dStrncpy(buf, ptr, slash - ptr);
  1027. buf[slash - ptr] = 0;
  1028. }
  1029. else
  1030. return NULL;
  1031. }
  1032. else
  1033. return NULL;
  1034. }
  1035. else
  1036. {
  1037. const char *slash = dStrchr(path, '/');
  1038. if(slash)
  1039. {
  1040. dStrncpy(buf, path, slash - path);
  1041. buf[slash - path] = 0;
  1042. }
  1043. else
  1044. return NULL;
  1045. }
  1046. return StringTable->insert(buf);
  1047. }
  1048. //-----------------------------------------------------------------------------
  1049. typedef HashMap<StringTableEntry, StringTableEntry> typePathExpandoMap;
  1050. static typePathExpandoMap PathExpandos;
  1051. //-----------------------------------------------------------------------------
  1052. void addPathExpando( const char* pExpandoName, const char* pPath )
  1053. {
  1054. // Sanity!
  1055. AssertFatal( pExpandoName != NULL, "Expando name cannot be NULL." );
  1056. AssertFatal( pPath != NULL, "Expando path cannot be NULL." );
  1057. // Fetch expando name.
  1058. StringTableEntry expandoName = StringTable->insert( pExpandoName );
  1059. // Fetch the length of the path.
  1060. S32 pathLength = dStrlen(pPath);
  1061. char pathBuffer[1024];
  1062. // Sanity!
  1063. if ( pathLength == 0 || pathLength >= sizeof(pathBuffer) )
  1064. {
  1065. Con::warnf( "Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath );
  1066. return;
  1067. }
  1068. // Strip repeat slashes.
  1069. if ( !Con::stripRepeatSlashes(pathBuffer, pPath, sizeof(pathBuffer) ) )
  1070. {
  1071. Con::warnf( "Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath );
  1072. return;
  1073. }
  1074. // Fetch new path length.
  1075. pathLength = dStrlen(pathBuffer);
  1076. // Sanity!
  1077. if ( pathLength == 0 )
  1078. {
  1079. Con::warnf( "Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath );
  1080. return;
  1081. }
  1082. // Remove any terminating slash.
  1083. if (pathBuffer[pathLength-1] == '/')
  1084. pathBuffer[pathLength-1] = 0;
  1085. // Fetch expanded path.
  1086. StringTableEntry expandedPath = StringTable->insert( pathBuffer );
  1087. // Info.
  1088. #if defined(TORQUE_DEBUG)
  1089. Con::printf("Adding path expando of '%s' as '%s'.", expandoName, expandedPath );
  1090. #endif
  1091. // Find any existing path expando.
  1092. typePathExpandoMap::iterator expandoItr = PathExpandos.find( pExpandoName );
  1093. // Does the expando exist?
  1094. if( expandoItr != PathExpandos.end() )
  1095. {
  1096. // Yes, so modify the path.
  1097. expandoItr->value = expandedPath;
  1098. return;
  1099. }
  1100. // Insert expando.
  1101. PathExpandos.insert( expandoName, expandedPath );
  1102. }
  1103. //-----------------------------------------------------------------------------
  1104. StringTableEntry getPathExpando( const char* pExpandoName )
  1105. {
  1106. // Sanity!
  1107. AssertFatal( pExpandoName != NULL, "Expando name cannot be NULL." );
  1108. // Fetch expando name.
  1109. StringTableEntry expandoName = StringTable->insert( pExpandoName );
  1110. // Find any existing path expando.
  1111. typePathExpandoMap::iterator expandoItr = PathExpandos.find( expandoName );
  1112. // Does the expando exist?
  1113. if( expandoItr != PathExpandos.end() )
  1114. {
  1115. // Yes, so return it.
  1116. return expandoItr->value;
  1117. }
  1118. // Not found.
  1119. return NULL;
  1120. }
  1121. //-----------------------------------------------------------------------------
  1122. void removePathExpando( const char* pExpandoName )
  1123. {
  1124. // Sanity!
  1125. AssertFatal( pExpandoName != NULL, "Expando name cannot be NULL." );
  1126. // Fetch expando name.
  1127. StringTableEntry expandoName = StringTable->insert( pExpandoName );
  1128. // Find any existing path expando.
  1129. typePathExpandoMap::iterator expandoItr = PathExpandos.find( expandoName );
  1130. // Does the expando exist?
  1131. if ( expandoItr == PathExpandos.end() )
  1132. {
  1133. // No, so warn.
  1134. #if defined(TORQUE_DEBUG)
  1135. Con::warnf("Removing path expando of '%s' but it does not exist.", expandoName );
  1136. #endif
  1137. return;
  1138. }
  1139. // Info.
  1140. #if defined(TORQUE_DEBUG)
  1141. Con::printf("Removing path expando of '%s' as '%s'.", expandoName, expandoItr->value );
  1142. #endif
  1143. // Remove expando.
  1144. PathExpandos.erase( expandoItr );
  1145. }
  1146. //-----------------------------------------------------------------------------
  1147. bool isPathExpando( const char* pExpandoName )
  1148. {
  1149. // Sanity!
  1150. AssertFatal( pExpandoName != NULL, "Expando name cannot be NULL." );
  1151. // Fetch expando name.
  1152. StringTableEntry expandoName = StringTable->insert( pExpandoName );
  1153. return PathExpandos.contains( expandoName );
  1154. }
  1155. //-----------------------------------------------------------------------------
  1156. U32 getPathExpandoCount( void )
  1157. {
  1158. return PathExpandos.size();
  1159. }
  1160. //-----------------------------------------------------------------------------
  1161. StringTableEntry getPathExpandoKey( U32 expandoIndex )
  1162. {
  1163. // Finish if index is out of range.
  1164. if ( expandoIndex >= PathExpandos.size() )
  1165. return NULL;
  1166. // Find indexed iterator.
  1167. typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
  1168. while( expandoIndex > 0 ) { ++expandoItr; --expandoIndex; }
  1169. return expandoItr->key;
  1170. }
  1171. //-----------------------------------------------------------------------------
  1172. StringTableEntry getPathExpandoValue( U32 expandoIndex )
  1173. {
  1174. // Finish if index is out of range.
  1175. if ( expandoIndex >= PathExpandos.size() )
  1176. return NULL;
  1177. // Find indexed iterator.
  1178. typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
  1179. while( expandoIndex > 0 ) { ++expandoItr; --expandoIndex; }
  1180. return expandoItr->value;
  1181. }
  1182. //-----------------------------------------------------------------------------
  1183. bool expandPath( char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint, const bool ensureTrailingSlash )
  1184. {
  1185. char pathBuffer[2048];
  1186. const char* pSrc = pSrcPath;
  1187. char* pSlash;
  1188. // Fetch leading character.
  1189. const char leadingToken = *pSrc;
  1190. // Fetch following token.
  1191. const char followingToken = leadingToken != 0 ? pSrc[1] : 0;
  1192. // Expando.
  1193. if ( leadingToken == '^' )
  1194. {
  1195. // Initial prefix search.
  1196. const char* pPrefixSrc = pSrc+1;
  1197. char* pPrefixDst = pathBuffer;
  1198. // Search for end of expando.
  1199. while( *pPrefixSrc != '/' && *pPrefixSrc != 0 )
  1200. {
  1201. // Copy prefix character.
  1202. *pPrefixDst++ = *pPrefixSrc++;
  1203. }
  1204. // Yes, so terminate the expando string.
  1205. *pPrefixDst = 0;
  1206. // Fetch the expando path.
  1207. StringTableEntry expandoPath = getPathExpando(pathBuffer);
  1208. // Does the expando exist?
  1209. if( expandoPath == NULL )
  1210. {
  1211. // No, so error.
  1212. Con::errorf("expandPath() : Could not find path expando '%s' for path '%s'.", pathBuffer, pSrcPath );
  1213. // Are we ensuring the trailing slash?
  1214. if ( ensureTrailingSlash )
  1215. {
  1216. // Yes, so ensure it.
  1217. Con::ensureTrailingSlash( pDstPath, pSrcPath );
  1218. }
  1219. else
  1220. {
  1221. // No, so just use the source path.
  1222. dStrcpy( pDstPath, pSrcPath );
  1223. }
  1224. return false;
  1225. }
  1226. // Skip the expando and the following slash.
  1227. pSrc += dStrlen(pathBuffer) + 1;
  1228. // Format the output path.
  1229. dSprintf( pathBuffer, sizeof(pathBuffer), "%s/%s", expandoPath, pSrc );
  1230. // Are we ensuring the trailing slash?
  1231. if ( ensureTrailingSlash )
  1232. {
  1233. // Yes, so ensure it.
  1234. Con::ensureTrailingSlash( pathBuffer, pathBuffer );
  1235. }
  1236. // Strip repeat slashes.
  1237. Con::stripRepeatSlashes( pDstPath, pathBuffer, size );
  1238. return true;
  1239. }
  1240. // Script-Relative.
  1241. if ( leadingToken == '.' )
  1242. {
  1243. // Fetch the code-block file-path.
  1244. const StringTableEntry codeblockFullPath = CodeBlock::getCurrentCodeBlockFullPath();
  1245. // Do we have a code block full path?
  1246. if( codeblockFullPath == NULL )
  1247. {
  1248. // No, so error.
  1249. Con::errorf("expandPath() : Could not find relative path from code-block for path '%s'.", pSrcPath );
  1250. // Are we ensuring the trailing slash?
  1251. if ( ensureTrailingSlash )
  1252. {
  1253. // Yes, so ensure it.
  1254. Con::ensureTrailingSlash( pDstPath, pSrcPath );
  1255. }
  1256. else
  1257. {
  1258. // No, so just use the source path.
  1259. dStrcpy( pDstPath, pSrcPath );
  1260. }
  1261. return false;
  1262. }
  1263. // Yes, so use it as the prefix.
  1264. dStrncpy(pathBuffer, codeblockFullPath, sizeof(pathBuffer) - 1);
  1265. // Find the final slash in the code-block.
  1266. pSlash = dStrrchr(pathBuffer, '/');
  1267. // Is this a parent directory token?
  1268. if ( followingToken == '.' )
  1269. {
  1270. // Yes, so terminate after the slash so we include it.
  1271. pSlash[1] = 0;
  1272. }
  1273. else
  1274. {
  1275. // No, it's a current directory token so terminate at the slash so we don't include it.
  1276. pSlash[0] = 0;
  1277. // Skip the current directory token.
  1278. pSrc++;
  1279. }
  1280. // Format the output path.
  1281. dStrncat(pathBuffer, "/", sizeof(pathBuffer) - 1 - strlen(pathBuffer));
  1282. dStrncat(pathBuffer, pSrc, sizeof(pathBuffer) - 1 - strlen(pathBuffer));
  1283. // Are we ensuring the trailing slash?
  1284. if ( ensureTrailingSlash )
  1285. {
  1286. // Yes, so ensure it.
  1287. Con::ensureTrailingSlash( pathBuffer, pathBuffer );
  1288. }
  1289. // Strip repeat slashes.
  1290. Con::stripRepeatSlashes( pDstPath, pathBuffer, size );
  1291. return true;
  1292. }
  1293. // All else.
  1294. //Using a special case here because the code below barfs on trying to build a full path for apk reading
  1295. #ifdef TORQUE_OS_ANDROID
  1296. if (leadingToken == '/' || strstr(pSrcPath, "/") == NULL)
  1297. Platform::makeFullPathName( pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint );
  1298. else
  1299. dSprintf(pathBuffer, sizeof(pathBuffer), "/%s", pSrcPath);
  1300. #else
  1301. Platform::makeFullPathName( pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint );
  1302. #endif
  1303. // Are we ensuring the trailing slash?
  1304. if ( ensureTrailingSlash )
  1305. {
  1306. // Yes, so ensure it.
  1307. Con::ensureTrailingSlash( pathBuffer, pathBuffer );
  1308. }
  1309. // Strip repeat slashes.
  1310. Con::stripRepeatSlashes( pDstPath, pathBuffer, size );
  1311. return true;
  1312. }
  1313. //-----------------------------------------------------------------------------
  1314. bool isBasePath( const char* SrcPath, const char* pBasePath )
  1315. {
  1316. char expandBuffer[1024];
  1317. Con::expandPath( expandBuffer, sizeof(expandBuffer), SrcPath );
  1318. return dStrnicmp(pBasePath, expandBuffer, dStrlen( pBasePath ) ) == 0;
  1319. }
  1320. //-----------------------------------------------------------------------------
  1321. void collapsePath( char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint )
  1322. {
  1323. // Check path against expandos. If there are multiple matches, choose the
  1324. // expando that produces the shortest relative path.
  1325. char pathBuffer[2048];
  1326. // Fetch expando count.
  1327. const U32 expandoCount = getPathExpandoCount();
  1328. // Iterate expandos.
  1329. U32 expandoRelativePathLength = U32_MAX;
  1330. for( U32 expandoIndex = 0; expandoIndex < expandoCount; ++expandoIndex )
  1331. {
  1332. // Fetch expando value (path).
  1333. StringTableEntry expandoValue = getPathExpandoValue( expandoIndex );
  1334. // Skip if not the base path.
  1335. if ( !isBasePath( pSrcPath, expandoValue ) )
  1336. continue;
  1337. // Fetch path relative to expando path.
  1338. StringTableEntry relativePath = Platform::makeRelativePathName( pSrcPath, expandoValue );
  1339. // If the relative path is simply a period
  1340. if ( relativePath[0] == '.' )
  1341. relativePath++;
  1342. if ( dStrlen(relativePath) > expandoRelativePathLength )
  1343. {
  1344. // This expando covers less of the path than any previous one found.
  1345. // We will keep the previous one.
  1346. continue;
  1347. }
  1348. // Keep track of the relative path length
  1349. expandoRelativePathLength = dStrlen(relativePath);
  1350. // Fetch expando key (name).
  1351. StringTableEntry expandoName = getPathExpandoKey( expandoIndex );
  1352. // Format against expando.
  1353. dSprintf( pathBuffer, sizeof(pathBuffer), "^%s/%s", expandoName, relativePath );
  1354. }
  1355. // Check if we've found a suitable expando
  1356. if ( expandoRelativePathLength != U32_MAX )
  1357. {
  1358. // Strip repeat slashes.
  1359. Con::stripRepeatSlashes( pDstPath, pathBuffer, size );
  1360. return;
  1361. }
  1362. // Fetch the working directory.
  1363. StringTableEntry workingDirectory = pWorkingDirectoryHint != NULL ? pWorkingDirectoryHint : Platform::getCurrentDirectory();
  1364. // Fetch path relative to current directory.
  1365. StringTableEntry relativePath = Platform::makeRelativePathName( pSrcPath, workingDirectory );
  1366. // If the relative path is simply a period
  1367. if ( relativePath[0] == '.' && relativePath[1] != '.' )
  1368. relativePath++;
  1369. // Format against expando.
  1370. dSprintf( pathBuffer, sizeof(pathBuffer), "%s/%s", workingDirectory, relativePath );
  1371. // Strip repeat slashes.
  1372. Con::stripRepeatSlashes( pDstPath, pathBuffer, size );
  1373. }
  1374. //-----------------------------------------------------------------------------
  1375. void ensureTrailingSlash( char* pDstPath, const char* pSrcPath )
  1376. {
  1377. // Copy to target.
  1378. dStrcpy( pDstPath, pSrcPath );
  1379. // Find trailing character index.
  1380. S32 trailIndex = dStrlen(pDstPath);
  1381. // Ignore if empty string.
  1382. if ( trailIndex == 0 )
  1383. return;
  1384. // Finish if the trailing slash already exists.
  1385. if ( pDstPath[trailIndex-1] == '/' )
  1386. return;
  1387. // Add trailing slash.
  1388. pDstPath[trailIndex++] = '/';
  1389. pDstPath[trailIndex] = 0;
  1390. }
  1391. //-----------------------------------------------------------------------------
  1392. bool stripRepeatSlashes( char* pDstPath, const char* pSrcPath, S32 dstSize )
  1393. {
  1394. // Note original destination.
  1395. char* pOriginalDst = pDstPath;
  1396. // Reset last source character.
  1397. char lastSrcChar = 0;
  1398. // Search source...
  1399. while ( dstSize > 0 )
  1400. {
  1401. // Fetch characters.
  1402. const char srcChar = *pSrcPath++;
  1403. // Do we have a repeat slash?
  1404. if ( srcChar == '/' && lastSrcChar == '/' )
  1405. {
  1406. // Yes, so skip it.
  1407. continue;
  1408. }
  1409. // No, so copy character.
  1410. *pDstPath++ = srcChar;
  1411. // Finish if end of source.
  1412. if ( srcChar == 0 )
  1413. return true;
  1414. // Reduce room left in destination.
  1415. dstSize--;
  1416. // Set last character.
  1417. lastSrcChar = srcChar;
  1418. }
  1419. // Terminate the destination string as we ran out of room.
  1420. *pOriginalDst = 0;
  1421. // Fail!
  1422. return false;
  1423. }
  1424. } // end of Console namespace