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