]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - keys.c
Removed all calls to strcpy; most of them are now calls to strlcpy or memcpy.
[xonotic/darkplaces.git] / keys.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:
17
18                 Free Software Foundation, Inc.
19                 59 Temple Place - Suite 330
20                 Boston, MA  02111-1307, USA
21 */
22
23 #include "quakedef.h"
24 #include "cl_video.h"
25
26 /*
27 key up events are sent even if in console mode
28 */
29
30 int                     edit_line = MAX_INPUTLINES-1;
31 int                     history_line = MAX_INPUTLINES-1;
32 char            key_lines[MAX_INPUTLINES][MAX_INPUTLINE];
33 int                     key_linepos;
34 qboolean        key_insert = true;      // insert key toggle (for editing)
35 keydest_t       key_dest;
36 int                     key_consoleactive;
37 char            *keybindings[MAX_BINDMAPS][MAX_KEYS];
38
39 static int      key_bmap, key_bmap2;
40 static unsigned char keydown[MAX_KEYS]; // 0 = up, 1 = down, 2 = repeating
41
42 typedef struct keyname_s
43 {
44         const char      *name;
45         int                     keynum;
46 }
47 keyname_t;
48
49 static const keyname_t   keynames[] = {
50         {"TAB", K_TAB},
51         {"ENTER", K_ENTER},
52         {"ESCAPE", K_ESCAPE},
53         {"SPACE", K_SPACE},
54         {"BACKSPACE", K_BACKSPACE},
55         {"UPARROW", K_UPARROW},
56         {"DOWNARROW", K_DOWNARROW},
57         {"LEFTARROW", K_LEFTARROW},
58         {"RIGHTARROW", K_RIGHTARROW},
59
60         {"ALT", K_ALT},
61         {"CTRL", K_CTRL},
62         {"SHIFT", K_SHIFT},
63
64         {"F1", K_F1},
65         {"F2", K_F2},
66         {"F3", K_F3},
67         {"F4", K_F4},
68         {"F5", K_F5},
69         {"F6", K_F6},
70         {"F7", K_F7},
71         {"F8", K_F8},
72         {"F9", K_F9},
73         {"F10", K_F10},
74         {"F11", K_F11},
75         {"F12", K_F12},
76
77         {"INS", K_INS},
78         {"DEL", K_DEL},
79         {"PGDN", K_PGDN},
80         {"PGUP", K_PGUP},
81         {"HOME", K_HOME},
82         {"END", K_END},
83
84         {"PAUSE", K_PAUSE},
85
86         {"MWHEELUP", K_MWHEELUP},
87         {"MWHEELDOWN", K_MWHEELDOWN},
88
89         {"MOUSE1", K_MOUSE1},
90         {"MOUSE2", K_MOUSE2},
91         {"MOUSE3", K_MOUSE3},
92         {"MOUSE4", K_MOUSE4},
93         {"MOUSE5", K_MOUSE5},
94         {"MOUSE6", K_MOUSE6},
95         {"MOUSE7", K_MOUSE7},
96         {"MOUSE8", K_MOUSE8},
97         {"MOUSE9", K_MOUSE9},
98         {"MOUSE10", K_MOUSE10},
99         {"MOUSE11", K_MOUSE11},
100         {"MOUSE12", K_MOUSE12},
101         {"MOUSE13", K_MOUSE13},
102         {"MOUSE14", K_MOUSE14},
103         {"MOUSE15", K_MOUSE15},
104         {"MOUSE16", K_MOUSE16},
105
106         {"NUMLOCK", K_NUMLOCK},
107         {"CAPSLOCK", K_CAPSLOCK},
108         {"SCROLLOCK", K_SCROLLOCK},
109
110         {"KP_HOME",                     K_KP_HOME },
111         {"KP_UPARROW",          K_KP_UPARROW },
112         {"KP_PGUP",                     K_KP_PGUP },
113         {"KP_LEFTARROW",        K_KP_LEFTARROW },
114         {"KP_RIGHTARROW",       K_KP_RIGHTARROW },
115         {"KP_END",                      K_KP_END },
116         {"KP_DOWNARROW",        K_KP_DOWNARROW },
117         {"KP_PGDN",                     K_KP_PGDN },
118         {"KP_INS",                      K_KP_INS },
119         {"KP_DEL",                      K_KP_DEL },
120         {"KP_SLASH",            K_KP_SLASH },
121
122         {"KP_0", K_KP_0},
123         {"KP_1", K_KP_1},
124         {"KP_2", K_KP_2},
125         {"KP_3", K_KP_3},
126         {"KP_4", K_KP_4},
127         {"KP_5", K_KP_5},
128         {"KP_6", K_KP_6},
129         {"KP_7", K_KP_7},
130         {"KP_8", K_KP_8},
131         {"KP_9", K_KP_9},
132         {"KP_PERIOD", K_KP_PERIOD},
133         {"KP_DIVIDE", K_KP_DIVIDE},
134         {"KP_MULTIPLY", K_KP_MULTIPLY},
135         {"KP_MINUS", K_KP_MINUS},
136         {"KP_PLUS", K_KP_PLUS},
137         {"KP_ENTER", K_KP_ENTER},
138         {"KP_EQUALS", K_KP_EQUALS},
139
140         {"JOY1",  K_JOY1},
141         {"JOY2",  K_JOY2},
142         {"JOY3",  K_JOY3},
143         {"JOY4",  K_JOY4},
144         {"JOY5",  K_JOY5},
145         {"JOY6",  K_JOY6},
146         {"JOY7",  K_JOY7},
147         {"JOY8",  K_JOY8},
148         {"JOY9",  K_JOY9},
149         {"JOY10", K_JOY10},
150         {"JOY11", K_JOY11},
151         {"JOY12", K_JOY12},
152         {"JOY13", K_JOY13},
153         {"JOY14", K_JOY14},
154         {"JOY15", K_JOY15},
155         {"JOY16", K_JOY16},
156
157         {"AUX1", K_AUX1},
158         {"AUX2", K_AUX2},
159         {"AUX3", K_AUX3},
160         {"AUX4", K_AUX4},
161         {"AUX5", K_AUX5},
162         {"AUX6", K_AUX6},
163         {"AUX7", K_AUX7},
164         {"AUX8", K_AUX8},
165         {"AUX9", K_AUX9},
166         {"AUX10", K_AUX10},
167         {"AUX11", K_AUX11},
168         {"AUX12", K_AUX12},
169         {"AUX13", K_AUX13},
170         {"AUX14", K_AUX14},
171         {"AUX15", K_AUX15},
172         {"AUX16", K_AUX16},
173         {"AUX17", K_AUX17},
174         {"AUX18", K_AUX18},
175         {"AUX19", K_AUX19},
176         {"AUX20", K_AUX20},
177         {"AUX21", K_AUX21},
178         {"AUX22", K_AUX22},
179         {"AUX23", K_AUX23},
180         {"AUX24", K_AUX24},
181         {"AUX25", K_AUX25},
182         {"AUX26", K_AUX26},
183         {"AUX27", K_AUX27},
184         {"AUX28", K_AUX28},
185         {"AUX29", K_AUX29},
186         {"AUX30", K_AUX30},
187         {"AUX31", K_AUX31},
188         {"AUX32", K_AUX32},
189
190         {"SEMICOLON", ';'},                     // because a raw semicolon seperates commands
191         {"TILDE", '~'},
192         {"BACKQUOTE", '`'},
193         {"QUOTE", '"'},
194         {"APOSTROPHE", '\''},
195
196         {NULL, 0}
197 };
198
199 /*
200 ==============================================================================
201
202                         LINE TYPING INTO THE CONSOLE
203
204 ==============================================================================
205 */
206
207 void
208 Key_ClearEditLine (int edit_line)
209 {
210         memset (key_lines[edit_line], '\0', sizeof(key_lines[edit_line]));
211         key_lines[edit_line][0] = ']';
212         key_linepos = 1;
213 }
214
215 /*
216 ====================
217 Interactive line editing and console scrollback
218 ====================
219 */
220 static void
221 Key_Console (int key, char ascii)
222 {
223         // LordHavoc: copied most of this from Q2 to improve keyboard handling
224         switch (key)
225         {
226         case K_KP_SLASH:
227                 key = '/';
228                 break;
229         case K_KP_MINUS:
230                 key = '-';
231                 break;
232         case K_KP_PLUS:
233                 key = '+';
234                 break;
235         case K_KP_HOME:
236                 key = '7';
237                 break;
238         case K_KP_UPARROW:
239                 key = '8';
240                 break;
241         case K_KP_PGUP:
242                 key = '9';
243                 break;
244         case K_KP_LEFTARROW:
245                 key = '4';
246                 break;
247         case K_KP_5:
248                 key = '5';
249                 break;
250         case K_KP_RIGHTARROW:
251                 key = '6';
252                 break;
253         case K_KP_END:
254                 key = '1';
255                 break;
256         case K_KP_DOWNARROW:
257                 key = '2';
258                 break;
259         case K_KP_PGDN:
260                 key = '3';
261                 break;
262         case K_KP_INS:
263                 key = '0';
264                 break;
265         case K_KP_DEL:
266                 key = '.';
267                 break;
268         }
269
270         if ((toupper(key) == 'V' && keydown[K_CTRL]) || ((key == K_INS || key == K_KP_INS) && keydown[K_SHIFT]))
271         {
272                 char *cbd;
273                 if ((cbd = Sys_GetClipboardData()) != 0)
274                 {
275                         int i;
276                         strtok(cbd, "\n\r\b");
277                         i = (int)strlen(cbd);
278                         if (i + key_linepos >= MAX_INPUTLINE)
279                                 i= MAX_INPUTLINE - key_linepos;
280                         if (i > 0)
281                         {
282                                 cbd[i]=0;
283                                 strlcat(key_lines[edit_line], cbd, sizeof(key_lines[edit_line]));
284                                 key_linepos += i;
285                         }
286                         Z_Free(cbd);
287                 }
288                 return;
289         }
290
291         if (key == 'l')
292         {
293                 if (keydown[K_CTRL])
294                 {
295                         Cbuf_AddText ("clear\n");
296                         return;
297                 }
298         }
299
300         if (key == K_ENTER || key == K_KP_ENTER)
301         {
302                 Cbuf_AddText (key_lines[edit_line]+1);  // skip the ]
303                 Cbuf_AddText ("\n");
304                 Con_Printf("%s\n",key_lines[edit_line]);
305                 // LordHavoc: redesigned edit_line/history_line
306                 edit_line = 31;
307                 history_line = edit_line;
308                 memmove(key_lines[0], key_lines[1], sizeof(key_lines[0]) * edit_line);
309                 key_lines[edit_line][0] = ']';
310                 key_lines[edit_line][1] = 0;    // EvilTypeGuy: null terminate
311                 key_linepos = 1;
312                 // force an update, because the command may take some time
313                 if (cls.state == ca_disconnected)
314                         CL_UpdateScreen ();
315                 return;
316         }
317
318         if (key == K_TAB)
319         {
320                 // Enhanced command completion
321                 // by EvilTypeGuy eviltypeguy@qeradiant.com
322                 // Thanks to Fett, Taniwha
323                 Con_CompleteCommandLine();
324                 return;
325         }
326
327         // Advanced Console Editing by Radix radix@planetquake.com
328         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
329         // Enhanced by [515]
330
331         // left arrow will just move left one without erasing, backspace will
332         // actually erase character
333         if (key == K_LEFTARROW || key == K_KP_LEFTARROW)
334         {
335                 if (key_linepos < 2)
336                         return;
337                 if(keydown[K_CTRL])
338                 {
339                         int             pos;
340                         char    k;
341                         pos = key_linepos-1;
342                         if(pos)
343                                 while(--pos)
344                                 {
345                                         k = key_lines[edit_line][pos];
346                                         if(k == '\"' || k == ';' || k == ' ' || k == '\'')
347                                                 break;
348                                 }
349                         key_linepos = pos + 1;
350                 }
351                 else
352                         key_linepos--;
353                 return;
354         }
355
356         // delete char before cursor
357         if (key == K_BACKSPACE || (key == 'h' && keydown[K_CTRL]))
358         {
359                 if (key_linepos > 1)
360                 {
361                         strlcpy(key_lines[edit_line] + key_linepos - 1, key_lines[edit_line] + key_linepos, sizeof(key_lines[edit_line]) + 1 - key_linepos);
362                         key_linepos--;
363                 }
364                 return;
365         }
366
367         // delete char on cursor
368         if (key == K_DEL || key == K_KP_DEL)
369         {
370                 size_t linelen;
371                 linelen = strlen(key_lines[edit_line]);
372                 if (key_linepos < (int)linelen)
373                         memmove(key_lines[edit_line] + key_linepos, key_lines[edit_line] + key_linepos + 1, linelen - key_linepos);
374                 return;
375         }
376
377
378         // if we're at the end, get one character from previous line,
379         // otherwise just go right one
380         if (key == K_RIGHTARROW || key == K_KP_RIGHTARROW)
381         {
382                 if (key_linepos >= (int)strlen(key_lines[edit_line]))
383                         return;
384                 if(keydown[K_CTRL])
385                 {
386                         int             pos, len;
387                         char    k;
388                         len = (int)strlen(key_lines[edit_line]);
389                         pos = key_linepos;
390                         while(++pos < len)
391                         {
392                                 k = key_lines[edit_line][pos];
393                                 if(k == '\"' || k == ';' || k == ' ' || k == '\'')
394                                         break;
395                         }
396                         key_linepos = pos;
397                 }
398                 else
399                         key_linepos++;
400                 return;
401         }
402
403         if (key == K_INS || key == K_KP_INS) // toggle insert mode
404         {
405                 key_insert ^= 1;
406                 return;
407         }
408
409         // End Advanced Console Editing
410
411         if (key == K_UPARROW || key == K_KP_UPARROW || (key == 'p' && keydown[K_CTRL]))
412         {
413                 if (history_line > 0 && key_lines[history_line-1][1])
414                 {
415                         size_t linelen;
416                         history_line--;
417                         linelen = strlen(key_lines[edit_line]);
418                         memcpy(key_lines[edit_line], key_lines[history_line], linelen + 1);
419                         key_linepos = (int)linelen;
420                 }
421                 return;
422         }
423
424         if (key == K_DOWNARROW || key == K_KP_DOWNARROW || (key == 'n' && keydown[K_CTRL]))
425         {
426                 history_line++;
427                 if (history_line >= edit_line)
428                 {
429                         history_line = edit_line;
430                         key_lines[edit_line][0] = ']';
431                         key_lines[edit_line][1] = 0;
432                         key_linepos = 1;
433                 }
434                 else
435                 {
436                         size_t linelen;
437                         linelen = strlen(key_lines[edit_line]);
438                         memcpy(key_lines[edit_line], key_lines[history_line], linelen + 1);
439                         key_linepos = (int)linelen;
440                 }
441                 return;
442         }
443
444         if (key == K_PGUP || key == K_KP_PGUP || key == K_MWHEELUP)
445         {
446                 con_backscroll += ((int) vid_conheight.integer >> 5);
447                 if (con_backscroll > con_totallines - (vid_conheight.integer>>3) - 1)
448                         con_backscroll = con_totallines - (vid_conheight.integer>>3) - 1;
449                 return;
450         }
451
452         if (key == K_PGDN || key == K_KP_PGDN || key == K_MWHEELDOWN)
453         {
454                 con_backscroll -= ((int) vid_conheight.integer >> 5);
455                 if (con_backscroll < 0)
456                         con_backscroll = 0;
457                 return;
458         }
459
460         if (key == K_HOME || key == K_KP_HOME)
461         {
462                 if (keydown[K_CTRL])
463                         con_backscroll = con_totallines - (vid_conheight.integer>>3) - 1;
464                 else
465                         key_linepos = 1;
466                 return;
467         }
468
469         if (key == K_END || key == K_KP_END)
470         {
471                 if (keydown[K_CTRL])
472                         con_backscroll = 0;
473                 else
474                         key_linepos = (int)strlen(key_lines[edit_line]);
475                 return;
476         }
477
478         // non printable
479         if (ascii < 32)
480                 return;
481
482         if (key_linepos < MAX_INPUTLINE-1)
483         {
484                 int len;
485                 len = (int)strlen(&key_lines[edit_line][key_linepos]);
486                 // check insert mode, or always insert if at end of line
487                 if (key_insert || len == 0)
488                 {
489                         // can't use strcpy to move string to right
490                         len++;
491                         memmove(&key_lines[edit_line][key_linepos + 1], &key_lines[edit_line][key_linepos], len);
492                 }
493                 key_lines[edit_line][key_linepos] = ascii;
494                 key_linepos++;
495         }
496 }
497
498 //============================================================================
499
500 qboolean        chat_team;
501 char            chat_buffer[MAX_INPUTLINE];
502 unsigned int    chat_bufferlen = 0;
503
504 static void
505 Key_Message (int key, char ascii)
506 {
507
508         if (key == K_ENTER)
509         {
510                 Cmd_ForwardStringToServer(va("%s %s", chat_team ? "say_team" : "say ", chat_buffer));
511
512                 key_dest = key_game;
513                 chat_bufferlen = 0;
514                 chat_buffer[0] = 0;
515                 return;
516         }
517
518         if (key == K_ESCAPE) {
519                 key_dest = key_game;
520                 chat_bufferlen = 0;
521                 chat_buffer[0] = 0;
522                 return;
523         }
524
525         if (key == K_BACKSPACE) {
526                 if (chat_bufferlen) {
527                         chat_bufferlen--;
528                         chat_buffer[chat_bufferlen] = 0;
529                 }
530                 return;
531         }
532
533         if (chat_bufferlen == sizeof (chat_buffer) - 1)
534                 return;                                                 // all full
535
536         if (!ascii)
537                 return;                                                 // non printable
538
539         chat_buffer[chat_bufferlen++] = ascii;
540         chat_buffer[chat_bufferlen] = 0;
541 }
542
543 //============================================================================
544
545
546 /*
547 ===================
548 Returns a key number to be used to index keybindings[] by looking at
549 the given string.  Single ascii characters return themselves, while
550 the K_* names are matched up.
551 ===================
552 */
553 int
554 Key_StringToKeynum (const char *str)
555 {
556         const keyname_t  *kn;
557
558         if (!str || !str[0])
559                 return -1;
560         if (!str[1])
561                 return tolower(str[0]);
562
563         for (kn = keynames; kn->name; kn++) {
564                 if (!strcasecmp (str, kn->name))
565                         return kn->keynum;
566         }
567         return -1;
568 }
569
570 /*
571 ===================
572 Returns a string (either a single ascii char, or a K_* name) for the
573 given keynum.
574 FIXME: handle quote special (general escape sequence?)
575 ===================
576 */
577 const char *
578 Key_KeynumToString (int keynum)
579 {
580         const keyname_t  *kn;
581         static char tinystr[2];
582
583         if (keynum == -1)
584                 return "<KEY NOT FOUND>";
585         if (keynum > 32 && keynum < 127) {      // printable ascii
586                 tinystr[0] = keynum;
587                 tinystr[1] = 0;
588                 return tinystr;
589         }
590
591         for (kn = keynames; kn->name; kn++)
592                 if (keynum == kn->keynum)
593                         return kn->name;
594
595         return "<UNKNOWN KEYNUM>";
596 }
597
598
599 void
600 Key_SetBinding (int keynum, int bindmap, const char *binding)
601 {
602         char *newbinding;
603         size_t l;
604
605         if (keynum == -1 || keynum >= MAX_KEYS)
606                 return;
607
608 // free old bindings
609         if (keybindings[bindmap][keynum]) {
610                 Z_Free (keybindings[bindmap][keynum]);
611                 keybindings[bindmap][keynum] = NULL;
612         }
613 // allocate memory for new binding
614         l = strlen (binding);
615         newbinding = (char *)Z_Malloc (l + 1);
616         memcpy (newbinding, binding, l + 1);
617         newbinding[l] = 0;
618         keybindings[bindmap][keynum] = newbinding;
619 }
620
621 static void
622 Key_In_Unbind_f (void)
623 {
624         int         b, m;
625
626         if (Cmd_Argc () != 3) {
627                 Con_Print("in_unbind <bindmap> <key> : remove commands from a key\n");
628                 return;
629         }
630
631         m = strtol(Cmd_Argv (1), NULL, 0);
632         if ((m < 0) || (m >= 8)) {
633                 Con_Printf("%d isn't a valid bindmap\n", m);
634                 return;
635         }
636
637         b = Key_StringToKeynum (Cmd_Argv (2));
638         if (b == -1) {
639                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (2));
640                 return;
641         }
642
643         Key_SetBinding (b, m, "");
644 }
645
646 static void
647 Key_In_Bind_f (void)
648 {
649         int         i, c, b, m;
650         char        cmd[MAX_INPUTLINE];
651
652         c = Cmd_Argc ();
653
654         if (c != 3 && c != 4) {
655                 Con_Print("in_bind <bindmap> <key> [command] : attach a command to a key\n");
656                 return;
657         }
658
659         m = strtol(Cmd_Argv (1), NULL, 0);
660         if ((m < 0) || (m >= 8)) {
661                 Con_Printf("%d isn't a valid bindmap\n", m);
662                 return;
663         }
664
665         b = Key_StringToKeynum (Cmd_Argv (2));
666         if (b == -1 || b >= MAX_KEYS) {
667                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (2));
668                 return;
669         }
670
671         if (c == 3) {
672                 if (keybindings[m][b])
673                         Con_Printf("\"%s\" = \"%s\"\n", Cmd_Argv (2), keybindings[m][b]);
674                 else
675                         Con_Printf("\"%s\" is not bound\n", Cmd_Argv (2));
676                 return;
677         }
678 // copy the rest of the command line
679         cmd[0] = 0;                                                     // start out with a null string
680         for (i = 3; i < c; i++) {
681                 strlcat (cmd, Cmd_Argv (i), sizeof (cmd));
682                 if (i != (c - 1))
683                         strlcat (cmd, " ", sizeof (cmd));
684         }
685
686         Key_SetBinding (b, m, cmd);
687 }
688
689 static void
690 Key_In_Bindmap_f (void)
691 {
692         int         m1, m2, c;
693
694         c = Cmd_Argc ();
695
696         if (c != 3) {
697                 Con_Print("in_bindmap <bindmap> <fallback>: set current bindmap and fallback\n");
698                 return;
699         }
700
701         m1 = strtol(Cmd_Argv (1), NULL, 0);
702         if ((m1 < 0) || (m1 >= 8)) {
703                 Con_Printf("%d isn't a valid bindmap\n", m1);
704                 return;
705         }
706
707         m2 = strtol(Cmd_Argv (2), NULL, 0);
708         if ((m2 < 0) || (m2 >= 8)) {
709                 Con_Printf("%d isn't a valid bindmap\n", m2);
710                 return;
711         }
712
713         key_bmap = m1;
714         key_bmap2 = m2;
715 }
716
717 static void
718 Key_Unbind_f (void)
719 {
720         int         b;
721
722         if (Cmd_Argc () != 2) {
723                 Con_Print("unbind <key> : remove commands from a key\n");
724                 return;
725         }
726
727         b = Key_StringToKeynum (Cmd_Argv (1));
728         if (b == -1) {
729                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (1));
730                 return;
731         }
732
733         Key_SetBinding (b, 0, "");
734 }
735
736 static void
737 Key_Unbindall_f (void)
738 {
739         int         i, j;
740
741         for (j = 0; j < 8; j++)
742                 for (i = 0; i < (int)(sizeof(keybindings[0])/sizeof(keybindings[0][0])); i++)
743                         if (keybindings[j][i])
744                                 Key_SetBinding (i, j, "");
745 }
746
747
748 static void
749 Key_Bind_f (void)
750 {
751         int         i, c, b;
752         char        cmd[MAX_INPUTLINE];
753
754         c = Cmd_Argc ();
755
756         if (c != 2 && c != 3) {
757                 Con_Print("bind <key> [command] : attach a command to a key\n");
758                 return;
759         }
760         b = Key_StringToKeynum (Cmd_Argv (1));
761         if (b == -1 || b >= MAX_KEYS) {
762                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (1));
763                 return;
764         }
765
766         if (c == 2) {
767                 if (keybindings[0][b])
768                         Con_Printf("\"%s\" = \"%s\"\n", Cmd_Argv (1), keybindings[0][b]);
769                 else
770                         Con_Printf("\"%s\" is not bound\n", Cmd_Argv (1));
771                 return;
772         }
773 // copy the rest of the command line
774         cmd[0] = 0;                                                     // start out with a null string
775         for (i = 2; i < c; i++) {
776                 strlcat (cmd, Cmd_Argv (i), sizeof (cmd));
777                 if (i != (c - 1))
778                         strlcat (cmd, " ", sizeof (cmd));
779         }
780
781         Key_SetBinding (b, 0, cmd);
782 }
783
784 /*
785 ============
786 Writes lines containing "bind key value"
787 ============
788 */
789 void
790 Key_WriteBindings (qfile_t *f)
791 {
792         int         i, j;
793
794         for (i = 0; i < (int)(sizeof(keybindings[0])/sizeof(keybindings[0][0])); i++)
795                 if (keybindings[0][i])
796                         FS_Printf(f, "bind \"%s\" \"%s\"\n",
797                                         Key_KeynumToString (i), keybindings[0][i]);
798         for (j = 1; j < 8; j++)
799                 for (i = 0; i < (int)(sizeof(keybindings[0])/sizeof(keybindings[0][0])); i++)
800                         if (keybindings[j][i])
801                                 FS_Printf(f, "in_bind %d \"%s\" \"%s\"\n",
802                                                 j, Key_KeynumToString (i), keybindings[j][i]);
803 }
804
805
806 void
807 Key_Init (void)
808 {
809         int         i;
810
811         for (i = 0; i < 32; i++) {
812                 key_lines[i][0] = ']';
813                 key_lines[i][1] = 0;
814         }
815         key_linepos = 1;
816
817 //
818 // register our functions
819 //
820         Cmd_AddCommand ("in_bind", Key_In_Bind_f, "binds a command to the specified key in the selected bindmap");
821         Cmd_AddCommand ("in_unbind", Key_In_Unbind_f, "removes command on the specified key in the selected bindmap");
822         Cmd_AddCommand ("in_bindmap", Key_In_Bindmap_f, "selects active foreground and background (used only if a key is not bound in the foreground) bindmaps for typing");
823
824         Cmd_AddCommand ("bind", Key_Bind_f, "binds a command to the specified key in bindmap 0");
825         Cmd_AddCommand ("unbind", Key_Unbind_f, "removes a command on the specified key in bindmap 0");
826         Cmd_AddCommand ("unbindall", Key_Unbindall_f, "removes all commands from all keys in all bindmaps (leaving only shift-escape and escape)");
827 }
828
829 const char *Key_GetBind (int key)
830 {
831         const char *bind;
832         if (key < 0 || key >= MAX_KEYS)
833                 return NULL;
834         bind = keybindings[key_bmap][key];
835         if (!bind)
836                 bind = keybindings[key_bmap2][key];
837         return bind;
838 }
839
840 qboolean CL_VM_InputEvent (qboolean pressed, int key);
841
842 /*
843 ===================
844 Called by the system between frames for both key up and key down events
845 Should NOT be called during an interrupt!
846 ===================
847 */
848 void
849 Key_Event (int key, char ascii, qboolean down)
850 {
851         const char *bind;
852         qboolean q;
853
854         if (key < 0 || key >= MAX_KEYS)
855                 return;
856
857         // get key binding
858         bind = keybindings[key_bmap][key];
859         if (!bind)
860                 bind = keybindings[key_bmap2][key];
861
862         if(key_dest == key_game)
863         {
864                 q = CL_VM_InputEvent(!down, key);
865                 if(q)
866                 {
867                         if (down)
868                                 keydown[key] = min(keydown[key] + 1, 2);
869                         else
870                                 keydown[key] = 0;
871                         return;
872                 }
873         }
874
875         if (down)
876         {
877                 // increment key repeat count each time a down is received so that things
878                 // which want to ignore key repeat can ignore it
879                 keydown[key] = min(keydown[key] + 1, 2);
880         }
881         else
882         {
883                 // clear repeat count now that the key is released
884                 keydown[key] = 0;
885                 // key up events only generate commands if the game key binding is a button
886                 // command (leading + sign).  These will occur even in console mode, to
887                 // keep the character from continuing an action started before a console
888                 // switch.  Button commands include the kenum as a parameter, so multiple
889                 // downs can be matched with ups
890                 if (bind && bind[0] == '+')
891                         Cbuf_AddText(va("-%s %i\n", bind + 1, key));
892         }
893
894         // key_consoleactive is a flag not a key_dest because the console is a
895         // high priority overlay ontop of the normal screen (designed as a safety
896         // feature so that developers and users can rescue themselves from a bad
897         // situation).
898         //
899         // this also means that toggling the console on/off does not lose the old
900         // key_dest state
901
902         // specially handle escape (togglemenu) and shift-escape (toggleconsole)
903         // engine bindings, these are not handled as normal binds so that the user
904         // can recover from a completely empty bindmap
905         if (key == K_ESCAPE)
906         {
907                 // ignore key repeats on escape
908                 if (keydown[key] > 1)
909                         return;
910                 // escape does these things:
911                 // key_consoleactive - close console
912                 // key_message - abort messagemode
913                 // key_menu - go to parent menu (or key_game)
914                 // key_game - open menu
915                 // in all modes shift-escape toggles console
916                 if (((key_consoleactive & KEY_CONSOLEACTIVE_USER) || keydown[K_SHIFT]) && down)
917                 {
918                         Con_ToggleConsole_f ();
919                         return;
920                 }
921                 switch (key_dest)
922                 {
923                         case key_message:
924                                 if (down)
925                                         Key_Message (key, ascii);
926                                 break;
927                         case key_menu:
928                                 MR_KeyEvent (key, ascii, down);
929                                 break;
930                         case key_game:
931                                 if (down)
932                                         MR_ToggleMenu_f ();
933                                 break;
934                         default:
935                                 Con_Printf ("Key_Event: Bad key_dest\n");
936                 }
937                 return;
938         }
939
940         // send function keydowns to interpreter no matter what mode is
941         if (key >= K_F1 && key <= K_F12 && down)
942         {
943                 // ignore key repeats on F1-F12 binds
944                 if (keydown[key] > 1)
945                         return;
946                 if (bind)
947                 {
948                         // button commands add keynum as a parm
949                         if (bind[0] == '+')
950                                 Cbuf_AddText (va("%s %i\n", bind, key));
951                         else
952                         {
953                                 Cbuf_AddText (bind);
954                                 Cbuf_AddText ("\n");
955                         }
956                 }
957                 return;
958         }
959
960 #if 1
961         // ignore binds (other than the above escape/F1-F12 keys) while in console
962         if (key_consoleactive && down)
963 #else
964         // respond to toggleconsole binds while in console unless the pressed key
965         // happens to be the color prefix character (such as on German keyboards)
966         if (key_consoleactive && down && (strncmp(bind, "toggleconsole", strlen("toggleconsole")) || ascii == STRING_COLOR_TAG))
967 #endif
968         {
969                 Key_Console (key, ascii);
970                 return;
971         }
972
973         // ignore binds while a video is played, let the video system handle the key event
974         if (cl_videoplaying)
975         {
976                 CL_Video_KeyEvent (key, ascii, keydown[key] != 0);
977                 return;
978         }
979
980         // anything else is a key press into the game, chat line, or menu
981         switch (key_dest)
982         {
983                 case key_message:
984                         if (down)
985                                 Key_Message (key, ascii);
986                         break;
987                 case key_menu:
988                         MR_KeyEvent (key, ascii, down);
989                         break;
990                 case key_game:
991                         // ignore key repeats on binds
992                         if (bind && keydown[key] == 1 && down)
993                         {
994                                 // button commands add keynum as a parm
995                                 if (bind[0] == '+')
996                                         Cbuf_AddText (va("%s %i\n", bind, key));
997                                 else
998                                 {
999                                         Cbuf_AddText (bind);
1000                                         Cbuf_AddText ("\n");
1001                                 }
1002                         }
1003                         break;
1004                 default:
1005                         Con_Printf ("Key_Event: Bad key_dest\n");
1006         }
1007 }
1008
1009 /*
1010 ===================
1011 Key_ClearStates
1012 ===================
1013 */
1014 void
1015 Key_ClearStates (void)
1016 {
1017         memset(keydown, 0, sizeof(keydown));
1018 }