]> git.xonotic.org Git - xonotic/darkplaces.git/blob - keys.c
physics: fix and refactor unsticking
[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_CLIENT | 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(cmd_state_t *cmd)
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 (cmd) > 1)
306         {
307                 if (!strcmp(Cmd_Argv(cmd, 1), "-c"))
308                 {
309                         ConBuffer_Clear(&history);
310                         return;
311                 }
312                 i = strtol(Cmd_Argv(cmd, 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 int Key_ClearEditLine(qboolean is_console)
667 {
668         if (is_console)
669         {
670                 key_line[0] = ']';
671                 key_line[1] = 0;
672                 return 1;
673         }
674         else
675         {
676                 chat_buffer[0] = 0;
677                 return 0;
678         }
679 }
680
681 // key modifier states
682 #define KM_NONE           (!keydown[K_CTRL] && !keydown[K_SHIFT] && !keydown[K_ALT])
683 #define KM_CTRL_SHIFT_ALT ( keydown[K_CTRL] &&  keydown[K_SHIFT] &&  keydown[K_ALT])
684 #define KM_CTRL_SHIFT     ( keydown[K_CTRL] &&  keydown[K_SHIFT] && !keydown[K_ALT])
685 #define KM_CTRL_ALT       ( keydown[K_CTRL] && !keydown[K_SHIFT] &&  keydown[K_ALT])
686 #define KM_SHIFT_ALT      (!keydown[K_CTRL] &&  keydown[K_SHIFT] &&  keydown[K_ALT])
687 #define KM_CTRL           ( keydown[K_CTRL] && !keydown[K_SHIFT] && !keydown[K_ALT])
688 #define KM_SHIFT          (!keydown[K_CTRL] &&  keydown[K_SHIFT] && !keydown[K_ALT])
689 #define KM_ALT            (!keydown[K_CTRL] && !keydown[K_SHIFT] &&  keydown[K_ALT])
690
691 /*
692 ====================
693 Interactive line editing and console scrollback
694 ====================
695 */
696
697 int chat_mode; // 0 for say, 1 for say_team, -1 for command
698 char chat_buffer[MAX_INPUTLINE];
699 int chat_bufferpos = 0;
700
701 int Key_AddChar(int unicode, qboolean is_console)
702 {
703         char *line;
704         char buf[16];
705         int len, blen, linepos;
706
707         if (is_console)
708         {
709                 line = key_line;
710                 linepos = key_linepos;
711         }
712         else
713         {
714                 line = chat_buffer;
715                 linepos = chat_bufferpos;
716         }
717
718         if (linepos >= MAX_INPUTLINE-1)
719                 return linepos;
720
721         blen = u8_fromchar(unicode, buf, sizeof(buf));
722         if (!blen)
723                 return linepos;
724         len = (int)strlen(&line[linepos]);
725         // check insert mode, or always insert if at end of line
726         if (key_insert || len == 0)
727         {
728                 if (linepos + len + blen >= MAX_INPUTLINE)
729                         return linepos;
730                 // can't use strcpy to move string to right
731                 len++;
732                 if (linepos + blen + len >= MAX_INPUTLINE)
733                         return linepos;
734                 memmove(&line[linepos + blen], &line[linepos], len);
735         }
736         else if (linepos + len + blen - u8_bytelen(line + linepos, 1) >= MAX_INPUTLINE)
737                 return linepos;
738         memcpy(line + linepos, buf, blen);
739         if (blen > len)
740                 line[linepos + blen] = 0;
741         linepos += blen;
742         return linepos;
743 }
744
745 // returns -1 if no key has been recognized
746 // returns linepos (>= 0) otherwise
747 // if is_console is true can modify key_line (doesn't change key_linepos)
748 int Key_Parse_CommonKeys(cmd_state_t *cmd, qboolean is_console, int key, int unicode)
749 {
750         char *line;
751         int linepos, linestart;
752         unsigned int linesize;
753         if (is_console)
754         {
755                 line = key_line;
756                 linepos = key_linepos;
757                 linesize = sizeof(key_line);
758                 linestart = 1;
759         }
760         else
761         {
762                 line = chat_buffer;
763                 linepos = chat_bufferpos;
764                 linesize = sizeof(chat_buffer);
765                 linestart = 0;
766         }
767
768         if ((key == 'v' && KM_CTRL) || ((key == K_INS || key == K_KP_INS) && KM_SHIFT))
769         {
770                 char *cbd, *p;
771                 if ((cbd = Sys_GetClipboardData()) != 0)
772                 {
773                         int i;
774 #if 1
775                         p = cbd;
776                         while (*p)
777                         {
778                                 if (*p == '\r' && *(p+1) == '\n')
779                                 {
780                                         *p++ = ';';
781                                         *p++ = ' ';
782                                 }
783                                 else if (*p == '\n' || *p == '\r' || *p == '\b')
784                                         *p++ = ';';
785                                 p++;
786                         }
787 #else
788                         strtok(cbd, "\n\r\b");
789 #endif
790                         i = (int)strlen(cbd);
791                         if (i + linepos >= MAX_INPUTLINE)
792                                 i= MAX_INPUTLINE - linepos - 1;
793                         if (i > 0)
794                         {
795                                 cbd[i] = 0;
796                                 memmove(line + linepos + i, line + linepos, linesize - linepos - i);
797                                 memcpy(line + linepos, cbd, i);
798                                 linepos += i;
799                         }
800                         Z_Free(cbd);
801                 }
802                 return linepos;
803         }
804
805         if (key == 'u' && KM_CTRL) // like vi/readline ^u: delete currently edited line
806         {
807                 return Key_ClearEditLine(is_console);
808         }
809
810         if (key == K_TAB)
811         {
812                 if (is_console && KM_CTRL) // append the cvar value to the cvar name
813                 {
814                         int             cvar_len, cvar_str_len, chars_to_move;
815                         char    k;
816                         char    cvar[MAX_INPUTLINE];
817                         const char *cvar_str;
818
819                         // go to the start of the variable
820                         while(--linepos)
821                         {
822                                 k = line[linepos];
823                                 if(k == '\"' || k == ';' || k == ' ' || k == '\'')
824                                         break;
825                         }
826                         linepos++;
827
828                         // save the variable name in cvar
829                         for(cvar_len=0; (k = line[linepos + cvar_len]) != 0; cvar_len++)
830                         {
831                                 if(k == '\"' || k == ';' || k == ' ' || k == '\'')
832                                         break;
833                                 cvar[cvar_len] = k;
834                         }
835                         if (cvar_len==0)
836                                 return linepos;
837                         cvar[cvar_len] = 0;
838
839                         // go to the end of the cvar
840                         linepos += cvar_len;
841
842                         // save the content of the variable in cvar_str
843                         cvar_str = Cvar_VariableString(&cvars_all, cvar, CVAR_CLIENT | CVAR_SERVER);
844                         cvar_str_len = (int)strlen(cvar_str);
845                         if (cvar_str_len==0)
846                                 return linepos;
847
848                         // insert space and cvar_str in line
849                         chars_to_move = (int)strlen(&line[linepos]);
850                         if (linepos + 1 + cvar_str_len + chars_to_move < MAX_INPUTLINE)
851                         {
852                                 if (chars_to_move)
853                                         memmove(&line[linepos + 1 + cvar_str_len], &line[linepos], chars_to_move);
854                                 line[linepos++] = ' ';
855                                 memcpy(&line[linepos], cvar_str, cvar_str_len);
856                                 linepos += cvar_str_len;
857                                 line[linepos + chars_to_move] = 0;
858                         }
859                         else
860                                 Con_Printf("Couldn't append cvar value, edit line too long.\n");
861                         return linepos;
862                 }
863
864                 if (KM_NONE)
865                         return Con_CompleteCommandLine(cmd, is_console);
866         }
867
868         // Advanced Console Editing by Radix radix@planetquake.com
869         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
870         // Enhanced by [515]
871         // Enhanced by terencehill
872
873         // move cursor to the previous character
874         if (key == K_LEFTARROW || key == K_KP_LEFTARROW)
875         {
876                 if(KM_CTRL) // move cursor to the previous word
877                 {
878                         int             pos;
879                         char    k;
880                         if (linepos <= linestart + 1)
881                                 return linestart;
882                         pos = linepos;
883
884                         do {
885                                 k = line[--pos];
886                                 if (!(k == '\"' || k == ';' || k == ' ' || k == '\''))
887                                         break;
888                         } while(pos > linestart); // skip all "; ' after the word
889
890                         if (pos == linestart)
891                                 return linestart;
892
893                         do {
894                                 k = line[--pos];
895                                 if (k == '\"' || k == ';' || k == ' ' || k == '\'')
896                                 {
897                                         pos++;
898                                         break;
899                                 }
900                         } while(pos > linestart);
901
902                         linepos = pos;
903                         return linepos;
904                 }
905
906                 if(KM_SHIFT) // move cursor to the previous character ignoring colors
907                 {
908                         int             pos;
909                         size_t          inchar = 0;
910                         if (linepos <= linestart + 1)
911                                 return linestart;
912                         pos = (int)u8_prevbyte(line + linestart, linepos - linestart) + linestart;
913                         while (pos > linestart)
914                                 if(pos-1 >= linestart && line[pos-1] == STRING_COLOR_TAG && isdigit(line[pos]))
915                                         pos-=2;
916                                 else if(pos-4 >= linestart && line[pos-4] == STRING_COLOR_TAG && line[pos-3] == STRING_COLOR_RGB_TAG_CHAR
917                                                 && isxdigit(line[pos-2]) && isxdigit(line[pos-1]) && isxdigit(line[pos]))
918                                         pos-=5;
919                                 else
920                                 {
921                                         if(pos-1 >= linestart && line[pos-1] == STRING_COLOR_TAG && line[pos] == STRING_COLOR_TAG) // consider ^^ as a character
922                                                 pos--;
923                                         pos--;
924                                         break;
925                                 }
926                         if (pos < linestart)
927                                 return linestart;
928                         // we need to move to the beginning of the character when in a wide character:
929                         u8_charidx(line, pos + 1, &inchar);
930                         linepos = (int)(pos + 1 - inchar);
931                         return linepos;
932                 }
933
934                 if(KM_NONE)
935                 {
936                         if (linepos <= linestart + 1)
937                                 return linestart;
938                         // hide ']' from u8_prevbyte otherwise it could go out of bounds
939                         linepos = (int)u8_prevbyte(line + linestart, linepos - linestart) + linestart;
940                         return linepos;
941                 }
942         }
943
944         // delete char before cursor
945         if ((key == K_BACKSPACE && KM_NONE) || (key == 'h' && KM_CTRL))
946         {
947                 if (linepos > linestart)
948                 {
949                         // hide ']' from u8_prevbyte otherwise it could go out of bounds
950                         int newpos = (int)u8_prevbyte(line + linestart, linepos - linestart) + linestart;
951                         strlcpy(line + newpos, line + linepos, linesize + 1 - linepos);
952                         linepos = newpos;
953                 }
954                 return linepos;
955         }
956
957         // delete char on cursor
958         if ((key == K_DEL || key == K_KP_DEL) && KM_NONE)
959         {
960                 size_t linelen;
961                 linelen = strlen(line);
962                 if (linepos < (int)linelen)
963                         memmove(line + linepos, line + linepos + u8_bytelen(line + linepos, 1), linelen - linepos);
964                 return linepos;
965         }
966
967         // move cursor to the next character
968         if (key == K_RIGHTARROW || key == K_KP_RIGHTARROW)
969         {
970                 if (KM_CTRL) // move cursor to the next word
971                 {
972                         int             pos, len;
973                         char    k;
974                         len = (int)strlen(line);
975                         if (linepos >= len)
976                                 return linepos;
977                         pos = linepos;
978
979                         while(++pos < len)
980                         {
981                                 k = line[pos];
982                                 if(k == '\"' || k == ';' || k == ' ' || k == '\'')
983                                         break;
984                         }
985
986                         if (pos < len) // skip all "; ' after the word
987                                 while(++pos < len)
988                                 {
989                                         k = line[pos];
990                                         if (!(k == '\"' || k == ';' || k == ' ' || k == '\''))
991                                                 break;
992                                 }
993                         linepos = pos;
994                         return linepos;
995                 }
996
997                 if (KM_SHIFT) // move cursor to the next character ignoring colors
998                 {
999                         int             pos, len;
1000                         len = (int)strlen(line);
1001                         if (linepos >= len)
1002                                 return linepos;
1003                         pos = linepos;
1004
1005                         // go beyond all initial consecutive color tags, if any
1006                         if(pos < len)
1007                                 while (line[pos] == STRING_COLOR_TAG)
1008                                 {
1009                                         if(isdigit(line[pos+1]))
1010                                                 pos+=2;
1011                                         else if(line[pos+1] == STRING_COLOR_RGB_TAG_CHAR && isxdigit(line[pos+2]) && isxdigit(line[pos+3]) && isxdigit(line[pos+4]))
1012                                                 pos+=5;
1013                                         else
1014                                                 break;
1015                                 }
1016
1017                         // skip the char
1018                         if (line[pos] == STRING_COLOR_TAG && line[pos+1] == STRING_COLOR_TAG) // consider ^^ as a character
1019                                 pos++;
1020                         pos += (int)u8_bytelen(line + pos, 1);
1021
1022                         // now go beyond all next consecutive color tags, if any
1023                         if(pos < len)
1024                                 while (line[pos] == STRING_COLOR_TAG)
1025                                 {
1026                                         if(isdigit(line[pos+1]))
1027                                                 pos+=2;
1028                                         else if(line[pos+1] == STRING_COLOR_RGB_TAG_CHAR && isxdigit(line[pos+2]) && isxdigit(line[pos+3]) && isxdigit(line[pos+4]))
1029                                                 pos+=5;
1030                                         else
1031                                                 break;
1032                                 }
1033                         linepos = pos;
1034                         return linepos;
1035                 }
1036
1037                 if (KM_NONE)
1038                 {
1039                         if (linepos >= (int)strlen(line))
1040                                 return linepos;
1041                         linepos += (int)u8_bytelen(line + linepos, 1);
1042                         return linepos;
1043                 }
1044         }
1045
1046         if ((key == K_INS || key == K_KP_INS) && KM_NONE) // toggle insert mode
1047         {
1048                 key_insert ^= 1;
1049                 return linepos;
1050         }
1051
1052         if (key == K_HOME || key == K_KP_HOME)
1053         {
1054                 if (is_console && KM_CTRL)
1055                 {
1056                         con_backscroll = CON_TEXTSIZE;
1057                         return linepos;
1058                 }
1059                 if (KM_NONE)
1060                         return linestart;
1061         }
1062
1063         if (key == K_END || key == K_KP_END)
1064         {
1065                 if (is_console && KM_CTRL)
1066                 {
1067                         con_backscroll = 0;
1068                         return linepos;
1069                 }
1070                 if (KM_NONE)
1071                         return (int)strlen(line);
1072         }
1073
1074         return -1;
1075 }
1076
1077 static int Key_Convert_NumPadKey(int key)
1078 {
1079         // LadyHavoc: copied most of this from Q2 to improve keyboard handling
1080         switch (key)
1081         {
1082                 case K_KP_SLASH:      return '/';
1083                 case K_KP_MINUS:      return '-';
1084                 case K_KP_PLUS:       return '+';
1085                 case K_KP_HOME:       return '7';
1086                 case K_KP_UPARROW:    return '8';
1087                 case K_KP_PGUP:       return '9';
1088                 case K_KP_LEFTARROW:  return '4';
1089                 case K_KP_5:          return '5';
1090                 case K_KP_RIGHTARROW: return '6';
1091                 case K_KP_END:        return '1';
1092                 case K_KP_DOWNARROW:  return '2';
1093                 case K_KP_PGDN:       return '3';
1094                 case K_KP_INS:        return '0';
1095                 case K_KP_DEL:        return '.';
1096         }
1097         return key;
1098 }
1099
1100 static void
1101 Key_Console(cmd_state_t *cmd, int key, int unicode)
1102 {
1103         int linepos;
1104
1105         key = Key_Convert_NumPadKey(key);
1106
1107         // Forbid Ctrl Alt shortcuts since on Windows they are used to type some characters
1108         // in certain non-English keyboards using the AltGr key (which emulates Ctrl Alt)
1109         // Reference: "Why Ctrl+Alt shouldn't be used as a shortcut modifier"
1110         //            https://blogs.msdn.microsoft.com/oldnewthing/20040329-00/?p=40003
1111         if (keydown[K_CTRL] && keydown[K_ALT])
1112                 goto add_char;
1113
1114         linepos = Key_Parse_CommonKeys(cmd, true, key, unicode);
1115         if (linepos >= 0)
1116         {
1117                 key_linepos = linepos;
1118                 return;
1119         }
1120
1121         if ((key == K_ENTER || key == K_KP_ENTER) && KM_NONE)
1122         {
1123                 Cbuf_AddText (cmd, key_line+1); // skip the ]
1124                 Cbuf_AddText (cmd, "\n");
1125                 Key_History_Push();
1126                 key_linepos = Key_ClearEditLine(true);
1127                 // force an update, because the command may take some time
1128                 if (cls.state == ca_disconnected)
1129                         CL_UpdateScreen ();
1130                 return;
1131         }
1132
1133         if (key == 'l' && KM_CTRL)
1134         {
1135                 Cbuf_AddText (cmd, "clear\n");
1136                 return;
1137         }
1138
1139         if (key == 'q' && KM_CTRL) // like zsh ^q: push line to history, don't execute, and clear
1140         {
1141                 // clear line
1142                 Key_History_Push();
1143                 key_linepos = Key_ClearEditLine(true);
1144                 return;
1145         }
1146
1147         // End Advanced Console Editing
1148
1149         if (((key == K_UPARROW || key == K_KP_UPARROW) && KM_NONE) || (key == 'p' && KM_CTRL))
1150         {
1151                 Key_History_Up();
1152                 return;
1153         }
1154
1155         if (((key == K_DOWNARROW || key == K_KP_DOWNARROW) && KM_NONE) || (key == 'n' && KM_CTRL))
1156         {
1157                 Key_History_Down();
1158                 return;
1159         }
1160
1161         if (keydown[K_CTRL])
1162         {
1163                 // prints all the matching commands
1164                 if (key == 'f' && KM_CTRL)
1165                 {
1166                         Key_History_Find_All();
1167                         return;
1168                 }
1169                 // Search forwards/backwards, pointing the history's index to the
1170                 // matching command but without fetching it to let one continue the search.
1171                 // To fetch it, it suffices to just press UP or DOWN.
1172                 if (key == 'r' && KM_CTRL_SHIFT)
1173                 {
1174                         Key_History_Find_Forwards();
1175                         return;
1176                 }
1177                 if (key == 'r' && KM_CTRL)
1178                 {
1179                         Key_History_Find_Backwards();
1180                         return;
1181                 }
1182
1183                 // go to the last/first command of the history
1184                 if (key == ',' && KM_CTRL)
1185                 {
1186                         Key_History_First();
1187                         return;
1188                 }
1189                 if (key == '.' && KM_CTRL)
1190                 {
1191                         Key_History_Last();
1192                         return;
1193                 }
1194         }
1195
1196         if (key == K_PGUP || key == K_KP_PGUP)
1197         {
1198                 if (KM_CTRL)
1199                 {
1200                         con_backscroll += ((vid_conheight.integer >> 2) / con_textsize.integer)-1;
1201                         return;
1202                 }
1203                 if (KM_NONE)
1204                 {
1205                         con_backscroll += ((vid_conheight.integer >> 1) / con_textsize.integer)-3;
1206                         return;
1207                 }
1208         }
1209
1210         if (key == K_PGDN || key == K_KP_PGDN)
1211         {
1212                 if (KM_CTRL)
1213                 {
1214                         con_backscroll -= ((vid_conheight.integer >> 2) / con_textsize.integer)-1;
1215                         return;
1216                 }
1217                 if (KM_NONE)
1218                 {
1219                         con_backscroll -= ((vid_conheight.integer >> 1) / con_textsize.integer)-3;
1220                         return;
1221                 }
1222         }
1223
1224         if (key == K_MWHEELUP)
1225         {
1226                 if (KM_CTRL)
1227                 {
1228                         con_backscroll += 1;
1229                         return;
1230                 }
1231                 if (KM_SHIFT)
1232                 {
1233                         con_backscroll += ((vid_conheight.integer >> 2) / con_textsize.integer)-1;
1234                         return;
1235                 }
1236                 if (KM_NONE)
1237                 {
1238                         con_backscroll += 5;
1239                         return;
1240                 }
1241         }
1242
1243         if (key == K_MWHEELDOWN)
1244         {
1245                 if (KM_CTRL)
1246                 {
1247                         con_backscroll -= 1;
1248                         return;
1249                 }
1250                 if (KM_SHIFT)
1251                 {
1252                         con_backscroll -= ((vid_conheight.integer >> 2) / con_textsize.integer)-1;
1253                         return;
1254                 }
1255                 if (KM_NONE)
1256                 {
1257                         con_backscroll -= 5;
1258                         return;
1259                 }
1260         }
1261
1262         if (keydown[K_CTRL])
1263         {
1264                 // text zoom in
1265                 if ((key == '+' || key == K_KP_PLUS) && KM_CTRL)
1266                 {
1267                         if (con_textsize.integer < 128)
1268                                 Cvar_SetValueQuick(&con_textsize, con_textsize.integer + 1);
1269                         return;
1270                 }
1271                 // text zoom out
1272                 if ((key == '-' || key == K_KP_MINUS) && KM_CTRL)
1273                 {
1274                         if (con_textsize.integer > 1)
1275                                 Cvar_SetValueQuick(&con_textsize, con_textsize.integer - 1);
1276                         return;
1277                 }
1278                 // text zoom reset
1279                 if ((key == '0' || key == K_KP_INS) && KM_CTRL)
1280                 {
1281                         Cvar_SetValueQuick(&con_textsize, atoi(Cvar_VariableDefString(&cvars_all, "con_textsize", CVAR_CLIENT | CVAR_SERVER)));
1282                         return;
1283                 }
1284         }
1285
1286 add_char:
1287
1288         // non printable
1289         if (unicode < 32)
1290                 return;
1291
1292         key_linepos = Key_AddChar(unicode, true);
1293 }
1294
1295 //============================================================================
1296
1297 static void
1298 Key_Message (cmd_state_t *cmd, int key, int ascii)
1299 {
1300         int linepos;
1301         char vabuf[1024];
1302
1303         key = Key_Convert_NumPadKey(key);
1304
1305         if (key == K_ENTER || key == K_KP_ENTER || ascii == 10 || ascii == 13)
1306         {
1307                 if(chat_mode < 0)
1308                         Cmd_ExecuteString(cmd, chat_buffer, src_command, true); // not Cbuf_AddText to allow semiclons in args; however, this allows no variables then. Use aliases!
1309                 else
1310                         CL_ForwardToServer(va(vabuf, sizeof(vabuf), "%s %s", chat_mode ? "say_team" : "say ", chat_buffer));
1311
1312                 key_dest = key_game;
1313                 chat_bufferpos = Key_ClearEditLine(false);
1314                 return;
1315         }
1316
1317         if (key == K_ESCAPE) {
1318                 key_dest = key_game;
1319                 chat_bufferpos = Key_ClearEditLine(false);
1320                 return;
1321         }
1322
1323         linepos = Key_Parse_CommonKeys(cmd, false, key, ascii);
1324         if (linepos >= 0)
1325         {
1326                 chat_bufferpos = linepos;
1327                 return;
1328         }
1329
1330         // ctrl+key generates an ascii value < 32 and shows a char from the charmap
1331         if (ascii > 0 && ascii < 32 && utf8_enable.integer)
1332                 ascii = 0xE000 + ascii;
1333
1334         if (!ascii)
1335                 return;                                                 // non printable
1336
1337         chat_bufferpos = Key_AddChar(ascii, false);
1338 }
1339
1340 //============================================================================
1341
1342
1343 /*
1344 ===================
1345 Returns a key number to be used to index keybindings[] by looking at
1346 the given string.  Single ascii characters return themselves, while
1347 the K_* names are matched up.
1348 ===================
1349 */
1350 int
1351 Key_StringToKeynum (const char *str)
1352 {
1353         const keyname_t  *kn;
1354
1355         if (!str || !str[0])
1356                 return -1;
1357         if (!str[1])
1358                 return tolower(str[0]);
1359
1360         for (kn = keynames; kn->name; kn++) {
1361                 if (!strcasecmp (str, kn->name))
1362                         return kn->keynum;
1363         }
1364         return -1;
1365 }
1366
1367 /*
1368 ===================
1369 Returns a string (either a single ascii char, or a K_* name) for the
1370 given keynum.
1371 FIXME: handle quote special (general escape sequence?)
1372 ===================
1373 */
1374 const char *
1375 Key_KeynumToString (int keynum, char *tinystr, size_t tinystrlength)
1376 {
1377         const keyname_t  *kn;
1378
1379         // -1 is an invalid code
1380         if (keynum < 0)
1381                 return "<KEY NOT FOUND>";
1382
1383         // search overrides first, because some characters are special
1384         for (kn = keynames; kn->name; kn++)
1385                 if (keynum == kn->keynum)
1386                         return kn->name;
1387
1388         // if it is printable, output it as a single character
1389         if (keynum > 32 && keynum < 256)
1390         {
1391                 if (tinystrlength >= 2)
1392                 {
1393                         tinystr[0] = keynum;
1394                         tinystr[1] = 0;
1395                 }
1396                 return tinystr;
1397         }
1398
1399         // if it is not overridden and not printable, we don't know what to do with it
1400         return "<UNKNOWN KEYNUM>";
1401 }
1402
1403
1404 qboolean
1405 Key_SetBinding (int keynum, int bindmap, const char *binding)
1406 {
1407         char *newbinding;
1408         size_t l;
1409
1410         if (keynum == -1 || keynum >= MAX_KEYS)
1411                 return false;
1412         if ((bindmap < 0) || (bindmap >= MAX_BINDMAPS))
1413                 return false;
1414
1415 // free old bindings
1416         if (keybindings[bindmap][keynum]) {
1417                 Z_Free (keybindings[bindmap][keynum]);
1418                 keybindings[bindmap][keynum] = NULL;
1419         }
1420         if(!binding[0]) // make "" binds be removed --blub
1421                 return true;
1422 // allocate memory for new binding
1423         l = strlen (binding);
1424         newbinding = (char *)Z_Malloc (l + 1);
1425         memcpy (newbinding, binding, l + 1);
1426         newbinding[l] = 0;
1427         keybindings[bindmap][keynum] = newbinding;
1428         return true;
1429 }
1430
1431 void Key_GetBindMap(int *fg, int *bg)
1432 {
1433         if(fg)
1434                 *fg = key_bmap;
1435         if(bg)
1436                 *bg = key_bmap2;
1437 }
1438
1439 qboolean Key_SetBindMap(int fg, int bg)
1440 {
1441         if(fg >= MAX_BINDMAPS)
1442                 return false;
1443         if(bg >= MAX_BINDMAPS)
1444                 return false;
1445         if(fg >= 0)
1446                 key_bmap = fg;
1447         if(bg >= 0)
1448                 key_bmap2 = bg;
1449         return true;
1450 }
1451
1452 static void
1453 Key_In_Unbind_f(cmd_state_t *cmd)
1454 {
1455         int         b, m;
1456         char *errchar = NULL;
1457
1458         if (Cmd_Argc (cmd) != 3) {
1459                 Con_Print("in_unbind <bindmap> <key> : remove commands from a key\n");
1460                 return;
1461         }
1462
1463         m = strtol(Cmd_Argv(cmd, 1), &errchar, 0);
1464         if ((m < 0) || (m >= MAX_BINDMAPS) || (errchar && *errchar)) {
1465                 Con_Printf("%s isn't a valid bindmap\n", Cmd_Argv(cmd, 1));
1466                 return;
1467         }
1468
1469         b = Key_StringToKeynum (Cmd_Argv(cmd, 2));
1470         if (b == -1) {
1471                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv(cmd, 2));
1472                 return;
1473         }
1474
1475         if(!Key_SetBinding (b, m, ""))
1476                 Con_Printf("Key_SetBinding failed for unknown reason\n");
1477 }
1478
1479 static void
1480 Key_In_Bind_f(cmd_state_t *cmd)
1481 {
1482         int         i, c, b, m;
1483         char        line[MAX_INPUTLINE];
1484         char *errchar = NULL;
1485
1486         c = Cmd_Argc (cmd);
1487
1488         if (c != 3 && c != 4) {
1489                 Con_Print("in_bind <bindmap> <key> [command] : attach a command to a key\n");
1490                 return;
1491         }
1492
1493         m = strtol(Cmd_Argv(cmd, 1), &errchar, 0);
1494         if ((m < 0) || (m >= MAX_BINDMAPS) || (errchar && *errchar)) {
1495                 Con_Printf("%s isn't a valid bindmap\n", Cmd_Argv(cmd, 1));
1496                 return;
1497         }
1498
1499         b = Key_StringToKeynum (Cmd_Argv(cmd, 2));
1500         if (b == -1 || b >= MAX_KEYS) {
1501                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv(cmd, 2));
1502                 return;
1503         }
1504
1505         if (c == 3) {
1506                 if (keybindings[m][b])
1507                         Con_Printf("\"%s\" = \"%s\"\n", Cmd_Argv(cmd, 2), keybindings[m][b]);
1508                 else
1509                         Con_Printf("\"%s\" is not bound\n", Cmd_Argv(cmd, 2));
1510                 return;
1511         }
1512 // copy the rest of the command line
1513         line[0] = 0;                                                    // start out with a null string
1514         for (i = 3; i < c; i++) {
1515                 strlcat (line, Cmd_Argv(cmd, i), sizeof (line));
1516                 if (i != (c - 1))
1517                         strlcat (line, " ", sizeof (line));
1518         }
1519
1520         if(!Key_SetBinding (b, m, line))
1521                 Con_Printf("Key_SetBinding failed for unknown reason\n");
1522 }
1523
1524 static void
1525 Key_In_Bindmap_f(cmd_state_t *cmd)
1526 {
1527         int         m1, m2, c;
1528         char *errchar = NULL;
1529
1530         c = Cmd_Argc (cmd);
1531
1532         if (c != 3) {
1533                 Con_Print("in_bindmap <bindmap> <fallback>: set current bindmap and fallback\n");
1534                 return;
1535         }
1536
1537         m1 = strtol(Cmd_Argv(cmd, 1), &errchar, 0);
1538         if ((m1 < 0) || (m1 >= MAX_BINDMAPS) || (errchar && *errchar)) {
1539                 Con_Printf("%s isn't a valid bindmap\n", Cmd_Argv(cmd, 1));
1540                 return;
1541         }
1542
1543         m2 = strtol(Cmd_Argv(cmd, 2), &errchar, 0);
1544         if ((m2 < 0) || (m2 >= MAX_BINDMAPS) || (errchar && *errchar)) {
1545                 Con_Printf("%s isn't a valid bindmap\n", Cmd_Argv(cmd, 2));
1546                 return;
1547         }
1548
1549         key_bmap = m1;
1550         key_bmap2 = m2;
1551 }
1552
1553 static void
1554 Key_Unbind_f(cmd_state_t *cmd)
1555 {
1556         int         b;
1557
1558         if (Cmd_Argc (cmd) != 2) {
1559                 Con_Print("unbind <key> : remove commands from a key\n");
1560                 return;
1561         }
1562
1563         b = Key_StringToKeynum (Cmd_Argv(cmd, 1));
1564         if (b == -1) {
1565                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv(cmd, 1));
1566                 return;
1567         }
1568
1569         if(!Key_SetBinding (b, 0, ""))
1570                 Con_Printf("Key_SetBinding failed for unknown reason\n");
1571 }
1572
1573 static void
1574 Key_Unbindall_f(cmd_state_t *cmd)
1575 {
1576         int         i, j;
1577
1578         for (j = 0; j < MAX_BINDMAPS; j++)
1579                 for (i = 0; i < (int)(sizeof(keybindings[0])/sizeof(keybindings[0][0])); i++)
1580                         if (keybindings[j][i])
1581                                 Key_SetBinding (i, j, "");
1582 }
1583
1584 static void
1585 Key_PrintBindList(int j)
1586 {
1587         char bindbuf[MAX_INPUTLINE];
1588         char tinystr[2];
1589         const char *p;
1590         int i;
1591
1592         for (i = 0; i < (int)(sizeof(keybindings[0])/sizeof(keybindings[0][0])); i++)
1593         {
1594                 p = keybindings[j][i];
1595                 if (p)
1596                 {
1597                         Cmd_QuoteString(bindbuf, sizeof(bindbuf), p, "\"\\", false);
1598                         if (j == 0)
1599                                 Con_Printf("^2%s ^7= \"%s\"\n", Key_KeynumToString (i, tinystr, sizeof(tinystr)), bindbuf);
1600                         else
1601                                 Con_Printf("^3bindmap %d: ^2%s ^7= \"%s\"\n", j, Key_KeynumToString (i, tinystr, sizeof(tinystr)), bindbuf);
1602                 }
1603         }
1604 }
1605
1606 static void
1607 Key_In_BindList_f(cmd_state_t *cmd)
1608 {
1609         int m;
1610         char *errchar = NULL;
1611
1612         if(Cmd_Argc(cmd) >= 2)
1613         {
1614                 m = strtol(Cmd_Argv(cmd, 1), &errchar, 0);
1615                 if ((m < 0) || (m >= MAX_BINDMAPS) || (errchar && *errchar)) {
1616                         Con_Printf("%s isn't a valid bindmap\n", Cmd_Argv(cmd, 1));
1617                         return;
1618                 }
1619                 Key_PrintBindList(m);
1620         }
1621         else
1622         {
1623                 for (m = 0; m < MAX_BINDMAPS; m++)
1624                         Key_PrintBindList(m);
1625         }
1626 }
1627
1628 static void
1629 Key_BindList_f(cmd_state_t *cmd)
1630 {
1631         Key_PrintBindList(0);
1632 }
1633
1634 static void
1635 Key_Bind_f(cmd_state_t *cmd)
1636 {
1637         int         i, c, b;
1638         char        line[MAX_INPUTLINE];
1639
1640         c = Cmd_Argc (cmd);
1641
1642         if (c != 2 && c != 3) {
1643                 Con_Print("bind <key> [command] : attach a command to a key\n");
1644                 return;
1645         }
1646         b = Key_StringToKeynum (Cmd_Argv(cmd, 1));
1647         if (b == -1 || b >= MAX_KEYS) {
1648                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv(cmd, 1));
1649                 return;
1650         }
1651
1652         if (c == 2) {
1653                 if (keybindings[0][b])
1654                         Con_Printf("\"%s\" = \"%s\"\n", Cmd_Argv(cmd, 1), keybindings[0][b]);
1655                 else
1656                         Con_Printf("\"%s\" is not bound\n", Cmd_Argv(cmd, 1));
1657                 return;
1658         }
1659 // copy the rest of the command line
1660         line[0] = 0;                                                    // start out with a null string
1661         for (i = 2; i < c; i++) {
1662                 strlcat (line, Cmd_Argv(cmd, i), sizeof (line));
1663                 if (i != (c - 1))
1664                         strlcat (line, " ", sizeof (line));
1665         }
1666
1667         if(!Key_SetBinding (b, 0, line))
1668                 Con_Printf("Key_SetBinding failed for unknown reason\n");
1669 }
1670
1671 /*
1672 ============
1673 Writes lines containing "bind key value"
1674 ============
1675 */
1676 void
1677 Key_WriteBindings (qfile_t *f)
1678 {
1679         int         i, j;
1680         char bindbuf[MAX_INPUTLINE];
1681         char tinystr[2];
1682         const char *p;
1683
1684         // Override default binds
1685         FS_Printf(f, "unbindall\n");
1686
1687         for (j = 0; j < MAX_BINDMAPS; j++)
1688         {
1689                 for (i = 0; i < (int)(sizeof(keybindings[0])/sizeof(keybindings[0][0])); i++)
1690                 {
1691                         p = keybindings[j][i];
1692                         if (p)
1693                         {
1694                                 Cmd_QuoteString(bindbuf, sizeof(bindbuf), p, "\"\\", false); // don't need to escape $ because cvars are not expanded inside bind
1695                                 if (j == 0)
1696                                         FS_Printf(f, "bind %s \"%s\"\n", Key_KeynumToString (i, tinystr, sizeof(tinystr)), bindbuf);
1697                                 else
1698                                         FS_Printf(f, "in_bind %d %s \"%s\"\n", j, Key_KeynumToString (i, tinystr, sizeof(tinystr)), bindbuf);
1699                         }
1700                 }
1701         }
1702 }
1703
1704
1705 void
1706 Key_Init (void)
1707 {
1708         Key_History_Init();
1709         key_linepos = Key_ClearEditLine(true);
1710
1711 //
1712 // register our functions
1713 //
1714         Cmd_AddCommand(CMD_CLIENT, "in_bind", Key_In_Bind_f, "binds a command to the specified key in the selected bindmap");
1715         Cmd_AddCommand(CMD_CLIENT, "in_unbind", Key_In_Unbind_f, "removes command on the specified key in the selected bindmap");
1716         Cmd_AddCommand(CMD_CLIENT, "in_bindlist", Key_In_BindList_f, "bindlist: displays bound keys for all bindmaps, or the given bindmap");
1717         Cmd_AddCommand(CMD_CLIENT, "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");
1718         Cmd_AddCommand(CMD_CLIENT, "in_releaseall", Key_ReleaseAll_f, "releases all currently pressed keys (debug command)");
1719
1720         Cmd_AddCommand(CMD_CLIENT, "bind", Key_Bind_f, "binds a command to the specified key in bindmap 0");
1721         Cmd_AddCommand(CMD_CLIENT, "unbind", Key_Unbind_f, "removes a command on the specified key in bindmap 0");
1722         Cmd_AddCommand(CMD_CLIENT, "bindlist", Key_BindList_f, "bindlist: displays bound keys for bindmap 0 bindmaps");
1723         Cmd_AddCommand(CMD_CLIENT, "unbindall", Key_Unbindall_f, "removes all commands from all keys in all bindmaps (leaving only shift-escape and escape)");
1724
1725         Cmd_AddCommand(CMD_CLIENT, "history", Key_History_f, "prints the history of executed commands (history X prints the last X entries, history -c clears the whole history)");
1726
1727         Cvar_RegisterVariable (&con_closeontoggleconsole);
1728 }
1729
1730 void
1731 Key_Shutdown (void)
1732 {
1733         Key_History_Shutdown();
1734 }
1735
1736 const char *Key_GetBind (int key, int bindmap)
1737 {
1738         const char *bind;
1739         if (key < 0 || key >= MAX_KEYS)
1740                 return NULL;
1741         if(bindmap >= MAX_BINDMAPS)
1742                 return NULL;
1743         if(bindmap >= 0)
1744         {
1745                 bind = keybindings[bindmap][key];
1746         }
1747         else
1748         {
1749                 bind = keybindings[key_bmap][key];
1750                 if (!bind)
1751                         bind = keybindings[key_bmap2][key];
1752         }
1753         return bind;
1754 }
1755
1756 void Key_FindKeysForCommand (const char *command, int *keys, int numkeys, int bindmap)
1757 {
1758         int             count;
1759         int             j;
1760         const char      *b;
1761
1762         for (j = 0;j < numkeys;j++)
1763                 keys[j] = -1;
1764
1765         if(bindmap >= MAX_BINDMAPS)
1766                 return;
1767
1768         count = 0;
1769
1770         for (j = 0; j < MAX_KEYS; ++j)
1771         {
1772                 b = Key_GetBind(j, bindmap);
1773                 if (!b)
1774                         continue;
1775                 if (!strcmp (b, command) )
1776                 {
1777                         keys[count++] = j;
1778                         if (count == numkeys)
1779                                 break;
1780                 }
1781         }
1782 }
1783
1784 /*
1785 ===================
1786 Called by the system between frames for both key up and key down events
1787 Should NOT be called during an interrupt!
1788 ===================
1789 */
1790 static char tbl_keyascii[MAX_KEYS];
1791 static keydest_t tbl_keydest[MAX_KEYS];
1792
1793 typedef struct eventqueueitem_s
1794 {
1795         int key;
1796         int ascii;
1797         qboolean down;
1798 }
1799 eventqueueitem_t;
1800 static int events_blocked = 0;
1801 static eventqueueitem_t eventqueue[32];
1802 static unsigned eventqueue_idx = 0;
1803
1804 static void Key_EventQueue_Add(int key, int ascii, qboolean down)
1805 {
1806         if(eventqueue_idx < sizeof(eventqueue) / sizeof(*eventqueue))
1807         {
1808                 eventqueue[eventqueue_idx].key = key;
1809                 eventqueue[eventqueue_idx].ascii = ascii;
1810                 eventqueue[eventqueue_idx].down = down;
1811                 ++eventqueue_idx;
1812         }
1813 }
1814
1815 void Key_EventQueue_Block(void)
1816 {
1817         // block key events until call to Unblock
1818         events_blocked = true;
1819 }
1820
1821 void Key_EventQueue_Unblock(void)
1822 {
1823         // unblocks key events again
1824         unsigned i;
1825         events_blocked = false;
1826         for(i = 0; i < eventqueue_idx; ++i)
1827                 Key_Event(eventqueue[i].key, eventqueue[i].ascii, eventqueue[i].down);
1828         eventqueue_idx = 0;
1829 }
1830
1831 void
1832 Key_Event (int key, int ascii, qboolean down)
1833 {
1834         cmd_state_t *cmd = &cmd_client;
1835         const char *bind;
1836         qboolean q;
1837         keydest_t keydest = key_dest;
1838         char vabuf[1024];
1839
1840         if (key < 0 || key >= MAX_KEYS)
1841                 return;
1842
1843         if(events_blocked)
1844         {
1845                 Key_EventQueue_Add(key, ascii, down);
1846                 return;
1847         }
1848
1849         // get key binding
1850         bind = keybindings[key_bmap][key];
1851         if (!bind)
1852                 bind = keybindings[key_bmap2][key];
1853
1854         if (developer_insane.integer)
1855                 Con_DPrintf("Key_Event(%i, '%c', %s) keydown %i bind \"%s\"\n", key, ascii ? ascii : '?', down ? "down" : "up", keydown[key], bind ? bind : "");
1856
1857         if(key_consoleactive)
1858                 keydest = key_console;
1859
1860         if (down)
1861         {
1862                 // increment key repeat count each time a down is received so that things
1863                 // which want to ignore key repeat can ignore it
1864                 keydown[key] = min(keydown[key] + 1, 2);
1865                 if(keydown[key] == 1) {
1866                         tbl_keyascii[key] = ascii;
1867                         tbl_keydest[key] = keydest;
1868                 } else {
1869                         ascii = tbl_keyascii[key];
1870                         keydest = tbl_keydest[key];
1871                 }
1872         }
1873         else
1874         {
1875                 // clear repeat count now that the key is released
1876                 keydown[key] = 0;
1877                 keydest = tbl_keydest[key];
1878                 ascii = tbl_keyascii[key];
1879         }
1880
1881         if(keydest == key_void)
1882                 return;
1883
1884         // key_consoleactive is a flag not a key_dest because the console is a
1885         // high priority overlay ontop of the normal screen (designed as a safety
1886         // feature so that developers and users can rescue themselves from a bad
1887         // situation).
1888         //
1889         // this also means that toggling the console on/off does not lose the old
1890         // key_dest state
1891
1892         // specially handle escape (togglemenu) and shift-escape (toggleconsole)
1893         // engine bindings, these are not handled as normal binds so that the user
1894         // can recover from a completely empty bindmap
1895         if (key == K_ESCAPE)
1896         {
1897                 // ignore key repeats on escape
1898                 if (keydown[key] > 1)
1899                         return;
1900
1901                 // escape does these things:
1902                 // key_consoleactive - close console
1903                 // key_message - abort messagemode
1904                 // key_menu - go to parent menu (or key_game)
1905                 // key_game - open menu
1906
1907                 // in all modes shift-escape toggles console
1908                 if (keydown[K_SHIFT])
1909                 {
1910                         if(down)
1911                         {
1912                                 Con_ToggleConsole_f(&cmd_client);
1913                                 tbl_keydest[key] = key_void; // esc release should go nowhere (especially not to key_menu or key_game)
1914                         }
1915                         return;
1916                 }
1917
1918                 switch (keydest)
1919                 {
1920                         case key_console:
1921                                 if(down)
1922                                 {
1923                                         if(key_consoleactive & KEY_CONSOLEACTIVE_FORCED)
1924                                         {
1925                                                 key_consoleactive &= ~KEY_CONSOLEACTIVE_USER;
1926 #ifdef CONFIG_MENU
1927                                                 MR_ToggleMenu(1);
1928 #endif
1929                                         }
1930                                         else
1931                                                 Con_ToggleConsole_f(&cmd_client);
1932                                 }
1933                                 break;
1934
1935                         case key_message:
1936                                 if (down)
1937                                         Key_Message (cmd, key, ascii); // that'll close the message input
1938                                 break;
1939
1940                         case key_menu:
1941                         case key_menu_grabbed:
1942 #ifdef CONFIG_MENU
1943                                 MR_KeyEvent (key, ascii, down);
1944 #endif
1945                                 break;
1946
1947                         case key_game:
1948                                 // csqc has priority over toggle menu if it wants to (e.g. handling escape for UI stuff in-game.. :sick:)
1949                                 q = CL_VM_InputEvent(down ? 0 : 1, key, ascii);
1950 #ifdef CONFIG_MENU
1951                                 if (!q && down)
1952                                         MR_ToggleMenu(1);
1953 #endif
1954                                 break;
1955
1956                         default:
1957                                 Con_Printf ("Key_Event: Bad key_dest\n");
1958                 }
1959                 return;
1960         }
1961
1962         // send function keydowns to interpreter no matter what mode is (unless the menu has specifically grabbed the keyboard, for rebinding keys)
1963         // VorteX: Omnicide does bind F* keys
1964         if (keydest != key_menu_grabbed)
1965         if (key >= K_F1 && key <= K_F12 && gamemode != GAME_BLOODOMNICIDE)
1966         {
1967                 if (bind)
1968                 {
1969                         if(keydown[key] == 1 && down)
1970                         {
1971                                 // button commands add keynum as a parm
1972                                 if (bind[0] == '+')
1973                                         Cbuf_AddText (cmd, va(vabuf, sizeof(vabuf), "%s %i\n", bind, key));
1974                                 else
1975                                 {
1976                                         Cbuf_AddText (cmd, bind);
1977                                         Cbuf_AddText (cmd, "\n");
1978                                 }
1979                         } else if(bind[0] == '+' && !down && keydown[key] == 0)
1980                                 Cbuf_AddText(cmd, va(vabuf, sizeof(vabuf), "-%s %i\n", bind + 1, key));
1981                 }
1982                 return;
1983         }
1984
1985         // send input to console if it wants it
1986         if (keydest == key_console)
1987         {
1988                 if (!down)
1989                         return;
1990                 // con_closeontoggleconsole enables toggleconsole keys to close the
1991                 // console, as long as they are not the color prefix character
1992                 // (special exemption for german keyboard layouts)
1993                 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))
1994                 {
1995                         Con_ToggleConsole_f(&cmd_client);
1996                         return;
1997                 }
1998
1999                 if (COM_CheckParm ("-noconsole"))
2000                         return; // only allow the key bind to turn off console
2001
2002                 Key_Console (cmd, key, ascii);
2003                 return;
2004         }
2005
2006         // handle toggleconsole in menu too
2007         if (keydest == key_menu)
2008         {
2009                 if (down && con_closeontoggleconsole.integer && bind && !strncmp(bind, "toggleconsole", strlen("toggleconsole")) && ascii != STRING_COLOR_TAG)
2010                 {
2011                         Cbuf_AddText(cmd, "toggleconsole\n");  // Deferred to next frame so we're not sending the text event to the console.
2012                         tbl_keydest[key] = key_void; // key release should go nowhere (especially not to key_menu or key_game)
2013                         return;
2014                 }
2015         }
2016
2017         // ignore binds while a video is played, let the video system handle the key event
2018         if (cl_videoplaying)
2019         {
2020                 if (gamemode == GAME_BLOODOMNICIDE) // menu controls key events
2021 #ifdef CONFIG_MENU
2022                         MR_KeyEvent(key, ascii, down);
2023 #else
2024                         {
2025                         }
2026 #endif
2027                 else
2028                         CL_Video_KeyEvent (key, ascii, keydown[key] != 0);
2029                 return;
2030         }
2031
2032         // anything else is a key press into the game, chat line, or menu
2033         switch (keydest)
2034         {
2035                 case key_message:
2036                         if (down)
2037                                 Key_Message (cmd, key, ascii);
2038                         break;
2039                 case key_menu:
2040                 case key_menu_grabbed:
2041 #ifdef CONFIG_MENU
2042                         MR_KeyEvent (key, ascii, down);
2043 #endif
2044                         break;
2045                 case key_game:
2046                         q = CL_VM_InputEvent(down ? 0 : 1, key, ascii);
2047                         // ignore key repeats on binds and only send the bind if the event hasnt been already processed by csqc
2048                         if (!q && bind)
2049                         {
2050                                 if(keydown[key] == 1 && down)
2051                                 {
2052                                         // button commands add keynum as a parm
2053                                         if (bind[0] == '+')
2054                                                 Cbuf_AddText (cmd, va(vabuf, sizeof(vabuf), "%s %i\n", bind, key));
2055                                         else
2056                                         {
2057                                                 Cbuf_AddText (cmd, bind);
2058                                                 Cbuf_AddText (cmd, "\n");
2059                                         }
2060                                 } else if(bind[0] == '+' && !down && keydown[key] == 0)
2061                                         Cbuf_AddText(cmd, va(vabuf, sizeof(vabuf), "-%s %i\n", bind + 1, key));
2062                         }
2063                         break;
2064                 default:
2065                         Con_Printf ("Key_Event: Bad key_dest\n");
2066         }
2067 }
2068
2069 // a helper to simulate release of ALL keys
2070 void
2071 Key_ReleaseAll (void)
2072 {
2073         int key;
2074         // clear the event queue first
2075         eventqueue_idx = 0;
2076         // then send all down events (possibly into the event queue)
2077         for(key = 0; key < MAX_KEYS; ++key)
2078                 if(keydown[key])
2079                         Key_Event(key, 0, false);
2080         // now all keys are guaranteed down (once the event queue is unblocked)
2081         // and only future events count
2082 }
2083
2084 void Key_ReleaseAll_f(cmd_state_t *cmd)
2085 {
2086         Key_ReleaseAll();
2087 }