From 9e9074d0ea349fb16cfdd492df66b8683a62f4b7 Mon Sep 17 00:00:00 2001 From: cloudwalk Date: Wed, 3 Jun 2020 15:28:17 +0000 Subject: [PATCH] Implement cvar callback functionality With these, cvars can run arbitrary functions to bounds-check themselves or perform some other task such as cleanup. Use the function Cvar_RegisterCallback. git-svn-id: svn://svn.icculus.org/twilight/trunk/darkplaces@12629 d7cf8633-e32d-0410-b094-e92efae38249 --- cvar.c | 16 ++++++++++++++-- cvar.h | 4 ++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/cvar.c b/cvar.c index affdc556..be6ed386 100644 --- a/cvar.c +++ b/cvar.c @@ -349,21 +349,28 @@ static void Cvar_SetQuick_Internal (cvar_t *var, const char *value) qboolean changed; size_t valuelen; char vabuf[1024]; + char new_value[MAX_INPUTLINE]; changed = strcmp(var->string, value) != 0; // LadyHavoc: don't reallocate when there is no change if (!changed) return; + memcpy(new_value,value,MAX_INPUTLINE); + + // Call the function stored in the cvar for bounds checking, cleanup, etc + if (var->callback) + var->callback(new_value); + // LadyHavoc: don't reallocate when the buffer is the same size - valuelen = strlen(value); + valuelen = strlen(new_value); if (!var->string || strlen(var->string) != valuelen) { Z_Free ((char *)var->string); // free the old value string var->string = (char *)Z_Malloc (valuelen + 1); } - memcpy ((char *)var->string, value, valuelen + 1); + memcpy ((char *)var->string, new_value, valuelen + 1); var->value = atof (var->string); var->integer = (int) var->value; if ((var->flags & CVAR_NOTIFY) && changed && sv.active && !sv_disablenotify.integer) @@ -482,6 +489,11 @@ void Cvar_SetValue(cvar_state_t *cvars, const char *var_name, float value) Cvar_Set(cvars, var_name, val); } +void Cvar_RegisterCallback(cvar_t *variable, void (*callback)(char *)) +{ + variable->callback = callback; +} + /* ============ Cvar_RegisterVariable diff --git a/cvar.h b/cvar.h index 4838824c..2bbcd1dc 100644 --- a/cvar.h +++ b/cvar.h @@ -131,6 +131,8 @@ typedef struct cvar_s const char *defstring; + void (*callback)(char *value); + // values at init (for Cvar_RestoreInitState) qboolean initstate; // indicates this existed at init int initflags; @@ -170,6 +172,8 @@ void Cvar_MenuOption(cvar_t *variable, int menu, int value[16], const char *name /// registers a cvar that already has the name, string, and optionally the /// archive elements set. +void Cvar_RegisterCallback(cvar_t *variable, void (*callback)(char *)); + void Cvar_RegisterVariable(cvar_t *variable); /// equivelant to " " typed at the console -- 2.39.2