console.cc 54 KB

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