console.cc 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  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 S32 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. dStrcpy(pathBuffer, codeblockFullPath );
  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. dSprintf( pathBuffer, sizeof(pathBuffer), "%s/%s", pathBuffer, pSrc );
  1282. // Are we ensuring the trailing slash?
  1283. if ( ensureTrailingSlash )
  1284. {
  1285. // Yes, so ensure it.
  1286. Con::ensureTrailingSlash( pathBuffer, pathBuffer );
  1287. }
  1288. // Strip repeat slashes.
  1289. Con::stripRepeatSlashes( pDstPath, pathBuffer, size );
  1290. return true;
  1291. }
  1292. // All else.
  1293. Platform::makeFullPathName( pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint );
  1294. // Are we ensuring the trailing slash?
  1295. if ( ensureTrailingSlash )
  1296. {
  1297. // Yes, so ensure it.
  1298. Con::ensureTrailingSlash( pathBuffer, pathBuffer );
  1299. }
  1300. // Strip repeat slashes.
  1301. Con::stripRepeatSlashes( pDstPath, pathBuffer, size );
  1302. return true;
  1303. }
  1304. //-----------------------------------------------------------------------------
  1305. bool isBasePath( const char* SrcPath, const char* pBasePath )
  1306. {
  1307. char expandBuffer[1024];
  1308. Con::expandPath( expandBuffer, sizeof(expandBuffer), SrcPath );
  1309. return dStrnicmp(pBasePath, expandBuffer, dStrlen( pBasePath ) ) == 0;
  1310. }
  1311. //-----------------------------------------------------------------------------
  1312. void collapsePath( char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint )
  1313. {
  1314. // Check path against expandos. If there are multiple matches, choose the
  1315. // expando that produces the shortest relative path.
  1316. char pathBuffer[2048];
  1317. // Fetch expando count.
  1318. const U32 expandoCount = getPathExpandoCount();
  1319. // Iterate expandos.
  1320. U32 expandoRelativePathLength = U32_MAX;
  1321. for( U32 expandoIndex = 0; expandoIndex < expandoCount; ++expandoIndex )
  1322. {
  1323. // Fetch expando value (path).
  1324. StringTableEntry expandoValue = getPathExpandoValue( expandoIndex );
  1325. // Skip if not the base path.
  1326. if ( !isBasePath( pSrcPath, expandoValue ) )
  1327. continue;
  1328. // Fetch path relative to expando path.
  1329. StringTableEntry relativePath = Platform::makeRelativePathName( pSrcPath, expandoValue );
  1330. // If the relative path is simply a period
  1331. if ( relativePath[0] == '.' )
  1332. relativePath++;
  1333. if ( dStrlen(relativePath) > expandoRelativePathLength )
  1334. {
  1335. // This expando covers less of the path than any previous one found.
  1336. // We will keep the previous one.
  1337. continue;
  1338. }
  1339. // Keep track of the relative path length
  1340. expandoRelativePathLength = dStrlen(relativePath);
  1341. // Fetch expando key (name).
  1342. StringTableEntry expandoName = getPathExpandoKey( expandoIndex );
  1343. // Format against expando.
  1344. dSprintf( pathBuffer, sizeof(pathBuffer), "^%s/%s", expandoName, relativePath );
  1345. }
  1346. // Check if we've found a suitable expando
  1347. if ( expandoRelativePathLength != U32_MAX )
  1348. {
  1349. // Strip repeat slashes.
  1350. Con::stripRepeatSlashes( pDstPath, pathBuffer, size );
  1351. return;
  1352. }
  1353. // Fetch the working directory.
  1354. StringTableEntry workingDirectory = pWorkingDirectoryHint != NULL ? pWorkingDirectoryHint : Platform::getCurrentDirectory();
  1355. // Fetch path relative to current directory.
  1356. StringTableEntry relativePath = Platform::makeRelativePathName( pSrcPath, workingDirectory );
  1357. // If the relative path is simply a period
  1358. if ( relativePath[0] == '.' && relativePath[1] != '.' )
  1359. relativePath++;
  1360. // Format against expando.
  1361. dSprintf( pathBuffer, sizeof(pathBuffer), "%s/%s", workingDirectory, relativePath );
  1362. // Strip repeat slashes.
  1363. Con::stripRepeatSlashes( pDstPath, pathBuffer, size );
  1364. }
  1365. //-----------------------------------------------------------------------------
  1366. void ensureTrailingSlash( char* pDstPath, const char* pSrcPath )
  1367. {
  1368. // Copy to target.
  1369. dStrcpy( pDstPath, pSrcPath );
  1370. // Find trailing character index.
  1371. S32 trailIndex = dStrlen(pDstPath);
  1372. // Ignore if empty string.
  1373. if ( trailIndex == 0 )
  1374. return;
  1375. // Finish if the trailing slash already exists.
  1376. if ( pDstPath[trailIndex-1] == '/' )
  1377. return;
  1378. // Add trailing slash.
  1379. pDstPath[trailIndex++] = '/';
  1380. pDstPath[trailIndex] = 0;
  1381. }
  1382. //-----------------------------------------------------------------------------
  1383. bool stripRepeatSlashes( char* pDstPath, const char* pSrcPath, S32 dstSize )
  1384. {
  1385. // Note original destination.
  1386. char* pOriginalDst = pDstPath;
  1387. // Reset last source character.
  1388. char lastSrcChar = 0;
  1389. // Search source...
  1390. while ( dstSize > 0 )
  1391. {
  1392. // Fetch characters.
  1393. const char srcChar = *pSrcPath++;
  1394. // Do we have a repeat slash?
  1395. if ( srcChar == '/' && lastSrcChar == '/' )
  1396. {
  1397. // Yes, so skip it.
  1398. continue;
  1399. }
  1400. // No, so copy character.
  1401. *pDstPath++ = srcChar;
  1402. // Finish if end of source.
  1403. if ( srcChar == 0 )
  1404. return true;
  1405. // Reduce room left in destination.
  1406. dstSize--;
  1407. // Set last character.
  1408. lastSrcChar = srcChar;
  1409. }
  1410. // Terminate the destination string as we ran out of room.
  1411. *pOriginalDst = 0;
  1412. // Fail!
  1413. return false;
  1414. }
  1415. } // end of Console namespace