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