XConsole.cpp 79 KB

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