XConsole.cpp 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. // Description : implementation of the CXConsole class.
  9. #include "CrySystem_precompiled.h"
  10. #include "XConsole.h"
  11. #include "XConsoleVariable.h"
  12. #include "System.h"
  13. #include "ConsoleBatchFile.h"
  14. #include <IRenderer.h>
  15. #include <ISystem.h>
  16. #include <ILog.h>
  17. #include <IFont.h>
  18. #include <ITexture.h>
  19. #include "ConsoleHelpGen.h" // CConsoleHelpGen
  20. #include <AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard.h>
  21. #include <AzFramework/Input/Devices/Mouse/InputDeviceMouse.h>
  22. #include <AzCore/std/string/conversions.h>
  23. #include <AzCore/std/algorithm.h>
  24. #include <AzCore/Time/ITime.h>
  25. //#define DEFENCE_CVAR_HASH_LOGGING
  26. // s should point to a buffer at least 65 chars long
  27. inline void BitsAlpha64(uint64 n, char* s)
  28. {
  29. for (int i = 0; n != 0; n >>= 1, i++)
  30. {
  31. if (n & 1)
  32. {
  33. *s++ = i < 32 ? static_cast<char>(i + 'z' - 31) : static_cast<char>(i + 'Z' - 63);
  34. }
  35. }
  36. *s++ = '\0';
  37. }
  38. static inline void AssertName([[maybe_unused]] const char* szName)
  39. {
  40. #ifdef _DEBUG
  41. assert(szName);
  42. // test for good console variable / command name
  43. const char* p = szName;
  44. bool bFirstChar = true;
  45. while (*p)
  46. {
  47. assert((*p >= 'a' && *p <= 'z')
  48. || (*p >= 'A' && *p <= 'Z')
  49. || (*p >= '0' && *p <= '9' && !bFirstChar)
  50. || *p == '_'
  51. || *p == '.');
  52. ++p;
  53. bFirstChar = false;
  54. }
  55. #endif
  56. }
  57. void ResetCVars(IConsoleCmdArgs*)
  58. {
  59. if (gEnv->pSystem)
  60. {
  61. CXConsole* pConsole = static_cast<CXConsole*>(gEnv->pSystem->GetIConsole());
  62. if (pConsole)
  63. {
  64. pConsole->ResetCVarsToDefaults();
  65. }
  66. }
  67. }
  68. //////////////////////////////////////////////////////////////////////////
  69. // user defined comparison - for nicer printout
  70. inline int GetCharPrio(char x)
  71. {
  72. if (x >= 'a' && x <= 'z')
  73. {
  74. x += 'A' - 'a'; // make upper case
  75. }
  76. if (x == '_')
  77. {
  78. return 300;
  79. }
  80. else
  81. {
  82. return x;
  83. }
  84. }
  85. void Command_SetWaitSeconds(IConsoleCmdArgs* pCmd)
  86. {
  87. CXConsole* pConsole = (CXConsole*)gEnv->pConsole;
  88. if (pCmd->GetArgCount() > 1)
  89. {
  90. pConsole->m_waitSeconds.SetSeconds(atof(pCmd->GetArg(1)));
  91. const AZ::TimeMs elaspedTimeMs = AZ::GetRealElapsedTimeMs();
  92. pConsole->m_waitSeconds += CTimeValue(AZ::TimeMsToSecondsDouble(elaspedTimeMs));
  93. }
  94. }
  95. void Command_SetWaitFrames(IConsoleCmdArgs* pCmd)
  96. {
  97. CXConsole* pConsole = (CXConsole*)gEnv->pConsole;
  98. if (pCmd->GetArgCount() > 1)
  99. {
  100. pConsole->m_waitFrames = max(0, atoi(pCmd->GetArg(1)));
  101. }
  102. }
  103. void ConsoleShow(IConsoleCmdArgs*)
  104. {
  105. gEnv->pConsole->ShowConsole(true);
  106. }
  107. void ConsoleHide(IConsoleCmdArgs*)
  108. {
  109. gEnv->pConsole->ShowConsole(false);
  110. }
  111. void Bind(IConsoleCmdArgs* cmdArgs)
  112. {
  113. if (cmdArgs->GetArgCount() >= 3)
  114. {
  115. AZStd::string arg;
  116. for (int i = 2; i < cmdArgs->GetArgCount(); ++i)
  117. {
  118. arg += cmdArgs->GetArg(i);
  119. arg += " ";
  120. }
  121. gEnv->pConsole->CreateKeyBind(cmdArgs->GetArg(1), arg.c_str());
  122. }
  123. }
  124. //////////////////////////////////////////////////////////////////////////
  125. int CXConsole::con_display_last_messages = 0;
  126. int CXConsole::con_line_buffer_size = 500;
  127. int CXConsole::con_showonload = 0;
  128. int CXConsole::con_debug = 0;
  129. int CXConsole::con_restricted = 0;
  130. //////////////////////////////////////////////////////////////////////
  131. // Construction/Destruction
  132. //////////////////////////////////////////////////////////////////////
  133. CXConsole::CXConsole()
  134. {
  135. m_fRepeatTimer = 0;
  136. m_pSysDeactivateConsole = 0;
  137. m_pImage = NULL;
  138. m_nCursorPos = 0;
  139. m_nScrollPos = 0;
  140. m_nScrollMax = 300;
  141. m_nTempScrollMax = m_nScrollMax;
  142. m_nScrollLine = 0;
  143. m_nHistoryPos = -1;
  144. m_nTabCount = 0;
  145. m_bConsoleActive = false;
  146. m_bActivationKeyEnable = true;
  147. m_bIsProcessingGroup = false;
  148. m_bIsConsoleKeyPressed = false;
  149. m_sdScrollDir = sdNONE;
  150. m_pSystem = NULL;
  151. m_bDrawCursor = true;
  152. m_fCursorBlinkTimer = 0;
  153. m_nCheatHashRangeFirst = 0;
  154. m_nCheatHashRangeLast = 0;
  155. m_bCheatHashDirty = false;
  156. m_nCheatHash = 0;
  157. m_bStaticBackground = false;
  158. m_nProgress = 0;
  159. m_nProgressRange = 0;
  160. m_nLoadingBackTexID = 0;
  161. m_deferredExecution = false;
  162. m_waitFrames = 0;
  163. m_waitSeconds = 0.0f;
  164. m_blockCounter = 0;
  165. m_intWrappers.reserve(128);
  166. m_floatWrappers.reserve(128);
  167. m_stringWrappers.reserve(128);
  168. AzFramework::ConsoleRequestBus::Handler::BusConnect();
  169. AzFramework::CommandRegistrationBus::Handler::BusConnect();
  170. AddCommand("resetcvars", (ConsoleCommandFunc)ResetCVars, 0, "Resets all cvars to their initial values");
  171. }
  172. //////////////////////////////////////////////////////////////////////////
  173. CXConsole::~CXConsole()
  174. {
  175. AzFramework::ConsoleRequestBus::Handler::BusDisconnect();
  176. AzFramework::CommandRegistrationBus::Handler::BusDisconnect();
  177. if (gEnv->pSystem)
  178. {
  179. gEnv->pSystem->GetIRemoteConsole()->UnregisterListener(this);
  180. }
  181. if (!m_mapVariables.empty())
  182. {
  183. while (!m_mapVariables.empty())
  184. {
  185. m_mapVariables.begin()->second->Release();
  186. }
  187. m_mapVariables.clear();
  188. }
  189. }
  190. //////////////////////////////////////////////////////////////////////////
  191. void CXConsole::FreeRenderResources()
  192. {
  193. }
  194. //////////////////////////////////////////////////////////////////////////
  195. void CXConsole::Release()
  196. {
  197. delete this;
  198. }
  199. #if ALLOW_AUDIT_CVARS
  200. void Command_AuditCVars(IConsoleCmdArgs* pArg)
  201. {
  202. CXConsole* pConsole = (CXConsole*)gEnv->pConsole;
  203. if (pConsole != NULL)
  204. {
  205. pConsole->AuditCVars(pArg);
  206. }
  207. }
  208. #endif // ALLOW_AUDIT_CVARS
  209. #if !defined(_RELEASE) && !defined(LINUX) && !defined(APPLE)
  210. void Command_DumpCommandsVars(IConsoleCmdArgs* Cmd)
  211. {
  212. const char* arg = "";
  213. if (Cmd->GetArgCount() > 1)
  214. {
  215. arg = Cmd->GetArg(1);
  216. }
  217. CXConsole* pConsole = (CXConsole*)gEnv->pConsole;
  218. // txt
  219. pConsole->DumpCommandsVarsTxt(arg);
  220. #if defined(WIN32) || defined(WIN64)
  221. // HTML
  222. {
  223. CConsoleHelpGen Generator(*pConsole);
  224. Generator.Work();
  225. }
  226. #endif
  227. }
  228. void Command_DumpVars(IConsoleCmdArgs* Cmd)
  229. {
  230. bool includeCheat = false;
  231. if (Cmd->GetArgCount() > 1)
  232. {
  233. const char* arg = Cmd->GetArg(1);
  234. int incCheat = atoi(arg);
  235. if (incCheat == 1)
  236. {
  237. includeCheat = true;
  238. }
  239. }
  240. CXConsole* pConsole = (CXConsole*)gEnv->pConsole;
  241. // txt
  242. pConsole->DumpVarsTxt(includeCheat);
  243. }
  244. #endif
  245. //////////////////////////////////////////////////////////////////////////
  246. void CXConsole::Init(ISystem* pSystem)
  247. {
  248. m_pSystem = static_cast<CSystem*>(pSystem);
  249. #if defined(_RELEASE)
  250. static const int kDeactivateConsoleDefault = 1;
  251. #else
  252. static const int kDeactivateConsoleDefault = 0;
  253. #endif
  254. m_pSysDeactivateConsole = REGISTER_INT("sys_DeactivateConsole", kDeactivateConsoleDefault, 0,
  255. "0: normal console behavior\n"
  256. "1: hide the console");
  257. REGISTER_CVAR(con_display_last_messages, 0, VF_NULL, ""); // keep default at 1, needed for gameplay
  258. REGISTER_CVAR(con_line_buffer_size, 1000, VF_NULL, "The number of lines to buffer in the console output window");
  259. REGISTER_CVAR(con_showonload, 0, VF_NULL, "Show console on level loading");
  260. REGISTER_CVAR(con_debug, 0, VF_CHEAT, "Log call stack on every GetCVar call");
  261. REGISTER_CVAR(con_restricted, con_restricted, VF_RESTRICTEDMODE, "0=normal mode / 1=restricted access to the console"); // later on VF_RESTRICTEDMODE should be removed (to 0)
  262. if (m_pSystem->IsDevMode() // unrestricted console for -DEVMODE
  263. || gEnv->IsDedicated()) // unrestricted console for dedicated server
  264. {
  265. con_restricted = 0;
  266. }
  267. m_nLoadingBackTexID = -1;
  268. REGISTER_COMMAND("ConsoleShow", &ConsoleShow, VF_NULL, "Opens the console");
  269. REGISTER_COMMAND("ConsoleHide", &ConsoleHide, VF_NULL, "Closes the console");
  270. #if ALLOW_AUDIT_CVARS
  271. REGISTER_COMMAND("audit_cvars", &Command_AuditCVars, VF_NULL, "Logs all console commands and cvars");
  272. #endif // ALLOW_AUDIT_CVARS
  273. #if !defined(_RELEASE) && !defined(LINUX) && !defined(APPLE)
  274. REGISTER_COMMAND("DumpCommandsVars", &Command_DumpCommandsVars, VF_NULL,
  275. "This console command dumps all console variables and commands to disk\n"
  276. "DumpCommandsVars [prefix]");
  277. REGISTER_COMMAND("DumpVars", &Command_DumpVars, VF_NULL,
  278. "This console command dumps all console variables to disk\n"
  279. "DumpVars [IncludeCheatCvars]");
  280. #endif
  281. REGISTER_COMMAND("Bind", &Bind, VF_NULL, "");
  282. REGISTER_COMMAND("wait_seconds", &Command_SetWaitSeconds, VF_BLOCKFRAME,
  283. "Forces the console to wait for a given number of seconds before the next deferred command is processed\n"
  284. "Works only in deferred command mode");
  285. REGISTER_COMMAND("wait_frames", &Command_SetWaitFrames, VF_BLOCKFRAME,
  286. "Forces the console to wait for a given number of frames before the next deferred command is processed\n"
  287. "Works only in deferred command mode");
  288. CConsoleBatchFile::Init();
  289. if (con_showonload)
  290. {
  291. ShowConsole(true);
  292. }
  293. pSystem->GetIRemoteConsole()->RegisterListener(this, "CXConsole");
  294. }
  295. void CXConsole::LogChangeMessage(const char* name, const bool isConst, const bool isCheat, const bool isReadOnly, const bool isDeprecated,
  296. const char* oldValue, const char* newValue, [[maybe_unused]] const bool isProcessingGroup, const bool allowChange)
  297. {
  298. AZStd::string logMessage = AZStd::string::format
  299. ("[CVARS]: [%s] variable [%s] from [%s] to [%s]%s; Marked as%s%s%s%s",
  300. (allowChange) ? "CHANGED" : "IGNORED CHANGE",
  301. name,
  302. oldValue,
  303. newValue,
  304. (m_bIsProcessingGroup) ? " as part of a cvar group" : "",
  305. (isConst) ? " [VF_CONST_CVAR]" : "",
  306. (isCheat) ? " [VF_CHEAT]" : "",
  307. (isReadOnly) ? " [VF_READONLY]" : "",
  308. (isDeprecated) ? " [VF_DEPRECATED]" : "");
  309. if (allowChange)
  310. {
  311. gEnv->pLog->LogWarning("%s", logMessage.c_str());
  312. gEnv->pLog->LogWarning("Modifying marked variables will not be allowed in Release mode!");
  313. }
  314. else
  315. {
  316. gEnv->pLog->LogError("%s", logMessage.c_str());
  317. }
  318. }
  319. //////////////////////////////////////////////////////////////////////////
  320. void CXConsole::RegisterVar(ICVar* pCVar, ConsoleVarFunc pChangeFunc)
  321. {
  322. // first register callback so setting the value from m_configVars
  323. // is calling pChangeFunc (that would be more correct but to not introduce new problems this code was not changed)
  324. // if (pChangeFunc)
  325. // pCVar->SetOnChangeCallback(pChangeFunc);
  326. bool isConst = pCVar->IsConstCVar();
  327. bool isCheat = ((pCVar->GetFlags() & (VF_CHEAT | VF_CHEAT_NOCHECK | VF_CHEAT_ALWAYS_CHECK)) != 0);
  328. bool isReadOnly = ((pCVar->GetFlags() & VF_READONLY) != 0);
  329. bool isDeprecated = ((pCVar->GetFlags() & VF_DEPRECATED) != 0);
  330. ConfigVars::iterator it = m_configVars.find(pCVar->GetName());
  331. if (it != m_configVars.end())
  332. {
  333. SConfigVar& var = it->second;
  334. bool allowChange = true;
  335. bool wasProcessingGroup = GetIsProcessingGroup();
  336. SetProcessingGroup(var.m_partOfGroup);
  337. if (
  338. #if CVAR_GROUPS_ARE_PRIVILEGED
  339. !m_bIsProcessingGroup &&
  340. #endif // !CVAR_GROUPS_ARE_PRIVILEGED
  341. (isConst || isCheat || isReadOnly || isDeprecated))
  342. {
  343. allowChange = !isDeprecated && ((gEnv->pSystem->IsDevMode()) || (gEnv->IsEditor()));
  344. if ((strcmp(pCVar->GetString(), var.m_value.c_str()) != 0) && (!(gEnv->IsEditor()) || isDeprecated))
  345. {
  346. #if LOG_CVAR_INFRACTIONS
  347. LogChangeMessage(pCVar->GetName(), isConst, isCheat,
  348. isReadOnly, isDeprecated, pCVar->GetString(), var.m_value.c_str(), m_bIsProcessingGroup, allowChange);
  349. #if LOG_CVAR_INFRACTIONS_CALLSTACK
  350. gEnv->pSystem->debug_LogCallStack();
  351. #endif // LOG_CVAR_INFRACTIONS_CALLSTACK
  352. #endif // LOG_CVAR_INFRACTIONS
  353. }
  354. }
  355. if (allowChange || ALLOW_CONST_CVAR_MODIFICATIONS)
  356. {
  357. pCVar->Set(var.m_value.c_str());
  358. pCVar->SetFlags(pCVar->GetFlags() | VF_WASINCONFIG);
  359. }
  360. SetProcessingGroup(wasProcessingGroup);
  361. }
  362. else
  363. {
  364. // Variable is not modified when just registered.
  365. pCVar->ClearFlags(VF_MODIFIED);
  366. }
  367. if (pChangeFunc)
  368. {
  369. pCVar->SetOnChangeCallback(pChangeFunc);
  370. }
  371. ConsoleVariablesMapItor::value_type value = ConsoleVariablesMapItor::value_type(pCVar->GetName(), pCVar);
  372. m_mapVariables.insert(value);
  373. if (auto consoleInterface = AZ::Interface<AZ::IConsole>::Get();
  374. consoleInterface != nullptr && !consoleInterface->HasCommand(pCVar->GetName(), AZ::ConsoleFunctorFlags::Null))
  375. {
  376. if (pCVar->GetType() == CVAR_INT)
  377. {
  378. m_intWrappers.emplace_back(pCVar->GetName(), pCVar->GetHelp(), pCVar->GetIVal());
  379. }
  380. else if (pCVar->GetType() == CVAR_FLOAT)
  381. {
  382. m_floatWrappers.emplace_back(pCVar->GetName(), pCVar->GetHelp(), pCVar->GetFVal());
  383. }
  384. else if (pCVar->GetType() == CVAR_STRING)
  385. {
  386. m_stringWrappers.emplace_back(pCVar->GetName(), pCVar->GetHelp(), pCVar->GetString());
  387. }
  388. }
  389. int flags = pCVar->GetFlags();
  390. if (flags & VF_CHEAT_ALWAYS_CHECK)
  391. {
  392. AddCheckedCVar(m_alwaysCheckedVariables, value);
  393. }
  394. else if ((flags & (VF_CHEAT | VF_CHEAT_NOCHECK)) == VF_CHEAT)
  395. {
  396. AddCheckedCVar(m_randomCheckedVariables, value);
  397. }
  398. }
  399. //////////////////////////////////////////////////////////////////////////
  400. void CXConsole::AddCheckedCVar(ConsoleVariablesVector& vector, const ConsoleVariablesVector::value_type& value)
  401. {
  402. ConsoleVariablesVector::iterator it = std::lower_bound(vector.begin(), vector.end(), value, CVarNameLess);
  403. if ((it == vector.end()) || strcmp(it->first, value.first))
  404. {
  405. vector.insert(it, value);
  406. }
  407. }
  408. //////////////////////////////////////////////////////////////////////////
  409. bool CXConsole::CVarNameLess(const std::pair<const char*, ICVar*>& lhs, const std::pair<const char*, ICVar*>& rhs)
  410. {
  411. return strcmp(lhs.first, rhs.first) < 0;
  412. }
  413. //////////////////////////////////////////////////////////////////////////
  414. void CXConsole::LoadConfigVar(const char* sVariable, const char* sValue)
  415. {
  416. ICVar* pCVar = GetCVar(sVariable);
  417. if (pCVar)
  418. {
  419. bool isConst = pCVar->IsConstCVar();
  420. bool isCheat = ((pCVar->GetFlags() & (VF_CHEAT | VF_CHEAT_NOCHECK | VF_CHEAT_ALWAYS_CHECK)) != 0);
  421. bool isReadOnly = ((pCVar->GetFlags() & VF_READONLY) != 0);
  422. bool isDeprecated = ((pCVar->GetFlags() & VF_DEPRECATED) != 0);
  423. bool allowChange = true;
  424. if (
  425. #if CVAR_GROUPS_ARE_PRIVILEGED
  426. !m_bIsProcessingGroup &&
  427. #endif // !CVAR_GROUPS_ARE_PRIVILEGED
  428. (isConst || isCheat || isReadOnly) || isDeprecated)
  429. {
  430. allowChange = !isDeprecated && (gEnv->pSystem->IsDevMode()) || (gEnv->IsEditor());
  431. if (!(gEnv->IsEditor()) || isDeprecated)
  432. {
  433. #if LOG_CVAR_INFRACTIONS
  434. LogChangeMessage(pCVar->GetName(), isConst, isCheat,
  435. isReadOnly, isDeprecated, pCVar->GetString(), sValue, m_bIsProcessingGroup, allowChange);
  436. #if LOG_CVAR_INFRACTIONS_CALLSTACK
  437. gEnv->pSystem->debug_LogCallStack();
  438. #endif // LOG_CVAR_INFRACTIONS_CALLSTACK
  439. #endif // LOG_CVAR_INFRACTIONS
  440. }
  441. }
  442. if (allowChange || ALLOW_CONST_CVAR_MODIFICATIONS)
  443. {
  444. pCVar->Set(sValue);
  445. pCVar->SetFlags(pCVar->GetFlags() | VF_WASINCONFIG);
  446. }
  447. return;
  448. }
  449. SConfigVar temp;
  450. temp.m_value = sValue;
  451. temp.m_partOfGroup = m_bIsProcessingGroup;
  452. m_configVars[sVariable] = temp;
  453. }
  454. //////////////////////////////////////////////////////////////////////////
  455. void CXConsole::EnableActivationKey(bool bEnable)
  456. {
  457. m_bActivationKeyEnable = bEnable;
  458. }
  459. //////////////////////////////////////////////////////////////////////////
  460. void CXConsole::SetClientDataProbeString(const char* pName, const char* pValue)
  461. {
  462. ICVar* pCVar = GetCVar(pName);
  463. if (pCVar)
  464. {
  465. pCVar->SetDataProbeString(pValue);
  466. }
  467. }
  468. //////////////////////////////////////////////////////////////////////////
  469. ICVar* CXConsole::Register(const char* sName, int* src, int iValue, int nFlags, const char* help, ConsoleVarFunc pChangeFunc, bool allowModify)
  470. {
  471. AssertName(sName);
  472. ICVar* pCVar = stl::find_in_map(m_mapVariables, sName, NULL);
  473. if (pCVar)
  474. {
  475. gEnv->pLog->LogError("[CVARS]: [DUPLICATE] CXConsole::Register(int): variable [%s] is already registered", pCVar->GetName());
  476. #if LOG_CVAR_INFRACTIONS_CALLSTACK
  477. gEnv->pSystem->debug_LogCallStack();
  478. #endif // LOG_CVAR_INFRACTIONS_CALLSTACK
  479. return pCVar;
  480. }
  481. if (!allowModify)
  482. {
  483. nFlags |= VF_CONST_CVAR;
  484. }
  485. pCVar = new CXConsoleVariableIntRef(this, sName, src, nFlags, help);
  486. *src = iValue;
  487. RegisterVar(pCVar, pChangeFunc);
  488. return pCVar;
  489. }
  490. //////////////////////////////////////////////////////////////////////////
  491. ICVar* CXConsole::Register(const char* sName, float* src, float fValue, int nFlags, const char* help, ConsoleVarFunc pChangeFunc, bool allowModify)
  492. {
  493. AssertName(sName);
  494. ICVar* pCVar = stl::find_in_map(m_mapVariables, sName, NULL);
  495. if (pCVar)
  496. {
  497. gEnv->pLog->Log("[CVARS]: [DUPLICATE] CXConsole::Register(float): variable [%s] is already registered", pCVar->GetName());
  498. #if LOG_CVAR_INFRACTIONS_CALLSTACK
  499. gEnv->pSystem->debug_LogCallStack();
  500. #endif // LOG_CVAR_INFRACTIONS_CALLSTACK
  501. return pCVar;
  502. }
  503. if (!allowModify)
  504. {
  505. nFlags |= VF_CONST_CVAR;
  506. }
  507. pCVar = new CXConsoleVariableFloatRef(this, sName, src, nFlags, help);
  508. *src = fValue;
  509. RegisterVar(pCVar, pChangeFunc);
  510. return pCVar;
  511. }
  512. //////////////////////////////////////////////////////////////////////////
  513. ICVar* CXConsole::Register(const char* sName, const char** src, const char* defaultValue, int nFlags, const char* help, ConsoleVarFunc pChangeFunc, bool allowModify)
  514. {
  515. AssertName(sName);
  516. ICVar* pCVar = stl::find_in_map(m_mapVariables, sName, NULL);
  517. if (pCVar)
  518. {
  519. gEnv->pLog->Log("[CVARS]: [DUPLICATE] CXConsole::Register(const char*): variable [%s] is already registered", pCVar->GetName());
  520. #if LOG_CVAR_INFRACTIONS_CALLSTACK
  521. gEnv->pSystem->debug_LogCallStack();
  522. #endif // LOG_CVAR_INFRACTIONS_CALLSTACK
  523. return pCVar;
  524. }
  525. if (!allowModify)
  526. {
  527. nFlags |= VF_CONST_CVAR;
  528. }
  529. pCVar = new CXConsoleVariableStringRef(this, sName, src, defaultValue, nFlags, help);
  530. RegisterVar(pCVar, pChangeFunc);
  531. return pCVar;
  532. }
  533. //////////////////////////////////////////////////////////////////////////
  534. ICVar* CXConsole::RegisterString(const char* sName, const char* sValue, int nFlags, const char* help, ConsoleVarFunc pChangeFunc)
  535. {
  536. AssertName(sName);
  537. ICVar* pCVar = stl::find_in_map(m_mapVariables, sName, NULL);
  538. if (pCVar)
  539. {
  540. gEnv->pLog->Log("[CVARS]: [DUPLICATE] CXConsole::RegisterString(const char*): variable [%s] is already registered", pCVar->GetName());
  541. #if LOG_CVAR_INFRACTIONS_CALLSTACK
  542. gEnv->pSystem->debug_LogCallStack();
  543. #endif // LOG_CVAR_INFRACTIONS_CALLSTACK
  544. return pCVar;
  545. }
  546. pCVar = new CXConsoleVariableString(this, sName, sValue, nFlags, help);
  547. RegisterVar(pCVar, pChangeFunc);
  548. return pCVar;
  549. }
  550. //////////////////////////////////////////////////////////////////////////
  551. ICVar* CXConsole::RegisterFloat(const char* sName, float fValue, int nFlags, const char* help, ConsoleVarFunc pChangeFunc)
  552. {
  553. AssertName(sName);
  554. ICVar* pCVar = stl::find_in_map(m_mapVariables, sName, NULL);
  555. if (pCVar)
  556. {
  557. gEnv->pLog->Log("[CVARS]: [DUPLICATE] CXConsole::RegisterFloat(): variable [%s] is already registered", pCVar->GetName());
  558. #if LOG_CVAR_INFRACTIONS_CALLSTACK
  559. gEnv->pSystem->debug_LogCallStack();
  560. #endif // LOG_CVAR_INFRACTIONS_CALLSTACK
  561. return pCVar;
  562. }
  563. pCVar = new CXConsoleVariableFloat(this, sName, fValue, nFlags, help);
  564. RegisterVar(pCVar, pChangeFunc);
  565. return pCVar;
  566. }
  567. //////////////////////////////////////////////////////////////////////////
  568. ICVar* CXConsole::RegisterInt(const char* sName, int iValue, int nFlags, const char* help, ConsoleVarFunc pChangeFunc)
  569. {
  570. AssertName(sName);
  571. ICVar* pCVar = stl::find_in_map(m_mapVariables, sName, NULL);
  572. if (pCVar)
  573. {
  574. gEnv->pLog->Log("[CVARS]: [DUPLICATE] CXConsole::RegisterInt(): variable [%s] is already registered", pCVar->GetName());
  575. #if LOG_CVAR_INFRACTIONS_CALLSTACK
  576. gEnv->pSystem->debug_LogCallStack();
  577. #endif // LOG_CVAR_INFRACTIONS_CALLSTACK
  578. return pCVar;
  579. }
  580. pCVar = new CXConsoleVariableInt(this, sName, iValue, nFlags, help);
  581. RegisterVar(pCVar, pChangeFunc);
  582. return pCVar;
  583. }
  584. //////////////////////////////////////////////////////////////////////////
  585. void CXConsole::UnregisterVariable(const char* sVarName, [[maybe_unused]] bool bDelete)
  586. {
  587. ConsoleVariablesMapItor itor;
  588. itor = m_mapVariables.find(sVarName);
  589. if (itor == m_mapVariables.end())
  590. {
  591. return;
  592. }
  593. ICVar* pCVar = itor->second;
  594. int32 flags = pCVar->GetFlags();
  595. if (flags & VF_CHEAT_ALWAYS_CHECK)
  596. {
  597. RemoveCheckedCVar(m_alwaysCheckedVariables, *itor);
  598. }
  599. else if ((flags & (VF_CHEAT | VF_CHEAT_NOCHECK)) == VF_CHEAT)
  600. {
  601. RemoveCheckedCVar(m_randomCheckedVariables, *itor);
  602. }
  603. m_mapVariables.erase(sVarName);
  604. delete pCVar;
  605. }
  606. void CXConsole::RemoveCheckedCVar(ConsoleVariablesVector& vector, const ConsoleVariablesVector::value_type& value)
  607. {
  608. ConsoleVariablesVector::iterator it = std::lower_bound(vector.begin(), vector.end(), value, CVarNameLess);
  609. if ((it != vector.end()) && !strcmp(it->first, value.first))
  610. {
  611. vector.erase(it);
  612. }
  613. }
  614. //////////////////////////////////////////////////////////////////////////
  615. void CXConsole::SetScrollMax(int value)
  616. {
  617. m_nScrollMax = value;
  618. m_nTempScrollMax = m_nScrollMax;
  619. }
  620. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  621. void CXConsole::ShowConsole(bool show, const int iRequestScrollMax)
  622. {
  623. if (m_pSysDeactivateConsole->GetIVal())
  624. {
  625. show = false;
  626. }
  627. SetStatus(show);
  628. if (iRequestScrollMax > 0)
  629. {
  630. m_nTempScrollMax = iRequestScrollMax; // temporary user request
  631. }
  632. else
  633. {
  634. m_nTempScrollMax = m_nScrollMax; // reset
  635. }
  636. if (m_bConsoleActive)
  637. {
  638. m_sdScrollDir = sdDOWN;
  639. }
  640. else
  641. {
  642. m_sdScrollDir = sdUP;
  643. }
  644. }
  645. //////////////////////////////////////////////////////////////////////////
  646. void CXConsole::CreateKeyBind(const char* sCmd, const char* sRes)
  647. {
  648. m_mapBinds.insert(ConsoleBindsMapItor::value_type(sCmd, sRes));
  649. }
  650. //////////////////////////////////////////////////////////////////////////
  651. void CXConsole::DumpKeyBinds(IKeyBindDumpSink* pCallback)
  652. {
  653. for (ConsoleBindsMap::iterator it = m_mapBinds.begin(); it != m_mapBinds.end(); ++it)
  654. {
  655. pCallback->OnKeyBindFound(it->first.c_str(), it->second.c_str());
  656. }
  657. }
  658. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  659. const char* CXConsole::FindKeyBind(const char* sCmd) const
  660. {
  661. ConsoleBindsMap::const_iterator it = m_mapBinds.find(sCmd);
  662. if (it != m_mapBinds.end())
  663. {
  664. return it->second.c_str();
  665. }
  666. return 0;
  667. }
  668. //////////////////////////////////////////////////////////////////////////
  669. void CXConsole::DumpCVars(ICVarDumpSink* pCallback, unsigned int nFlagsFilter)
  670. {
  671. ConsoleVariablesMapItor It = m_mapVariables.begin();
  672. while (It != m_mapVariables.end())
  673. {
  674. if ((nFlagsFilter == 0) || ((nFlagsFilter != 0) && (It->second->GetFlags() & nFlagsFilter)))
  675. {
  676. pCallback->OnElementFound(It->second);
  677. }
  678. ++It;
  679. }
  680. }
  681. //////////////////////////////////////////////////////////////////////////
  682. ICVar* CXConsole::GetCVar(const char* sName)
  683. {
  684. assert(sName);
  685. if (con_debug)
  686. {
  687. // Log call stack on get cvar.
  688. CryLog("GetCVar(\"%s\") called", sName);
  689. m_pSystem->debug_LogCallStack();
  690. }
  691. // Fast map lookup for case-sensitive match.
  692. ConsoleVariablesMapItor it;
  693. it = m_mapVariables.find(sName);
  694. if (it != m_mapVariables.end())
  695. {
  696. return it->second;
  697. }
  698. /*
  699. if(!bCaseSensitive)
  700. {
  701. // Much slower but allows names with wrong case (use only where performance doesn't matter).
  702. for(it=m_mapVariables.begin(); it!=m_mapVariables.end(); ++it)
  703. {
  704. if(azstricmp(it->first,sName)==0)
  705. return it->second;
  706. }
  707. }
  708. test else
  709. {
  710. for(it=m_mapVariables.begin(); it!=m_mapVariables.end(); ++it)
  711. {
  712. if(azstricmp(it->first,sName)==0)
  713. {
  714. CryFatalError("Error: Wrong case for '%s','%s'",it->first,sName);
  715. }
  716. }
  717. }
  718. */
  719. return NULL; // haven't found this name
  720. }
  721. //////////////////////////////////////////////////////////////////////////
  722. char* CXConsole::GetVariable([[maybe_unused]] const char* szVarName, [[maybe_unused]] const char* szFileName, [[maybe_unused]] const char* def_val)
  723. {
  724. assert(m_pSystem);
  725. return 0;
  726. }
  727. //////////////////////////////////////////////////////////////////////////
  728. float CXConsole::GetVariable([[maybe_unused]] const char* szVarName, [[maybe_unused]] const char* szFileName, [[maybe_unused]] float def_val)
  729. {
  730. assert(m_pSystem);
  731. return 0;
  732. }
  733. //////////////////////////////////////////////////////////////////////////
  734. bool CXConsole::GetStatus()
  735. {
  736. return m_bConsoleActive;
  737. }
  738. //////////////////////////////////////////////////////////////////////////
  739. void CXConsole::Clear()
  740. {
  741. m_dqConsoleBuffer.clear();
  742. }
  743. //////////////////////////////////////////////////////////////////////////
  744. void CXConsole::Update()
  745. {
  746. if (!m_pSystem)
  747. {
  748. return;
  749. }
  750. if (m_bIsConsoleKeyPressed)
  751. {
  752. m_sInputBuffer.clear();
  753. m_nCursorPos = 0;
  754. m_bIsConsoleKeyPressed = false;
  755. }
  756. // Execute the deferred commands
  757. ExecuteDeferredCommands();
  758. }
  759. //////////////////////////////////////////////////////////////////////////////////////////////////////////////
  760. void CXConsole::OnConsoleCommand(const char* cmd)
  761. {
  762. ExecuteString(cmd, false);
  763. }
  764. //////////////////////////////////////////////////////////////////////////////////////////////////////////////
  765. const char* CXConsole::GetHistoryElement(const bool bUpOrDown)
  766. {
  767. if (bUpOrDown)
  768. {
  769. if (!m_dqHistory.empty())
  770. {
  771. if (m_nHistoryPos < (int)(m_dqHistory.size() - 1))
  772. {
  773. m_nHistoryPos++;
  774. m_sReturnString = m_dqHistory[m_nHistoryPos];
  775. return m_sReturnString.c_str();
  776. }
  777. }
  778. }
  779. else
  780. {
  781. if (m_nHistoryPos > 0)
  782. {
  783. m_nHistoryPos--;
  784. m_sReturnString = m_dqHistory[m_nHistoryPos];
  785. return m_sReturnString.c_str();
  786. }
  787. }
  788. return 0;
  789. }
  790. //////////////////////////////////////////////////////////////////////////
  791. bool CXConsole::GetLineNo(const int indwLineNo, char* outszBuffer, const int indwBufferSize) const
  792. {
  793. assert(outszBuffer);
  794. assert(indwBufferSize > 0);
  795. outszBuffer[0] = 0;
  796. ConsoleBuffer::const_reverse_iterator ritor = m_dqConsoleBuffer.rbegin();
  797. ritor += indwLineNo;
  798. if (indwLineNo >= (int)m_dqConsoleBuffer.size())
  799. {
  800. return false;
  801. }
  802. const char* buf = ritor->c_str();// GetBuf(k);
  803. if (*buf > 0 && *buf < 32)
  804. {
  805. buf++; // to jump over verbosity level character
  806. }
  807. azstrcpy(outszBuffer, indwBufferSize, buf);
  808. return true;
  809. }
  810. //////////////////////////////////////////////////////////////////////////
  811. int CXConsole::GetLineCount() const
  812. {
  813. return static_cast<int>(m_dqConsoleBuffer.size());
  814. }
  815. //////////////////////////////////////////////////////////////////////////
  816. void CXConsole::ScrollConsole()
  817. {
  818. }
  819. //////////////////////////////////////////////////////////////////////////
  820. bool CXConsole::AddCommand(const char* sCommand, ConsoleCommandFunc func, int nFlags, const char* sHelp)
  821. {
  822. AssertName(sCommand);
  823. if (m_mapCommands.find(sCommand) == m_mapCommands.end())
  824. {
  825. CConsoleCommand cmd;
  826. cmd.m_sName = sCommand;
  827. cmd.m_func = func;
  828. if (sHelp)
  829. {
  830. cmd.m_sHelp = sHelp;
  831. }
  832. cmd.m_nFlags = nFlags;
  833. m_mapCommands.insert(std::make_pair(cmd.m_sName, cmd));
  834. return true;
  835. }
  836. else
  837. {
  838. gEnv->pLog->LogError("[CVARS]: [DUPLICATE] CXConsole::AddCommand(): console command [%s] is already registered", sCommand);
  839. #if LOG_CVAR_INFRACTIONS_CALLSTACK
  840. gEnv->pSystem->debug_LogCallStack();
  841. #endif // LOG_CVAR_INFRACTIONS_CALLSTACK
  842. return false;
  843. }
  844. }
  845. //////////////////////////////////////////////////////////////////////////
  846. bool CXConsole::AddCommand(const char* sCommand, const char* sScriptFunc, int nFlags, const char* sHelp)
  847. {
  848. AssertName(sCommand);
  849. if (m_mapCommands.find(sCommand) == m_mapCommands.end())
  850. {
  851. CConsoleCommand cmd;
  852. cmd.m_sName = sCommand;
  853. cmd.m_sCommand = sScriptFunc;
  854. if (sHelp)
  855. {
  856. cmd.m_sHelp = sHelp;
  857. }
  858. cmd.m_nFlags = nFlags;
  859. m_mapCommands.insert(std::make_pair(cmd.m_sName, cmd));
  860. return true;
  861. }
  862. else
  863. {
  864. gEnv->pLog->LogError("[CVARS]: [DUPLICATE] CXConsole::AddCommand(): script command [%s] is already registered", sCommand);
  865. #if LOG_CVAR_INFRACTIONS_CALLSTACK
  866. gEnv->pSystem->debug_LogCallStack();
  867. #endif // LOG_CVAR_INFRACTIONS_CALLSTACK
  868. return false;
  869. }
  870. }
  871. //////////////////////////////////////////////////////////////////////////
  872. void CXConsole::RemoveCommand(const char* sName)
  873. {
  874. ConsoleCommandsMap::iterator ite = m_mapCommands.find(sName);
  875. if (ite != m_mapCommands.end())
  876. {
  877. m_mapCommands.erase(ite);
  878. }
  879. }
  880. //////////////////////////////////////////////////////////////////////////
  881. inline bool hasprefix(const char* s, const char* prefix)
  882. {
  883. while (*prefix)
  884. {
  885. if (*prefix++ != *s++)
  886. {
  887. return false;
  888. }
  889. }
  890. return true;
  891. }
  892. //////////////////////////////////////////////////////////////////////////
  893. const char* CXConsole::GetFlagsString(const uint32 dwFlags)
  894. {
  895. static char sFlags[256];
  896. // hiding this makes it a bit more difficult for cheaters
  897. // if(dwFlags&VF_CHEAT) azstrcat( sFlags,"CHEAT, ");
  898. azstrcpy(sFlags, AZ_ARRAY_SIZE(sFlags), "");
  899. if (dwFlags & VF_READONLY)
  900. {
  901. azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "READONLY, ");
  902. }
  903. if (dwFlags & VF_DEPRECATED)
  904. {
  905. azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "DEPRECATED, ");
  906. }
  907. if (dwFlags & VF_DUMPTODISK)
  908. {
  909. azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "DUMPTODISK, ");
  910. }
  911. if (dwFlags & VF_REQUIRE_LEVEL_RELOAD)
  912. {
  913. azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "REQUIRE_LEVEL_RELOAD, ");
  914. }
  915. if (dwFlags & VF_REQUIRE_APP_RESTART)
  916. {
  917. azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "REQUIRE_APP_RESTART, ");
  918. }
  919. if (dwFlags & VF_RESTRICTEDMODE)
  920. {
  921. azstrcat(sFlags, AZ_ARRAY_SIZE(sFlags), "RESTRICTEDMODE, ");
  922. }
  923. if (sFlags[0] != 0)
  924. {
  925. sFlags[strlen(sFlags) - 2] = 0; // remove ending ", "
  926. }
  927. return sFlags;
  928. }
  929. #if ALLOW_AUDIT_CVARS
  930. void CXConsole::AuditCVars(IConsoleCmdArgs* pArg)
  931. {
  932. int numArgs = pArg->GetArgCount();
  933. int cheatMask = VF_CHEAT | VF_CHEAT_NOCHECK | VF_CHEAT_ALWAYS_CHECK;
  934. int constMask = VF_CONST_CVAR;
  935. int readOnlyMask = VF_READONLY;
  936. int devOnlyMask = VF_DEV_ONLY;
  937. int dediOnlyMask = VF_DEDI_ONLY;
  938. int excludeMask = cheatMask | constMask | readOnlyMask | devOnlyMask | dediOnlyMask;
  939. if (numArgs > 1)
  940. {
  941. while (numArgs > 1)
  942. {
  943. const char* arg = pArg->GetArg(numArgs - 1);
  944. if (azstricmp(arg, "cheat") == 0)
  945. {
  946. excludeMask &= ~cheatMask;
  947. }
  948. if (azstricmp(arg, "const") == 0)
  949. {
  950. excludeMask &= ~constMask;
  951. }
  952. if (azstricmp(arg, "readonly") == 0)
  953. {
  954. excludeMask &= ~readOnlyMask;
  955. }
  956. if (azstricmp(arg, "dev") == 0)
  957. {
  958. excludeMask &= ~devOnlyMask;
  959. }
  960. if (azstricmp(arg, "dedi") == 0)
  961. {
  962. excludeMask &= ~dediOnlyMask;
  963. }
  964. --numArgs;
  965. }
  966. }
  967. int commandCount = 0;
  968. int cvarCount = 0;
  969. CryLogAlways("[CVARS]: [BEGIN AUDIT]");
  970. for (ConsoleCommandsMapItor it = m_mapCommands.begin(); it != m_mapCommands.end(); ++it)
  971. {
  972. CConsoleCommand& command = it->second;
  973. int cheatFlags = (command.m_nFlags & cheatMask);
  974. int devOnlyFlags = (command.m_nFlags & devOnlyMask);
  975. int dediOnlyFlags = (command.m_nFlags & dediOnlyMask);
  976. bool shouldLog = ((cheatFlags | devOnlyFlags | dediOnlyFlags) == 0) || (((cheatFlags | devOnlyFlags | dediOnlyFlags) & ~excludeMask) != 0);
  977. if (shouldLog)
  978. {
  979. CryLogAlways("[CVARS]: [COMMAND] %s%s%s%s%s",
  980. command.m_sName.c_str(),
  981. (cheatFlags != 0) ? " [VF_CHEAT]" : "",
  982. (devOnlyFlags != 0) ? " [VF_DEV_ONLY]" : "",
  983. (dediOnlyFlags != 0) ? " [VF_DEDI_ONLY]" : "",
  984. ""
  985. );
  986. ++commandCount;
  987. }
  988. }
  989. for (ConsoleVariablesMapItor it = m_mapVariables.begin(); it != m_mapVariables.end(); ++it)
  990. {
  991. ICVar* pVariable = it->second;
  992. int flags = pVariable->GetFlags();
  993. int cheatFlags = (flags & cheatMask);
  994. int constFlags = (flags & constMask);
  995. int readOnlyFlags = (flags & readOnlyMask);
  996. int devOnlyFlags = (flags & devOnlyMask);
  997. int dediOnlyFlags = (flags & dediOnlyMask);
  998. bool shouldLog = ((cheatFlags | constFlags | readOnlyFlags | devOnlyFlags | dediOnlyFlags) == 0) || (((cheatFlags | constFlags | readOnlyFlags | devOnlyFlags | dediOnlyFlags) & ~excludeMask) != 0);
  999. if (shouldLog)
  1000. {
  1001. CryLogAlways("[CVARS]: [VARIABLE] %s%s%s%s%s%s%s",
  1002. pVariable->GetName(),
  1003. (cheatFlags != 0) ? " [VF_CHEAT]" : "",
  1004. (constFlags != 0) ? " [VF_CONST_CVAR]" : "",
  1005. (readOnlyFlags != 0) ? " [VF_READONLY]" : "",
  1006. (devOnlyFlags != 0) ? " [VF_DEV_ONLY]" : "",
  1007. (dediOnlyFlags != 0) ? " [VF_DEDI_ONLY]" : "",
  1008. ""
  1009. );
  1010. ++cvarCount;
  1011. }
  1012. }
  1013. CryLogAlways("[CVARS]: [END AUDIT] (commands %d/%" PRISIZE_T "; variables %d/%" PRISIZE_T ")", commandCount, m_mapCommands.size(), cvarCount, m_mapVariables.size());
  1014. }
  1015. #endif // ALLOW_AUDIT_CVARS
  1016. //////////////////////////////////////////////////////////////////////////
  1017. #ifndef _RELEASE
  1018. void CXConsole::DumpCommandsVarsTxt(const char* prefix)
  1019. {
  1020. FILE* f0 = nullptr;
  1021. azfopen(&f0, "consolecommandsandvars.txt", "w");
  1022. if (!f0)
  1023. {
  1024. return;
  1025. }
  1026. ConsoleCommandsMapItor itrCmd, itrCmdEnd = m_mapCommands.end();
  1027. ConsoleVariablesMapItor itrVar, itrVarEnd = m_mapVariables.end();
  1028. fprintf(f0, " CHEAT: stays in the default value if cheats are not disabled\n");
  1029. fprintf(f0, " REQUIRE_NET_SYNC: cannot be changed on client and when connecting it's sent to the client\n");
  1030. fprintf(f0, " SAVEGAME: stored when saving a savegame\n");
  1031. fprintf(f0, " READONLY: can not be changed by the user\n");
  1032. fprintf(f0, "-------------------------\n");
  1033. fprintf(f0, "\n");
  1034. for (itrCmd = m_mapCommands.begin(); itrCmd != itrCmdEnd; ++itrCmd)
  1035. {
  1036. CConsoleCommand& cmd = itrCmd->second;
  1037. if (hasprefix(cmd.m_sName.c_str(), prefix))
  1038. {
  1039. const char* sFlags = GetFlagsString(cmd.m_nFlags);
  1040. fprintf(f0, "Command: %s %s\nscript: %s\nhelp: %s\n\n", cmd.m_sName.c_str(), sFlags, cmd.m_sCommand.c_str(), cmd.m_sHelp.c_str());
  1041. }
  1042. }
  1043. for (itrVar = m_mapVariables.begin(); itrVar != itrVarEnd; ++itrVar)
  1044. {
  1045. ICVar* var = itrVar->second;
  1046. const char* types[] = { "?", "int", "float", "string", "?" };
  1047. var->GetRealIVal(); // assert inside checks consistency for all cvars
  1048. if (hasprefix(var->GetName(), prefix))
  1049. {
  1050. const char* sFlags = GetFlagsString(var->GetFlags());
  1051. fprintf(f0, "variable: %s %s\ntype: %s\ncurrent: %s\nhelp: %s\n\n", var->GetName(), sFlags, types[var->GetType()], var->GetString(), var->GetHelp());
  1052. }
  1053. }
  1054. fclose(f0);
  1055. ConsoleLogInputResponse("successfully wrote consolecommandsandvars.txt");
  1056. }
  1057. void CXConsole::DumpVarsTxt(const bool includeCheat)
  1058. {
  1059. FILE* f0 = nullptr;
  1060. azfopen(&f0, "consolevars.txt", "w");
  1061. if (!f0)
  1062. {
  1063. return;
  1064. }
  1065. ConsoleVariablesMapItor itrVar, itrVarEnd = m_mapVariables.end();
  1066. fprintf(f0, " REQUIRE_NET_SYNC: cannot be changed on client and when connecting it's sent to the client\n");
  1067. fprintf(f0, " SAVEGAME: stored when saving a savegame\n");
  1068. fprintf(f0, " READONLY: can not be changed by the user\n");
  1069. fprintf(f0, "-------------------------\n");
  1070. fprintf(f0, "\n");
  1071. for (itrVar = m_mapVariables.begin(); itrVar != itrVarEnd; ++itrVar)
  1072. {
  1073. ICVar* var = itrVar->second;
  1074. const char* types[] = { "?", "int", "float", "string", "?" };
  1075. var->GetRealIVal(); // assert inside checks consistency for all cvars
  1076. const int flags = var->GetFlags();
  1077. if ((includeCheat == true) || (flags & VF_CHEAT) == 0)
  1078. {
  1079. const char* sFlags = GetFlagsString(flags);
  1080. fprintf(f0, "variable: %s %s\ntype: %s\ncurrent: %s\nhelp: %s\n\n", var->GetName(), sFlags, types[var->GetType()], var->GetString(), var->GetHelp());
  1081. }
  1082. }
  1083. fclose(f0);
  1084. ConsoleLogInputResponse("successfully wrote consolevars.txt");
  1085. }
  1086. #endif
  1087. //////////////////////////////////////////////////////////////////////////
  1088. void CXConsole::DisplayHelp(const char* help, const char* name)
  1089. {
  1090. if (help == 0 || *help == 0)
  1091. {
  1092. ConsoleLogInputResponse("No help available for $3%s", name);
  1093. }
  1094. else
  1095. {
  1096. auto PrintHelpLine = [this](AZStd::string_view line)
  1097. {
  1098. ConsoleLogInputResponse(" $3%.*s", AZ_STRING_ARG(line));
  1099. };
  1100. AZ::StringFunc::TokenizeVisitor(help, PrintHelpLine, '\n');
  1101. }
  1102. }
  1103. void CXConsole::ExecuteString(const char* command, const bool bSilentMode, const bool bDeferExecution)
  1104. {
  1105. if (!m_deferredExecution && !bDeferExecution)
  1106. {
  1107. // This is a regular mode
  1108. ExecuteStringInternal(command, false, bSilentMode); // not from console
  1109. return;
  1110. }
  1111. // Store the string commands into a list and defer the execution for later.
  1112. // The commands will be processed in CXConsole::Update()
  1113. AZStd::string str(command);
  1114. AZ::StringFunc::TrimWhiteSpace(str, true, false);
  1115. // Unroll the exec command
  1116. bool unroll = (0 == AZ::StringFunc::Find(str, "exec", 0, false, false));
  1117. if (unroll)
  1118. {
  1119. bool oldDeferredExecution = m_deferredExecution;
  1120. // Make sure that the unrolled commands are processed with deferred mode on
  1121. m_deferredExecution = true;
  1122. ExecuteStringInternal(str.c_str(), false, bSilentMode);
  1123. // Restore to the previous setting
  1124. m_deferredExecution = oldDeferredExecution;
  1125. }
  1126. else
  1127. {
  1128. m_deferredCommands.push_back(SDeferredCommand(str.c_str(), bSilentMode));
  1129. }
  1130. }
  1131. // This method is used by the ConsoleRequestBus to allow executing of console commands
  1132. // This can be used from anywhere in code or via script since the bus is relected to the behavior context
  1133. void CXConsole::ExecuteConsoleCommand(const char* command)
  1134. {
  1135. ExecuteString(command, true, true);
  1136. }
  1137. void CXConsole::ResetCVarsToDefaults()
  1138. {
  1139. ConsoleVariablesMapItor It = m_mapVariables.begin();
  1140. while (It != m_mapVariables.end())
  1141. {
  1142. It->second->Reset();
  1143. ++It;
  1144. }
  1145. }
  1146. void CXConsole::SplitCommands(const char* line, std::list<AZStd::string>& split)
  1147. {
  1148. const char* start = line;
  1149. AZStd::string working;
  1150. while (true)
  1151. {
  1152. char ch = *line++;
  1153. switch (ch)
  1154. {
  1155. case '\'':
  1156. case '\"':
  1157. while ((*line++ != ch) && *line)
  1158. {
  1159. ;
  1160. }
  1161. break;
  1162. case '\n':
  1163. case '\r':
  1164. case ';':
  1165. case '\0':
  1166. {
  1167. working.assign(start, line - 1);
  1168. AZ::StringFunc::TrimWhiteSpace(working, true, true);
  1169. if (!working.empty())
  1170. {
  1171. split.push_back(working);
  1172. }
  1173. start = line;
  1174. if (ch == '\0')
  1175. {
  1176. return;
  1177. }
  1178. }
  1179. break;
  1180. }
  1181. }
  1182. }
  1183. //////////////////////////////////////////////////////////////////////////
  1184. void CXConsole::ExecuteStringInternal(const char* command, const bool bFromConsole, const bool bSilentMode)
  1185. {
  1186. AzFramework::ConsoleNotificationBus::Broadcast(&AzFramework::ConsoleNotificationBus::Events::OnConsoleCommandExecuted, command);
  1187. assert(command);
  1188. assert(command[0] != '\\'); // caller should remove leading "\\"
  1189. ///////////////////////////
  1190. //Execute as string
  1191. if (command[0] == '#' || command[0] == '@')
  1192. {
  1193. if (!con_restricted || !bFromConsole) // in restricted mode we allow only VF_RESTRICTEDMODE CVars&CCmd
  1194. {
  1195. AddLine(command);
  1196. if (m_pSystem->IsDevMode())
  1197. {
  1198. m_bDrawCursor = 0;
  1199. }
  1200. else
  1201. {
  1202. // Warning.
  1203. // No Cheat warnings. ConsoleWarning("Console execution is cheat protected");
  1204. }
  1205. return;
  1206. }
  1207. }
  1208. ConsoleCommandsMapItor itrCmd;
  1209. ConsoleVariablesMapItor itrVar;
  1210. std::list<AZStd::string> lineCommands;
  1211. SplitCommands(command, lineCommands);
  1212. AZStd::string sTemp;
  1213. AZStd::string sCommand, sLineCommand;
  1214. while (!lineCommands.empty())
  1215. {
  1216. AZStd::string::size_type nPos;
  1217. {
  1218. sTemp = lineCommands.front();
  1219. sCommand = lineCommands.front();
  1220. sLineCommand = sCommand;
  1221. lineCommands.pop_front();
  1222. if (!bSilentMode)
  1223. {
  1224. if (GetStatus())
  1225. {
  1226. AddLine(sTemp.c_str());
  1227. }
  1228. }
  1229. nPos = sTemp.find_first_of('=');
  1230. if (nPos != AZStd::string::npos)
  1231. {
  1232. sCommand = sTemp.substr(0, nPos);
  1233. }
  1234. else if ((nPos = sTemp.find_first_of(' ')) != AZStd::string::npos)
  1235. {
  1236. sCommand = sTemp.substr(0, nPos);
  1237. }
  1238. else
  1239. {
  1240. sCommand = sTemp;
  1241. }
  1242. AZ::StringFunc::TrimWhiteSpace(sCommand, true, true);
  1243. //////////////////////////////////////////
  1244. // Search for CVars
  1245. if (sCommand.length() > 1 && sCommand[0] == '?')
  1246. {
  1247. sTemp = sCommand.substr(1);
  1248. FindVar(sTemp.c_str());
  1249. continue;
  1250. }
  1251. }
  1252. //////////////////////////////////////////
  1253. //Check if is a command
  1254. itrCmd = m_mapCommands.find(sCommand);
  1255. if (itrCmd != m_mapCommands.end())
  1256. {
  1257. if (((itrCmd->second).m_nFlags & VF_RESTRICTEDMODE) || !con_restricted || !bFromConsole) // in restricted mode we allow only VF_RESTRICTEDMODE CVars&CCmd
  1258. {
  1259. if (itrCmd->second.m_nFlags & VF_BLOCKFRAME)
  1260. {
  1261. m_blockCounter++;
  1262. }
  1263. {
  1264. sTemp = sLineCommand;
  1265. }
  1266. ExecuteCommand((itrCmd->second), sTemp);
  1267. continue;
  1268. }
  1269. }
  1270. //////////////////////////////////////////
  1271. //Check if is a variable
  1272. itrVar = m_mapVariables.find(sCommand.c_str());
  1273. if (itrVar != m_mapVariables.end())
  1274. {
  1275. ICVar* pCVar = itrVar->second;
  1276. if ((pCVar->GetFlags() & VF_RESTRICTEDMODE) || !con_restricted || !bFromConsole) // in restricted mode we allow only VF_RESTRICTEDMODE CVars&CCmd
  1277. {
  1278. if (pCVar->GetFlags() & VF_BLOCKFRAME)
  1279. {
  1280. m_blockCounter++;
  1281. }
  1282. if (nPos != AZStd::string::npos)
  1283. {
  1284. sTemp = sTemp.substr(nPos + 1); // remove the command from sTemp
  1285. AZ::StringFunc::StripEnds(sTemp, " \t\r\n\"\'");
  1286. if (sTemp == "?")
  1287. {
  1288. ICVar* v = itrVar->second;
  1289. DisplayHelp(v->GetHelp(), sCommand.c_str());
  1290. return;
  1291. }
  1292. if (!sTemp.empty() || (pCVar->GetType() == CVAR_STRING))
  1293. {
  1294. pCVar->Set(sTemp.c_str());
  1295. }
  1296. }
  1297. // the following line calls AddLine() indirectly
  1298. if (!bSilentMode)
  1299. {
  1300. DisplayVarValue(pCVar);
  1301. }
  1302. //ConsoleLogInputResponse("%s=%s",pCVar->GetName(),pCVar->GetString());
  1303. continue;
  1304. }
  1305. }
  1306. if (!bSilentMode)
  1307. {
  1308. ConsoleWarning("Unknown command: %s", sCommand.c_str());
  1309. }
  1310. }
  1311. }
  1312. //////////////////////////////////////////////////////////////////////////
  1313. void CXConsole::ExecuteDeferredCommands()
  1314. {
  1315. TDeferredCommandList::iterator it;
  1316. if (m_waitFrames)
  1317. {
  1318. --m_waitFrames;
  1319. return;
  1320. }
  1321. if (m_waitSeconds.GetValue())
  1322. {
  1323. const AZ::TimeMs elaspsedTimeMs = AZ::GetRealElapsedTimeMs();
  1324. const double elaspedTimeSec = AZ::TimeMsToSecondsDouble(elaspsedTimeMs);
  1325. if (m_waitSeconds > CTimeValue(elaspedTimeSec))
  1326. {
  1327. return;
  1328. }
  1329. // Help to avoid overflow problems
  1330. m_waitSeconds.SetValue(0);
  1331. }
  1332. const int blockCounter = m_blockCounter;
  1333. // Signal the console that we executing a deferred command
  1334. //m_deferredExecution = true;
  1335. while (!m_deferredCommands.empty())
  1336. {
  1337. it = m_deferredCommands.begin();
  1338. ExecuteStringInternal(it->command.c_str(), false, it->silentMode);
  1339. m_deferredCommands.pop_front();
  1340. // A blocker command was executed
  1341. if (m_blockCounter != blockCounter)
  1342. {
  1343. break;
  1344. }
  1345. }
  1346. }
  1347. //////////////////////////////////////////////////////////////////////////
  1348. void CXConsole::ExecuteCommand(CConsoleCommand& cmd, AZStd::string& str, bool bIgnoreDevMode)
  1349. {
  1350. CryLog ("[CONSOLE] Executing console command '%s'", str.c_str());
  1351. INDENT_LOG_DURING_SCOPE();
  1352. std::vector<AZStd::string> args;
  1353. size_t t;
  1354. {
  1355. t = 1;
  1356. const char* start = str.c_str();
  1357. const char* commandLine = start;
  1358. while (char ch = *commandLine++)
  1359. {
  1360. switch (ch)
  1361. {
  1362. case '\'':
  1363. case '\"':
  1364. {
  1365. while ((*commandLine++ != ch) && *commandLine)
  1366. {
  1367. ;
  1368. }
  1369. args.push_back(AZStd::string(start + 1, commandLine - 1));
  1370. start = commandLine;
  1371. break;
  1372. }
  1373. case ' ':
  1374. start = commandLine;
  1375. break;
  1376. default:
  1377. {
  1378. if ((*commandLine == ' ') || !*commandLine)
  1379. {
  1380. args.push_back(AZStd::string(start, commandLine));
  1381. start = commandLine + 1;
  1382. }
  1383. }
  1384. break;
  1385. }
  1386. }
  1387. if (args.size() >= 2 && args[1] == "?")
  1388. {
  1389. DisplayHelp(cmd.m_sHelp.c_str(), cmd.m_sName.c_str());
  1390. return;
  1391. }
  1392. if (((cmd.m_nFlags & (VF_CHEAT | VF_CHEAT_NOCHECK | VF_CHEAT_ALWAYS_CHECK)) != 0) && !(gEnv->IsEditor()))
  1393. {
  1394. #if LOG_CVAR_INFRACTIONS
  1395. gEnv->pLog->LogError("[CVARS]: [EXECUTE] command %s is marked [VF_CHEAT]", cmd.m_sName.c_str());
  1396. #if LOG_CVAR_INFRACTIONS_CALLSTACK
  1397. gEnv->pSystem->debug_LogCallStack();
  1398. #endif // LOG_CVAR_INFRACTIONS_CALLSTACK
  1399. #endif // LOG_CVAR_INFRACTIONS
  1400. if (!(gEnv->IsEditor()) && !(m_pSystem->IsDevMode()) && !bIgnoreDevMode)
  1401. {
  1402. return;
  1403. }
  1404. }
  1405. }
  1406. if (cmd.m_func)
  1407. {
  1408. // This is function command, execute it with a list of parameters.
  1409. CConsoleCommandArgs cmdArgs(str, args);
  1410. cmd.m_func(&cmdArgs);
  1411. return;
  1412. }
  1413. AZStd::string buf;
  1414. {
  1415. // only do this for commands with script implementation
  1416. for (;; )
  1417. {
  1418. t = str.find_first_of("\\", t);
  1419. if (t == AZStd::string::npos)
  1420. {
  1421. break;
  1422. }
  1423. str.replace(t, 1, "\\\\", 2);
  1424. t += 2;
  1425. }
  1426. for (t = 1;; )
  1427. {
  1428. t = str.find_first_of("\"", t);
  1429. if (t == AZStd::string::npos)
  1430. {
  1431. break;
  1432. }
  1433. str.replace(t, 1, "\\\"", 2);
  1434. t += 2;
  1435. }
  1436. buf = cmd.m_sCommand;
  1437. size_t pp = buf.find("%%");
  1438. if (pp != AZStd::string::npos)
  1439. {
  1440. AZStd::string list = "";
  1441. for (unsigned int i = 1; i < args.size(); i++)
  1442. {
  1443. list += "\"" + args[i] + "\"";
  1444. if (i < args.size() - 1)
  1445. {
  1446. list += ",";
  1447. }
  1448. }
  1449. buf.replace(pp, 2, list);
  1450. }
  1451. else if ((pp = buf.find("%line")) != AZStd::string::npos)
  1452. {
  1453. AZStd::string tmp = "\"" + str.substr(str.find(" ") + 1) + "\"";
  1454. if (args.size() > 1)
  1455. {
  1456. buf.replace(pp, 5, tmp);
  1457. }
  1458. else
  1459. {
  1460. buf.replace(pp, 5, "");
  1461. }
  1462. }
  1463. else
  1464. {
  1465. for (unsigned int i = 1; i <= args.size(); i++)
  1466. {
  1467. char pat[10];
  1468. azsnprintf(pat, AZ_ARRAY_SIZE(pat), "%%%d", i);
  1469. size_t pos = buf.find(pat);
  1470. if (pos == AZStd::string::npos)
  1471. {
  1472. if (i != args.size())
  1473. {
  1474. ConsoleWarning("Too many arguments for: %s", cmd.m_sName.c_str());
  1475. return;
  1476. }
  1477. }
  1478. else
  1479. {
  1480. if (i == args.size())
  1481. {
  1482. ConsoleWarning("Not enough arguments for: %s", cmd.m_sName.c_str());
  1483. return;
  1484. }
  1485. AZStd::string arg = "\"" + args[i] + "\"";
  1486. buf.replace(pos, strlen(pat), arg);
  1487. }
  1488. }
  1489. }
  1490. }
  1491. m_bDrawCursor = 0;
  1492. }
  1493. //////////////////////////////////////////////////////////////////////////
  1494. void CXConsole::Exit(const char* szExitComments, ...)
  1495. {
  1496. char sResultMessageText[1024] = "";
  1497. if (szExitComments)
  1498. {
  1499. // make result string
  1500. va_list arglist;
  1501. va_start(arglist, szExitComments);
  1502. vsprintf_s(sResultMessageText, szExitComments, arglist);
  1503. va_end(arglist);
  1504. }
  1505. else
  1506. {
  1507. azstrcpy(sResultMessageText, AZ_ARRAY_SIZE(sResultMessageText), "No comments from application");
  1508. }
  1509. CryFatalError("%s", sResultMessageText);
  1510. }
  1511. //////////////////////////////////////////////////////////////////////////
  1512. void CXConsole::RegisterAutoComplete(const char* sVarOrCommand, IConsoleArgumentAutoComplete* pArgAutoComplete)
  1513. {
  1514. m_mapArgumentAutoComplete[sVarOrCommand] = pArgAutoComplete;
  1515. }
  1516. //////////////////////////////////////////////////////////////////////////
  1517. void CXConsole::UnRegisterAutoComplete(const char* sVarOrCommand)
  1518. {
  1519. ArgumentAutoCompleteMap::iterator it;
  1520. it = m_mapArgumentAutoComplete.find(sVarOrCommand);
  1521. if (it != m_mapArgumentAutoComplete.end())
  1522. {
  1523. m_mapArgumentAutoComplete.erase(it);
  1524. }
  1525. }
  1526. //////////////////////////////////////////////////////////////////////////
  1527. void CXConsole::ResetAutoCompletion()
  1528. {
  1529. m_nTabCount = 0;
  1530. m_sPrevTab = "";
  1531. }
  1532. //////////////////////////////////////////////////////////////////////////
  1533. const char* CXConsole::ProcessCompletion(const char* szInputBuffer)
  1534. {
  1535. m_sInputBuffer = szInputBuffer;
  1536. int offset = (szInputBuffer[0] == '\\' ? 1 : 0); // legacy support
  1537. if ((m_sPrevTab.size() > strlen(szInputBuffer + offset)) || _strnicmp(m_sPrevTab.c_str(), (szInputBuffer + offset), m_sPrevTab.size()))
  1538. {
  1539. m_nTabCount = 0;
  1540. m_sPrevTab = "";
  1541. }
  1542. if (m_sInputBuffer.empty())
  1543. {
  1544. return (char*)m_sInputBuffer.c_str();
  1545. }
  1546. int nMatch = 0;
  1547. ConsoleCommandsMapItor itrCmds;
  1548. ConsoleVariablesMapItor itrVars;
  1549. bool showlist = !m_nTabCount && m_sPrevTab == "";
  1550. if (m_nTabCount == 0)
  1551. {
  1552. if (m_sInputBuffer.size() > 0)
  1553. {
  1554. if (m_sInputBuffer[0] == '\\')
  1555. {
  1556. m_sPrevTab = &m_sInputBuffer.c_str()[1]; // legacy support
  1557. }
  1558. else
  1559. {
  1560. m_sPrevTab = m_sInputBuffer;
  1561. }
  1562. }
  1563. else
  1564. {
  1565. m_sPrevTab = "";
  1566. }
  1567. }
  1568. //try to search in command list
  1569. bool bArgumentAutoComplete = false;
  1570. std::vector<AZStd::string> matches;
  1571. if (m_sPrevTab.find(' ') != AZStd::string::npos)
  1572. {
  1573. bool bProcessAutoCompl = true;
  1574. // Find command.
  1575. AZStd::string sVar = m_sPrevTab.substr(0, m_sPrevTab.find(' '));
  1576. ICVar* pCVar = GetCVar(sVar.c_str());
  1577. if (pCVar)
  1578. {
  1579. if (!(pCVar->GetFlags() & VF_RESTRICTEDMODE) && con_restricted) // in restricted mode we allow only VF_RESTRICTEDMODE CVars&CCmd
  1580. {
  1581. bProcessAutoCompl = false;
  1582. }
  1583. }
  1584. ConsoleCommandsMap::iterator it = m_mapCommands.find(sVar);
  1585. if (it != m_mapCommands.end())
  1586. {
  1587. CConsoleCommand& ccmd = it->second;
  1588. if (!(ccmd.m_nFlags & VF_RESTRICTEDMODE) && con_restricted) // in restricted mode we allow only VF_RESTRICTEDMODE CVars&CCmd
  1589. {
  1590. bProcessAutoCompl = false;
  1591. }
  1592. }
  1593. if (bProcessAutoCompl)
  1594. {
  1595. IConsoleArgumentAutoComplete* pArgumentAutoComplete = stl::find_in_map(m_mapArgumentAutoComplete, sVar, 0);
  1596. if (pArgumentAutoComplete)
  1597. {
  1598. int nMatches = pArgumentAutoComplete->GetCount();
  1599. for (int i = 0; i < nMatches; i++)
  1600. {
  1601. AZStd::string cmd = AZStd::string(sVar) + " " + pArgumentAutoComplete->GetValue(i);
  1602. if (_strnicmp(m_sPrevTab.c_str(), cmd.c_str(), m_sPrevTab.length()) == 0)
  1603. {
  1604. {
  1605. bArgumentAutoComplete = true;
  1606. matches.push_back(cmd);
  1607. }
  1608. }
  1609. }
  1610. }
  1611. }
  1612. }
  1613. if (!bArgumentAutoComplete)
  1614. {
  1615. itrCmds = m_mapCommands.begin();
  1616. while (itrCmds != m_mapCommands.end())
  1617. {
  1618. CConsoleCommand& cmd = itrCmds->second;
  1619. if ((cmd.m_nFlags & VF_RESTRICTEDMODE) || !con_restricted) // in restricted mode we allow only VF_RESTRICTEDMODE CVars&CCmd
  1620. {
  1621. if (_strnicmp(m_sPrevTab.c_str(), itrCmds->first.c_str(), m_sPrevTab.length()) == 0)
  1622. {
  1623. {
  1624. matches.push_back((char* const)itrCmds->first.c_str());
  1625. }
  1626. }
  1627. }
  1628. ++itrCmds;
  1629. }
  1630. // try to search in console variables
  1631. itrVars = m_mapVariables.begin();
  1632. while (itrVars != m_mapVariables.end())
  1633. {
  1634. ICVar* pVar = itrVars->second;
  1635. if ((pVar->GetFlags() & VF_RESTRICTEDMODE) || !con_restricted) // in restricted mode we allow only VF_RESTRICTEDMODE CVars&CCmd
  1636. {//if(itrVars->first.compare(0,m_sPrevTab.length(),m_sPrevTab)==0)
  1637. if (_strnicmp(m_sPrevTab.c_str(), itrVars->first, m_sPrevTab.length()) == 0)
  1638. {
  1639. {
  1640. matches.push_back((char* const)itrVars->first);
  1641. }
  1642. }
  1643. }
  1644. ++itrVars;
  1645. }
  1646. }
  1647. if (!matches.empty())
  1648. {
  1649. std::sort(matches.begin(), matches.end()); // to sort commands with variables
  1650. }
  1651. if (showlist && !matches.empty())
  1652. {
  1653. ConsoleLogInput(" "); // empty line before auto completion
  1654. for (std::vector<AZStd::string>::iterator i = matches.begin(); i != matches.end(); ++i)
  1655. {
  1656. // List matching variables
  1657. const char* sVar = i->c_str();
  1658. ICVar* pVar = GetCVar(sVar);
  1659. if (pVar)
  1660. {
  1661. DisplayVarValue(pVar);
  1662. }
  1663. else
  1664. {
  1665. ConsoleLogInputResponse(" $3%s $6(Command)", sVar);
  1666. }
  1667. }
  1668. }
  1669. for (std::vector<AZStd::string>::iterator i = matches.begin(); i != matches.end(); ++i)
  1670. {
  1671. if (m_nTabCount <= nMatch)
  1672. {
  1673. m_sInputBuffer = *i;
  1674. m_sInputBuffer += " ";
  1675. m_nTabCount = nMatch + 1;
  1676. return (char*)m_sInputBuffer.c_str();
  1677. }
  1678. nMatch++;
  1679. }
  1680. if (m_nTabCount > 0)
  1681. {
  1682. m_nTabCount = 0;
  1683. m_sInputBuffer = m_sPrevTab;
  1684. m_sInputBuffer = ProcessCompletion(m_sInputBuffer.c_str());
  1685. }
  1686. return (char*)m_sInputBuffer.c_str();
  1687. }
  1688. //////////////////////////////////////////////////////////////////////////
  1689. void CXConsole::DisplayVarValue(ICVar* pVar)
  1690. {
  1691. if (!pVar)
  1692. {
  1693. return;
  1694. }
  1695. const char* sFlagsString = GetFlagsString(pVar->GetFlags());
  1696. AZStd::string sValue = (pVar->GetFlags() & VF_INVISIBLE) ? "" : pVar->GetString();
  1697. AZStd::string sVar = pVar->GetName();
  1698. char szRealState[40] = "";
  1699. if (pVar->GetType() == CVAR_INT)
  1700. {
  1701. int iRealState = pVar->GetRealIVal();
  1702. if (iRealState != pVar->GetIVal())
  1703. {
  1704. if (iRealState == -1)
  1705. {
  1706. azstrcpy(szRealState, AZ_ARRAY_SIZE(szRealState), " RealState=Custom");
  1707. }
  1708. else
  1709. {
  1710. sprintf_s(szRealState, " RealState=%d", iRealState);
  1711. }
  1712. }
  1713. }
  1714. if (pVar->GetFlags() & VF_BITFIELD)
  1715. {
  1716. uint64 val64 = pVar->GetI64Val();
  1717. uint64 alphaBits = val64 & ~63LL;
  1718. uint32 nonAlphaBits = val64 & 63;
  1719. if (alphaBits != 0)
  1720. {
  1721. // the bottom 6 bits can't be set by char entry, so show them separately
  1722. char alphaChars[65]; // 1 char per bit + '\0'
  1723. BitsAlpha64(alphaBits, alphaChars);
  1724. sValue += " (";
  1725. if (nonAlphaBits != 0)
  1726. {
  1727. char nonAlphaChars[3] = { 0 }; // 1..63 + '\0'
  1728. azitoa(nonAlphaBits, nonAlphaChars, AZ_ARRAY_SIZE(nonAlphaChars), 10);
  1729. sValue += nonAlphaChars;
  1730. sValue += ", ";
  1731. }
  1732. sValue += alphaChars;
  1733. sValue += ")";
  1734. }
  1735. }
  1736. if (gEnv->IsEditor())
  1737. {
  1738. ConsoleLogInputResponse("%s=%s [ %s ]%s", sVar.c_str(), sValue.c_str(), sFlagsString, szRealState);
  1739. }
  1740. else
  1741. {
  1742. ConsoleLogInputResponse(" $3%s = $6%s $5[%s]$4%s", sVar.c_str(), sValue.c_str(), sFlagsString, szRealState);
  1743. }
  1744. }
  1745. //////////////////////////////////////////////////////////////////////////
  1746. bool CXConsole::IsOpened()
  1747. {
  1748. return m_nScrollPos == m_nTempScrollMax;
  1749. }
  1750. //////////////////////////////////////////////////////////////////////////
  1751. void CXConsole::PrintLine(AZStd::string_view s)
  1752. {
  1753. AddLine(s);
  1754. }
  1755. //////////////////////////////////////////////////////////////////////////
  1756. void CXConsole::PrintLineAppendWithPrevLine(AZStd::string_view s)
  1757. {
  1758. AddLineAppendWithPrevLine(s);
  1759. }
  1760. //////////////////////////////////////////////////////////////////////////
  1761. void CXConsole::AddLine(AZStd::string_view inputStr)
  1762. {
  1763. if (inputStr.empty())
  1764. {
  1765. return;
  1766. }
  1767. // split out each line
  1768. auto ParseLine = [this](AZStd::string line)
  1769. {
  1770. m_dqConsoleBuffer.push_back(line);
  1771. // Remove any lines that are larger than the console line buffer size
  1772. // set via the console variable "con_line_buffer_size"
  1773. while (static_cast<int>(m_dqConsoleBuffer.size()) > con_line_buffer_size)
  1774. {
  1775. m_dqConsoleBuffer.pop_front();
  1776. }
  1777. // tell everyone who is interested (e.g. dedicated server printout)
  1778. for (IOutputPrintSink* outputSink : m_OutputSinks)
  1779. {
  1780. outputSink->Print(line.c_str());
  1781. }
  1782. };
  1783. AZ::StringFunc::TokenizeVisitor(inputStr, ParseLine, "\r\n");
  1784. }
  1785. //////////////////////////////////////////////////////////////////////////
  1786. void CXConsole::AddOutputPrintSink(IOutputPrintSink* inpSink)
  1787. {
  1788. assert(inpSink);
  1789. m_OutputSinks.push_back(inpSink);
  1790. }
  1791. //////////////////////////////////////////////////////////////////////////
  1792. void CXConsole::RemoveOutputPrintSink(IOutputPrintSink* inpSink)
  1793. {
  1794. assert(inpSink);
  1795. int nCount = static_cast<int>(m_OutputSinks.size());
  1796. for (int i = 0; i < nCount; i++)
  1797. {
  1798. if (m_OutputSinks[i] == inpSink)
  1799. {
  1800. if (nCount <= 1)
  1801. {
  1802. m_OutputSinks.clear();
  1803. }
  1804. else
  1805. {
  1806. m_OutputSinks[i] = m_OutputSinks.back();
  1807. m_OutputSinks.pop_back();
  1808. }
  1809. return;
  1810. }
  1811. }
  1812. assert(0);
  1813. }
  1814. //////////////////////////////////////////////////////////////////////////
  1815. void CXConsole::AddLineAppendWithPrevLine(AZStd::string_view inputStr)
  1816. {
  1817. if (m_dqConsoleBuffer.empty())
  1818. {
  1819. // Append is only allowed if there was an existing previous line
  1820. return;
  1821. }
  1822. // Replace line separators with spaces
  1823. auto ParseLine = [this, firstIteration = true](AZStd::string_view line) mutable
  1824. {
  1825. // Add <space> between lines
  1826. if (!firstIteration)
  1827. {
  1828. m_dqConsoleBuffer.back() += ' ';
  1829. }
  1830. firstIteration = false;
  1831. // Append the now space separated string into with the last line
  1832. // in the console buffer double ended queue
  1833. m_dqConsoleBuffer.back() += line;
  1834. };
  1835. AZ::StringFunc::TokenizeVisitor(inputStr, ParseLine, "\r\n");
  1836. // tell everyone who is interested (e.g. dedicated server printout)
  1837. for (IOutputPrintSink* outputSink : m_OutputSinks)
  1838. {
  1839. outputSink->Print(m_dqConsoleBuffer.back().c_str());
  1840. }
  1841. }
  1842. //////////////////////////////////////////////////////////////////////////
  1843. void CXConsole::AddInputUTF8(const AZStd::string& textUTF8)
  1844. {
  1845. // Ignore control characters like backspace and tab
  1846. AZStd::string textUTF8ToInsert;
  1847. for (int i = 0; i < textUTF8.length(); ++i)
  1848. {
  1849. const char charToInsert = textUTF8.at(i);
  1850. if (!AZStd::is_cntrl(charToInsert))
  1851. {
  1852. textUTF8ToInsert += charToInsert;
  1853. }
  1854. }
  1855. const char* utf8_buf = textUTF8ToInsert.c_str();
  1856. if (m_nCursorPos < (int)(m_sInputBuffer.length()))
  1857. {
  1858. m_sInputBuffer.insert(m_nCursorPos, utf8_buf);
  1859. }
  1860. else
  1861. {
  1862. m_sInputBuffer = m_sInputBuffer + utf8_buf;
  1863. }
  1864. m_nCursorPos += strlen(utf8_buf);
  1865. }
  1866. //////////////////////////////////////////////////////////////////////////
  1867. void CXConsole::ExecuteInputBuffer()
  1868. {
  1869. AZStd::string sTemp = m_sInputBuffer;
  1870. if (m_sInputBuffer.empty())
  1871. {
  1872. return;
  1873. }
  1874. m_sInputBuffer = "";
  1875. AddCommandToHistory(sTemp.c_str());
  1876. {
  1877. ExecuteStringInternal(sTemp.c_str(), true); // from console
  1878. }
  1879. m_nCursorPos = 0;
  1880. }
  1881. //////////////////////////////////////////////////////////////////////////
  1882. void CXConsole::RemoveInputChar(bool bBackSpace)
  1883. {
  1884. if (m_sInputBuffer.empty())
  1885. {
  1886. return;
  1887. }
  1888. if (bBackSpace)
  1889. {
  1890. if (m_nCursorPos > 0)
  1891. {
  1892. const char* const pBase = m_sInputBuffer.c_str();
  1893. const char* pCursor = pBase + m_nCursorPos;
  1894. const char* const pEnd = pCursor;
  1895. pCursor -= Utf8::Internal::sequence_length(pCursor); // Remove one UCS code-point, doesn't account for combining diacritics
  1896. size_t length = pEnd - pCursor;
  1897. m_sInputBuffer.erase(pCursor - pBase, length);
  1898. m_nCursorPos -= length;
  1899. }
  1900. }
  1901. else
  1902. {
  1903. if (m_nCursorPos < (int)(m_sInputBuffer.length()))
  1904. {
  1905. const char* const pBase = m_sInputBuffer.c_str();
  1906. const char* pCursor = pBase + m_nCursorPos;
  1907. const char* const pBegin = pCursor;
  1908. pCursor -= Utf8::Internal::sequence_length(pCursor); // Remove one UCS code-point, doesn't account for combining diacritics
  1909. size_t length = pCursor - pBegin;
  1910. m_sInputBuffer.erase(pBegin - pBase, length);
  1911. }
  1912. }
  1913. }
  1914. //////////////////////////////////////////////////////////////////////////
  1915. void CXConsole::AddCommandToHistory(const char* szCommand)
  1916. {
  1917. assert(szCommand);
  1918. m_nHistoryPos = -1;
  1919. if (!m_dqHistory.empty())
  1920. {
  1921. // add only if the command is != than the last
  1922. if (m_dqHistory.front() != szCommand)
  1923. {
  1924. m_dqHistory.push_front(szCommand);
  1925. }
  1926. }
  1927. else
  1928. {
  1929. m_dqHistory.push_front(szCommand);
  1930. }
  1931. while (m_dqHistory.size() > MAX_HISTORY_ENTRIES)
  1932. {
  1933. m_dqHistory.pop_back();
  1934. }
  1935. }
  1936. //////////////////////////////////////////////////////////////////////////
  1937. void CXConsole::Copy()
  1938. {
  1939. #ifdef AZ_PLATFORM_WINDOWS
  1940. if (m_sInputBuffer.empty())
  1941. {
  1942. return;
  1943. }
  1944. if (!OpenClipboard(NULL))
  1945. {
  1946. return;
  1947. }
  1948. size_t stringLength = m_sInputBuffer.length();
  1949. size_t requiredBufferSize = stringLength + 1; // for the null
  1950. if (HGLOBAL hGlobal = GlobalAlloc(GHND, requiredBufferSize))
  1951. {
  1952. if (LPVOID pGlobal = GlobalLock(hGlobal))
  1953. {
  1954. azstrcpy((char*)pGlobal, requiredBufferSize, m_sInputBuffer.c_str());
  1955. GlobalUnlock(hGlobal);
  1956. EmptyClipboard();
  1957. SetClipboardData(CF_TEXT, hGlobal);
  1958. CloseClipboard();
  1959. }
  1960. }
  1961. return;
  1962. #endif //AZ_PLATFORM_WINDOWS
  1963. }
  1964. //////////////////////////////////////////////////////////////////////////
  1965. void CXConsole::Paste()
  1966. {
  1967. #if defined(AZ_PLATFORM_WINDOWS)
  1968. if (OpenClipboard(NULL) != 0)
  1969. {
  1970. AZStd::string data;
  1971. const HANDLE wideData = GetClipboardData(CF_UNICODETEXT);
  1972. if (wideData)
  1973. {
  1974. const LPCWSTR pWideData = (LPCWSTR)GlobalLock(wideData);
  1975. if (pWideData)
  1976. {
  1977. AZStd::to_string(data, pWideData);
  1978. GlobalUnlock(wideData);
  1979. }
  1980. }
  1981. CloseClipboard();
  1982. Utf8::Unchecked::octet_iterator end(data.end());
  1983. for (Utf8::Unchecked::octet_iterator it(data.begin()); it != end; ++it)
  1984. {
  1985. const wchar_t cp = static_cast<wchar_t>(*it);
  1986. if (cp != '\r')
  1987. {
  1988. // Convert UCS code-point into UTF-8 string
  1989. AZStd::fixed_string<5> utf8_buf = {0};
  1990. AZStd::to_string(utf8_buf.data(), 5, { &cp, 1 });
  1991. AddInputUTF8(utf8_buf.c_str());
  1992. }
  1993. }
  1994. }
  1995. #endif //AZ_PLATFORM_WINDOWS
  1996. }
  1997. //////////////////////////////////////////////////////////////////////////
  1998. int CXConsole::GetNumVars()
  1999. {
  2000. return static_cast<int>(m_mapVariables.size());
  2001. }
  2002. //////////////////////////////////////////////////////////////////////////
  2003. int CXConsole::GetNumVisibleVars()
  2004. {
  2005. int numVars = 0;
  2006. for (auto& v : m_mapVariables)
  2007. {
  2008. if ((v.second->GetFlags() & VF_INVISIBLE) == 0)
  2009. ++numVars;
  2010. }
  2011. return numVars;
  2012. }
  2013. //////////////////////////////////////////////////////////////////////////
  2014. size_t CXConsole::GetSortedVars(AZStd::vector<AZStd::string_view>& pszArray, const char* szPrefix)
  2015. {
  2016. // This method used to insert instead of push_back, so we need to clear first
  2017. pszArray.clear();
  2018. size_t iPrefixLen = szPrefix ? strlen(szPrefix) : 0;
  2019. // variables
  2020. {
  2021. ConsoleVariablesMap::const_iterator it, end = m_mapVariables.end();
  2022. for (it = m_mapVariables.begin(); it != end; ++it)
  2023. {
  2024. if (szPrefix)
  2025. {
  2026. if (_strnicmp(it->first, szPrefix, iPrefixLen) != 0)
  2027. {
  2028. continue;
  2029. }
  2030. }
  2031. if (it->second->GetFlags() & VF_INVISIBLE)
  2032. {
  2033. continue;
  2034. }
  2035. pszArray.push_back(it->first);
  2036. }
  2037. }
  2038. // commands
  2039. {
  2040. ConsoleCommandsMap::iterator it, end = m_mapCommands.end();
  2041. for (it = m_mapCommands.begin(); it != end; ++it)
  2042. {
  2043. if (szPrefix)
  2044. {
  2045. if (_strnicmp(it->first.c_str(), szPrefix, iPrefixLen) != 0)
  2046. {
  2047. continue;
  2048. }
  2049. }
  2050. if (it->second.m_nFlags & VF_INVISIBLE)
  2051. {
  2052. continue;
  2053. }
  2054. pszArray.push_back(it->first.c_str());
  2055. }
  2056. }
  2057. std::sort(pszArray.begin(), pszArray.end());
  2058. return pszArray.size();
  2059. }
  2060. //////////////////////////////////////////////////////////////////////////
  2061. void CXConsole::FindVar(const char* substr)
  2062. {
  2063. AZStd::vector<AZStd::string_view> cmds;
  2064. size_t cmdCount = GetSortedVars(cmds);
  2065. for (size_t i = 0; i < cmdCount; i++)
  2066. {
  2067. if (AZ::StringFunc::Find(cmds[i], substr) != AZStd::string::npos)
  2068. {
  2069. ICVar* pCvar = gEnv->pConsole->GetCVar(cmds[i].data());
  2070. if (pCvar)
  2071. {
  2072. DisplayVarValue(pCvar);
  2073. }
  2074. else
  2075. {
  2076. ConsoleLogInputResponse(" $3%.*s $6(Command)", aznumeric_cast<int>(cmds[i].size()), cmds[i].data());
  2077. }
  2078. }
  2079. }
  2080. }
  2081. //////////////////////////////////////////////////////////////////////////
  2082. const char* CXConsole::AutoComplete(const char* substr)
  2083. {
  2084. // following code can be optimized
  2085. AZStd::vector<AZStd::string_view> cmds;
  2086. size_t cmdCount = GetSortedVars(cmds);
  2087. size_t substrLen = substr ? strlen(substr) : 0;
  2088. // If substring is empty return first command.
  2089. if (substrLen == 0 && cmdCount > 0)
  2090. {
  2091. return cmds[0].data();
  2092. }
  2093. // find next
  2094. for (size_t i = 0; i < cmdCount; i++)
  2095. {
  2096. const char* szCmd = cmds[i].data();
  2097. size_t cmdlen = cmds[i].size();
  2098. if (cmdlen >= substrLen && memcmp(szCmd, substr, substrLen) == 0)
  2099. {
  2100. if (substrLen == cmdlen)
  2101. {
  2102. i++;
  2103. if (i < cmdCount)
  2104. {
  2105. return cmds[i].data();
  2106. }
  2107. return cmds[i - 1].data();
  2108. }
  2109. return cmds[i].data();
  2110. }
  2111. }
  2112. // then first matching case insensitive
  2113. for (size_t i = 0; i < cmdCount; i++)
  2114. {
  2115. const char* szCmd = cmds[i].data();
  2116. size_t cmdlen = cmds[i].size();
  2117. if (cmdlen >= substrLen && azstrnicmp(szCmd, substr, substrLen) == 0)
  2118. {
  2119. if (substrLen == cmdlen)
  2120. {
  2121. i++;
  2122. if (i < cmdCount)
  2123. {
  2124. return cmds[i].data();
  2125. }
  2126. return cmds[i - 1].data();
  2127. }
  2128. return cmds[i].data();
  2129. }
  2130. }
  2131. // Not found.
  2132. return "";
  2133. }
  2134. void CXConsole::SetInputLine(const char* szLine)
  2135. {
  2136. assert(szLine);
  2137. m_sInputBuffer = szLine;
  2138. m_nCursorPos = m_sInputBuffer.size();
  2139. }
  2140. //////////////////////////////////////////////////////////////////////////
  2141. const char* CXConsole::AutoCompletePrev(const char* substr)
  2142. {
  2143. AZStd::vector<AZStd::string_view> cmds;
  2144. GetSortedVars(cmds);
  2145. // If substring is empty return last command.
  2146. if (strlen(substr) == 0 && !cmds.empty())
  2147. {
  2148. return cmds.back().data();
  2149. }
  2150. for (const AZStd::string_view& cmd : cmds)
  2151. {
  2152. if (azstricmp(substr, cmd.data()) == 0)
  2153. {
  2154. return cmd.data();
  2155. }
  2156. }
  2157. return AutoComplete(substr);
  2158. }
  2159. //////////////////////////////////////////////////////////////////////////
  2160. inline size_t sizeOf (const AZStd::string& str)
  2161. {
  2162. return str.capacity() + 1;
  2163. }
  2164. //////////////////////////////////////////////////////////////////////////
  2165. inline size_t sizeOf (const char* sz)
  2166. {
  2167. return sz ? strlen(sz) + 1 : 0;
  2168. }
  2169. //////////////////////////////////////////////////////////////////////////
  2170. void CXConsole::ConsoleLogInputResponse(const char* format, ...)
  2171. {
  2172. va_list args;
  2173. va_start(args, format);
  2174. gEnv->pLog->LogV(ILog::eInputResponse, format, args);
  2175. va_end(args);
  2176. }
  2177. //////////////////////////////////////////////////////////////////////////
  2178. void CXConsole::ConsoleLogInput(const char* format, ...)
  2179. {
  2180. va_list args;
  2181. va_start(args, format);
  2182. gEnv->pLog->LogV(ILog::eInput, format, args);
  2183. va_end(args);
  2184. }
  2185. //////////////////////////////////////////////////////////////////////////
  2186. void CXConsole::ConsoleWarning(const char* format, ...)
  2187. {
  2188. va_list args;
  2189. va_start(args, format);
  2190. gEnv->pLog->LogV(ILog::eWarningAlways, format, args);
  2191. va_end(args);
  2192. }
  2193. //////////////////////////////////////////////////////////////////////////
  2194. bool CXConsole::OnBeforeVarChange(ICVar* pVar, const char* sNewValue)
  2195. {
  2196. bool isConst = pVar->IsConstCVar();
  2197. bool isCheat = ((pVar->GetFlags() & (VF_CHEAT | VF_CHEAT_NOCHECK | VF_CHEAT_ALWAYS_CHECK)) != 0);
  2198. bool isReadOnly = ((pVar->GetFlags() & VF_READONLY) != 0);
  2199. bool isDeprecated = ((pVar->GetFlags() & VF_DEPRECATED) != 0);
  2200. if (
  2201. #if CVAR_GROUPS_ARE_PRIVILEGED
  2202. !m_bIsProcessingGroup &&
  2203. #endif // !CVAR_GROUPS_ARE_PRIVILEGED
  2204. (isConst || isCheat || isReadOnly || isDeprecated))
  2205. {
  2206. bool allowChange = !isDeprecated && ((gEnv->pSystem->IsDevMode()) || (gEnv->IsEditor()));
  2207. if (!(gEnv->IsEditor()) || isDeprecated)
  2208. {
  2209. #if LOG_CVAR_INFRACTIONS
  2210. LogChangeMessage(pVar->GetName(), isConst, isCheat,
  2211. isReadOnly, isDeprecated, pVar->GetString(), sNewValue, m_bIsProcessingGroup, allowChange);
  2212. #if LOG_CVAR_INFRACTIONS_CALLSTACK
  2213. gEnv->pSystem->debug_LogCallStack();
  2214. #endif // LOG_CVAR_INFRACTIONS_CALLSTACK
  2215. #endif // LOG_CVAR_INFRACTIONS
  2216. }
  2217. if (!allowChange && !ALLOW_CONST_CVAR_MODIFICATIONS)
  2218. {
  2219. return false;
  2220. }
  2221. }
  2222. if (!m_consoleVarSinks.empty())
  2223. {
  2224. ConsoleVarSinks::iterator it, next;
  2225. for (it = m_consoleVarSinks.begin(); it != m_consoleVarSinks.end(); it = next)
  2226. {
  2227. next = it;
  2228. next++;
  2229. if (!(*it)->OnBeforeVarChange(pVar, sNewValue))
  2230. {
  2231. return false;
  2232. }
  2233. }
  2234. }
  2235. return true;
  2236. }
  2237. //////////////////////////////////////////////////////////////////////////
  2238. void CXConsole::OnAfterVarChange(ICVar* pVar)
  2239. {
  2240. if (!m_consoleVarSinks.empty())
  2241. {
  2242. ConsoleVarSinks::iterator it, next;
  2243. for (it = m_consoleVarSinks.begin(); it != m_consoleVarSinks.end(); it = next)
  2244. {
  2245. next = it;
  2246. next++;
  2247. (*it)->OnAfterVarChange(pVar);
  2248. }
  2249. }
  2250. }
  2251. //////////////////////////////////////////////////////////////////////////
  2252. void CXConsole_ExecuteCommandTrampoline(IConsoleCmdArgs* args)
  2253. {
  2254. if (gEnv && gEnv->pSystem && gEnv->pSystem->GetIConsole())
  2255. {
  2256. CXConsole* pConsole = static_cast<CXConsole*>(gEnv->pSystem->GetIConsole());
  2257. pConsole->ExecuteRegisteredCommand(args);
  2258. }
  2259. }
  2260. //////////////////////////////////////////////////////////////////////////
  2261. void CXConsole::ExecuteRegisteredCommand(IConsoleCmdArgs* args)
  2262. {
  2263. if (args->GetArgCount() == 0)
  2264. {
  2265. AZ_Error("console", false, "Invalid number of args sent");
  2266. return;
  2267. }
  2268. const char* commandIdentifier = args->GetArg(0);
  2269. auto itCommandEntry = m_commandRegistrationMap.find(commandIdentifier);
  2270. if (itCommandEntry == m_commandRegistrationMap.end())
  2271. {
  2272. AZ_Error("console", false, "Command %s not found in the command registry", commandIdentifier);
  2273. return;
  2274. }
  2275. AZStd::vector<AZStd::string_view> input;
  2276. input.reserve(args->GetArgCount());
  2277. for (int i = 0; i < args->GetArgCount(); ++i)
  2278. {
  2279. input.push_back(args->GetArg(i));
  2280. }
  2281. CommandRegistrationEntry& entry = itCommandEntry->second;
  2282. const AzFramework::CommandResult output = entry.m_callback(input);
  2283. if (output != AzFramework::CommandResult::Success)
  2284. {
  2285. if (output == AzFramework::CommandResult::ErrorWrongNumberOfArguments)
  2286. {
  2287. AZ_Warning("console", false, "Command does not have the right number of arguments (send = %d)", input.size());
  2288. }
  2289. else
  2290. {
  2291. AZ_Warning("console", false, "Command returned a generic error");
  2292. }
  2293. }
  2294. }
  2295. //////////////////////////////////////////////////////////////////////////
  2296. bool CXConsole::RegisterCommand(AZStd::string_view identifier, AZStd::string_view helpText, AZ::u32 commandFlags, AzFramework::CommandFunction callback)
  2297. {
  2298. if (identifier.empty())
  2299. {
  2300. AZ_Error("console", false, "RegisterCommand() requires a valid identifier");
  2301. return false;
  2302. }
  2303. if (!callback)
  2304. {
  2305. AZ_Error("console", false, "RegisterCommand() requires a valid callback");
  2306. return false;
  2307. }
  2308. if (m_commandRegistrationMap.find(identifier) != m_commandRegistrationMap.end())
  2309. {
  2310. AZ_Warning("console", false, "Command '%.*s' already found in the command registry.", static_cast<int>(identifier.size()), identifier.data());
  2311. return false;
  2312. }
  2313. // command flags should match "enum EVarFlags" values
  2314. const int flags = static_cast<int>(commandFlags);
  2315. CommandRegistrationEntry entry;
  2316. entry.m_callback = callback;
  2317. entry.m_id = identifier;
  2318. if (!helpText.empty())
  2319. {
  2320. entry.m_helpText = helpText;
  2321. }
  2322. if (!AddCommand(entry.m_id.c_str(), CXConsole_ExecuteCommandTrampoline, flags, entry.m_helpText.empty() ? nullptr : entry.m_helpText.c_str()))
  2323. {
  2324. AZ_Warning("console", false, "Command %s already found in the command registry.", entry.m_id.c_str());
  2325. return false;
  2326. }
  2327. m_commandRegistrationMap.insert(AZStd::make_pair(entry.m_id, entry));
  2328. return true;
  2329. }
  2330. //////////////////////////////////////////////////////////////////////////
  2331. bool CXConsole::UnregisterCommand(AZStd::string_view identifier)
  2332. {
  2333. if (m_commandRegistrationMap.erase(identifier) == 1)
  2334. {
  2335. RemoveCommand(identifier.data());
  2336. return true;
  2337. }
  2338. return false;
  2339. }
  2340. //////////////////////////////////////////////////////////////////////////
  2341. void CXConsole::AddConsoleVarSink(IConsoleVarSink* pSink)
  2342. {
  2343. m_consoleVarSinks.push_back(pSink);
  2344. }
  2345. //////////////////////////////////////////////////////////////////////////
  2346. void CXConsole::RemoveConsoleVarSink(IConsoleVarSink* pSink)
  2347. {
  2348. m_consoleVarSinks.remove(pSink);
  2349. }