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