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