b4a40ed8a3d8d45b45f593780e336104e5738841
[divverent/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 cvar_t con_closeontoggleconsole = {CVAR_SAVE, "con_closeontoggleconsole","1", "allows toggleconsole binds to close the console as well"};
27
28 /*
29 key up events are sent even if in console mode
30 */
31
32 char            key_line[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 int         history_line;
39 char            history_savedline[MAX_INPUTLINE];
40 conbuffer_t history;
41
42 extern cvar_t   con_textsize;
43
44
45 static void Key_History_Init(void)
46 {
47         qfile_t *historyfile;
48         ConBuffer_Init(&history, HIST_TEXTSIZE, HIST_MAXLINES, zonemempool);
49
50         historyfile = FS_OpenRealFile("darkplaces_history.txt", "rb", false); // rb to handle unix line endings on windows too
51         if(historyfile)
52         {
53                 char buf[MAX_INPUTLINE];
54                 int bufpos;
55                 int c;
56
57                 bufpos = 0;
58                 for(;;)
59                 {
60                         c = FS_Getc(historyfile);
61                         if(c < 0 || c == 0 || c == '\r' || c == '\n')
62                         {
63                                 if(bufpos > 0)
64                                 {
65                                         buf[bufpos] = 0;
66                                         ConBuffer_AddLine(&history, buf, bufpos, 0);
67                                         bufpos = 0;
68                                 }
69                                 if(c < 0)
70                                         break;
71                         }
72                         else
73                         {
74                                 if(bufpos < MAX_INPUTLINE - 1)
75                                         buf[bufpos++] = c;
76                         }
77                 }
78
79                 FS_Close(historyfile);
80         }
81
82         history_line = -1;
83 }
84
85 static void Key_History_Shutdown(void)
86 {
87         // TODO write history to a file
88
89         qfile_t *historyfile = FS_OpenRealFile("darkplaces_history.txt", "w", false);
90         if(historyfile)
91         {
92                 int i;
93                 for(i = 0; i < CONBUFFER_LINES_COUNT(&history); ++i)
94                         FS_Printf(historyfile, "%s\n", ConBuffer_GetLine(&history, i));
95                 FS_Close(historyfile);
96         }
97
98         ConBuffer_Shutdown(&history);
99 }
100
101 static void Key_History_Push(void)
102 {
103         if(key_line[1]) // empty?
104         if(strcmp(key_line, "]quit")) // putting these into the history just sucks
105         if(strncmp(key_line, "]quit ", 6)) // putting these into the history just sucks
106                 ConBuffer_AddLine(&history, key_line + 1, strlen(key_line) - 1, 0);
107         Con_Printf("%s\n", key_line); // don't mark empty lines as history
108         history_line = -1;
109 }
110
111 static void Key_History_Up(void)
112 {
113         if(history_line == -1) // editing the "new" line
114                 strlcpy(history_savedline, key_line + 1, sizeof(history_savedline));
115
116         if(history_line == -1)
117         {
118                 history_line = CONBUFFER_LINES_COUNT(&history) - 1;
119                 if(history_line != -1)
120                 {
121                         strlcpy(key_line + 1, ConBuffer_GetLine(&history, history_line), sizeof(key_line) - 1);
122                         key_linepos = strlen(key_line);
123                 }
124         }
125         else if(history_line > 0)
126         {
127                 --history_line; // this also does -1 -> 0, so it is good
128                 strlcpy(key_line + 1, ConBuffer_GetLine(&history, history_line), sizeof(key_line) - 1);
129                 key_linepos = strlen(key_line);
130         }
131 }
132
133 static void Key_History_Down(void)
134 {
135         if(history_line == -1) // editing the "new" line
136                 return;
137
138         if(history_line < CONBUFFER_LINES_COUNT(&history) - 1)
139         {
140                 ++history_line;
141                 strlcpy(key_line + 1, ConBuffer_GetLine(&history, history_line), sizeof(key_line) - 1);
142         }
143         else
144         {
145                 history_line = -1;
146                 strlcpy(key_line + 1, history_savedline, sizeof(key_line) - 1);
147         }
148
149         key_linepos = strlen(key_line);
150 }
151
152 static int      key_bmap, key_bmap2;
153 static unsigned char keydown[MAX_KEYS]; // 0 = up, 1 = down, 2 = repeating
154
155 typedef struct keyname_s
156 {
157         const char      *name;
158         int                     keynum;
159 }
160 keyname_t;
161
162 static const keyname_t   keynames[] = {
163         {"TAB", K_TAB},
164         {"ENTER", K_ENTER},
165         {"ESCAPE", K_ESCAPE},
166         {"SPACE", K_SPACE},
167
168         // spacer so it lines up with keys.h
169
170         {"BACKSPACE", K_BACKSPACE},
171         {"UPARROW", K_UPARROW},
172         {"DOWNARROW", K_DOWNARROW},
173         {"LEFTARROW", K_LEFTARROW},
174         {"RIGHTARROW", K_RIGHTARROW},
175
176         {"ALT", K_ALT},
177         {"CTRL", K_CTRL},
178         {"SHIFT", K_SHIFT},
179
180         {"F1", K_F1},
181         {"F2", K_F2},
182         {"F3", K_F3},
183         {"F4", K_F4},
184         {"F5", K_F5},
185         {"F6", K_F6},
186         {"F7", K_F7},
187         {"F8", K_F8},
188         {"F9", K_F9},
189         {"F10", K_F10},
190         {"F11", K_F11},
191         {"F12", K_F12},
192
193         {"INS", K_INS},
194         {"DEL", K_DEL},
195         {"PGDN", K_PGDN},
196         {"PGUP", K_PGUP},
197         {"HOME", K_HOME},
198         {"END", K_END},
199
200         {"PAUSE", K_PAUSE},
201
202         {"NUMLOCK", K_NUMLOCK},
203         {"CAPSLOCK", K_CAPSLOCK},
204         {"SCROLLOCK", K_SCROLLOCK},
205
206         {"KP_INS",                      K_KP_INS },
207         {"KP_0", K_KP_0},
208         {"KP_END",                      K_KP_END },
209         {"KP_1", K_KP_1},
210         {"KP_DOWNARROW",        K_KP_DOWNARROW },
211         {"KP_2", K_KP_2},
212         {"KP_PGDN",                     K_KP_PGDN },
213         {"KP_3", K_KP_3},
214         {"KP_LEFTARROW",        K_KP_LEFTARROW },
215         {"KP_4", K_KP_4},
216         {"KP_5", K_KP_5},
217         {"KP_RIGHTARROW",       K_KP_RIGHTARROW },
218         {"KP_6", K_KP_6},
219         {"KP_HOME",                     K_KP_HOME },
220         {"KP_7", K_KP_7},
221         {"KP_UPARROW",          K_KP_UPARROW },
222         {"KP_8", K_KP_8},
223         {"KP_PGUP",                     K_KP_PGUP },
224         {"KP_9", K_KP_9},
225         {"KP_DEL",                      K_KP_DEL },
226         {"KP_PERIOD", K_KP_PERIOD},
227         {"KP_SLASH",            K_KP_SLASH },
228         {"KP_DIVIDE", K_KP_DIVIDE},
229         {"KP_MULTIPLY", K_KP_MULTIPLY},
230         {"KP_MINUS", K_KP_MINUS},
231         {"KP_PLUS", K_KP_PLUS},
232         {"KP_ENTER", K_KP_ENTER},
233         {"KP_EQUALS", K_KP_EQUALS},
234
235
236
237         {"MOUSE1", K_MOUSE1},
238
239         {"MOUSE2", K_MOUSE2},
240         {"MOUSE3", K_MOUSE3},
241         {"MWHEELUP", K_MWHEELUP},
242         {"MWHEELDOWN", K_MWHEELDOWN},
243         {"MOUSE4", K_MOUSE4},
244         {"MOUSE5", K_MOUSE5},
245         {"MOUSE6", K_MOUSE6},
246         {"MOUSE7", K_MOUSE7},
247         {"MOUSE8", K_MOUSE8},
248         {"MOUSE9", K_MOUSE9},
249         {"MOUSE10", K_MOUSE10},
250         {"MOUSE11", K_MOUSE11},
251         {"MOUSE12", K_MOUSE12},
252         {"MOUSE13", K_MOUSE13},
253         {"MOUSE14", K_MOUSE14},
254         {"MOUSE15", K_MOUSE15},
255         {"MOUSE16", K_MOUSE16},
256
257
258
259
260         {"JOY1",  K_JOY1},
261         {"JOY2",  K_JOY2},
262         {"JOY3",  K_JOY3},
263         {"JOY4",  K_JOY4},
264         {"JOY5",  K_JOY5},
265         {"JOY6",  K_JOY6},
266         {"JOY7",  K_JOY7},
267         {"JOY8",  K_JOY8},
268         {"JOY9",  K_JOY9},
269         {"JOY10", K_JOY10},
270         {"JOY11", K_JOY11},
271         {"JOY12", K_JOY12},
272         {"JOY13", K_JOY13},
273         {"JOY14", K_JOY14},
274         {"JOY15", K_JOY15},
275         {"JOY16", K_JOY16},
276
277
278
279
280
281
282         {"AUX1", K_AUX1},
283         {"AUX2", K_AUX2},
284         {"AUX3", K_AUX3},
285         {"AUX4", K_AUX4},
286         {"AUX5", K_AUX5},
287         {"AUX6", K_AUX6},
288         {"AUX7", K_AUX7},
289         {"AUX8", K_AUX8},
290         {"AUX9", K_AUX9},
291         {"AUX10", K_AUX10},
292         {"AUX11", K_AUX11},
293         {"AUX12", K_AUX12},
294         {"AUX13", K_AUX13},
295         {"AUX14", K_AUX14},
296         {"AUX15", K_AUX15},
297         {"AUX16", K_AUX16},
298         {"AUX17", K_AUX17},
299         {"AUX18", K_AUX18},
300         {"AUX19", K_AUX19},
301         {"AUX20", K_AUX20},
302         {"AUX21", K_AUX21},
303         {"AUX22", K_AUX22},
304         {"AUX23", K_AUX23},
305         {"AUX24", K_AUX24},
306         {"AUX25", K_AUX25},
307         {"AUX26", K_AUX26},
308         {"AUX27", K_AUX27},
309         {"AUX28", K_AUX28},
310         {"AUX29", K_AUX29},
311         {"AUX30", K_AUX30},
312         {"AUX31", K_AUX31},
313         {"AUX32", K_AUX32},
314
315         {"SEMICOLON", ';'},                     // because a raw semicolon separates commands
316         {"TILDE", '~'},
317         {"BACKQUOTE", '`'},
318         {"QUOTE", '"'},
319         {"APOSTROPHE", '\''},
320         {"BACKSLASH", '\\'},            // because a raw backslash is used for special characters
321
322         {"MIDINOTE0", K_MIDINOTE0},
323         {"MIDINOTE1", K_MIDINOTE1},
324         {"MIDINOTE2", K_MIDINOTE2},
325         {"MIDINOTE3", K_MIDINOTE3},
326         {"MIDINOTE4", K_MIDINOTE4},
327         {"MIDINOTE5", K_MIDINOTE5},
328         {"MIDINOTE6", K_MIDINOTE6},
329         {"MIDINOTE7", K_MIDINOTE7},
330         {"MIDINOTE8", K_MIDINOTE8},
331         {"MIDINOTE9", K_MIDINOTE9},
332         {"MIDINOTE10", K_MIDINOTE10},
333         {"MIDINOTE11", K_MIDINOTE11},
334         {"MIDINOTE12", K_MIDINOTE12},
335         {"MIDINOTE13", K_MIDINOTE13},
336         {"MIDINOTE14", K_MIDINOTE14},
337         {"MIDINOTE15", K_MIDINOTE15},
338         {"MIDINOTE16", K_MIDINOTE16},
339         {"MIDINOTE17", K_MIDINOTE17},
340         {"MIDINOTE18", K_MIDINOTE18},
341         {"MIDINOTE19", K_MIDINOTE19},
342         {"MIDINOTE20", K_MIDINOTE20},
343         {"MIDINOTE21", K_MIDINOTE21},
344         {"MIDINOTE22", K_MIDINOTE22},
345         {"MIDINOTE23", K_MIDINOTE23},
346         {"MIDINOTE24", K_MIDINOTE24},
347         {"MIDINOTE25", K_MIDINOTE25},
348         {"MIDINOTE26", K_MIDINOTE26},
349         {"MIDINOTE27", K_MIDINOTE27},
350         {"MIDINOTE28", K_MIDINOTE28},
351         {"MIDINOTE29", K_MIDINOTE29},
352         {"MIDINOTE30", K_MIDINOTE30},
353         {"MIDINOTE31", K_MIDINOTE31},
354         {"MIDINOTE32", K_MIDINOTE32},
355         {"MIDINOTE33", K_MIDINOTE33},
356         {"MIDINOTE34", K_MIDINOTE34},
357         {"MIDINOTE35", K_MIDINOTE35},
358         {"MIDINOTE36", K_MIDINOTE36},
359         {"MIDINOTE37", K_MIDINOTE37},
360         {"MIDINOTE38", K_MIDINOTE38},
361         {"MIDINOTE39", K_MIDINOTE39},
362         {"MIDINOTE40", K_MIDINOTE40},
363         {"MIDINOTE41", K_MIDINOTE41},
364         {"MIDINOTE42", K_MIDINOTE42},
365         {"MIDINOTE43", K_MIDINOTE43},
366         {"MIDINOTE44", K_MIDINOTE44},
367         {"MIDINOTE45", K_MIDINOTE45},
368         {"MIDINOTE46", K_MIDINOTE46},
369         {"MIDINOTE47", K_MIDINOTE47},
370         {"MIDINOTE48", K_MIDINOTE48},
371         {"MIDINOTE49", K_MIDINOTE49},
372         {"MIDINOTE50", K_MIDINOTE50},
373         {"MIDINOTE51", K_MIDINOTE51},
374         {"MIDINOTE52", K_MIDINOTE52},
375         {"MIDINOTE53", K_MIDINOTE53},
376         {"MIDINOTE54", K_MIDINOTE54},
377         {"MIDINOTE55", K_MIDINOTE55},
378         {"MIDINOTE56", K_MIDINOTE56},
379         {"MIDINOTE57", K_MIDINOTE57},
380         {"MIDINOTE58", K_MIDINOTE58},
381         {"MIDINOTE59", K_MIDINOTE59},
382         {"MIDINOTE60", K_MIDINOTE60},
383         {"MIDINOTE61", K_MIDINOTE61},
384         {"MIDINOTE62", K_MIDINOTE62},
385         {"MIDINOTE63", K_MIDINOTE63},
386         {"MIDINOTE64", K_MIDINOTE64},
387         {"MIDINOTE65", K_MIDINOTE65},
388         {"MIDINOTE66", K_MIDINOTE66},
389         {"MIDINOTE67", K_MIDINOTE67},
390         {"MIDINOTE68", K_MIDINOTE68},
391         {"MIDINOTE69", K_MIDINOTE69},
392         {"MIDINOTE70", K_MIDINOTE70},
393         {"MIDINOTE71", K_MIDINOTE71},
394         {"MIDINOTE72", K_MIDINOTE72},
395         {"MIDINOTE73", K_MIDINOTE73},
396         {"MIDINOTE74", K_MIDINOTE74},
397         {"MIDINOTE75", K_MIDINOTE75},
398         {"MIDINOTE76", K_MIDINOTE76},
399         {"MIDINOTE77", K_MIDINOTE77},
400         {"MIDINOTE78", K_MIDINOTE78},
401         {"MIDINOTE79", K_MIDINOTE79},
402         {"MIDINOTE80", K_MIDINOTE80},
403         {"MIDINOTE81", K_MIDINOTE81},
404         {"MIDINOTE82", K_MIDINOTE82},
405         {"MIDINOTE83", K_MIDINOTE83},
406         {"MIDINOTE84", K_MIDINOTE84},
407         {"MIDINOTE85", K_MIDINOTE85},
408         {"MIDINOTE86", K_MIDINOTE86},
409         {"MIDINOTE87", K_MIDINOTE87},
410         {"MIDINOTE88", K_MIDINOTE88},
411         {"MIDINOTE89", K_MIDINOTE89},
412         {"MIDINOTE90", K_MIDINOTE90},
413         {"MIDINOTE91", K_MIDINOTE91},
414         {"MIDINOTE92", K_MIDINOTE92},
415         {"MIDINOTE93", K_MIDINOTE93},
416         {"MIDINOTE94", K_MIDINOTE94},
417         {"MIDINOTE95", K_MIDINOTE95},
418         {"MIDINOTE96", K_MIDINOTE96},
419         {"MIDINOTE97", K_MIDINOTE97},
420         {"MIDINOTE98", K_MIDINOTE98},
421         {"MIDINOTE99", K_MIDINOTE99},
422         {"MIDINOTE100", K_MIDINOTE100},
423         {"MIDINOTE101", K_MIDINOTE101},
424         {"MIDINOTE102", K_MIDINOTE102},
425         {"MIDINOTE103", K_MIDINOTE103},
426         {"MIDINOTE104", K_MIDINOTE104},
427         {"MIDINOTE105", K_MIDINOTE105},
428         {"MIDINOTE106", K_MIDINOTE106},
429         {"MIDINOTE107", K_MIDINOTE107},
430         {"MIDINOTE108", K_MIDINOTE108},
431         {"MIDINOTE109", K_MIDINOTE109},
432         {"MIDINOTE110", K_MIDINOTE110},
433         {"MIDINOTE111", K_MIDINOTE111},
434         {"MIDINOTE112", K_MIDINOTE112},
435         {"MIDINOTE113", K_MIDINOTE113},
436         {"MIDINOTE114", K_MIDINOTE114},
437         {"MIDINOTE115", K_MIDINOTE115},
438         {"MIDINOTE116", K_MIDINOTE116},
439         {"MIDINOTE117", K_MIDINOTE117},
440         {"MIDINOTE118", K_MIDINOTE118},
441         {"MIDINOTE119", K_MIDINOTE119},
442         {"MIDINOTE120", K_MIDINOTE120},
443         {"MIDINOTE121", K_MIDINOTE121},
444         {"MIDINOTE122", K_MIDINOTE122},
445         {"MIDINOTE123", K_MIDINOTE123},
446         {"MIDINOTE124", K_MIDINOTE124},
447         {"MIDINOTE125", K_MIDINOTE125},
448         {"MIDINOTE126", K_MIDINOTE126},
449         {"MIDINOTE127", K_MIDINOTE127},
450
451         {NULL, 0}
452 };
453
454 /*
455 ==============================================================================
456
457                         LINE TYPING INTO THE CONSOLE
458
459 ==============================================================================
460 */
461
462 void
463 Key_ClearEditLine (int edit_line)
464 {
465         memset (key_line, '\0', sizeof(key_line));
466         key_line[0] = ']';
467         key_linepos = 1;
468 }
469
470 /*
471 ====================
472 Interactive line editing and console scrollback
473 ====================
474 */
475 static void
476 Key_Console (int key, int ascii)
477 {
478         // LordHavoc: copied most of this from Q2 to improve keyboard handling
479         switch (key)
480         {
481         case K_KP_SLASH:
482                 key = '/';
483                 break;
484         case K_KP_MINUS:
485                 key = '-';
486                 break;
487         case K_KP_PLUS:
488                 key = '+';
489                 break;
490         case K_KP_HOME:
491                 key = '7';
492                 break;
493         case K_KP_UPARROW:
494                 key = '8';
495                 break;
496         case K_KP_PGUP:
497                 key = '9';
498                 break;
499         case K_KP_LEFTARROW:
500                 key = '4';
501                 break;
502         case K_KP_5:
503                 key = '5';
504                 break;
505         case K_KP_RIGHTARROW:
506                 key = '6';
507                 break;
508         case K_KP_END:
509                 key = '1';
510                 break;
511         case K_KP_DOWNARROW:
512                 key = '2';
513                 break;
514         case K_KP_PGDN:
515                 key = '3';
516                 break;
517         case K_KP_INS:
518                 key = '0';
519                 break;
520         case K_KP_DEL:
521                 key = '.';
522                 break;
523         }
524
525         if ((key == 'v' && keydown[K_CTRL]) || ((key == K_INS || key == K_KP_INS) && keydown[K_SHIFT]))
526         {
527                 char *cbd, *p;
528                 if ((cbd = Sys_GetClipboardData()) != 0)
529                 {
530                         int i;
531 #if 1
532                         p = cbd;
533                         while (*p)
534                         {
535                                 if (*p == '\r' && *(p+1) == '\n')
536                                 {
537                                         *p++ = ';';
538                                         *p++ = ' ';
539                                 }
540                                 else if (*p == '\n' || *p == '\r' || *p == '\b')
541                                         *p++ = ';';
542                                 p++;
543                         }
544 #else
545                         strtok(cbd, "\n\r\b");
546 #endif
547                         i = (int)strlen(cbd);
548                         if (i + key_linepos >= MAX_INPUTLINE)
549                                 i= MAX_INPUTLINE - key_linepos - 1;
550                         if (i > 0)
551                         {
552                                 // terencehill: insert the clipboard text between the characters of the line
553                                 char *temp = (char *) Z_Malloc(MAX_INPUTLINE);
554                                 cbd[i]=0;
555                                 temp[0]=0;
556                                 if ( key_linepos < (int)strlen(key_line) )
557                                         strlcpy(temp, key_line + key_linepos, (int)strlen(key_line) - key_linepos +1);
558                                 key_line[key_linepos] = 0;
559                                 strlcat(key_line, cbd, sizeof(key_line));
560                                 if (temp[0])
561                                         strlcat(key_line, temp, sizeof(key_line));
562                                 Z_Free(temp);
563                                 key_linepos += i;
564                         }
565                         Z_Free(cbd);
566                 }
567                 return;
568         }
569
570         if (key == 'l' && keydown[K_CTRL])
571         {
572                 Cbuf_AddText ("clear\n");
573                 return;
574         }
575
576         if (key == 'u' && keydown[K_CTRL]) // like vi/readline ^u: delete currently edited line
577         {
578                 // clear line
579                 key_line[0] = ']';
580                 key_line[1] = 0;
581                 key_linepos = 1;
582                 return;
583         }
584
585         if (key == 'q' && keydown[K_CTRL]) // like zsh ^q: push line to history, don't execute, and clear
586         {
587                 // clear line
588                 Key_History_Push();
589                 key_line[0] = ']';
590                 key_line[1] = 0;
591                 key_linepos = 1;
592                 return;
593         }
594
595         if (key == K_ENTER || key == K_KP_ENTER)
596         {
597                 Cbuf_AddText (key_line+1);      // skip the ]
598                 Cbuf_AddText ("\n");
599                 Key_History_Push();
600                 key_line[0] = ']';
601                 key_line[1] = 0;        // EvilTypeGuy: null terminate
602                 key_linepos = 1;
603                 // force an update, because the command may take some time
604                 if (cls.state == ca_disconnected)
605                         CL_UpdateScreen ();
606                 return;
607         }
608
609         if (key == K_TAB)
610         {
611                 if(keydown[K_CTRL]) // append to the cvar its value
612                 {
613                         int             cvar_len, cvar_str_len, chars_to_move;
614                         char    k;
615                         char    cvar[MAX_INPUTLINE];
616                         const char *cvar_str;
617                         
618                         // go to the start of the variable
619                         while(--key_linepos)
620                         {
621                                 k = key_line[key_linepos];
622                                 if(k == '\"' || k == ';' || k == ' ' || k == '\'')
623                                         break;
624                         }
625                         key_linepos++;
626                         
627                         // save the variable name in cvar
628                         for(cvar_len=0; (k = key_line[key_linepos + cvar_len]) != 0; cvar_len++)
629                         {
630                                 if(k == '\"' || k == ';' || k == ' ' || k == '\'')
631                                         break;
632                                 cvar[cvar_len] = k;
633                         }
634                         if (cvar_len==0)
635                                 return;
636                         cvar[cvar_len] = 0;
637                         
638                         // go to the end of the cvar
639                         key_linepos += cvar_len;
640                         
641                         // save the content of the variable in cvar_str
642                         cvar_str = Cvar_VariableString(cvar);
643                         cvar_str_len = strlen(cvar_str);
644                         if (cvar_str_len==0)
645                                 return;
646                         
647                         // insert space and cvar_str in key_line
648                         chars_to_move = strlen(&key_line[key_linepos]);
649                         if (key_linepos + 1 + cvar_str_len + chars_to_move < MAX_INPUTLINE)
650                         {
651                                 if (chars_to_move)
652                                         memmove(&key_line[key_linepos + 1 + cvar_str_len], &key_line[key_linepos], chars_to_move);
653                                 key_line[key_linepos++] = ' ';
654                                 memcpy(&key_line[key_linepos], cvar_str, cvar_str_len);
655                                 key_linepos += cvar_str_len;
656                                 key_line[key_linepos + chars_to_move] = 0;
657                         }
658                         else
659                                 Con_Printf("Couldn't append cvar value, edit line too long.\n");
660                         return;
661                 }
662                 // Enhanced command completion
663                 // by EvilTypeGuy eviltypeguy@qeradiant.com
664                 // Thanks to Fett, Taniwha
665                 Con_CompleteCommandLine();
666                 return;
667         }
668
669         // Advanced Console Editing by Radix radix@planetquake.com
670         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
671         // Enhanced by [515]
672         // Enhanced by terencehill
673
674         // move cursor to the previous character
675         if (key == K_LEFTARROW || key == K_KP_LEFTARROW)
676         {
677                 if (key_linepos < 2)
678                         return;
679                 if(keydown[K_CTRL]) // move cursor to the previous word
680                 {
681                         int             pos;
682                         char    k;
683                         pos = key_linepos-1;
684
685                         if(pos) // skip all "; ' after the word
686                                 while(--pos)
687                                 {
688                                         k = key_line[pos];
689                                         if (!(k == '\"' || k == ';' || k == ' ' || k == '\''))
690                                                 break;
691                                 }
692
693                         if(pos)
694                                 while(--pos)
695                                 {
696                                         k = key_line[pos];
697                                         if(k == '\"' || k == ';' || k == ' ' || k == '\'')
698                                                 break;
699                                 }
700                         key_linepos = pos + 1;
701                 }
702                 else if(keydown[K_SHIFT]) // move cursor to the previous character ignoring colors
703                 {
704                         int             pos;
705                         pos = key_linepos-1;
706                         while (pos)
707                                 if(pos-1 > 0 && key_line[pos-1] == STRING_COLOR_TAG && isdigit(key_line[pos]))
708                                         pos-=2;
709                                 else if(pos-4 > 0 && key_line[pos-4] == STRING_COLOR_TAG && key_line[pos-3] == STRING_COLOR_RGB_TAG_CHAR
710                                                 && isxdigit(key_line[pos-2]) && isxdigit(key_line[pos-1]) && isxdigit(key_line[pos]))
711                                         pos-=5;
712                                 else
713                                 {
714                                         if(pos-1 > 0 && key_line[pos-1] == STRING_COLOR_TAG && key_line[pos] == STRING_COLOR_TAG) // consider ^^ as a character
715                                                 pos--;
716                                         pos--;
717                                         break;
718                                 }
719                         key_linepos = pos + 1;
720                 }
721                 else
722                         key_linepos--;
723                 return;
724         }
725
726         // delete char before cursor
727         if (key == K_BACKSPACE || (key == 'h' && keydown[K_CTRL]))
728         {
729                 if (key_linepos > 1)
730                 {
731                         strlcpy(key_line + key_linepos - 1, key_line + key_linepos, sizeof(key_line) + 1 - key_linepos);
732                         key_linepos--;
733                 }
734                 return;
735         }
736
737         // delete char on cursor
738         if (key == K_DEL || key == K_KP_DEL)
739         {
740                 size_t linelen;
741                 linelen = strlen(key_line);
742                 if (key_linepos < (int)linelen)
743                         memmove(key_line + key_linepos, key_line + key_linepos + 1, linelen - key_linepos);
744                 return;
745         }
746
747
748         // move cursor to the next character
749         if (key == K_RIGHTARROW || key == K_KP_RIGHTARROW)
750         {
751                 if (key_linepos >= (int)strlen(key_line))
752                         return;
753                 if(keydown[K_CTRL]) // move cursor to the next word
754                 {
755                         int             pos, len;
756                         char    k;
757                         len = (int)strlen(key_line);
758                         pos = key_linepos;
759
760                         while(++pos < len)
761                         {
762                                 k = key_line[pos];
763                                 if(k == '\"' || k == ';' || k == ' ' || k == '\'')
764                                         break;
765                         }
766                         
767                         if (pos < len) // skip all "; ' after the word
768                                 while(++pos < len)
769                                 {
770                                         k = key_line[pos];
771                                         if (!(k == '\"' || k == ';' || k == ' ' || k == '\''))
772                                                 break;
773                                 }
774                         key_linepos = pos;
775                 }
776                 else if(keydown[K_SHIFT]) // move cursor to the next character ignoring colors
777                 {
778                         int             pos, len;
779                         len = (int)strlen(key_line);
780                         pos = key_linepos;
781                         
782                         // go beyond all initial consecutive color tags, if any
783                         if(pos < len)
784                                 while (key_line[pos] == STRING_COLOR_TAG)
785                                 {
786                                         if(isdigit(key_line[pos+1]))
787                                                 pos+=2;
788                                         else if(key_line[pos+1] == STRING_COLOR_RGB_TAG_CHAR && isxdigit(key_line[pos+2]) && isxdigit(key_line[pos+3]) && isxdigit(key_line[pos+4]))
789                                                 pos+=5;
790                                         else
791                                                 break;
792                                 }
793                         
794                         // skip the char
795                         if (key_line[pos] == STRING_COLOR_TAG && key_line[pos+1] == STRING_COLOR_TAG) // consider ^^ as a character
796                                 pos++;
797                         pos++;
798                         
799                         // now go beyond all next consecutive color tags, if any
800                         if(pos < len)
801                                 while (key_line[pos] == STRING_COLOR_TAG)
802                                 {
803                                         if(isdigit(key_line[pos+1]))
804                                                 pos+=2;
805                                         else if(key_line[pos+1] == STRING_COLOR_RGB_TAG_CHAR && isxdigit(key_line[pos+2]) && isxdigit(key_line[pos+3]) && isxdigit(key_line[pos+4]))
806                                                 pos+=5;
807                                         else
808                                                 break;
809                                 }
810                         key_linepos = pos;
811                 }
812                 else
813                         key_linepos++;
814                 return;
815         }
816
817         if (key == K_INS || key == K_KP_INS) // toggle insert mode
818         {
819                 key_insert ^= 1;
820                 return;
821         }
822
823         // End Advanced Console Editing
824
825         if (key == K_UPARROW || key == K_KP_UPARROW || (key == 'p' && keydown[K_CTRL]))
826         {
827                 Key_History_Up();
828                 return;
829         }
830
831         if (key == K_DOWNARROW || key == K_KP_DOWNARROW || (key == 'n' && keydown[K_CTRL]))
832         {
833                 Key_History_Down();
834                 return;
835         }
836         // ~1.0795 = 82/76  using con_textsize 64 76 is height of the char, 6 is the distance between 2 lines
837         if (key == K_PGUP || key == K_KP_PGUP)
838         {
839                 if(keydown[K_CTRL])
840                 {
841                         con_backscroll += ((vid_conheight.integer >> 2) / con_textsize.integer)-1;
842                 }
843                 else
844                         con_backscroll += ((vid_conheight.integer >> 1) / con_textsize.integer)-3;
845                 return;
846         }
847
848         if (key == K_PGDN || key == K_KP_PGDN)
849         {
850                 if(keydown[K_CTRL])
851                 {
852                         con_backscroll -= ((vid_conheight.integer >> 2) / con_textsize.integer)-1;
853                 }
854                 else
855                         con_backscroll -= ((vid_conheight.integer >> 1) / con_textsize.integer)-3;
856                 return;
857         }
858  
859         if (key == K_MWHEELUP)
860         {
861                 if(keydown[K_CTRL])
862                         con_backscroll += 1;
863                 else if(keydown[K_SHIFT])
864                         con_backscroll += ((vid_conheight.integer >> 2) / con_textsize.integer)-1;
865                 else
866                         con_backscroll += 5;
867                 return;
868         }
869
870         if (key == K_MWHEELDOWN)
871         {
872                 if(keydown[K_CTRL])
873                         con_backscroll -= 1;
874                 else if(keydown[K_SHIFT])
875                         con_backscroll -= ((vid_conheight.integer >> 2) / con_textsize.integer)-1;
876                 else
877                         con_backscroll -= 5;
878                 return;
879         }
880
881         if (keydown[K_CTRL])
882         {
883                 // text zoom in
884                 if (key == '+' || key == K_KP_PLUS)
885                 {
886                         if (con_textsize.integer < 128)
887                                 Cvar_SetValueQuick(&con_textsize, con_textsize.integer + 1);
888                         return;
889                 }
890                 // text zoom out
891                 if (key == '-' || key == K_KP_MINUS)
892                 {
893                         if (con_textsize.integer > 1)
894                                 Cvar_SetValueQuick(&con_textsize, con_textsize.integer - 1);
895                         return;
896                 }
897                 // text zoom reset
898                 if (key == '0' || key == K_KP_INS)
899                 {
900                         Cvar_SetValueQuick(&con_textsize, atoi(Cvar_VariableDefString("con_textsize")));
901                         return;
902                 }
903         }
904
905         if (key == K_HOME || key == K_KP_HOME)
906         {
907                 if (keydown[K_CTRL])
908                         con_backscroll = INT_MAX;
909                 else
910                         key_linepos = 1;
911                 return;
912         }
913
914         if (key == K_END || key == K_KP_END)
915         {
916                 if (keydown[K_CTRL])
917                         con_backscroll = 0;
918                 else
919                         key_linepos = (int)strlen(key_line);
920                 return;
921         }
922
923         // non printable
924         if (ascii < 32)
925                 return;
926
927         if (key_linepos < MAX_INPUTLINE-1)
928         {
929                 int len;
930                 len = (int)strlen(&key_line[key_linepos]);
931                 // check insert mode, or always insert if at end of line
932                 if (key_insert || len == 0)
933                 {
934                         // can't use strcpy to move string to right
935                         len++;
936                         memmove(&key_line[key_linepos + 1], &key_line[key_linepos], len);
937                 }
938                 key_line[key_linepos] = ascii;
939                 key_linepos++;
940         }
941 }
942
943 //============================================================================
944
945 int chat_mode;
946 char            chat_buffer[MAX_INPUTLINE];
947 unsigned int    chat_bufferlen = 0;
948
949 extern int Nicks_CompleteChatLine(char *buffer, size_t size, unsigned int pos);
950
951 static void
952 Key_Message (int key, int ascii)
953 {
954
955         if (key == K_ENTER || ascii == 10 || ascii == 13)
956         {
957                 if(chat_mode < 0)
958                         Cmd_ExecuteString(chat_buffer, src_command); // not Cbuf_AddText to allow semiclons in args; however, this allows no variables then. Use aliases!
959                 else
960                         Cmd_ForwardStringToServer(va("%s %s", chat_mode ? "say_team" : "say ", chat_buffer));
961
962                 key_dest = key_game;
963                 chat_bufferlen = 0;
964                 chat_buffer[0] = 0;
965                 return;
966         }
967
968         // TODO add support for arrow keys and simple editing
969
970         if (key == K_ESCAPE) {
971                 key_dest = key_game;
972                 chat_bufferlen = 0;
973                 chat_buffer[0] = 0;
974                 return;
975         }
976
977         if (key == K_BACKSPACE) {
978                 if (chat_bufferlen) {
979                         chat_bufferlen--;
980                         chat_buffer[chat_bufferlen] = 0;
981                 }
982                 return;
983         }
984
985         if(key == K_TAB) {
986                 chat_bufferlen = Nicks_CompleteChatLine(chat_buffer, sizeof(chat_buffer), chat_bufferlen);
987                 return;
988         }
989
990         if (chat_bufferlen == sizeof (chat_buffer) - 1)
991                 return;                                                 // all full
992
993         if (!ascii)
994                 return;                                                 // non printable
995
996         chat_buffer[chat_bufferlen++] = ascii;
997         chat_buffer[chat_bufferlen] = 0;
998 }
999
1000 //============================================================================
1001
1002
1003 /*
1004 ===================
1005 Returns a key number to be used to index keybindings[] by looking at
1006 the given string.  Single ascii characters return themselves, while
1007 the K_* names are matched up.
1008 ===================
1009 */
1010 int
1011 Key_StringToKeynum (const char *str)
1012 {
1013         const keyname_t  *kn;
1014
1015         if (!str || !str[0])
1016                 return -1;
1017         if (!str[1])
1018                 return tolower(str[0]);
1019
1020         for (kn = keynames; kn->name; kn++) {
1021                 if (!strcasecmp (str, kn->name))
1022                         return kn->keynum;
1023         }
1024         return -1;
1025 }
1026
1027 /*
1028 ===================
1029 Returns a string (either a single ascii char, or a K_* name) for the
1030 given keynum.
1031 FIXME: handle quote special (general escape sequence?)
1032 ===================
1033 */
1034 const char *
1035 Key_KeynumToString (int keynum)
1036 {
1037         const keyname_t  *kn;
1038         static char tinystr[2];
1039
1040         // -1 is an invalid code
1041         if (keynum < 0)
1042                 return "<KEY NOT FOUND>";
1043
1044         // search overrides first, because some characters are special
1045         for (kn = keynames; kn->name; kn++)
1046                 if (keynum == kn->keynum)
1047                         return kn->name;
1048
1049         // if it is printable, output it as a single character
1050         if (keynum > 32 && keynum < 256)
1051         {
1052                 tinystr[0] = keynum;
1053                 tinystr[1] = 0;
1054                 return tinystr;
1055         }
1056
1057         // if it is not overridden and not printable, we don't know what to do with it
1058         return "<UNKNOWN KEYNUM>";
1059 }
1060
1061
1062 void
1063 Key_SetBinding (int keynum, int bindmap, const char *binding)
1064 {
1065         char *newbinding;
1066         size_t l;
1067
1068         if (keynum == -1 || keynum >= MAX_KEYS)
1069                 return;
1070
1071 // free old bindings
1072         if (keybindings[bindmap][keynum]) {
1073                 Z_Free (keybindings[bindmap][keynum]);
1074                 keybindings[bindmap][keynum] = NULL;
1075         }
1076         if(!binding[0]) // make "" binds be removed --blub
1077                 return;
1078 // allocate memory for new binding
1079         l = strlen (binding);
1080         newbinding = (char *)Z_Malloc (l + 1);
1081         memcpy (newbinding, binding, l + 1);
1082         newbinding[l] = 0;
1083         keybindings[bindmap][keynum] = newbinding;
1084 }
1085
1086 static void
1087 Key_In_Unbind_f (void)
1088 {
1089         int         b, m;
1090         char *errchar = NULL;
1091
1092         if (Cmd_Argc () != 3) {
1093                 Con_Print("in_unbind <bindmap> <key> : remove commands from a key\n");
1094                 return;
1095         }
1096
1097         m = strtol(Cmd_Argv (1), &errchar, 0);
1098         if ((m < 0) || (m >= 8) || (errchar && *errchar)) {
1099                 Con_Printf("%s isn't a valid bindmap\n", Cmd_Argv(1));
1100                 return;
1101         }
1102
1103         b = Key_StringToKeynum (Cmd_Argv (2));
1104         if (b == -1) {
1105                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (2));
1106                 return;
1107         }
1108
1109         Key_SetBinding (b, m, "");
1110 }
1111
1112 static void
1113 Key_In_Bind_f (void)
1114 {
1115         int         i, c, b, m;
1116         char        cmd[MAX_INPUTLINE];
1117         char *errchar = NULL;
1118
1119         c = Cmd_Argc ();
1120
1121         if (c != 3 && c != 4) {
1122                 Con_Print("in_bind <bindmap> <key> [command] : attach a command to a key\n");
1123                 return;
1124         }
1125
1126         m = strtol(Cmd_Argv (1), &errchar, 0);
1127         if ((m < 0) || (m >= 8) || (errchar && *errchar)) {
1128                 Con_Printf("%s isn't a valid bindmap\n", Cmd_Argv(1));
1129                 return;
1130         }
1131
1132         b = Key_StringToKeynum (Cmd_Argv (2));
1133         if (b == -1 || b >= MAX_KEYS) {
1134                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (2));
1135                 return;
1136         }
1137
1138         if (c == 3) {
1139                 if (keybindings[m][b])
1140                         Con_Printf("\"%s\" = \"%s\"\n", Cmd_Argv (2), keybindings[m][b]);
1141                 else
1142                         Con_Printf("\"%s\" is not bound\n", Cmd_Argv (2));
1143                 return;
1144         }
1145 // copy the rest of the command line
1146         cmd[0] = 0;                                                     // start out with a null string
1147         for (i = 3; i < c; i++) {
1148                 strlcat (cmd, Cmd_Argv (i), sizeof (cmd));
1149                 if (i != (c - 1))
1150                         strlcat (cmd, " ", sizeof (cmd));
1151         }
1152
1153         Key_SetBinding (b, m, cmd);
1154 }
1155
1156 static void
1157 Key_In_Bindmap_f (void)
1158 {
1159         int         m1, m2, c;
1160         char *errchar = NULL;
1161
1162         c = Cmd_Argc ();
1163
1164         if (c != 3) {
1165                 Con_Print("in_bindmap <bindmap> <fallback>: set current bindmap and fallback\n");
1166                 return;
1167         }
1168
1169         m1 = strtol(Cmd_Argv (1), &errchar, 0);
1170         if ((m1 < 0) || (m1 >= 8) || (errchar && *errchar)) {
1171                 Con_Printf("%s isn't a valid bindmap\n", Cmd_Argv(1));
1172                 return;
1173         }
1174
1175         m2 = strtol(Cmd_Argv (2), &errchar, 0);
1176         if ((m2 < 0) || (m2 >= 8) || (errchar && *errchar)) {
1177                 Con_Printf("%s isn't a valid bindmap\n", Cmd_Argv(2));
1178                 return;
1179         }
1180
1181         key_bmap = m1;
1182         key_bmap2 = m2;
1183 }
1184
1185 static void
1186 Key_Unbind_f (void)
1187 {
1188         int         b;
1189
1190         if (Cmd_Argc () != 2) {
1191                 Con_Print("unbind <key> : remove commands from a key\n");
1192                 return;
1193         }
1194
1195         b = Key_StringToKeynum (Cmd_Argv (1));
1196         if (b == -1) {
1197                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (1));
1198                 return;
1199         }
1200
1201         Key_SetBinding (b, 0, "");
1202 }
1203
1204 static void
1205 Key_Unbindall_f (void)
1206 {
1207         int         i, j;
1208
1209         for (j = 0; j < 8; j++)
1210                 for (i = 0; i < (int)(sizeof(keybindings[0])/sizeof(keybindings[0][0])); i++)
1211                         if (keybindings[j][i])
1212                                 Key_SetBinding (i, j, "");
1213 }
1214
1215 static void
1216 Key_PrintBindList(int j)
1217 {
1218         char bindbuf[MAX_INPUTLINE];
1219         const char *p;
1220         int i;
1221
1222         for (i = 0; i < (int)(sizeof(keybindings[0])/sizeof(keybindings[0][0])); i++)
1223         {
1224                 p = keybindings[j][i];
1225                 if (p)
1226                 {
1227                         Cmd_QuoteString(bindbuf, sizeof(bindbuf), p, "\"\\");
1228                         if (j == 0)
1229                                 Con_Printf("^2%s ^7= \"%s\"\n", Key_KeynumToString (i), bindbuf);
1230                         else
1231                                 Con_Printf("^3bindmap %d: ^2%s ^7= \"%s\"\n", j, Key_KeynumToString (i), bindbuf);
1232                 }
1233         }
1234 }
1235
1236 static void
1237 Key_In_BindList_f (void)
1238 {
1239         int m;
1240         char *errchar = NULL;
1241
1242         if(Cmd_Argc() >= 2)
1243         {
1244                 m = strtol(Cmd_Argv(1), &errchar, 0);
1245                 if ((m < 0) || (m >= 8) || (errchar && *errchar)) {
1246                         Con_Printf("%s isn't a valid bindmap\n", Cmd_Argv(1));
1247                         return;
1248                 }
1249                 Key_PrintBindList(m);
1250         }
1251         else
1252         {
1253                 for (m = 0; m < MAX_BINDMAPS; m++)
1254                         Key_PrintBindList(m);
1255         }
1256 }
1257
1258 static void
1259 Key_BindList_f (void)
1260 {
1261         Key_PrintBindList(0);
1262 }
1263
1264 static void
1265 Key_Bind_f (void)
1266 {
1267         int         i, c, b;
1268         char        cmd[MAX_INPUTLINE];
1269
1270         c = Cmd_Argc ();
1271
1272         if (c != 2 && c != 3) {
1273                 Con_Print("bind <key> [command] : attach a command to a key\n");
1274                 return;
1275         }
1276         b = Key_StringToKeynum (Cmd_Argv (1));
1277         if (b == -1 || b >= MAX_KEYS) {
1278                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (1));
1279                 return;
1280         }
1281
1282         if (c == 2) {
1283                 if (keybindings[0][b])
1284                         Con_Printf("\"%s\" = \"%s\"\n", Cmd_Argv (1), keybindings[0][b]);
1285                 else
1286                         Con_Printf("\"%s\" is not bound\n", Cmd_Argv (1));
1287                 return;
1288         }
1289 // copy the rest of the command line
1290         cmd[0] = 0;                                                     // start out with a null string
1291         for (i = 2; i < c; i++) {
1292                 strlcat (cmd, Cmd_Argv (i), sizeof (cmd));
1293                 if (i != (c - 1))
1294                         strlcat (cmd, " ", sizeof (cmd));
1295         }
1296
1297         Key_SetBinding (b, 0, cmd);
1298 }
1299
1300 /*
1301 ============
1302 Writes lines containing "bind key value"
1303 ============
1304 */
1305 void
1306 Key_WriteBindings (qfile_t *f)
1307 {
1308         int         i, j;
1309         char bindbuf[MAX_INPUTLINE];
1310         const char *p;
1311
1312         for (j = 0; j < MAX_BINDMAPS; j++)
1313         {
1314                 for (i = 0; i < (int)(sizeof(keybindings[0])/sizeof(keybindings[0][0])); i++)
1315                 {
1316                         p = keybindings[j][i];
1317                         if (p)
1318                         {
1319                                 Cmd_QuoteString(bindbuf, sizeof(bindbuf), p, "\"\\"); // don't need to escape $ because cvars are not expanded inside bind
1320                                 if (j == 0)
1321                                         FS_Printf(f, "bind %s \"%s\"\n", Key_KeynumToString (i), bindbuf);
1322                                 else
1323                                         FS_Printf(f, "in_bind %d %s \"%s\"\n", j, Key_KeynumToString (i), bindbuf);
1324                         }
1325                 }
1326         }
1327 }
1328
1329
1330 void
1331 Key_Init (void)
1332 {
1333         Key_History_Init();
1334         key_line[0] = ']';
1335         key_line[1] = 0;
1336         key_linepos = 1;
1337
1338 //
1339 // register our functions
1340 //
1341         Cmd_AddCommand ("in_bind", Key_In_Bind_f, "binds a command to the specified key in the selected bindmap");
1342         Cmd_AddCommand ("in_unbind", Key_In_Unbind_f, "removes command on the specified key in the selected bindmap");
1343         Cmd_AddCommand ("in_bindlist", Key_In_BindList_f, "bindlist: displays bound keys for all bindmaps, or the given bindmap");
1344         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");
1345
1346         Cmd_AddCommand ("bind", Key_Bind_f, "binds a command to the specified key in bindmap 0");
1347         Cmd_AddCommand ("unbind", Key_Unbind_f, "removes a command on the specified key in bindmap 0");
1348         Cmd_AddCommand ("bindlist", Key_BindList_f, "bindlist: displays bound keys for bindmap 0 bindmaps");
1349         Cmd_AddCommand ("unbindall", Key_Unbindall_f, "removes all commands from all keys in all bindmaps (leaving only shift-escape and escape)");
1350
1351         Cvar_RegisterVariable (&con_closeontoggleconsole);
1352 }
1353
1354 void
1355 Key_Shutdown (void)
1356 {
1357         Key_History_Shutdown();
1358 }
1359
1360 const char *Key_GetBind (int key)
1361 {
1362         const char *bind;
1363         if (key < 0 || key >= MAX_KEYS)
1364                 return NULL;
1365         bind = keybindings[key_bmap][key];
1366         if (!bind)
1367                 bind = keybindings[key_bmap2][key];
1368         return bind;
1369 }
1370
1371 qboolean CL_VM_InputEvent (qboolean down, int key, int ascii);
1372
1373 /*
1374 ===================
1375 Called by the system between frames for both key up and key down events
1376 Should NOT be called during an interrupt!
1377 ===================
1378 */
1379 static char tbl_keyascii[MAX_KEYS];
1380 static keydest_t tbl_keydest[MAX_KEYS];
1381
1382 void
1383 Key_Event (int key, int ascii, qboolean down)
1384 {
1385         const char *bind;
1386         qboolean q;
1387         keydest_t keydest = key_dest;
1388
1389         if (key < 0 || key >= MAX_KEYS)
1390                 return;
1391
1392         // get key binding
1393         bind = keybindings[key_bmap][key];
1394         if (!bind)
1395                 bind = keybindings[key_bmap2][key];
1396
1397         if (developer.integer >= 1000)
1398                 Con_Printf("Key_Event(%i, '%c', %s) keydown %i bind \"%s\"\n", key, ascii, down ? "down" : "up", keydown[key], bind ? bind : "");
1399
1400         if(key_consoleactive)
1401                 keydest = key_console;
1402         
1403         if (down)
1404         {
1405                 // increment key repeat count each time a down is received so that things
1406                 // which want to ignore key repeat can ignore it
1407                 keydown[key] = min(keydown[key] + 1, 2);
1408                 if(keydown[key] == 1) {
1409                         tbl_keyascii[key] = ascii;
1410                         tbl_keydest[key] = keydest;
1411                 } else {
1412                         ascii = tbl_keyascii[key];
1413                         keydest = tbl_keydest[key];
1414                 }
1415         }
1416         else
1417         {
1418                 // clear repeat count now that the key is released
1419                 keydown[key] = 0;
1420                 keydest = tbl_keydest[key];
1421                 ascii = tbl_keyascii[key];
1422         }
1423
1424         if(keydest == key_void)
1425                 return;
1426         
1427         // key_consoleactive is a flag not a key_dest because the console is a
1428         // high priority overlay ontop of the normal screen (designed as a safety
1429         // feature so that developers and users can rescue themselves from a bad
1430         // situation).
1431         //
1432         // this also means that toggling the console on/off does not lose the old
1433         // key_dest state
1434
1435         // specially handle escape (togglemenu) and shift-escape (toggleconsole)
1436         // engine bindings, these are not handled as normal binds so that the user
1437         // can recover from a completely empty bindmap
1438         if (key == K_ESCAPE)
1439         {
1440                 // ignore key repeats on escape
1441                 if (keydown[key] > 1)
1442                         return;
1443
1444                 // escape does these things:
1445                 // key_consoleactive - close console
1446                 // key_message - abort messagemode
1447                 // key_menu - go to parent menu (or key_game)
1448                 // key_game - open menu
1449
1450                 // in all modes shift-escape toggles console
1451                 if (keydown[K_SHIFT])
1452                 {
1453                         if(down)
1454                         {
1455                                 Con_ToggleConsole_f ();
1456                                 tbl_keydest[key] = key_void; // esc release should go nowhere (especially not to key_menu or key_game)
1457                         }
1458                         return;
1459                 }
1460
1461                 switch (keydest)
1462                 {
1463                         case key_console:
1464                                 if(down)
1465                                 {
1466                                         if(key_consoleactive & KEY_CONSOLEACTIVE_FORCED)
1467                                         {
1468                                                 key_consoleactive &= ~KEY_CONSOLEACTIVE_USER;
1469                                                 MR_ToggleMenu_f ();
1470                                         }
1471                                         else
1472                                                 Con_ToggleConsole_f();
1473                                 }
1474                                 break;
1475
1476                         case key_message:
1477                                 if (down)
1478                                         Key_Message (key, ascii); // that'll close the message input
1479                                 break;
1480
1481                         case key_menu:
1482                         case key_menu_grabbed:
1483                                 MR_KeyEvent (key, ascii, down);
1484                                 break;
1485
1486                         case key_game:
1487                                 // csqc has priority over toggle menu if it wants to (e.g. handling escape for UI stuff in-game.. :sick:)
1488                                 q = CL_VM_InputEvent(down, key, ascii);
1489                                 if (!q && down)
1490                                         MR_ToggleMenu_f ();
1491                                 break;
1492
1493                         default:
1494                                 Con_Printf ("Key_Event: Bad key_dest\n");
1495                 }
1496                 return;
1497         }
1498
1499         // send function keydowns to interpreter no matter what mode is (unless the menu has specifically grabbed the keyboard, for rebinding keys)
1500         if (keydest != key_menu_grabbed)
1501         if (key >= K_F1 && key <= K_F12)
1502         {
1503                 if (bind)
1504                 {
1505                         if(keydown[key] == 1 && down)
1506                         {
1507                                 // button commands add keynum as a parm
1508                                 if (bind[0] == '+')
1509                                         Cbuf_AddText (va("%s %i\n", bind, key));
1510                                 else
1511                                 {
1512                                         Cbuf_AddText (bind);
1513                                         Cbuf_AddText ("\n");
1514                                 }
1515                         } else if(bind[0] == '+' && !down && keydown[key] == 0)
1516                                 Cbuf_AddText(va("-%s %i\n", bind + 1, key));
1517                 }
1518                 return;
1519         }
1520
1521         // send input to console if it wants it
1522         if (keydest == key_console)
1523         {
1524                 if (!down)
1525                         return;
1526                 // con_closeontoggleconsole enables toggleconsole keys to close the
1527                 // console, as long as they are not the color prefix character
1528                 // (special exemption for german keyboard layouts)
1529                 if (con_closeontoggleconsole.integer && bind && !strncmp(bind, "toggleconsole", strlen("toggleconsole")) && (key_consoleactive & KEY_CONSOLEACTIVE_USER) && ascii != STRING_COLOR_TAG)
1530                 {
1531                         Con_ToggleConsole_f ();
1532                         return;
1533                 }
1534                 Key_Console (key, ascii);
1535                 return;
1536         }
1537
1538         // handle toggleconsole in menu too
1539         if (keydest == key_menu)
1540         {
1541                 if (down && con_closeontoggleconsole.integer && bind && !strncmp(bind, "toggleconsole", strlen("toggleconsole")) && ascii != STRING_COLOR_TAG)
1542                 {
1543                         Con_ToggleConsole_f ();
1544                         tbl_keydest[key] = key_void; // key release should go nowhere (especially not to key_menu or key_game)
1545                         return;
1546                 }
1547         }
1548
1549         // ignore binds while a video is played, let the video system handle the key event
1550         if (cl_videoplaying)
1551         {
1552                 CL_Video_KeyEvent (key, ascii, keydown[key] != 0);
1553                 return;
1554         }
1555
1556         // anything else is a key press into the game, chat line, or menu
1557         switch (keydest)
1558         {
1559                 case key_message:
1560                         if (down)
1561                                 Key_Message (key, ascii);
1562                         break;
1563                 case key_menu:
1564                 case key_menu_grabbed:
1565                         MR_KeyEvent (key, ascii, down);
1566                         break;
1567                 case key_game:
1568                         q = CL_VM_InputEvent(down, key, ascii);
1569                         // ignore key repeats on binds and only send the bind if the event hasnt been already processed by csqc
1570                         if (!q && bind)
1571                         {
1572                                 if(keydown[key] == 1 && down)
1573                                 {
1574                                         // button commands add keynum as a parm
1575                                         if (bind[0] == '+')
1576                                                 Cbuf_AddText (va("%s %i\n", bind, key));
1577                                         else
1578                                         {
1579                                                 Cbuf_AddText (bind);
1580                                                 Cbuf_AddText ("\n");
1581                                         }
1582                                 } else if(bind[0] == '+' && !down && keydown[key] == 0)
1583                                         Cbuf_AddText(va("-%s %i\n", bind + 1, key));
1584                         }
1585                         break;
1586                 default:
1587                         Con_Printf ("Key_Event: Bad key_dest\n");
1588         }
1589 }
1590
1591 /*
1592 ===================
1593 Key_ClearStates
1594 ===================
1595 */
1596 void
1597 Key_ClearStates (void)
1598 {
1599         memset(keydown, 0, sizeof(keydown));
1600 }