]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - cmd.c
alias expansion, cvar expansion: support optional arguments
[xonotic/darkplaces.git] / cmd.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // cmd.c -- Quake script command processing module
21
22 #include "quakedef.h"
23 #include "thread.h"
24
25 typedef struct cmdalias_s
26 {
27         struct cmdalias_s *next;
28         char name[MAX_ALIAS_NAME];
29         char *value;
30         qboolean initstate; // indicates this command existed at init
31         char *initialvalue; // backup copy of value at init
32 } cmdalias_t;
33
34 static cmdalias_t *cmd_alias;
35
36 static qboolean cmd_wait;
37
38 static mempool_t *cmd_mempool;
39
40 static char cmd_tokenizebuffer[CMD_TOKENIZELENGTH];
41 static int cmd_tokenizebufferpos = 0;
42
43 //=============================================================================
44
45 /*
46 ============
47 Cmd_Wait_f
48
49 Causes execution of the remainder of the command buffer to be delayed until
50 next frame.  This allows commands like:
51 bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2"
52 ============
53 */
54 static void Cmd_Wait_f (void)
55 {
56         cmd_wait = true;
57 }
58
59 typedef struct cmddeferred_s
60 {
61         struct cmddeferred_s *next;
62         char *value;
63         double delay;
64 } cmddeferred_t;
65
66 static cmddeferred_t *cmd_deferred_list = NULL;
67
68 /*
69 ============
70 Cmd_Defer_f
71
72 Cause a command to be executed after a delay.
73 ============
74 */
75 static void Cmd_Defer_f (void)
76 {
77         if(Cmd_Argc() == 1)
78         {
79                 cmddeferred_t *next = cmd_deferred_list;
80                 if(!next)
81                         Con_Printf("No commands are pending.\n");
82                 while(next)
83                 {
84                         Con_Printf("-> In %9.2f: %s\n", next->delay, next->value);
85                         next = next->next;
86                 }
87         } else if(Cmd_Argc() == 2 && !strcasecmp("clear", Cmd_Argv(1)))
88         {
89                 while(cmd_deferred_list)
90                 {
91                         cmddeferred_t *cmd = cmd_deferred_list;
92                         cmd_deferred_list = cmd->next;
93                         Mem_Free(cmd->value);
94                         Mem_Free(cmd);
95                 }
96         } else if(Cmd_Argc() == 3)
97         {
98                 const char *value = Cmd_Argv(2);
99                 cmddeferred_t *defcmd = (cmddeferred_t*)Mem_Alloc(tempmempool, sizeof(*defcmd));
100                 size_t len = strlen(value);
101
102                 defcmd->delay = atof(Cmd_Argv(1));
103                 defcmd->value = (char*)Mem_Alloc(tempmempool, len+1);
104                 memcpy(defcmd->value, value, len+1);
105                 defcmd->next = NULL;
106
107                 if(cmd_deferred_list)
108                 {
109                         cmddeferred_t *next = cmd_deferred_list;
110                         while(next->next)
111                                 next = next->next;
112                         next->next = defcmd;
113                 } else
114                         cmd_deferred_list = defcmd;
115                 /* Stupid me... this changes the order... so commands with the same delay go blub :S
116                   defcmd->next = cmd_deferred_list;
117                   cmd_deferred_list = defcmd;*/
118         } else {
119                 Con_Printf("usage: defer <seconds> <command>\n"
120                            "       defer clear\n");
121                 return;
122         }
123 }
124
125 /*
126 ============
127 Cmd_Centerprint_f
128
129 Print something to the center of the screen using SCR_Centerprint
130 ============
131 */
132 static void Cmd_Centerprint_f (void)
133 {
134         char msg[MAX_INPUTLINE];
135         unsigned int i, c, p;
136         c = Cmd_Argc();
137         if(c >= 2)
138         {
139                 strlcpy(msg, Cmd_Argv(1), sizeof(msg));
140                 for(i = 2; i < c; ++i)
141                 {
142                         strlcat(msg, " ", sizeof(msg));
143                         strlcat(msg, Cmd_Argv(i), sizeof(msg));
144                 }
145                 c = strlen(msg);
146                 for(p = 0, i = 0; i < c; ++i)
147                 {
148                         if(msg[i] == '\\')
149                         {
150                                 if(msg[i+1] == 'n')
151                                         msg[p++] = '\n';
152                                 else if(msg[i+1] == '\\')
153                                         msg[p++] = '\\';
154                                 else {
155                                         msg[p++] = '\\';
156                                         msg[p++] = msg[i+1];
157                                 }
158                                 ++i;
159                         } else {
160                                 msg[p++] = msg[i];
161                         }
162                 }
163                 msg[p] = '\0';
164                 SCR_CenterPrint(msg);
165         }
166 }
167
168 /*
169 =============================================================================
170
171                                                 COMMAND BUFFER
172
173 =============================================================================
174 */
175
176 static sizebuf_t        cmd_text;
177 static unsigned char            cmd_text_buf[CMDBUFSIZE];
178 void *cmd_text_mutex = NULL;
179
180 #define Cbuf_LockThreadMutex() (cmd_text_mutex ? Thread_LockMutex(cmd_text_mutex),1 : 0)
181 #define Cbuf_UnlockThreadMutex() (cmd_text_mutex ? Thread_UnlockMutex(cmd_text_mutex),1 : 0)
182
183 /*
184 ============
185 Cbuf_AddText
186
187 Adds command text at the end of the buffer
188 ============
189 */
190 void Cbuf_AddText (const char *text)
191 {
192         int             l;
193
194         l = (int)strlen(text);
195
196         Cbuf_LockThreadMutex();
197         if (cmd_text.cursize + l >= cmd_text.maxsize)
198                 Con_Print("Cbuf_AddText: overflow\n");
199         else
200                 SZ_Write(&cmd_text, (const unsigned char *)text, l);
201         Cbuf_UnlockThreadMutex();
202 }
203
204
205 /*
206 ============
207 Cbuf_InsertText
208
209 Adds command text immediately after the current command
210 Adds a \n to the text
211 FIXME: actually change the command buffer to do less copying
212 ============
213 */
214 void Cbuf_InsertText (const char *text)
215 {
216         size_t l = strlen(text);
217         Cbuf_LockThreadMutex();
218         // we need to memmove the existing text and stuff this in before it...
219         if (cmd_text.cursize + l >= (size_t)cmd_text.maxsize)
220                 Con_Print("Cbuf_InsertText: overflow\n");
221         else
222         {
223                 // we don't have a SZ_Prepend, so...
224                 memmove(cmd_text.data + l, cmd_text.data, cmd_text.cursize);
225                 cmd_text.cursize += l;
226                 memcpy(cmd_text.data, text, l);
227         }
228         Cbuf_UnlockThreadMutex();
229 }
230
231 /*
232 ============
233 Cbuf_Execute_Deferred --blub
234 ============
235 */
236 static void Cbuf_Execute_Deferred (void)
237 {
238         static double oldrealtime = 0;
239         cmddeferred_t *cmd, *prev;
240         double eat;
241         if (realtime - oldrealtime < 0 || realtime - oldrealtime > 1800) oldrealtime = realtime;
242         eat = realtime - oldrealtime;
243         if (eat < (1.0 / 120.0))
244                 return;
245         oldrealtime = realtime;
246         prev = NULL;
247         cmd = cmd_deferred_list;
248         while(cmd)
249         {
250                 cmd->delay -= eat;
251                 if(cmd->delay <= 0)
252                 {
253                         Cbuf_AddText(cmd->value);
254                         Cbuf_AddText(";\n");
255                         Mem_Free(cmd->value);
256
257                         if(prev) {
258                                 prev->next = cmd->next;
259                                 Mem_Free(cmd);
260                                 cmd = prev->next;
261                         } else {
262                                 cmd_deferred_list = cmd->next;
263                                 Mem_Free(cmd);
264                                 cmd = cmd_deferred_list;
265                         }
266                         continue;
267                 }
268                 prev = cmd;
269                 cmd = cmd->next;
270         }
271 }
272
273 /*
274 ============
275 Cbuf_Execute
276 ============
277 */
278 static qboolean Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias );
279 void Cbuf_Execute (void)
280 {
281         int i;
282         char *text;
283         char line[MAX_INPUTLINE];
284         char preprocessed[MAX_INPUTLINE];
285         char *firstchar;
286         qboolean quotes;
287         char *comment;
288
289         // LordHavoc: making sure the tokenizebuffer doesn't get filled up by repeated crashes
290         cmd_tokenizebufferpos = 0;
291
292         while (cmd_text.cursize)
293         {
294 // find a \n or ; line break
295                 text = (char *)cmd_text.data;
296
297                 quotes = false;
298                 comment = NULL;
299                 for (i=0 ; i < cmd_text.cursize ; i++)
300                 {
301                         if(!comment)
302                         {
303                                 if (text[i] == '"')
304                                         quotes = !quotes;
305
306                                 if(quotes)
307                                 {
308                                         // make sure i doesn't get > cursize which causes a negative
309                                         // size in memmove, which is fatal --blub
310                                         if (i < (cmd_text.cursize-1) && (text[i] == '\\' && (text[i+1] == '"' || text[i+1] == '\\')))
311                                                 i++;
312                                 }
313                                 else
314                                 {
315                                         if(text[i] == '/' && text[i + 1] == '/' && (i == 0 || ISWHITESPACE(text[i-1])))
316                                                 comment = &text[i];
317                                         if(text[i] == ';')
318                                                 break;  // don't break if inside a quoted string or comment
319                                 }
320                         }
321
322                         if (text[i] == '\r' || text[i] == '\n')
323                                 break;
324                 }
325
326                 // better than CRASHING on overlong input lines that may SOMEHOW enter the buffer
327                 if(i >= MAX_INPUTLINE)
328                 {
329                         Con_Printf("Warning: console input buffer had an overlong line. Ignored.\n");
330                         line[0] = 0;
331                 }
332                 else
333                 {
334                         memcpy (line, text, comment ? (comment - text) : i);
335                         line[comment ? (comment - text) : i] = 0;
336                 }
337
338 // delete the text from the command buffer and move remaining commands down
339 // this is necessary because commands (exec, alias) can insert data at the
340 // beginning of the text buffer
341
342                 if (i == cmd_text.cursize)
343                         cmd_text.cursize = 0;
344                 else
345                 {
346                         i++;
347                         cmd_text.cursize -= i;
348                         memmove (cmd_text.data, text+i, cmd_text.cursize);
349                 }
350
351 // execute the command line
352                 firstchar = line;
353                 while(*firstchar && ISWHITESPACE(*firstchar))
354                         ++firstchar;
355                 if(
356                         (strncmp(firstchar, "alias", 5) || !ISWHITESPACE(firstchar[5]))
357                         &&
358                         (strncmp(firstchar, "bind", 4) || !ISWHITESPACE(firstchar[4]))
359                         &&
360                         (strncmp(firstchar, "in_bind", 7) || !ISWHITESPACE(firstchar[7]))
361                 )
362                 {
363                         if(Cmd_PreprocessString( line, preprocessed, sizeof(preprocessed), NULL ))
364                                 Cmd_ExecuteString (preprocessed, src_command, false);
365                 }
366                 else
367                 {
368                         Cmd_ExecuteString (line, src_command, false);
369                 }
370
371                 if (cmd_wait)
372                 {       // skip out while text still remains in buffer, leaving it
373                         // for next frame
374                         cmd_wait = false;
375                         break;
376                 }
377         }
378 }
379
380 void Cbuf_Frame(void)
381 {
382         Cbuf_Execute_Deferred();
383         if (cmd_text.cursize)
384         {
385                 SV_LockThreadMutex();
386                 Cbuf_Execute();
387                 SV_UnlockThreadMutex();
388         }
389 }
390
391 /*
392 ==============================================================================
393
394                                                 SCRIPT COMMANDS
395
396 ==============================================================================
397 */
398
399 /*
400 ===============
401 Cmd_StuffCmds_f
402
403 Adds command line parameters as script statements
404 Commands lead with a +, and continue until a - or another +
405 quake +prog jctest.qp +cmd amlev1
406 quake -nosound +cmd amlev1
407 ===============
408 */
409 qboolean host_stuffcmdsrun = false;
410 static void Cmd_StuffCmds_f (void)
411 {
412         int             i, j, l;
413         // this is for all commandline options combined (and is bounds checked)
414         char    build[MAX_INPUTLINE];
415
416         if (Cmd_Argc () != 1)
417         {
418                 Con_Print("stuffcmds : execute command line parameters\n");
419                 return;
420         }
421
422         // no reason to run the commandline arguments twice
423         if (host_stuffcmdsrun)
424                 return;
425
426         host_stuffcmdsrun = true;
427         build[0] = 0;
428         l = 0;
429         for (i = 0;i < com_argc;i++)
430         {
431                 if (com_argv[i] && com_argv[i][0] == '+' && (com_argv[i][1] < '0' || com_argv[i][1] > '9') && l + strlen(com_argv[i]) - 1 <= sizeof(build) - 1)
432                 {
433                         j = 1;
434                         while (com_argv[i][j])
435                                 build[l++] = com_argv[i][j++];
436                         i++;
437                         for (;i < com_argc;i++)
438                         {
439                                 if (!com_argv[i])
440                                         continue;
441                                 if ((com_argv[i][0] == '+' || com_argv[i][0] == '-') && (com_argv[i][1] < '0' || com_argv[i][1] > '9'))
442                                         break;
443                                 if (l + strlen(com_argv[i]) + 4 > sizeof(build) - 1)
444                                         break;
445                                 build[l++] = ' ';
446                                 if (strchr(com_argv[i], ' '))
447                                         build[l++] = '\"';
448                                 for (j = 0;com_argv[i][j];j++)
449                                         build[l++] = com_argv[i][j];
450                                 if (strchr(com_argv[i], ' '))
451                                         build[l++] = '\"';
452                         }
453                         build[l++] = '\n';
454                         i--;
455                 }
456         }
457         // now terminate the combined string and prepend it to the command buffer
458         // we already reserved space for the terminator
459         build[l++] = 0;
460         Cbuf_InsertText (build);
461 }
462
463 static void Cmd_Exec(const char *filename)
464 {
465         char *f;
466         qboolean isdefaultcfg = strlen(filename) >= 11 && !strcmp(filename + strlen(filename) - 11, "default.cfg");
467
468         if (!strcmp(filename, "config.cfg"))
469         {
470                 filename = CONFIGFILENAME;
471                 if (COM_CheckParm("-noconfig"))
472                         return; // don't execute config.cfg
473         }
474
475         f = (char *)FS_LoadFile (filename, tempmempool, false, NULL);
476         if (!f)
477         {
478                 Con_Printf("couldn't exec %s\n",filename);
479                 return;
480         }
481         Con_Printf("execing %s\n",filename);
482
483         // if executing default.cfg for the first time, lock the cvar defaults
484         // it may seem backwards to insert this text BEFORE the default.cfg
485         // but Cbuf_InsertText inserts before, so this actually ends up after it.
486         if (isdefaultcfg)
487                 Cbuf_InsertText("\ncvar_lockdefaults\n");
488
489         // insert newline after the text to make sure the last line is terminated (some text editors omit the trailing newline)
490         // (note: insertion order here is backwards from execution order, so this adds it after the text, by calling it before...)
491         Cbuf_InsertText ("\n");
492         Cbuf_InsertText (f);
493         Mem_Free(f);
494
495         if (isdefaultcfg)
496         {
497                 // special defaults for specific games go here, these execute before default.cfg
498                 // Nehahra pushable crates malfunction in some levels if this is on
499                 // Nehahra NPC AI is confused by blowupfallenzombies
500                 if (gamemode == GAME_NEHAHRA)
501                         Cbuf_InsertText("\nsv_gameplayfix_upwardvelocityclearsongroundflag 0\nsv_gameplayfix_blowupfallenzombies 0\n\n");
502                 // hipnotic mission pack has issues in their 'friendly monster' ai, which seem to attempt to attack themselves for some reason when findradius() returns non-solid entities.
503                 // hipnotic mission pack has issues with bobbing water entities 'jittering' between different heights on alternate frames at the default 0.0138889 ticrate, 0.02 avoids this issue
504                 // hipnotic mission pack has issues in their proximity mine sticking code, which causes them to bounce off.
505                 if (gamemode == GAME_HIPNOTIC)
506                         Cbuf_InsertText("\nsv_gameplayfix_blowupfallenzombies 0\nsys_ticrate 0.02\nsv_gameplayfix_slidemoveprojectiles 0\n\n");
507                 // rogue mission pack has a guardian boss that does not wake up if findradius returns one of the entities around its spawn area
508                 if (gamemode == GAME_ROGUE)
509                         Cbuf_InsertText("\nsv_gameplayfix_findradiusdistancetobox 0\n\n");
510                 if (gamemode == GAME_NEXUIZ)
511                         Cbuf_InsertText("\nsv_gameplayfix_q2airaccelerate 1\nsv_gameplayfix_stepmultipletimes 1\n\n");
512                 if (gamemode == GAME_TENEBRAE)
513                         Cbuf_InsertText("\nr_shadow_gloss 2\nr_shadow_bumpscale_basetexture 4\n\n");
514                 // Steel Storm: Burning Retribution csqc misinterprets CSQC_InputEvent if type is a value other than 0 or 1
515                 if (gamemode == GAME_STEELSTORM)
516                         Cbuf_InsertText("\ncl_csqc_generatemousemoveevents 0\n\n");
517         }
518 }
519
520 /*
521 ===============
522 Cmd_Exec_f
523 ===============
524 */
525 static void Cmd_Exec_f (void)
526 {
527         fssearch_t *s;
528         int i;
529
530         if (Cmd_Argc () != 2)
531         {
532                 Con_Print("exec <filename> : execute a script file\n");
533                 return;
534         }
535
536         s = FS_Search(Cmd_Argv(1), true, true);
537         if(!s || !s->numfilenames)
538         {
539                 Con_Printf("couldn't exec %s\n",Cmd_Argv(1));
540                 return;
541         }
542
543         for(i = 0; i < s->numfilenames; ++i)
544                 Cmd_Exec(s->filenames[i]);
545
546         FS_FreeSearch(s);
547 }
548
549
550 /*
551 ===============
552 Cmd_Echo_f
553
554 Just prints the rest of the line to the console
555 ===============
556 */
557 static void Cmd_Echo_f (void)
558 {
559         int             i;
560
561         for (i=1 ; i<Cmd_Argc() ; i++)
562                 Con_Printf("%s ",Cmd_Argv(i));
563         Con_Print("\n");
564 }
565
566 // DRESK - 5/14/06
567 // Support Doom3-style Toggle Console Command
568 /*
569 ===============
570 Cmd_Toggle_f
571
572 Toggles a specified console variable amongst the values specified (default is 0 and 1)
573 ===============
574 */
575 static void Cmd_Toggle_f(void)
576 {
577         // Acquire Number of Arguments
578         int nNumArgs = Cmd_Argc();
579
580         if(nNumArgs == 1)
581                 // No Arguments Specified; Print Usage
582                 Con_Print("Toggle Console Variable - Usage\n  toggle <variable> - toggles between 0 and 1\n  toggle <variable> <value> - toggles between 0 and <value>\n  toggle <variable> [string 1] [string 2]...[string n] - cycles through all strings\n");
583         else
584         { // Correct Arguments Specified
585                 // Acquire Potential CVar
586                 cvar_t* cvCVar = Cvar_FindVar( Cmd_Argv(1) );
587
588                 if(cvCVar != NULL)
589                 { // Valid CVar
590                         if(nNumArgs == 2)
591                         { // Default Usage
592                                 if(cvCVar->integer)
593                                         Cvar_SetValueQuick(cvCVar, 0);
594                                 else
595                                         Cvar_SetValueQuick(cvCVar, 1);
596                         }
597                         else
598                         if(nNumArgs == 3)
599                         { // 0 and Specified Usage
600                                 if(cvCVar->integer == atoi(Cmd_Argv(2) ) )
601                                         // CVar is Specified Value; // Reset to 0
602                                         Cvar_SetValueQuick(cvCVar, 0);
603                                 else
604                                 if(cvCVar->integer == 0)
605                                         // CVar is 0; Specify Value
606                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
607                                 else
608                                         // CVar does not match; Reset to 0
609                                         Cvar_SetValueQuick(cvCVar, 0);
610                         }
611                         else
612                         { // Variable Values Specified
613                                 int nCnt;
614                                 int bFound = 0;
615
616                                 for(nCnt = 2; nCnt < nNumArgs; nCnt++)
617                                 { // Cycle through Values
618                                         if( strcmp(cvCVar->string, Cmd_Argv(nCnt) ) == 0)
619                                         { // Current Value Located; Increment to Next
620                                                 if( (nCnt + 1) == nNumArgs)
621                                                         // Max Value Reached; Reset
622                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
623                                                 else
624                                                         // Next Value
625                                                         Cvar_SetQuick(cvCVar, Cmd_Argv(nCnt + 1) );
626
627                                                 // End Loop
628                                                 nCnt = nNumArgs;
629                                                 // Assign Found
630                                                 bFound = 1;
631                                         }
632                                 }
633                                 if(!bFound)
634                                         // Value not Found; Reset to Original
635                                         Cvar_SetQuick(cvCVar, Cmd_Argv(2) );
636                         }
637
638                 }
639                 else
640                 { // Invalid CVar
641                         Con_Printf("ERROR : CVar '%s' not found\n", Cmd_Argv(1) );
642                 }
643         }
644 }
645
646 /*
647 ===============
648 Cmd_Alias_f
649
650 Creates a new command that executes a command string (possibly ; seperated)
651 ===============
652 */
653 static void Cmd_Alias_f (void)
654 {
655         cmdalias_t      *a;
656         char            cmd[MAX_INPUTLINE];
657         int                     i, c;
658         const char              *s;
659         size_t          alloclen;
660
661         if (Cmd_Argc() == 1)
662         {
663                 Con_Print("Current alias commands:\n");
664                 for (a = cmd_alias ; a ; a=a->next)
665                         Con_Printf("%s : %s", a->name, a->value);
666                 return;
667         }
668
669         s = Cmd_Argv(1);
670         if (strlen(s) >= MAX_ALIAS_NAME)
671         {
672                 Con_Print("Alias name is too long\n");
673                 return;
674         }
675
676         // if the alias already exists, reuse it
677         for (a = cmd_alias ; a ; a=a->next)
678         {
679                 if (!strcmp(s, a->name))
680                 {
681                         Z_Free (a->value);
682                         break;
683                 }
684         }
685
686         if (!a)
687         {
688                 cmdalias_t *prev, *current;
689
690                 a = (cmdalias_t *)Z_Malloc (sizeof(cmdalias_t));
691                 strlcpy (a->name, s, sizeof (a->name));
692                 // insert it at the right alphanumeric position
693                 for( prev = NULL, current = cmd_alias ; current && strcmp( current->name, a->name ) < 0 ; prev = current, current = current->next )
694                         ;
695                 if( prev ) {
696                         prev->next = a;
697                 } else {
698                         cmd_alias = a;
699                 }
700                 a->next = current;
701         }
702
703
704 // copy the rest of the command line
705         cmd[0] = 0;             // start out with a null string
706         c = Cmd_Argc();
707         for (i=2 ; i < c ; i++)
708         {
709                 if (i != 2)
710                         strlcat (cmd, " ", sizeof (cmd));
711                 strlcat (cmd, Cmd_Argv(i), sizeof (cmd));
712         }
713         strlcat (cmd, "\n", sizeof (cmd));
714
715         alloclen = strlen (cmd) + 1;
716         if(alloclen >= 2)
717                 cmd[alloclen - 2] = '\n'; // to make sure a newline is appended even if too long
718         a->value = (char *)Z_Malloc (alloclen);
719         memcpy (a->value, cmd, alloclen);
720 }
721
722 /*
723 ===============
724 Cmd_UnAlias_f
725
726 Remove existing aliases.
727 ===============
728 */
729 static void Cmd_UnAlias_f (void)
730 {
731         cmdalias_t      *a, *p;
732         int i;
733         const char *s;
734
735         if(Cmd_Argc() == 1)
736         {
737                 Con_Print("unalias: Usage: unalias alias1 [alias2 ...]\n");
738                 return;
739         }
740
741         for(i = 1; i < Cmd_Argc(); ++i)
742         {
743                 s = Cmd_Argv(i);
744                 p = NULL;
745                 for(a = cmd_alias; a; p = a, a = a->next)
746                 {
747                         if(!strcmp(s, a->name))
748                         {
749                                 if (a->initstate) // we can not remove init aliases
750                                         continue;
751                                 if(a == cmd_alias)
752                                         cmd_alias = a->next;
753                                 if(p)
754                                         p->next = a->next;
755                                 Z_Free(a->value);
756                                 Z_Free(a);
757                                 break;
758                         }
759                 }
760                 if(!a)
761                         Con_Printf("unalias: %s alias not found\n", s);
762         }
763 }
764
765 /*
766 =============================================================================
767
768                                         COMMAND EXECUTION
769
770 =============================================================================
771 */
772
773 typedef struct cmd_function_s
774 {
775         struct cmd_function_s *next;
776         const char *name;
777         const char *description;
778         xcommand_t consolefunction;
779         xcommand_t clientfunction;
780         qboolean csqcfunc;
781         qboolean initstate; // indicates this command existed at init
782 } cmd_function_t;
783
784 static int cmd_argc;
785 static const char *cmd_argv[MAX_ARGS];
786 static const char *cmd_null_string = "";
787 static const char *cmd_args;
788 cmd_source_t cmd_source;
789
790
791 static cmd_function_t *cmd_functions;           // possible commands to execute
792
793 static const char *Cmd_GetDirectCvarValue(const char *varname, cmdalias_t *alias, qboolean *is_multiple)
794 {
795         cvar_t *cvar;
796         long argno;
797         char *endptr;
798         char vabuf[1024];
799
800         if(is_multiple)
801                 *is_multiple = false;
802
803         if(!varname || !*varname)
804                 return NULL;
805
806         if(alias)
807         {
808                 if(!strcmp(varname, "*"))
809                 {
810                         if(is_multiple)
811                                 *is_multiple = true;
812                         return Cmd_Args();
813                 }
814                 else if(!strcmp(varname, "#"))
815                 {
816                         return va(vabuf, sizeof(vabuf), "%d", Cmd_Argc());
817                 }
818                 else if(varname[strlen(varname) - 1] == '-')
819                 {
820                         argno = strtol(varname, &endptr, 10);
821                         if(endptr == varname + strlen(varname) - 1)
822                         {
823                                 // whole string is a number, apart from the -
824                                 const char *p = Cmd_Args();
825                                 for(; argno > 1; --argno)
826                                         if(!COM_ParseToken_Console(&p))
827                                                 break;
828                                 if(p)
829                                 {
830                                         if(is_multiple)
831                                                 *is_multiple = true;
832
833                                         // kill pre-argument whitespace
834                                         for (;*p && ISWHITESPACE(*p);p++)
835                                                 ;
836
837                                         return p;
838                                 }
839                         }
840                 }
841                 else
842                 {
843                         argno = strtol(varname, &endptr, 10);
844                         if(*endptr == 0)
845                         {
846                                 // whole string is a number
847                                 // NOTE: we already made sure we don't have an empty cvar name!
848                                 if(argno >= 0 && argno < Cmd_Argc())
849                                         return Cmd_Argv(argno);
850                         }
851                 }
852         }
853
854         if((cvar = Cvar_FindVar(varname)) && !(cvar->flags & CVAR_PRIVATE))
855                 return cvar->string;
856
857         return NULL;
858 }
859
860 qboolean Cmd_QuoteString(char *out, size_t outlen, const char *in, const char *quoteset, qboolean putquotes)
861 {
862         qboolean quote_quot = !!strchr(quoteset, '"');
863         qboolean quote_backslash = !!strchr(quoteset, '\\');
864         qboolean quote_dollar = !!strchr(quoteset, '$');
865
866         if(putquotes)
867         {
868                 if(outlen <= 2)
869                 {
870                         *out++ = 0;
871                         return false;
872                 }
873                 *out++ = '"'; --outlen;
874                 --outlen;
875         }
876
877         while(*in)
878         {
879                 if(*in == '"' && quote_quot)
880                 {
881                         if(outlen <= 2)
882                                 goto fail;
883                         *out++ = '\\'; --outlen;
884                         *out++ = '"'; --outlen;
885                 }
886                 else if(*in == '\\' && quote_backslash)
887                 {
888                         if(outlen <= 2)
889                                 goto fail;
890                         *out++ = '\\'; --outlen;
891                         *out++ = '\\'; --outlen;
892                 }
893                 else if(*in == '$' && quote_dollar)
894                 {
895                         if(outlen <= 2)
896                                 goto fail;
897                         *out++ = '$'; --outlen;
898                         *out++ = '$'; --outlen;
899                 }
900                 else
901                 {
902                         if(outlen <= 1)
903                                 goto fail;
904                         *out++ = *in; --outlen;
905                 }
906                 ++in;
907         }
908         if(putquotes)
909                 *out++ = '"';
910         *out++ = 0;
911         return true;
912 fail:
913         if(putquotes)
914                 *out++ = '"';
915         *out++ = 0;
916         return false;
917 }
918
919 static const char *Cmd_GetCvarValue(const char *var, size_t varlen, cmdalias_t *alias)
920 {
921         static char varname[MAX_INPUTLINE]; // cmd_mutex
922         static char varval[MAX_INPUTLINE]; // cmd_mutex
923         const char *varstr = NULL;
924         char *varfunc;
925         qboolean required = false;
926         qboolean optional = false;
927         static char asis[] = "asis"; // just to suppress const char warnings
928
929         if(varlen >= MAX_INPUTLINE)
930                 varlen = MAX_INPUTLINE - 1;
931         memcpy(varname, var, varlen);
932         varname[varlen] = 0;
933         varfunc = strchr(varname, ' ');
934
935         if(varfunc)
936         {
937                 *varfunc = 0;
938                 ++varfunc;
939         }
940
941         if(*var == 0)
942         {
943                 // empty cvar name?
944                 if(alias)
945                         Con_Printf("Warning: Could not expand $ in alias %s\n", alias->name);
946                 else
947                         Con_Printf("Warning: Could not expand $\n");
948                 return "$";
949         }
950
951         if(varfunc)
952         {
953                 char *p;
954                 // ? means optional
955                 while((p = strchr(varfunc, '?')))
956                 {
957                         optional = true;
958                         memmove(p, p+1, strlen(p)); // with final NUL
959                 }
960                 // ! means required
961                 while((p = strchr(varfunc, '!')))
962                 {
963                         required = true;
964                         memmove(p, p+1, strlen(p)); // with final NUL
965                 }
966                 // kill spaces
967                 while((p = strchr(varfunc, ' ')))
968                 {
969                         memmove(p, p+1, strlen(p)); // with final NUL
970                 }
971         }
972
973         if(varname[0] == '$')
974                 varstr = Cmd_GetDirectCvarValue(Cmd_GetDirectCvarValue(varname + 1, alias, NULL), alias, NULL);
975         else
976         {
977                 qboolean is_multiple = false;
978                 // Exception: $* and $n- don't use the quoted form by default
979                 varstr = Cmd_GetDirectCvarValue(varname, alias, &is_multiple);
980                 if(is_multiple)
981                         if(!varfunc)
982                                 varfunc = asis;
983         }
984
985         if(!varstr)
986         {
987                 if(required)
988                 {
989                         if(alias)
990                                 Con_Printf("Error: Could not expand $%s in alias %s\n", varname, alias->name);
991                         else
992                                 Con_Printf("Error: Could not expand $%s\n", varname);
993                         return NULL;
994                 }
995                 else if(optional)
996                 {
997                         return "";
998                 }
999                 else
1000                 {
1001                         if(alias)
1002                                 Con_Printf("Warning: Could not expand $%s in alias %s\n", varname, alias->name);
1003                         else
1004                                 Con_Printf("Warning: Could not expand $%s\n", varname);
1005                         dpsnprintf(varval, sizeof(varval), "$%s", varname);
1006                         return varval;
1007                 }
1008         }
1009
1010         if(!varfunc || !strcmp(varfunc, "q")) // note: quoted form is default, use "asis" to override!
1011         {
1012                 // quote it so it can be used inside double quotes
1013                 // we just need to replace " by \", and of course, double backslashes
1014                 Cmd_QuoteString(varval, sizeof(varval), varstr, "\"\\", false);
1015                 return varval;
1016         }
1017         else if(!strcmp(varfunc, "asis"))
1018         {
1019                 return varstr;
1020         }
1021         else
1022                 Con_Printf("Unknown variable function %s\n", varfunc);
1023
1024         return varstr;
1025 }
1026
1027 /*
1028 Cmd_PreprocessString
1029
1030 Preprocesses strings and replaces $*, $param#, $cvar accordingly. Also strips comments.
1031 */
1032 static qboolean Cmd_PreprocessString( const char *intext, char *outtext, unsigned maxoutlen, cmdalias_t *alias ) {
1033         const char *in;
1034         size_t eat, varlen;
1035         unsigned outlen;
1036         const char *val;
1037
1038         // don't crash if there's no room in the outtext buffer
1039         if( maxoutlen == 0 ) {
1040                 return false;
1041         }
1042         maxoutlen--; // because of \0
1043
1044         in = intext;
1045         outlen = 0;
1046
1047         while( *in && outlen < maxoutlen ) {
1048                 if( *in == '$' ) {
1049                         // this is some kind of expansion, see what comes after the $
1050                         in++;
1051
1052                         // The console does the following preprocessing:
1053                         //
1054                         // - $$ is transformed to a single dollar sign.
1055                         // - $var or ${var} are expanded to the contents of the named cvar,
1056                         //   with quotation marks and backslashes quoted so it can safely
1057                         //   be used inside quotation marks (and it should always be used
1058                         //   that way)
1059                         // - ${var asis} inserts the cvar value as is, without doing this
1060                         //   quoting
1061                         // - ${var ?} silently expands to the empty string if
1062                         //   $var does not exist
1063                         // - ${var !} fails expansion and executes nothing if
1064                         //   $var does not exist
1065                         // - prefix the cvar name with a dollar sign to do indirection;
1066                         //   for example, if $x has the value timelimit, ${$x} will return
1067                         //   the value of $timelimit
1068                         // - when expanding an alias, the special variable name $* refers
1069                         //   to all alias parameters, and a number refers to that numbered
1070                         //   alias parameter, where the name of the alias is $0, the first
1071                         //   parameter is $1 and so on; as a special case, $* inserts all
1072                         //   parameters, without extra quoting, so one can use $* to just
1073                         //   pass all parameters around. All parameters starting from $n
1074                         //   can be referred to as $n- (so $* is equivalent to $1-).
1075                         // - ${* q} and ${n- q} force quoting anyway
1076                         //
1077                         // Note: when expanding an alias, cvar expansion is done in the SAME step
1078                         // as alias expansion so that alias parameters or cvar values containing
1079                         // dollar signs have no unwanted bad side effects. However, this needs to
1080                         // be accounted for when writing complex aliases. For example,
1081                         //   alias foo "set x NEW; echo $x"
1082                         // actually expands to
1083                         //   "set x NEW; echo OLD"
1084                         // and will print OLD! To work around this, use a second alias:
1085                         //   alias foo "set x NEW; foo2"
1086                         //   alias foo2 "echo $x"
1087                         //
1088                         // Also note: lines starting with alias are exempt from cvar expansion.
1089                         // If you want cvar expansion, write "alias" instead:
1090                         //
1091                         //   set x 1
1092                         //   alias foo "echo $x"
1093                         //   "alias" bar "echo $x"
1094                         //   set x 2
1095                         //
1096                         // foo will print 2, because the variable $x will be expanded when the alias
1097                         // gets expanded. bar will print 1, because the variable $x was expanded
1098                         // at definition time. foo can be equivalently defined as
1099                         //
1100                         //   "alias" foo "echo $$x"
1101                         //
1102                         // because at definition time, $$ will get replaced to a single $.
1103
1104                         if( *in == '$' ) {
1105                                 val = "$";
1106                                 eat = 1;
1107                         } else if(*in == '{') {
1108                                 varlen = strcspn(in + 1, "}");
1109                                 if(in[varlen + 1] == '}')
1110                                 {
1111                                         val = Cmd_GetCvarValue(in + 1, varlen, alias);
1112                                         if(!val)
1113                                                 return false;
1114                                         eat = varlen + 2;
1115                                 }
1116                                 else
1117                                 {
1118                                         // ran out of data?
1119                                         val = NULL;
1120                                         eat = varlen + 1;
1121                                 }
1122                         } else {
1123                                 varlen = strspn(in, "#*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
1124                                 val = Cmd_GetCvarValue(in, varlen, alias);
1125                                 if(!val)
1126                                         return false;
1127                                 eat = varlen;
1128                         }
1129                         if(val)
1130                         {
1131                                 // insert the cvar value
1132                                 while(*val && outlen < maxoutlen)
1133                                         outtext[outlen++] = *val++;
1134                                 in += eat;
1135                         }
1136                         else
1137                         {
1138                                 // copy the unexpanded text
1139                                 outtext[outlen++] = '$';
1140                                 while(eat && outlen < maxoutlen)
1141                                 {
1142                                         outtext[outlen++] = *in++;
1143                                         --eat;
1144                                 }
1145                         }
1146                 }
1147                 else 
1148                         outtext[outlen++] = *in++;
1149         }
1150         outtext[outlen] = 0;
1151         return true;
1152 }
1153
1154 /*
1155 ============
1156 Cmd_ExecuteAlias
1157
1158 Called for aliases and fills in the alias into the cbuffer
1159 ============
1160 */
1161 static void Cmd_ExecuteAlias (cmdalias_t *alias)
1162 {
1163         static char buffer[ MAX_INPUTLINE ]; // cmd_mutex
1164         static char buffer2[ MAX_INPUTLINE ]; // cmd_mutex
1165         qboolean ret = Cmd_PreprocessString( alias->value, buffer, sizeof(buffer) - 2, alias );
1166         if(!ret)
1167                 return;
1168         // insert at start of command buffer, so that aliases execute in order
1169         // (fixes bug introduced by Black on 20050705)
1170
1171         // Note: Cbuf_PreprocessString will be called on this string AGAIN! So we
1172         // have to make sure that no second variable expansion takes place, otherwise
1173         // alias parameters containing dollar signs can have bad effects.
1174         Cmd_QuoteString(buffer2, sizeof(buffer2), buffer, "$", false);
1175         Cbuf_InsertText( buffer2 );
1176 }
1177
1178 /*
1179 ========
1180 Cmd_List
1181
1182         CmdList Added by EvilTypeGuy eviltypeguy@qeradiant.com
1183         Thanks to Matthias "Maddes" Buecher, http://www.inside3d.com/qip/
1184
1185 ========
1186 */
1187 static void Cmd_List_f (void)
1188 {
1189         cmd_function_t *cmd;
1190         const char *partial;
1191         size_t len;
1192         int count;
1193         qboolean ispattern;
1194
1195         if (Cmd_Argc() > 1)
1196         {
1197                 partial = Cmd_Argv (1);
1198                 len = strlen(partial);
1199         }
1200         else
1201         {
1202                 partial = NULL;
1203                 len = 0;
1204         }
1205
1206         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1207
1208         count = 0;
1209         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1210         {
1211                 if (partial && (ispattern ? !matchpattern_with_separator(cmd->name, partial, false, "", false) : strncmp(partial, cmd->name, len)))
1212                         continue;
1213                 Con_Printf("%s : %s\n", cmd->name, cmd->description);
1214                 count++;
1215         }
1216
1217         if (len)
1218         {
1219                 if(ispattern)
1220                         Con_Printf("%i Command%s matching \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1221                 else
1222                         Con_Printf("%i Command%s beginning with \"%s\"\n\n", count, (count > 1) ? "s" : "", partial);
1223         }
1224         else
1225                 Con_Printf("%i Command%s\n\n", count, (count > 1) ? "s" : "");
1226 }
1227
1228 static void Cmd_Apropos_f(void)
1229 {
1230         cmd_function_t *cmd;
1231         cvar_t *cvar;
1232         cmdalias_t *alias;
1233         const char *partial;
1234         int count;
1235         qboolean ispattern;
1236         char vabuf[1024];
1237
1238         if (Cmd_Argc() > 1)
1239                 partial = Cmd_Args();
1240         else
1241         {
1242                 Con_Printf("usage: apropos <string>\n");
1243                 return;
1244         }
1245
1246         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
1247         if(!ispattern)
1248                 partial = va(vabuf, sizeof(vabuf), "*%s*", partial);
1249
1250         count = 0;
1251         for (cvar = cvar_vars; cvar; cvar = cvar->next)
1252         {
1253                 if (!matchpattern_with_separator(cvar->name, partial, true, "", false))
1254                 if (!matchpattern_with_separator(cvar->description, partial, true, "", false))
1255                         continue;
1256                 Con_Printf ("cvar ^3%s^7 is \"%s\" [\"%s\"] %s\n", cvar->name, cvar->string, cvar->defstring, cvar->description);
1257                 count++;
1258         }
1259         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1260         {
1261                 if (!matchpattern_with_separator(cmd->name, partial, true, "", false))
1262                 if (!matchpattern_with_separator(cmd->description, partial, true, "", false))
1263                         continue;
1264                 Con_Printf("command ^2%s^7: %s\n", cmd->name, cmd->description);
1265                 count++;
1266         }
1267         for (alias = cmd_alias; alias; alias = alias->next)
1268         {
1269                 // procede here a bit differently as an alias value always got a final \n
1270                 if (!matchpattern_with_separator(alias->name, partial, true, "", false))
1271                 if (!matchpattern_with_separator(alias->value, partial, true, "\n", false)) // when \n is as separator wildcards don't match it
1272                         continue;
1273                 Con_Printf("alias ^5%s^7: %s", alias->name, alias->value); // do not print an extra \n
1274                 count++;
1275         }
1276         Con_Printf("%i result%s\n\n", count, (count > 1) ? "s" : "");
1277 }
1278
1279 /*
1280 ============
1281 Cmd_Init
1282 ============
1283 */
1284 void Cmd_Init (void)
1285 {
1286         cmd_mempool = Mem_AllocPool("commands", 0, NULL);
1287         // space for commands and script files
1288         cmd_text.data = cmd_text_buf;
1289         cmd_text.maxsize = sizeof(cmd_text_buf);
1290         cmd_text.cursize = 0;
1291
1292         if (Thread_HasThreads())
1293                 cmd_text_mutex = Thread_CreateMutex();
1294 }
1295
1296 void Cmd_Init_Commands (void)
1297 {
1298 //
1299 // register our commands
1300 //
1301         Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f, "execute commandline parameters (must be present in quake.rc script)");
1302         Cmd_AddCommand ("exec",Cmd_Exec_f, "execute a script file");
1303         Cmd_AddCommand ("echo",Cmd_Echo_f, "print a message to the console (useful in scripts)");
1304         Cmd_AddCommand ("alias",Cmd_Alias_f, "create a script function (parameters are passed in as $X (being X a number), $* for all parameters, $X- for all parameters starting from $X). Without arguments show the list of all alias");
1305         Cmd_AddCommand ("unalias",Cmd_UnAlias_f, "remove an alias");
1306         Cmd_AddCommand ("cmd", Cmd_ForwardToServer, "send a console commandline to the server (used by some mods)");
1307         Cmd_AddCommand ("wait", Cmd_Wait_f, "make script execution wait for next rendered frame");
1308         Cmd_AddCommand ("set", Cvar_Set_f, "create or change the value of a console variable");
1309         Cmd_AddCommand ("seta", Cvar_SetA_f, "create or change the value of a console variable that will be saved to config.cfg");
1310         Cmd_AddCommand ("unset", Cvar_Del_f, "delete a cvar (does not work for static ones like _cl_name, or read-only ones)");
1311 #ifdef FILLALLCVARSWITHRUBBISH
1312         Cmd_AddCommand ("fillallcvarswithrubbish", Cvar_FillAll_f, "fill all cvars with a specified number of characters to provoke buffer overruns");
1313 #endif /* FILLALLCVARSWITHRUBBISH */
1314
1315         // 2000-01-09 CmdList, CvarList commands By Matthias "Maddes" Buecher
1316         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
1317         Cmd_AddCommand ("cmdlist", Cmd_List_f, "lists all console commands beginning with the specified prefix or matching the specified wildcard pattern");
1318         Cmd_AddCommand ("cvarlist", Cvar_List_f, "lists all console variables beginning with the specified prefix or matching the specified wildcard pattern");
1319         Cmd_AddCommand ("apropos", Cmd_Apropos_f, "lists all console variables/commands/aliases containing the specified string in the name or description");
1320
1321         Cmd_AddCommand ("cvar_lockdefaults", Cvar_LockDefaults_f, "stores the current values of all cvars into their default values, only used once during startup after parsing default.cfg");
1322         Cmd_AddCommand ("cvar_resettodefaults_all", Cvar_ResetToDefaults_All_f, "sets all cvars to their locked default values");
1323         Cmd_AddCommand ("cvar_resettodefaults_nosaveonly", Cvar_ResetToDefaults_NoSaveOnly_f, "sets all non-saved cvars to their locked default values (variables that will not be saved to config.cfg)");
1324         Cmd_AddCommand ("cvar_resettodefaults_saveonly", Cvar_ResetToDefaults_SaveOnly_f, "sets all saved cvars to their locked default values (variables that will be saved to config.cfg)");
1325
1326         Cmd_AddCommand ("cprint", Cmd_Centerprint_f, "print something at the screen center");
1327         Cmd_AddCommand ("defer", Cmd_Defer_f, "execute a command in the future");
1328
1329         // DRESK - 5/14/06
1330         // Support Doom3-style Toggle Command
1331         Cmd_AddCommand( "toggle", Cmd_Toggle_f, "toggles a console variable's values (use for more info)");
1332 }
1333
1334 /*
1335 ============
1336 Cmd_Shutdown
1337 ============
1338 */
1339 void Cmd_Shutdown(void)
1340 {
1341         if (cmd_text_mutex)
1342         {
1343                 // we usually have this locked when we get here from Host_Quit_f
1344                 Cbuf_UnlockThreadMutex();
1345                 Thread_DestroyMutex(cmd_text_mutex);
1346         }
1347         cmd_text_mutex = NULL;
1348
1349         Mem_FreePool(&cmd_mempool);
1350 }
1351
1352 /*
1353 ============
1354 Cmd_Argc
1355 ============
1356 */
1357 int             Cmd_Argc (void)
1358 {
1359         return cmd_argc;
1360 }
1361
1362 /*
1363 ============
1364 Cmd_Argv
1365 ============
1366 */
1367 const char *Cmd_Argv (int arg)
1368 {
1369         if (arg >= cmd_argc )
1370                 return cmd_null_string;
1371         return cmd_argv[arg];
1372 }
1373
1374 /*
1375 ============
1376 Cmd_Args
1377 ============
1378 */
1379 const char *Cmd_Args (void)
1380 {
1381         return cmd_args;
1382 }
1383
1384
1385 /*
1386 ============
1387 Cmd_TokenizeString
1388
1389 Parses the given string into command line tokens.
1390 ============
1391 */
1392 // AK: This function should only be called from ExcuteString because the current design is a bit of an hack
1393 static void Cmd_TokenizeString (const char *text)
1394 {
1395         int l;
1396
1397         cmd_argc = 0;
1398         cmd_args = NULL;
1399
1400         while (1)
1401         {
1402                 // skip whitespace up to a /n
1403                 while (*text && ISWHITESPACE(*text) && *text != '\r' && *text != '\n')
1404                         text++;
1405
1406                 // line endings:
1407                 // UNIX: \n
1408                 // Mac: \r
1409                 // Windows: \r\n
1410                 if (*text == '\n' || *text == '\r')
1411                 {
1412                         // a newline separates commands in the buffer
1413                         if (*text == '\r' && text[1] == '\n')
1414                                 text++;
1415                         text++;
1416                         break;
1417                 }
1418
1419                 if (!*text)
1420                         return;
1421
1422                 if (cmd_argc == 1)
1423                         cmd_args = text;
1424
1425                 if (!COM_ParseToken_Console(&text))
1426                         return;
1427
1428                 if (cmd_argc < MAX_ARGS)
1429                 {
1430                         l = (int)strlen(com_token) + 1;
1431                         if (cmd_tokenizebufferpos + l > CMD_TOKENIZELENGTH)
1432                         {
1433                                 Con_Printf("Cmd_TokenizeString: ran out of %i character buffer space for command arguements\n", CMD_TOKENIZELENGTH);
1434                                 break;
1435                         }
1436                         memcpy (cmd_tokenizebuffer + cmd_tokenizebufferpos, com_token, l);
1437                         cmd_argv[cmd_argc] = cmd_tokenizebuffer + cmd_tokenizebufferpos;
1438                         cmd_tokenizebufferpos += l;
1439                         cmd_argc++;
1440                 }
1441         }
1442 }
1443
1444
1445 /*
1446 ============
1447 Cmd_AddCommand
1448 ============
1449 */
1450 void Cmd_AddCommand_WithClientCommand (const char *cmd_name, xcommand_t consolefunction, xcommand_t clientfunction, const char *description)
1451 {
1452         cmd_function_t *cmd;
1453         cmd_function_t *prev, *current;
1454
1455 // fail if the command is a variable name
1456         if (Cvar_FindVar( cmd_name ))
1457         {
1458                 Con_Printf("Cmd_AddCommand: %s already defined as a var\n", cmd_name);
1459                 return;
1460         }
1461
1462 // fail if the command already exists
1463         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1464         {
1465                 if (!strcmp (cmd_name, cmd->name))
1466                 {
1467                         if (consolefunction || clientfunction)
1468                         {
1469                                 Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name);
1470                                 return;
1471                         }
1472                         else    //[515]: csqc
1473                         {
1474                                 cmd->csqcfunc = true;
1475                                 return;
1476                         }
1477                 }
1478         }
1479
1480         cmd = (cmd_function_t *)Mem_Alloc(cmd_mempool, sizeof(cmd_function_t));
1481         cmd->name = cmd_name;
1482         cmd->consolefunction = consolefunction;
1483         cmd->clientfunction = clientfunction;
1484         cmd->description = description;
1485         if(!consolefunction && !clientfunction)                 //[515]: csqc
1486                 cmd->csqcfunc = true;
1487         cmd->next = cmd_functions;
1488
1489 // insert it at the right alphanumeric position
1490         for( prev = NULL, current = cmd_functions ; current && strcmp( current->name, cmd->name ) < 0 ; prev = current, current = current->next )
1491                 ;
1492         if( prev ) {
1493                 prev->next = cmd;
1494         } else {
1495                 cmd_functions = cmd;
1496         }
1497         cmd->next = current;
1498 }
1499
1500 void Cmd_AddCommand (const char *cmd_name, xcommand_t function, const char *description)
1501 {
1502         Cmd_AddCommand_WithClientCommand (cmd_name, function, NULL, description);
1503 }
1504
1505 /*
1506 ============
1507 Cmd_Exists
1508 ============
1509 */
1510 qboolean Cmd_Exists (const char *cmd_name)
1511 {
1512         cmd_function_t  *cmd;
1513
1514         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1515                 if (!strcmp (cmd_name,cmd->name))
1516                         return true;
1517
1518         return false;
1519 }
1520
1521
1522 /*
1523 ============
1524 Cmd_CompleteCommand
1525 ============
1526 */
1527 const char *Cmd_CompleteCommand (const char *partial)
1528 {
1529         cmd_function_t *cmd;
1530         size_t len;
1531
1532         len = strlen(partial);
1533
1534         if (!len)
1535                 return NULL;
1536
1537 // check functions
1538         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1539                 if (!strncasecmp(partial, cmd->name, len))
1540                         return cmd->name;
1541
1542         return NULL;
1543 }
1544
1545 /*
1546         Cmd_CompleteCountPossible
1547
1548         New function for tab-completion system
1549         Added by EvilTypeGuy
1550         Thanks to Fett erich@heintz.com
1551         Thanks to taniwha
1552
1553 */
1554 int Cmd_CompleteCountPossible (const char *partial)
1555 {
1556         cmd_function_t *cmd;
1557         size_t len;
1558         int h;
1559
1560         h = 0;
1561         len = strlen(partial);
1562
1563         if (!len)
1564                 return 0;
1565
1566         // Loop through the command list and count all partial matches
1567         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1568                 if (!strncasecmp(partial, cmd->name, len))
1569                         h++;
1570
1571         return h;
1572 }
1573
1574 /*
1575         Cmd_CompleteBuildList
1576
1577         New function for tab-completion system
1578         Added by EvilTypeGuy
1579         Thanks to Fett erich@heintz.com
1580         Thanks to taniwha
1581
1582 */
1583 const char **Cmd_CompleteBuildList (const char *partial)
1584 {
1585         cmd_function_t *cmd;
1586         size_t len = 0;
1587         size_t bpos = 0;
1588         size_t sizeofbuf = (Cmd_CompleteCountPossible (partial) + 1) * sizeof (const char *);
1589         const char **buf;
1590
1591         len = strlen(partial);
1592         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1593         // Loop through the alias list and print all matches
1594         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1595                 if (!strncasecmp(partial, cmd->name, len))
1596                         buf[bpos++] = cmd->name;
1597
1598         buf[bpos] = NULL;
1599         return buf;
1600 }
1601
1602 // written by LordHavoc
1603 void Cmd_CompleteCommandPrint (const char *partial)
1604 {
1605         cmd_function_t *cmd;
1606         size_t len = strlen(partial);
1607         // Loop through the command list and print all matches
1608         for (cmd = cmd_functions; cmd; cmd = cmd->next)
1609                 if (!strncasecmp(partial, cmd->name, len))
1610                         Con_Printf("^2%s^7: %s\n", cmd->name, cmd->description);
1611 }
1612
1613 /*
1614         Cmd_CompleteAlias
1615
1616         New function for tab-completion system
1617         Added by EvilTypeGuy
1618         Thanks to Fett erich@heintz.com
1619         Thanks to taniwha
1620
1621 */
1622 const char *Cmd_CompleteAlias (const char *partial)
1623 {
1624         cmdalias_t *alias;
1625         size_t len;
1626
1627         len = strlen(partial);
1628
1629         if (!len)
1630                 return NULL;
1631
1632         // Check functions
1633         for (alias = cmd_alias; alias; alias = alias->next)
1634                 if (!strncasecmp(partial, alias->name, len))
1635                         return alias->name;
1636
1637         return NULL;
1638 }
1639
1640 // written by LordHavoc
1641 void Cmd_CompleteAliasPrint (const char *partial)
1642 {
1643         cmdalias_t *alias;
1644         size_t len = strlen(partial);
1645         // Loop through the alias list and print all matches
1646         for (alias = cmd_alias; alias; alias = alias->next)
1647                 if (!strncasecmp(partial, alias->name, len))
1648                         Con_Printf("^5%s^7: %s", alias->name, alias->value);
1649 }
1650
1651
1652 /*
1653         Cmd_CompleteAliasCountPossible
1654
1655         New function for tab-completion system
1656         Added by EvilTypeGuy
1657         Thanks to Fett erich@heintz.com
1658         Thanks to taniwha
1659
1660 */
1661 int Cmd_CompleteAliasCountPossible (const char *partial)
1662 {
1663         cmdalias_t      *alias;
1664         size_t          len;
1665         int                     h;
1666
1667         h = 0;
1668
1669         len = strlen(partial);
1670
1671         if (!len)
1672                 return 0;
1673
1674         // Loop through the command list and count all partial matches
1675         for (alias = cmd_alias; alias; alias = alias->next)
1676                 if (!strncasecmp(partial, alias->name, len))
1677                         h++;
1678
1679         return h;
1680 }
1681
1682 /*
1683         Cmd_CompleteAliasBuildList
1684
1685         New function for tab-completion system
1686         Added by EvilTypeGuy
1687         Thanks to Fett erich@heintz.com
1688         Thanks to taniwha
1689
1690 */
1691 const char **Cmd_CompleteAliasBuildList (const char *partial)
1692 {
1693         cmdalias_t *alias;
1694         size_t len = 0;
1695         size_t bpos = 0;
1696         size_t sizeofbuf = (Cmd_CompleteAliasCountPossible (partial) + 1) * sizeof (const char *);
1697         const char **buf;
1698
1699         len = strlen(partial);
1700         buf = (const char **)Mem_Alloc(tempmempool, sizeofbuf + sizeof (const char *));
1701         // Loop through the alias list and print all matches
1702         for (alias = cmd_alias; alias; alias = alias->next)
1703                 if (!strncasecmp(partial, alias->name, len))
1704                         buf[bpos++] = alias->name;
1705
1706         buf[bpos] = NULL;
1707         return buf;
1708 }
1709
1710 void Cmd_ClearCsqcFuncs (void)
1711 {
1712         cmd_function_t *cmd;
1713         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1714                 cmd->csqcfunc = false;
1715 }
1716
1717 /*
1718 ============
1719 Cmd_ExecuteString
1720
1721 A complete command line has been parsed, so try to execute it
1722 FIXME: lookupnoadd the token to speed search?
1723 ============
1724 */
1725 void Cmd_ExecuteString (const char *text, cmd_source_t src, qboolean lockmutex)
1726 {
1727         int oldpos;
1728         int found;
1729         cmd_function_t *cmd;
1730         cmdalias_t *a;
1731
1732         oldpos = cmd_tokenizebufferpos;
1733         cmd_source = src;
1734         found = false;
1735
1736         Cmd_TokenizeString (text);
1737
1738 // execute the command line
1739         if (!Cmd_Argc())
1740                 goto done; // no tokens
1741
1742 // check functions
1743         for (cmd=cmd_functions ; cmd ; cmd=cmd->next)
1744         {
1745                 if (!strcasecmp (cmd_argv[0],cmd->name))
1746                 {
1747                         if (cmd->csqcfunc && CL_VM_ConsoleCommand (text))       //[515]: csqc
1748                                 goto done;
1749                         switch (src)
1750                         {
1751                         case src_command:
1752                                 if (cmd->consolefunction)
1753                                         cmd->consolefunction ();
1754                                 else if (cmd->clientfunction)
1755                                 {
1756                                         if (cls.state == ca_connected)
1757                                         {
1758                                                 // forward remote commands to the server for execution
1759                                                 Cmd_ForwardToServer();
1760                                         }
1761                                         else
1762                                                 Con_Printf("Can not send command \"%s\", not connected.\n", Cmd_Argv(0));
1763                                 }
1764                                 else
1765                                         Con_Printf("Command \"%s\" can not be executed\n", Cmd_Argv(0));
1766                                 found = true;
1767                                 goto command_found;
1768                         case src_client:
1769                                 if (cmd->clientfunction)
1770                                 {
1771                                         cmd->clientfunction ();
1772                                         goto done;
1773                                 }
1774                                 break;
1775                         }
1776                         break;
1777                 }
1778         }
1779 command_found:
1780
1781         // if it's a client command and no command was found, say so.
1782         if (cmd_source == src_client)
1783         {
1784                 Con_Printf("player \"%s\" tried to %s\n", host_client->name, text);
1785                 goto done;
1786         }
1787
1788 // check alias
1789         for (a=cmd_alias ; a ; a=a->next)
1790         {
1791                 if (!strcasecmp (cmd_argv[0], a->name))
1792                 {
1793                         Cmd_ExecuteAlias(a);
1794                         goto done;
1795                 }
1796         }
1797
1798         if(found) // if the command was hooked and found, all is good
1799                 goto done;
1800
1801 // check cvars
1802         if (!Cvar_Command () && host_framecount > 0)
1803                 Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0));
1804
1805 done:
1806         cmd_tokenizebufferpos = oldpos;
1807 }
1808
1809
1810 /*
1811 ===================
1812 Cmd_ForwardStringToServer
1813
1814 Sends an entire command string over to the server, unprocessed
1815 ===================
1816 */
1817 void Cmd_ForwardStringToServer (const char *s)
1818 {
1819         char temp[128];
1820         if (cls.state != ca_connected)
1821         {
1822                 Con_Printf("Can't \"%s\", not connected\n", s);
1823                 return;
1824         }
1825
1826         if (!cls.netcon)
1827                 return;
1828
1829         // LordHavoc: thanks to Fuh for bringing the pure evil of SZ_Print to my
1830         // attention, it has been eradicated from here, its only (former) use in
1831         // all of darkplaces.
1832         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1833                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1834         else
1835                 MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
1836         if ((!strncmp(s, "say ", 4) || !strncmp(s, "say_team ", 9)) && cl_locs_enable.integer)
1837         {
1838                 // say/say_team commands can replace % character codes with status info
1839                 while (*s)
1840                 {
1841                         if (*s == '%' && s[1])
1842                         {
1843                                 // handle proquake message macros
1844                                 temp[0] = 0;
1845                                 switch (s[1])
1846                                 {
1847                                 case 'l': // current location
1848                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.movement_origin);
1849                                         break;
1850                                 case 'h': // current health
1851                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_HEALTH]);
1852                                         break;
1853                                 case 'a': // current armor
1854                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ARMOR]);
1855                                         break;
1856                                 case 'x': // current rockets
1857                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_ROCKETS]);
1858                                         break;
1859                                 case 'c': // current cells
1860                                         dpsnprintf(temp, sizeof(temp), "%i", cl.stats[STAT_CELLS]);
1861                                         break;
1862                                 // silly proquake macros
1863                                 case 'd': // loc at last death
1864                                         CL_Locs_FindLocationName(temp, sizeof(temp), cl.lastdeathorigin);
1865                                         break;
1866                                 case 't': // current time
1867                                         dpsnprintf(temp, sizeof(temp), "%.0f:%.0f", floor(cl.time / 60), cl.time - floor(cl.time / 60) * 60);
1868                                         break;
1869                                 case 'r': // rocket launcher status ("I have RL", "I need rockets", "I need RL")
1870                                         if (!(cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER))
1871                                                 dpsnprintf(temp, sizeof(temp), "I need RL");
1872                                         else if (!cl.stats[STAT_ROCKETS])
1873                                                 dpsnprintf(temp, sizeof(temp), "I need rockets");
1874                                         else
1875                                                 dpsnprintf(temp, sizeof(temp), "I have RL");
1876                                         break;
1877                                 case 'p': // powerup status (outputs "quad" "pent" and "eyes" according to status)
1878                                         if (cl.stats[STAT_ITEMS] & IT_QUAD)
1879                                         {
1880                                                 if (temp[0])
1881                                                         strlcat(temp, " ", sizeof(temp));
1882                                                 strlcat(temp, "quad", sizeof(temp));
1883                                         }
1884                                         if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY)
1885                                         {
1886                                                 if (temp[0])
1887                                                         strlcat(temp, " ", sizeof(temp));
1888                                                 strlcat(temp, "pent", sizeof(temp));
1889                                         }
1890                                         if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1891                                         {
1892                                                 if (temp[0])
1893                                                         strlcat(temp, " ", sizeof(temp));
1894                                                 strlcat(temp, "eyes", sizeof(temp));
1895                                         }
1896                                         break;
1897                                 case 'w': // weapon status (outputs "SSG:NG:SNG:GL:RL:LG" with the text between : characters omitted if you lack the weapon)
1898                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_SHOTGUN)
1899                                                 strlcat(temp, "SSG", sizeof(temp));
1900                                         strlcat(temp, ":", sizeof(temp));
1901                                         if (cl.stats[STAT_ITEMS] & IT_NAILGUN)
1902                                                 strlcat(temp, "NG", sizeof(temp));
1903                                         strlcat(temp, ":", sizeof(temp));
1904                                         if (cl.stats[STAT_ITEMS] & IT_SUPER_NAILGUN)
1905                                                 strlcat(temp, "SNG", sizeof(temp));
1906                                         strlcat(temp, ":", sizeof(temp));
1907                                         if (cl.stats[STAT_ITEMS] & IT_GRENADE_LAUNCHER)
1908                                                 strlcat(temp, "GL", sizeof(temp));
1909                                         strlcat(temp, ":", sizeof(temp));
1910                                         if (cl.stats[STAT_ITEMS] & IT_ROCKET_LAUNCHER)
1911                                                 strlcat(temp, "RL", sizeof(temp));
1912                                         strlcat(temp, ":", sizeof(temp));
1913                                         if (cl.stats[STAT_ITEMS] & IT_LIGHTNING)
1914                                                 strlcat(temp, "LG", sizeof(temp));
1915                                         break;
1916                                 default:
1917                                         // not a recognized macro, print it as-is...
1918                                         temp[0] = s[0];
1919                                         temp[1] = s[1];
1920                                         temp[2] = 0;
1921                                         break;
1922                                 }
1923                                 // write the resulting text
1924                                 SZ_Write(&cls.netcon->message, (unsigned char *)temp, strlen(temp));
1925                                 s += 2;
1926                                 continue;
1927                         }
1928                         MSG_WriteByte(&cls.netcon->message, *s);
1929                         s++;
1930                 }
1931                 MSG_WriteByte(&cls.netcon->message, 0);
1932         }
1933         else // any other command is passed on as-is
1934                 SZ_Write(&cls.netcon->message, (const unsigned char *)s, (int)strlen(s) + 1);
1935 }
1936
1937 /*
1938 ===================
1939 Cmd_ForwardToServer
1940
1941 Sends the entire command line over to the server
1942 ===================
1943 */
1944 void Cmd_ForwardToServer (void)
1945 {
1946         const char *s;
1947         char vabuf[1024];
1948         if (!strcasecmp(Cmd_Argv(0), "cmd"))
1949         {
1950                 // we want to strip off "cmd", so just send the args
1951                 s = Cmd_Argc() > 1 ? Cmd_Args() : "";
1952         }
1953         else
1954         {
1955                 // we need to keep the command name, so send Cmd_Argv(0), a space and then Cmd_Args()
1956                 s = va(vabuf, sizeof(vabuf), "%s %s", Cmd_Argv(0), Cmd_Argc() > 1 ? Cmd_Args() : "");
1957         }
1958         // don't send an empty forward message if the user tries "cmd" by itself
1959         if (!s || !*s)
1960                 return;
1961         Cmd_ForwardStringToServer(s);
1962 }
1963
1964
1965 /*
1966 ================
1967 Cmd_CheckParm
1968
1969 Returns the position (1 to argc-1) in the command's argument list
1970 where the given parameter apears, or 0 if not present
1971 ================
1972 */
1973
1974 int Cmd_CheckParm (const char *parm)
1975 {
1976         int i;
1977
1978         if (!parm)
1979         {
1980                 Con_Printf ("Cmd_CheckParm: NULL");
1981                 return 0;
1982         }
1983
1984         for (i = 1; i < Cmd_Argc (); i++)
1985                 if (!strcasecmp (parm, Cmd_Argv (i)))
1986                         return i;
1987
1988         return 0;
1989 }
1990
1991
1992
1993 void Cmd_SaveInitState(void)
1994 {
1995         cmd_function_t *f;
1996         cmdalias_t *a;
1997         for (f = cmd_functions;f;f = f->next)
1998                 f->initstate = true;
1999         for (a = cmd_alias;a;a = a->next)
2000         {
2001                 a->initstate = true;
2002                 a->initialvalue = Mem_strdup(zonemempool, a->value);
2003         }
2004         Cvar_SaveInitState();
2005 }
2006
2007 void Cmd_RestoreInitState(void)
2008 {
2009         cmd_function_t *f, **fp;
2010         cmdalias_t *a, **ap;
2011         for (fp = &cmd_functions;(f = *fp);)
2012         {
2013                 if (f->initstate)
2014                         fp = &f->next;
2015                 else
2016                 {
2017                         // destroy this command, it didn't exist at init
2018                         Con_DPrintf("Cmd_RestoreInitState: Destroying command %s\n", f->name);
2019                         *fp = f->next;
2020                         Z_Free(f);
2021                 }
2022         }
2023         for (ap = &cmd_alias;(a = *ap);)
2024         {
2025                 if (a->initstate)
2026                 {
2027                         // restore this alias, it existed at init
2028                         if (strcmp(a->value ? a->value : "", a->initialvalue ? a->initialvalue : ""))
2029                         {
2030                                 Con_DPrintf("Cmd_RestoreInitState: Restoring alias %s\n", a->name);
2031                                 if (a->value)
2032                                         Z_Free(a->value);
2033                                 a->value = Mem_strdup(zonemempool, a->initialvalue);
2034                         }
2035                         ap = &a->next;
2036                 }
2037                 else
2038                 {
2039                         // free this alias, it didn't exist at init...
2040                         Con_DPrintf("Cmd_RestoreInitState: Destroying alias %s\n", a->name);
2041                         *ap = a->next;
2042                         if (a->value)
2043                                 Z_Free(a->value);
2044                         Z_Free(a);
2045                 }
2046         }
2047         Cvar_RestoreInitState();
2048 }