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