core/ConVarManager.cpp
author Scott Ehlert <ds@alliedmods.net>
Tue Mar 06 23:59:25 2007 +0000 (2007-03-06)
changeset 582 00c843a1bb18
parent 580 416aecc7de51
child 583 9fab8343cc15
permissions -rw-r--r--
Many things:
1) General code clean-up in convar manager
2) Fixed bug where convar handles were not being cached for pre-existing convars
3) Fixed bug where a convar's old value and new value were switched in the ConVarChanged hooks
4) Made convar and concmd listings more consistent, I think
5) Alphabetized convar listing
6) Minor clean-up in event manager
     1 /**
     2 * ===============================================================
     3 * SourceMod (C)2004-2007 AlliedModders LLC.  All rights reserved.
     4 * ===============================================================
     5 *
     6 * This file is not open source and may not be copied without explicit
     7 * written permission of AlliedModders LLC.  This file may not be redistributed 
     8 * in whole or significant part.
     9 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
    10 *
    11 * Version: $Id$
    12 */
    13 
    14 #include "ConVarManager.h"
    15 #include "PluginSys.h"
    16 #include "ForwardSys.h"
    17 #include "HandleSys.h"
    18 #include "sm_srvcmds.h"
    19 #include "sm_stringutil.h"
    20 #include <sh_vector.h>
    21 
    22 ConVarManager g_ConVarManager;
    23 
    24 const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
    25 typedef List<const ConVar *> ConVarList;
    26 
    27 ConVarManager::ConVarManager() : m_ConVarType(0)
    28 {
    29 	/* Create a convar lookup trie */
    30 	m_ConVarCache = sm_trie_create();
    31 }
    32 
    33 ConVarManager::~ConVarManager()
    34 {
    35 	List<ConVarInfo *>::iterator iter;
    36 
    37 	/* Destroy our convar lookup trie */
    38 	sm_trie_destroy(m_ConVarCache);
    39 
    40 	/* Destroy all the ConVarInfo structures */
    41 	for (iter = m_ConVars.begin(); iter != m_ConVars.end(); iter++)
    42 	{
    43 		delete (*iter);
    44 	}
    45 
    46 	m_ConVars.clear();
    47 }
    48 
    49 void ConVarManager::OnSourceModAllInitialized()
    50 {
    51 	HandleAccess sec;
    52 
    53 	/* Set up access rights for the 'ConVar' handle type */
    54 	sec.access[HandleAccess_Read] = 0;
    55 	sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
    56 	sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
    57 
    58 	/* Create the 'ConVar' handle type */
    59 	m_ConVarType = g_HandleSys.CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
    60 
    61 	/* Add the 'convars' option to the 'sm' console command */
    62 	g_RootMenu.AddRootConsoleCommand("convars", "View convars created by a plugin", this);
    63 }
    64 
    65 void ConVarManager::OnSourceModShutdown()
    66 {
    67 	IChangeableForward *fwd;
    68 	List<ConVarInfo *>::iterator i;
    69 
    70 	/* Iterate list of ConVarInfo structures */
    71 	for (i = m_ConVars.begin(); i != m_ConVars.end(); i++)
    72 	{
    73 		fwd = (*i)->changeForward;
    74 
    75 		/* Free any convar-change forwards that still exist */
    76 		if (fwd)
    77 		{
    78 			g_Forwards.ReleaseForward(fwd);
    79 		}
    80 	}
    81 
    82 	/* Remove the 'convars' option from the 'sm' console command */
    83 	g_RootMenu.RemoveRootConsoleCommand("convars", this);
    84 
    85 	/* Remove the 'ConVar' handle type */
    86 	g_HandleSys.RemoveType(m_ConVarType, g_pCoreIdent);
    87 }
    88 
    89 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
    90 {
    91 	ConVarList *pConVarList;
    92 
    93 	/* If plugin has a convar list, free its memory */
    94 	if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
    95 	{
    96 		delete pConVarList;
    97 	}
    98 }
    99 
   100 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
   101 {
   102 	ConVarInfo *info;
   103 	ConVar *pConVar = static_cast<ConVar *>(object);
   104 
   105 	/* Find convar in lookup trie */
   106 	sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), reinterpret_cast<void **>(&info));
   107 
   108 	/* If convar was created by SourceMod plugin... */
   109 	if (info->sourceMod)
   110 	{
   111 		/* Delete string allocations */
   112 		delete [] pConVar->GetName(); 
   113 		delete [] pConVar->GetDefault();
   114 		delete [] pConVar->GetHelpText();
   115 
   116 		/* Then unlink it from SourceMM */
   117 		g_SMAPI->UnregisterConCmdBase(g_PLAPI, pConVar);
   118 	}
   119 }
   120 
   121 void ConVarManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
   122 {
   123 	if (argcount >= 3)
   124 	{
   125 		/* Get plugin index that was passed */
   126 		int id = atoi(g_RootMenu.GetArgument(2));
   127 		
   128 		/* Get plugin object */
   129 		CPlugin *plugin = g_PluginSys.GetPluginByOrder(id);
   130 
   131 		if (!plugin)
   132 		{
   133 			g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
   134 			return;
   135 		}
   136 
   137 		/* Get plugin name */
   138 		const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
   139 		const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
   140 
   141 		ConVarList *pConVarList;
   142 		ConVarList::iterator iter;
   143 
   144 		/* If no convar list... */
   145 		if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
   146 		{
   147 			g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
   148 			return;
   149 		}
   150 
   151 		g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
   152 		g_RootMenu.ConsolePrint("  %-32.31s %s", "[Name]", "[Value]");
   153 
   154 		/* Iterate convar list and display each one */
   155 		for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
   156 		{
   157 			const ConVar *pConVar = (*iter);
   158 			g_RootMenu.ConsolePrint("  %-32.31s %s", pConVar->GetName(), pConVar->GetString()); 
   159 		}
   160 
   161 		return;
   162 	}
   163 
   164 	/* Display usage of subcommand */
   165 	g_RootMenu.ConsolePrint("[SM] Usage: sm convars <plugin #>");
   166 }
   167 
   168 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)
   169 {
   170 	ConVar *pConVar = NULL;
   171 	ConVarInfo *pInfo = NULL;
   172 	ConVarList *pConVarList = 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 }