console.cc 50 KB

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