core/ConVarManager.cpp
author Scott Ehlert <ds@alliedmods.net>
Thu Mar 22 21:50:20 2007 +0000 (2007-03-22)
changeset 653 ef60870067ff
parent 628 b11949f893a5
child 696 d5cc8d0fa899
permissions -rw-r--r--
More consistency of some sort...

Oh god, what has possessed me to do this?
     1 /**
     2  * vim: set ts=4 :
     3  * ===============================================================
     4  * SourceMod (C)2004-2007 AlliedModders LLC.  All rights reserved.
     5  * ===============================================================
     6  *
     7  * This file is not open source and may not be copied without explicit
     8  * written permission of AlliedModders LLC.  This file may not be redistributed 
     9  * in whole or significant part.
    10  * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
    11  *
    12  * Version: $Id$
    13  */
    14 
    15 #include "ConVarManager.h"
    16 #include "PluginSys.h"
    17 #include "ForwardSys.h"
    18 #include "HandleSys.h"
    19 #include "sm_srvcmds.h"
    20 #include "sm_stringutil.h"
    21 #include <sh_vector.h>
    22 
    23 ConVarManager g_ConVarManager;
    24 
    25 const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
    26 typedef List<const ConVar *> ConVarList;
    27 
    28 ConVarManager::ConVarManager() : m_ConVarType(0)
    29 {
    30 	/* Create a convar lookup trie */
    31 	m_ConVarCache = sm_trie_create();
    32 }
    33 
    34 ConVarManager::~ConVarManager()
    35 {
    36 	List<ConVarInfo *>::iterator iter;
    37 
    38 	/* Destroy our convar lookup trie */
    39 	sm_trie_destroy(m_ConVarCache);
    40 
    41 	/* Destroy all the ConVarInfo structures */
    42 	for (iter = m_ConVars.begin(); iter != m_ConVars.end(); iter++)
    43 	{
    44 		delete (*iter);
    45 	}
    46 
    47 	m_ConVars.clear();
    48 }
    49 
    50 void ConVarManager::OnSourceModAllInitialized()
    51 {
    52 	HandleAccess sec;
    53 
    54 	/* Set up access rights for the 'ConVar' handle type */
    55 	sec.access[HandleAccess_Read] = 0;
    56 	sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
    57 	sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
    58 
    59 	/* Create the 'ConVar' handle type */
    60 	m_ConVarType = g_HandleSys.CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
    61 
    62 	/* Add the 'convars' option to the 'sm' console command */
    63 	g_RootMenu.AddRootConsoleCommand("convars", "View convars created by a plugin", this);
    64 }
    65 
    66 void ConVarManager::OnSourceModShutdown()
    67 {
    68 	IChangeableForward *fwd;
    69 	List<ConVarInfo *>::iterator i;
    70 
    71 	/* Iterate list of ConVarInfo structures */
    72 	for (i = m_ConVars.begin(); i != m_ConVars.end(); i++)
    73 	{
    74 		fwd = (*i)->changeForward;
    75 
    76 		/* Free any convar-change forwards that still exist */
    77 		if (fwd)
    78 		{
    79 			g_Forwards.ReleaseForward(fwd);
    80 		}
    81 	}
    82 
    83 	/* Remove the 'convars' option from the 'sm' console command */
    84 	g_RootMenu.RemoveRootConsoleCommand("convars", this);
    85 
    86 	/* Remove the 'ConVar' handle type */
    87 	g_HandleSys.RemoveType(m_ConVarType, g_pCoreIdent);
    88 }
    89 
    90 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
    91 {
    92 	ConVarList *pConVarList;
    93 
    94 	/* If plugin has a convar list, free its memory */
    95 	if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
    96 	{
    97 		delete pConVarList;
    98 	}
    99 }
   100 
   101 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
   102 {
   103 	ConVarInfo *info;
   104 	ConVar *pConVar = static_cast<ConVar *>(object);
   105 
   106 	/* Find convar in lookup trie */
   107 	sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), reinterpret_cast<void **>(&info));
   108 
   109 	/* If convar was created by SourceMod plugin... */
   110 	if (info->sourceMod)
   111 	{
   112 		/* Delete string allocations */
   113 		delete [] pConVar->GetName(); 
   114 		delete [] pConVar->GetDefault();
   115 		delete [] pConVar->GetHelpText();
   116 
   117 		/* Then unlink it from SourceMM */
   118 		g_SMAPI->UnregisterConCmdBase(g_PLAPI, pConVar);
   119 	}
   120 }
   121 
   122 void ConVarManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
   123 {
   124 	if (argcount >= 3)
   125 	{
   126 		/* Get plugin index that was passed */
   127 		int id = atoi(g_RootMenu.GetArgument(2));
   128 		
   129 		/* Get plugin object */
   130 		CPlugin *plugin = g_PluginSys.GetPluginByOrder(id);
   131 
   132 		if (!plugin)
   133 		{
   134 			g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
   135 			return;
   136 		}
   137 
   138 		/* Get plugin name */
   139 		const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
   140 		const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
   141 
   142 		ConVarList *pConVarList;
   143 		ConVarList::iterator iter;
   144 
   145 		/* If no convar list... */
   146 		if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
   147 		{
   148 			g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
   149 			return;
   150 		}
   151 
   152 		g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
   153 		g_RootMenu.ConsolePrint("  %-32.31s %s", "[Name]", "[Value]");
   154 
   155 		/* Iterate convar list and display each one */
   156 		for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
   157 		{
   158 			const ConVar *pConVar = (*iter);
   159 			g_RootMenu.ConsolePrint("  %-32.31s %s", pConVar->GetName(), pConVar->GetString()); 
   160 		}
   161 
   162 		return;
   163 	}
   164 
   165 	/* Display usage of subcommand */
   166 	g_RootMenu.ConsolePrint("[SM] Usage: sm convars <plugin #>");
   167 }
   168 
   169 Handle_t ConVarManager::CreateConVar(IPluginContext *pContext, const char *name, const char *defaultVal, const char *description, int flags, bool hasMin, float min, bool hasMax, float max)
   170 {
   171 	ConVar *pConVar = NULL;
   172 	ConVarInfo *pInfo = NULL;
   173 	Handle_t hndl = 0;
   174 
   175 	/* Find out if the convar exists already */
   176 	pConVar = icvar->FindVar(name);
   177 
   178 	/* If the convar already exists... */
   179 	if (pConVar)
   180 	{
   181 		/* First find out if we already have a handle to it */
   182 		if (sm_trie_retrieve(m_ConVarCache, name, (void **)&pInfo))
   183 		{
   184 			return pInfo->handle;
   185 		} else {
   186 			/* If we don't, then create a new handle from the convar */
   187 			hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
   188 
   189 			/* Create and initialize ConVarInfo structure */
   190 			pInfo = new ConVarInfo();
   191 			pInfo->handle = hndl;
   192 			pInfo->sourceMod = false;
   193 			pInfo->changeForward = NULL;
   194 			pInfo->origCallback = pConVar->GetCallback();
   195 
   196 			/* Insert struct into caches */
   197 			m_ConVars.push_back(pInfo);
   198 			sm_trie_insert(m_ConVarCache, name, pInfo);
   199 
   200 			return hndl;
   201 		}
   202 	}
   203 
   204 	// To prevent creating a convar that has the same name as a console command... ugh
   205 	ConCommandBase *pBase = icvar->GetCommands();
   206 
   207 	while (pBase)
   208 	{
   209 		if (pBase->IsCommand() && strcmp(pBase->GetName(), name) == 0)
   210 		{
   211 			return BAD_HANDLE;
   212 		}
   213 
   214 		pBase = const_cast<ConCommandBase *>(pBase->GetNext());
   215 	}
   216 
   217 	/* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
   218 	pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
   219 
   220 	/* Add convar to plugin's list */
   221 	AddConVarToPluginList(pContext, pConVar);
   222 
   223 	/* Create a handle from the new convar */
   224 	hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
   225 
   226 	/* Create and initialize ConVarInfo structure */
   227 	pInfo = new ConVarInfo();
   228 	pInfo->handle = hndl;
   229 	pInfo->sourceMod = true;
   230 	pInfo->changeForward = NULL;
   231 	pInfo->origCallback = NULL;
   232 
   233 	/* Insert struct into caches */
   234 	m_ConVars.push_back(pInfo);
   235 	sm_trie_insert(m_ConVarCache, name, pInfo);
   236 
   237 	return hndl;
   238 }
   239 
   240 Handle_t ConVarManager::FindConVar(const char *name)
   241 {
   242 	ConVar *pConVar = NULL;
   243 	ConVarInfo *pInfo;
   244 	Handle_t hndl;
   245 
   246 	/* Search for convar */
   247 	pConVar = icvar->FindVar(name);
   248 
   249 	/* If it doesn't exist, then return an invalid handle */
   250 	if (!pConVar)
   251 	{
   252 		return BAD_HANDLE;
   253 	}
   254 
   255 	/* At this point, the convar exists. So, find out if we already have a handle */
   256 	if (sm_trie_retrieve(m_ConVarCache, name, (void **)&pInfo))
   257 	{
   258 		return pInfo->handle;
   259 	}
   260 
   261 	/* If we don't have a handle, then create a new one */
   262 	hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
   263 
   264 	/* Create and initilize ConVarInfo structure */
   265 	pInfo = new ConVarInfo();
   266 	pInfo->handle = hndl;
   267 	pInfo->sourceMod = false;
   268 	pInfo->changeForward = NULL;
   269 	pInfo->origCallback = pConVar->GetCallback();
   270 
   271 	/* Insert struct into our caches */
   272 	m_ConVars.push_back(pInfo);
   273 	sm_trie_insert(m_ConVarCache, name, pInfo);
   274 
   275 	return hndl;
   276 }
   277 
   278 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
   279 {
   280 	ConVarInfo *pInfo;
   281 	IChangeableForward *pForward;
   282 
   283 	/* Find the convar in the lookup trie */
   284 	if (sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), (void **)&pInfo))
   285 	{
   286 		/* Get the forward */
   287 		pForward = pInfo->changeForward;
   288 
   289 		/* If forward does not exist, create it */
   290 		if (!pForward)
   291 		{
   292 			pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
   293 			pInfo->changeForward = pForward;
   294 
   295 			/* Install our own callback */
   296 			pConVar->InstallChangeCallback(OnConVarChanged);
   297 		}
   298 
   299 		/* Add function to forward's list */
   300 		pForward->AddFunction(pFunction);
   301 	}
   302 }
   303 
   304 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
   305 {
   306 	ConVarInfo *pInfo;
   307 	IChangeableForward *pForward;
   308 	IPluginContext *pContext = pFunction->GetParentContext();
   309 
   310 	/* Find the convar in the lookup trie */
   311 	if (sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), (void **)&pInfo))
   312 	{
   313 		/* Get the forward */
   314 		pForward = pInfo->changeForward;
   315 
   316 		/* If the forward doesn't exist, we can't unhook anything */
   317 		if (!pForward)
   318 		{
   319 			pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
   320 			return;
   321 		}
   322 
   323 		/* Remove the function from the forward's list */
   324 		if (!pForward->RemoveFunction(pFunction))
   325 		{
   326 			pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
   327 			return;
   328 		}
   329 
   330 		/* If the forward now has 0 functions in it... */
   331 		if (pForward->GetFunctionCount() == 0)
   332 		{
   333 			/* Free this forward */
   334 			g_Forwards.ReleaseForward(pForward);
   335 			pInfo->changeForward = NULL;
   336 
   337 			/* Put back the original convar callback */
   338 			pConVar->InstallChangeCallback(pInfo->origCallback);
   339 		}
   340 	}
   341 }
   342 
   343 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
   344 {
   345 	ConVarList *pConVarList;
   346 	ConVarList::iterator iter;
   347 	bool inserted = false;
   348 	const char *orig = pConVar->GetName();
   349 
   350 	IPlugin *plugin = g_PluginSys.FindPluginByContext(pContext->GetContext());
   351 
   352 	/* Check plugin for an existing convar list */
   353 	if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
   354 	{
   355 		pConVarList = new ConVarList();
   356 		plugin->SetProperty("ConVarList", pConVarList);
   357 	}
   358 
   359 	/* Insert convar into list which is sorted alphabetically */
   360 	for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
   361 	{
   362 		if (strcmp(orig, (*iter)->GetName()) < 0)
   363 		{
   364 			pConVarList->insert(iter, pConVar);
   365 			inserted = true;
   366 			break;
   367 		}
   368 	}
   369 
   370 	if (!inserted)
   371 	{
   372 		pConVarList->push_back(pConVar);
   373 	}
   374 }
   375 
   376 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
   377 {
   378 	/* If the values are the same, exit early in order to not trigger callbacks */
   379 	if (strcmp(pConVar->GetString(), oldValue) == 0)
   380 	{
   381 		return;
   382 	}
   383 
   384 	Trie *pCache = g_ConVarManager.GetConVarCache();
   385 	ConVarInfo *pInfo;
   386 
   387 	/* Find the convar in the lookup trie */
   388 	sm_trie_retrieve(pCache, pConVar->GetName(), (void **)&pInfo);
   389 
   390 	FnChangeCallback origCallback = pInfo->origCallback;
   391 	IChangeableForward *pForward = pInfo->changeForward;
   392 
   393 	/* If there was a change callback installed previously, call it */
   394 	if (origCallback)
   395 	{
   396 		origCallback(pConVar, oldValue);
   397 	}
   398 
   399 	/* Now call forwards in plugins that have hooked this */
   400 	pForward->PushCell(pInfo->handle);
   401 	pForward->PushString(oldValue);
   402 	pForward->PushString(pConVar->GetString());
   403 	pForward->Execute(NULL);
   404 }
   405 
   406 static int s_YamagramState = 0;
   407 
   408 void _YamagramPrinterTwoPointOhOh(int yamagram)
   409 {
   410 	switch (yamagram)
   411 	{
   412 	case 0:
   413 		g_RootMenu.ConsolePrint("Answer the following questions correctly and Gaben may not eat you after all.");
   414 		g_RootMenu.ConsolePrint("You will be given one hint in the form of my patented yamagrams.");
   415 		g_RootMenu.ConsolePrint("Type sm_nana to see the last question.");
   416 		g_RootMenu.ConsolePrint("Type sm_nana <answer> to attempt an answer of the question.");
   417 		g_RootMenu.ConsolePrint("-------------------------------");
   418 		_YamagramPrinterTwoPointOhOh(1);
   419 		return;
   420 	case 1:
   421 		g_RootMenu.ConsolePrint("Question Ichi (1)");
   422 		g_RootMenu.ConsolePrint("One can turn into a cow by doing what action?");
   423 		g_RootMenu.ConsolePrint("Hint: AGE SANS GRIT");
   424 		break;
   425 	case 2:
   426 		g_RootMenu.ConsolePrint("Question Ni (2)");
   427 		g_RootMenu.ConsolePrint("What kind of hat should you wear when using the Internet?");
   428 		g_RootMenu.ConsolePrint("Hint: BRR MOOSE");
   429 		break;
   430 	case 3:
   431 		g_RootMenu.ConsolePrint("Question San (3)");
   432 		g_RootMenu.ConsolePrint("Who is the lead developer of SourceMod?");
   433 		g_RootMenu.ConsolePrint("Hint: VEAL BANDANA DID RIP SOON");
   434 		break;
   435 	case 4:
   436 		g_RootMenu.ConsolePrint("Question Yon (4)");
   437 		g_RootMenu.ConsolePrint("A terrible translation of 'SVN Revision' to Japanese romaji might be ...");
   438 		g_RootMenu.ConsolePrint("Hint: I TAKE IN AN AIR OK");
   439 		break;
   440 	case 5:
   441 		g_RootMenu.ConsolePrint("Question Go (5)");
   442 		g_RootMenu.ConsolePrint("What is a fundamental concept in the game of Go?");
   443 		g_RootMenu.ConsolePrint("Hint: AD LADEN THIEF");
   444 		break;
   445 	case 6:
   446 		g_RootMenu.ConsolePrint("Question Roku (6)");
   447 		g_RootMenu.ConsolePrint("Why am I asking all these strange questions?");
   448 		g_RootMenu.ConsolePrint("Hint: CHUBBY TITAN EATS EWE WAGE DATA");
   449 		break;
   450 	case 7:
   451 		g_RootMenu.ConsolePrint("Question Nana (7)");
   452 		g_RootMenu.ConsolePrint("What is my name?");
   453 		g_RootMenu.ConsolePrint("Hint: AD MODE LAG US");
   454 		break;
   455 	default:
   456 		break;
   457 	}
   458 
   459 	s_YamagramState = yamagram;
   460 }
   461 
   462 void _IntExt_CallYamagrams()
   463 {
   464 	bool correct = false;
   465 	const char *arg = engine->Cmd_Args();
   466 
   467 	if (!arg || arg[0] == '\0')
   468 	{
   469 		_YamagramPrinterTwoPointOhOh(s_YamagramState);
   470 		return;
   471 	}
   472 
   473 	switch (s_YamagramState)
   474 	{
   475 	case 1:
   476 		correct = !strcasecmp(arg, "eating grass");
   477 		break;
   478 	case 2:
   479 		correct = !strcasecmp(arg, "sombrero");
   480 		break;
   481 	case 3:
   482 		correct = !strcasecmp(arg, "david bailopan anderson");
   483 		break;
   484 	case 4:
   485 		correct = !strcasecmp(arg, "kaitei no kairan");
   486 		break;
   487 	case 5:
   488 		correct = !strcasecmp(arg, "life and death");
   489 		break;
   490 	case 6:
   491 		correct = !strcasecmp(arg, "because gabe wanted it that way");
   492 		if (correct)
   493 		{
   494 			g_RootMenu.ConsolePrint("Congratulations, you have answered 6 of my questions.");
   495 			g_RootMenu.ConsolePrint("However, I have one final question for you. It wouldn't be nana without it.");
   496 			g_RootMenu.ConsolePrint("-------------------------------");
   497 			_YamagramPrinterTwoPointOhOh(7);
   498 			return;
   499 		}
   500 		break;
   501 	case 7:
   502 		correct = !strcasecmp(arg, "damaged soul");
   503 		if (correct)
   504 		{
   505 			g_RootMenu.ConsolePrint("You don't know how lucky you are to still be alive!");
   506 			g_RootMenu.ConsolePrint("Congratulations. You have answered all 7 questions correctly.");
   507 			g_RootMenu.ConsolePrint("The SourceMod Dev Team will be at your door with anti-Gaben grenades");
   508 			g_RootMenu.ConsolePrint("within seconds. You will also be provided with a rocket launcher,");
   509 			g_RootMenu.ConsolePrint("just in case Alfred decides to strike you with a blitzkrieg in retaliation.");
   510 
   511 			s_YamagramState = 0;
   512 			return;
   513 		}
   514 		break;
   515 	default:
   516 		break;
   517 	}
   518 
   519 	if (s_YamagramState > 0)
   520 	{
   521 		if (correct)
   522 		{
   523 			g_RootMenu.ConsolePrint("Correct! You are one step closer to avoiding the deadly jaws of Gaben.");
   524 			g_RootMenu.ConsolePrint("-------------------------------");
   525 			s_YamagramState++;
   526 		} else {
   527 			g_RootMenu.ConsolePrint("Wrong! You better be more careful. Gaben may be at your door at any minute.");
   528 			return;
   529 		}
   530 	}
   531 
   532 	_YamagramPrinterTwoPointOhOh(s_YamagramState);
   533 }
   534 
   535 void _IntExt_EnableYamagrams()
   536 {
   537 	static ConCommand *pCmd = NULL;
   538 	if (!pCmd)
   539 	{
   540 		pCmd = new ConCommand("sm_nana", _IntExt_CallYamagrams, "Try these yamagrams!", FCVAR_GAMEDLL);
   541 		g_RootMenu.ConsolePrint("[SM] Warning: Gaben has been alerted of your actions. You may be eaten.");
   542 	} else {
   543 		g_RootMenu.ConsolePrint("[SM] Gaben has already been alerted of your actions...");
   544 	}
   545 }
   546 
   547 void _IntExt_OnHostnameChanged(ConVar *pConVar, char const *oldValue)
   548 {
   549 	if (strcmp(oldValue, "Good morning, DS-san.") == 0
   550 		&& strcmp(pConVar->GetString(), "Good night, talking desk lamp.") == 0)
   551 	{
   552 		_IntExt_EnableYamagrams();
   553 	}
   554 }