Attempt to stabilize ODE. Now using constant step (sys_ticrate set steptime) - on...
[divverent/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"};
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         {"SEMICOLON", ';'},                     // because a raw semicolon separates commands
477         {"TILDE", '~'},
478         {"BACKQUOTE", '`'},
479         {"QUOTE", '"'},
480         {"APOSTROPHE", '\''},
481         {"BACKSLASH", '\\'},            // because a raw backslash is used for special characters
482
483         {"MIDINOTE0", K_MIDINOTE0},
484         {"MIDINOTE1", K_MIDINOTE1},
485         {"MIDINOTE2", K_MIDINOTE2},
486         {"MIDINOTE3", K_MIDINOTE3},
487         {"MIDINOTE4", K_MIDINOTE4},
488         {"MIDINOTE5", K_MIDINOTE5},
489         {"MIDINOTE6", K_MIDINOTE6},
490         {"MIDINOTE7", K_MIDINOTE7},
491         {"MIDINOTE8", K_MIDINOTE8},
492         {"MIDINOTE9", K_MIDINOTE9},
493         {"MIDINOTE10", K_MIDINOTE10},
494         {"MIDINOTE11", K_MIDINOTE11},
495         {"MIDINOTE12", K_MIDINOTE12},
496         {"MIDINOTE13", K_MIDINOTE13},
497         {"MIDINOTE14", K_MIDINOTE14},
498         {"MIDINOTE15", K_MIDINOTE15},
499         {"MIDINOTE16", K_MIDINOTE16},
500         {"MIDINOTE17", K_MIDINOTE17},
501         {"MIDINOTE18", K_MIDINOTE18},
502         {"MIDINOTE19", K_MIDINOTE19},
503         {"MIDINOTE20", K_MIDINOTE20},
504         {"MIDINOTE21", K_MIDINOTE21},
505         {"MIDINOTE22", K_MIDINOTE22},
506         {"MIDINOTE23", K_MIDINOTE23},
507         {"MIDINOTE24", K_MIDINOTE24},
508         {"MIDINOTE25", K_MIDINOTE25},
509         {"MIDINOTE26", K_MIDINOTE26},
510         {"MIDINOTE27", K_MIDINOTE27},
511         {"MIDINOTE28", K_MIDINOTE28},
512         {"MIDINOTE29", K_MIDINOTE29},
513         {"MIDINOTE30", K_MIDINOTE30},
514         {"MIDINOTE31", K_MIDINOTE31},
515         {"MIDINOTE32", K_MIDINOTE32},
516         {"MIDINOTE33", K_MIDINOTE33},
517         {"MIDINOTE34", K_MIDINOTE34},
518         {"MIDINOTE35", K_MIDINOTE35},
519         {"MIDINOTE36", K_MIDINOTE36},
520         {"MIDINOTE37", K_MIDINOTE37},
521         {"MIDINOTE38", K_MIDINOTE38},
522         {"MIDINOTE39", K_MIDINOTE39},
523         {"MIDINOTE40", K_MIDINOTE40},
524         {"MIDINOTE41", K_MIDINOTE41},
525         {"MIDINOTE42", K_MIDINOTE42},
526         {"MIDINOTE43", K_MIDINOTE43},
527         {"MIDINOTE44", K_MIDINOTE44},
528         {"MIDINOTE45", K_MIDINOTE45},
529         {"MIDINOTE46", K_MIDINOTE46},
530         {"MIDINOTE47", K_MIDINOTE47},
531         {"MIDINOTE48", K_MIDINOTE48},
532         {"MIDINOTE49", K_MIDINOTE49},
533         {"MIDINOTE50", K_MIDINOTE50},
534         {"MIDINOTE51", K_MIDINOTE51},
535         {"MIDINOTE52", K_MIDINOTE52},
536         {"MIDINOTE53", K_MIDINOTE53},
537         {"MIDINOTE54", K_MIDINOTE54},
538         {"MIDINOTE55", K_MIDINOTE55},
539         {"MIDINOTE56", K_MIDINOTE56},
540         {"MIDINOTE57", K_MIDINOTE57},
541         {"MIDINOTE58", K_MIDINOTE58},
542         {"MIDINOTE59", K_MIDINOTE59},
543         {"MIDINOTE60", K_MIDINOTE60},
544         {"MIDINOTE61", K_MIDINOTE61},
545         {"MIDINOTE62", K_MIDINOTE62},
546         {"MIDINOTE63", K_MIDINOTE63},
547         {"MIDINOTE64", K_MIDINOTE64},
548         {"MIDINOTE65", K_MIDINOTE65},
549         {"MIDINOTE66", K_MIDINOTE66},
550         {"MIDINOTE67", K_MIDINOTE67},
551         {"MIDINOTE68", K_MIDINOTE68},
552         {"MIDINOTE69", K_MIDINOTE69},
553         {"MIDINOTE70", K_MIDINOTE70},
554         {"MIDINOTE71", K_MIDINOTE71},
555         {"MIDINOTE72", K_MIDINOTE72},
556         {"MIDINOTE73", K_MIDINOTE73},
557         {"MIDINOTE74", K_MIDINOTE74},
558         {"MIDINOTE75", K_MIDINOTE75},
559         {"MIDINOTE76", K_MIDINOTE76},
560         {"MIDINOTE77", K_MIDINOTE77},
561         {"MIDINOTE78", K_MIDINOTE78},
562         {"MIDINOTE79", K_MIDINOTE79},
563         {"MIDINOTE80", K_MIDINOTE80},
564         {"MIDINOTE81", K_MIDINOTE81},
565         {"MIDINOTE82", K_MIDINOTE82},
566         {"MIDINOTE83", K_MIDINOTE83},
567         {"MIDINOTE84", K_MIDINOTE84},
568         {"MIDINOTE85", K_MIDINOTE85},
569         {"MIDINOTE86", K_MIDINOTE86},
570         {"MIDINOTE87", K_MIDINOTE87},
571         {"MIDINOTE88", K_MIDINOTE88},
572         {"MIDINOTE89", K_MIDINOTE89},
573         {"MIDINOTE90", K_MIDINOTE90},
574         {"MIDINOTE91", K_MIDINOTE91},
575         {"MIDINOTE92", K_MIDINOTE92},
576         {"MIDINOTE93", K_MIDINOTE93},
577         {"MIDINOTE94", K_MIDINOTE94},
578         {"MIDINOTE95", K_MIDINOTE95},
579         {"MIDINOTE96", K_MIDINOTE96},
580         {"MIDINOTE97", K_MIDINOTE97},
581         {"MIDINOTE98", K_MIDINOTE98},
582         {"MIDINOTE99", K_MIDINOTE99},
583         {"MIDINOTE100", K_MIDINOTE100},
584         {"MIDINOTE101", K_MIDINOTE101},
585         {"MIDINOTE102", K_MIDINOTE102},
586         {"MIDINOTE103", K_MIDINOTE103},
587         {"MIDINOTE104", K_MIDINOTE104},
588         {"MIDINOTE105", K_MIDINOTE105},
589         {"MIDINOTE106", K_MIDINOTE106},
590         {"MIDINOTE107", K_MIDINOTE107},
591         {"MIDINOTE108", K_MIDINOTE108},
592         {"MIDINOTE109", K_MIDINOTE109},
593         {"MIDINOTE110", K_MIDINOTE110},
594         {"MIDINOTE111", K_MIDINOTE111},
595         {"MIDINOTE112", K_MIDINOTE112},
596         {"MIDINOTE113", K_MIDINOTE113},
597         {"MIDINOTE114", K_MIDINOTE114},
598         {"MIDINOTE115", K_MIDINOTE115},
599         {"MIDINOTE116", K_MIDINOTE116},
600         {"MIDINOTE117", K_MIDINOTE117},
601         {"MIDINOTE118", K_MIDINOTE118},
602         {"MIDINOTE119", K_MIDINOTE119},
603         {"MIDINOTE120", K_MIDINOTE120},
604         {"MIDINOTE121", K_MIDINOTE121},
605         {"MIDINOTE122", K_MIDINOTE122},
606         {"MIDINOTE123", K_MIDINOTE123},
607         {"MIDINOTE124", K_MIDINOTE124},
608         {"MIDINOTE125", K_MIDINOTE125},
609         {"MIDINOTE126", K_MIDINOTE126},
610         {"MIDINOTE127", K_MIDINOTE127},
611
612         {NULL, 0}
613 };
614
615 /*
616 ==============================================================================
617
618                         LINE TYPING INTO THE CONSOLE
619
620 ==============================================================================
621 */
622
623 void
624 Key_ClearEditLine (int edit_line)
625 {
626         memset (key_line, '\0', sizeof(key_line));
627         key_line[0] = ']';
628         key_linepos = 1;
629 }
630
631 /*
632 ====================
633 Interactive line editing and console scrollback
634 ====================
635 */
636 static void
637 Key_Console (int key, int unicode)
638 {
639         // LordHavoc: copied most of this from Q2 to improve keyboard handling
640         switch (key)
641         {
642         case K_KP_SLASH:
643                 key = '/';
644                 break;
645         case K_KP_MINUS:
646                 key = '-';
647                 break;
648         case K_KP_PLUS:
649                 key = '+';
650                 break;
651         case K_KP_HOME:
652                 key = '7';
653                 break;
654         case K_KP_UPARROW:
655                 key = '8';
656                 break;
657         case K_KP_PGUP:
658                 key = '9';
659                 break;
660         case K_KP_LEFTARROW:
661                 key = '4';
662                 break;
663         case K_KP_5:
664                 key = '5';
665                 break;
666         case K_KP_RIGHTARROW:
667                 key = '6';
668                 break;
669         case K_KP_END:
670                 key = '1';
671                 break;
672         case K_KP_DOWNARROW:
673                 key = '2';
674                 break;
675         case K_KP_PGDN:
676                 key = '3';
677                 break;
678         case K_KP_INS:
679                 key = '0';
680                 break;
681         case K_KP_DEL:
682                 key = '.';
683                 break;
684         }
685
686         if ((key == 'v' && keydown[K_CTRL]) || ((key == K_INS || key == K_KP_INS) && keydown[K_SHIFT]))
687         {
688                 char *cbd, *p;
689                 if ((cbd = Sys_GetClipboardData()) != 0)
690                 {
691                         int i;
692 #if 1
693                         p = cbd;
694                         while (*p)
695                         {
696                                 if (*p == '\r' && *(p+1) == '\n')
697                                 {
698                                         *p++ = ';';
699                                         *p++ = ' ';
700                                 }
701                                 else if (*p == '\n' || *p == '\r' || *p == '\b')
702                                         *p++ = ';';
703                                 p++;
704                         }
705 #else
706                         strtok(cbd, "\n\r\b");
707 #endif
708                         i = (int)strlen(cbd);
709                         if (i + key_linepos >= MAX_INPUTLINE)
710                                 i= MAX_INPUTLINE - key_linepos - 1;
711                         if (i > 0)
712                         {
713                                 // terencehill: insert the clipboard text between the characters of the line
714                                 /*
715                                 char *temp = (char *) Z_Malloc(MAX_INPUTLINE);
716                                 cbd[i]=0;
717                                 temp[0]=0;
718                                 if ( key_linepos < (int)strlen(key_line) )
719                                         strlcpy(temp, key_line + key_linepos, (int)strlen(key_line) - key_linepos +1);
720                                 key_line[key_linepos] = 0;
721                                 strlcat(key_line, cbd, sizeof(key_line));
722                                 if (temp[0])
723                                         strlcat(key_line, temp, sizeof(key_line));
724                                 Z_Free(temp);
725                                 key_linepos += i;
726                                 */
727                                 // blub: I'm changing this to use memmove() like the rest of the code does.
728                                 cbd[i] = 0;
729                                 memmove(key_line + key_linepos + i, key_line + key_linepos, sizeof(key_line) - key_linepos - i);
730                                 memcpy(key_line + key_linepos, cbd, i);
731                                 key_linepos += i;
732                         }
733                         Z_Free(cbd);
734                 }
735                 return;
736         }
737
738         if (key == 'l' && keydown[K_CTRL])
739         {
740                 Cbuf_AddText ("clear\n");
741                 return;
742         }
743
744         if (key == 'u' && keydown[K_CTRL]) // like vi/readline ^u: delete currently edited line
745         {
746                 // clear line
747                 key_line[0] = ']';
748                 key_line[1] = 0;
749                 key_linepos = 1;
750                 return;
751         }
752
753         if (key == 'q' && keydown[K_CTRL]) // like zsh ^q: push line to history, don't execute, and clear
754         {
755                 // clear line
756                 Key_History_Push();
757                 key_line[0] = ']';
758                 key_line[1] = 0;
759                 key_linepos = 1;
760                 return;
761         }
762
763         if (key == K_ENTER || key == K_KP_ENTER)
764         {
765                 Cbuf_AddText (key_line+1);      // skip the ]
766                 Cbuf_AddText ("\n");
767                 Key_History_Push();
768                 key_line[0] = ']';
769                 key_line[1] = 0;        // EvilTypeGuy: null terminate
770                 key_linepos = 1;
771                 // force an update, because the command may take some time
772                 if (cls.state == ca_disconnected)
773                         CL_UpdateScreen ();
774                 return;
775         }
776
777         if (key == K_TAB)
778         {
779                 if(keydown[K_CTRL]) // append to the cvar its value
780                 {
781                         int             cvar_len, cvar_str_len, chars_to_move;
782                         char    k;
783                         char    cvar[MAX_INPUTLINE];
784                         const char *cvar_str;
785                         
786                         // go to the start of the variable
787                         while(--key_linepos)
788                         {
789                                 k = key_line[key_linepos];
790                                 if(k == '\"' || k == ';' || k == ' ' || k == '\'')
791                                         break;
792                         }
793                         key_linepos++;
794                         
795                         // save the variable name in cvar
796                         for(cvar_len=0; (k = key_line[key_linepos + cvar_len]) != 0; cvar_len++)
797                         {
798                                 if(k == '\"' || k == ';' || k == ' ' || k == '\'')
799                                         break;
800                                 cvar[cvar_len] = k;
801                         }
802                         if (cvar_len==0)
803                                 return;
804                         cvar[cvar_len] = 0;
805                         
806                         // go to the end of the cvar
807                         key_linepos += cvar_len;
808                         
809                         // save the content of the variable in cvar_str
810                         cvar_str = Cvar_VariableString(cvar);
811                         cvar_str_len = strlen(cvar_str);
812                         if (cvar_str_len==0)
813                                 return;
814                         
815                         // insert space and cvar_str in key_line
816                         chars_to_move = strlen(&key_line[key_linepos]);
817                         if (key_linepos + 1 + cvar_str_len + chars_to_move < MAX_INPUTLINE)
818                         {
819                                 if (chars_to_move)
820                                         memmove(&key_line[key_linepos + 1 + cvar_str_len], &key_line[key_linepos], chars_to_move);
821                                 key_line[key_linepos++] = ' ';
822                                 memcpy(&key_line[key_linepos], cvar_str, cvar_str_len);
823                                 key_linepos += cvar_str_len;
824                                 key_line[key_linepos + chars_to_move] = 0;
825                         }
826                         else
827                                 Con_Printf("Couldn't append cvar value, edit line too long.\n");
828                         return;
829                 }
830                 // Enhanced command completion
831                 // by EvilTypeGuy eviltypeguy@qeradiant.com
832                 // Thanks to Fett, Taniwha
833                 Con_CompleteCommandLine();
834                 return;
835         }
836
837         // Advanced Console Editing by Radix radix@planetquake.com
838         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
839         // Enhanced by [515]
840         // Enhanced by terencehill
841
842         // move cursor to the previous character
843         if (key == K_LEFTARROW || key == K_KP_LEFTARROW)
844         {
845                 if (key_linepos < 2)
846                         return;
847                 if(keydown[K_CTRL]) // move cursor to the previous word
848                 {
849                         int             pos;
850                         char    k;
851                         pos = key_linepos-1;
852
853                         if(pos) // skip all "; ' after the word
854                                 while(--pos)
855                                 {
856                                         k = key_line[pos];
857                                         if (!(k == '\"' || k == ';' || k == ' ' || k == '\''))
858                                                 break;
859                                 }
860
861                         if(pos)
862                                 while(--pos)
863                                 {
864                                         k = key_line[pos];
865                                         if(k == '\"' || k == ';' || k == ' ' || k == '\'')
866                                                 break;
867                                 }
868                         key_linepos = pos + 1;
869                 }
870                 else if(keydown[K_SHIFT]) // move cursor to the previous character ignoring colors
871                 {
872                         int             pos;
873                         size_t          inchar = 0;
874                         pos = u8_prevbyte(key_line+1, key_linepos-1) + 1; // do NOT give the ']' to u8_prevbyte
875                         while (pos)
876                                 if(pos-1 > 0 && key_line[pos-1] == STRING_COLOR_TAG && isdigit(key_line[pos]))
877                                         pos-=2;
878                                 else if(pos-4 > 0 && key_line[pos-4] == STRING_COLOR_TAG && key_line[pos-3] == STRING_COLOR_RGB_TAG_CHAR
879                                                 && isxdigit(key_line[pos-2]) && isxdigit(key_line[pos-1]) && isxdigit(key_line[pos]))
880                                         pos-=5;
881                                 else
882                                 {
883                                         if(pos-1 > 0 && key_line[pos-1] == STRING_COLOR_TAG && key_line[pos] == STRING_COLOR_TAG) // consider ^^ as a character
884                                                 pos--;
885                                         pos--;
886                                         break;
887                                 }
888                         // we need to move to the beginning of the character when in a wide character:
889                         u8_charidx(key_line, pos + 1, &inchar);
890                         key_linepos = pos + 1 - inchar;
891                 }
892                 else
893                 {
894                         key_linepos = u8_prevbyte(key_line+1, key_linepos-1) + 1; // do NOT give the ']' to u8_prevbyte
895                 }
896                 return;
897         }
898
899         // delete char before cursor
900         if (key == K_BACKSPACE || (key == 'h' && keydown[K_CTRL]))
901         {
902                 if (key_linepos > 1)
903                 {
904                         int newpos = u8_prevbyte(key_line+1, key_linepos-1) + 1; // do NOT give the ']' to u8_prevbyte
905                         strlcpy(key_line + newpos, key_line + key_linepos, sizeof(key_line) + 1 - key_linepos);
906                         key_linepos = newpos;
907                 }
908                 return;
909         }
910
911         // delete char on cursor
912         if (key == K_DEL || key == K_KP_DEL)
913         {
914                 size_t linelen;
915                 linelen = strlen(key_line);
916                 if (key_linepos < (int)linelen)
917                         memmove(key_line + key_linepos, key_line + key_linepos + u8_bytelen(key_line + key_linepos, 1), linelen - key_linepos);
918                 return;
919         }
920
921
922         // move cursor to the next character
923         if (key == K_RIGHTARROW || key == K_KP_RIGHTARROW)
924         {
925                 if (key_linepos >= (int)strlen(key_line))
926                         return;
927                 if(keydown[K_CTRL]) // move cursor to the next word
928                 {
929                         int             pos, len;
930                         char    k;
931                         len = (int)strlen(key_line);
932                         pos = key_linepos;
933
934                         while(++pos < len)
935                         {
936                                 k = key_line[pos];
937                                 if(k == '\"' || k == ';' || k == ' ' || k == '\'')
938                                         break;
939                         }
940                         
941                         if (pos < len) // skip all "; ' after the word
942                                 while(++pos < len)
943                                 {
944                                         k = key_line[pos];
945                                         if (!(k == '\"' || k == ';' || k == ' ' || k == '\''))
946                                                 break;
947                                 }
948                         key_linepos = pos;
949                 }
950                 else if(keydown[K_SHIFT]) // move cursor to the next character ignoring colors
951                 {
952                         int             pos, len;
953                         len = (int)strlen(key_line);
954                         pos = key_linepos;
955                         
956                         // go beyond all initial consecutive color tags, if any
957                         if(pos < len)
958                                 while (key_line[pos] == STRING_COLOR_TAG)
959                                 {
960                                         if(isdigit(key_line[pos+1]))
961                                                 pos+=2;
962                                         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]))
963                                                 pos+=5;
964                                         else
965                                                 break;
966                                 }
967                         
968                         // skip the char
969                         if (key_line[pos] == STRING_COLOR_TAG && key_line[pos+1] == STRING_COLOR_TAG) // consider ^^ as a character
970                                 pos++;
971                         pos += u8_bytelen(key_line + pos, 1);
972                         
973                         // now go beyond all next consecutive color tags, if any
974                         if(pos < len)
975                                 while (key_line[pos] == STRING_COLOR_TAG)
976                                 {
977                                         if(isdigit(key_line[pos+1]))
978                                                 pos+=2;
979                                         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]))
980                                                 pos+=5;
981                                         else
982                                                 break;
983                                 }
984                         key_linepos = pos;
985                 }
986                 else
987                         key_linepos += u8_bytelen(key_line + key_linepos, 1);
988                 return;
989         }
990
991         if (key == K_INS || key == K_KP_INS) // toggle insert mode
992         {
993                 key_insert ^= 1;
994                 return;
995         }
996
997         // End Advanced Console Editing
998
999         if (key == K_UPARROW || key == K_KP_UPARROW || (key == 'p' && keydown[K_CTRL]))
1000         {
1001                 Key_History_Up();
1002                 return;
1003         }
1004
1005         if (key == K_DOWNARROW || key == K_KP_DOWNARROW || (key == 'n' && keydown[K_CTRL]))
1006         {
1007                 Key_History_Down();
1008                 return;
1009         }
1010         // ~1.0795 = 82/76  using con_textsize 64 76 is height of the char, 6 is the distance between 2 lines
1011
1012         if (keydown[K_CTRL])
1013         {
1014                 // prints all the matching commands
1015                 if (key == 'f')
1016                 {
1017                         Key_History_Find_All();
1018                         return;
1019                 }
1020                 // Search forwards/backwards, pointing the history's index to the
1021                 // matching command but without fetching it to let one continue the search.
1022                 // To fetch it, it suffices to just press UP or DOWN.
1023                 if (key == 'r')
1024                 {
1025                         if (keydown[K_SHIFT])
1026                                 Key_History_Find_Forwards();
1027                         else
1028                                 Key_History_Find_Backwards();
1029                         return;
1030                 }
1031                 // go to the last/first command of the history
1032                 if (key == ',')
1033                 {
1034                         Key_History_First();
1035                         return;
1036                 }
1037                 if (key == '.')
1038                 {
1039                         Key_History_Last();
1040                         return;
1041                 }
1042         }
1043
1044         if (key == K_PGUP || key == K_KP_PGUP)
1045         {
1046                 if(keydown[K_CTRL])
1047                 {
1048                         con_backscroll += ((vid_conheight.integer >> 2) / con_textsize.integer)-1;
1049                 }
1050                 else
1051                         con_backscroll += ((vid_conheight.integer >> 1) / con_textsize.integer)-3;
1052                 return;
1053         }
1054
1055         if (key == K_PGDN || key == K_KP_PGDN)
1056         {
1057                 if(keydown[K_CTRL])
1058                 {
1059                         con_backscroll -= ((vid_conheight.integer >> 2) / con_textsize.integer)-1;
1060                 }
1061                 else
1062                         con_backscroll -= ((vid_conheight.integer >> 1) / con_textsize.integer)-3;
1063                 return;
1064         }
1065  
1066         if (key == K_MWHEELUP)
1067         {
1068                 if(keydown[K_CTRL])
1069                         con_backscroll += 1;
1070                 else if(keydown[K_SHIFT])
1071                         con_backscroll += ((vid_conheight.integer >> 2) / con_textsize.integer)-1;
1072                 else
1073                         con_backscroll += 5;
1074                 return;
1075         }
1076
1077         if (key == K_MWHEELDOWN)
1078         {
1079                 if(keydown[K_CTRL])
1080                         con_backscroll -= 1;
1081                 else if(keydown[K_SHIFT])
1082                         con_backscroll -= ((vid_conheight.integer >> 2) / con_textsize.integer)-1;
1083                 else
1084                         con_backscroll -= 5;
1085                 return;
1086         }
1087
1088         if (keydown[K_CTRL])
1089         {
1090                 // text zoom in
1091                 if (key == '+' || key == K_KP_PLUS)
1092                 {
1093                         if (con_textsize.integer < 128)
1094                                 Cvar_SetValueQuick(&con_textsize, con_textsize.integer + 1);
1095                         return;
1096                 }
1097                 // text zoom out
1098                 if (key == '-' || key == K_KP_MINUS)
1099                 {
1100                         if (con_textsize.integer > 1)
1101                                 Cvar_SetValueQuick(&con_textsize, con_textsize.integer - 1);
1102                         return;
1103                 }
1104                 // text zoom reset
1105                 if (key == '0' || key == K_KP_INS)
1106                 {
1107                         Cvar_SetValueQuick(&con_textsize, atoi(Cvar_VariableDefString("con_textsize")));
1108                         return;
1109                 }
1110         }
1111
1112         if (key == K_HOME || key == K_KP_HOME)
1113         {
1114                 if (keydown[K_CTRL])
1115                         con_backscroll = CON_TEXTSIZE;
1116                 else
1117                         key_linepos = 1;
1118                 return;
1119         }
1120
1121         if (key == K_END || key == K_KP_END)
1122         {
1123                 if (keydown[K_CTRL])
1124                         con_backscroll = 0;
1125                 else
1126                         key_linepos = (int)strlen(key_line);
1127                 return;
1128         }
1129
1130         // non printable
1131         if (unicode < 32)
1132                 return;
1133
1134         if (key_linepos < MAX_INPUTLINE-1)
1135         {
1136                 char buf[16];
1137                 int len;
1138                 int blen;
1139                 blen = u8_fromchar(unicode, buf, sizeof(buf));
1140                 if (!blen)
1141                         return;
1142                 len = (int)strlen(&key_line[key_linepos]);
1143                 // check insert mode, or always insert if at end of line
1144                 if (key_insert || len == 0)
1145                 {
1146                         // can't use strcpy to move string to right
1147                         len++;
1148                         //memmove(&key_line[key_linepos + u8_bytelen(key_line + key_linepos, 1)], &key_line[key_linepos], len);
1149                         memmove(&key_line[key_linepos + blen], &key_line[key_linepos], len);
1150                 }
1151                 memcpy(key_line + key_linepos, buf, blen);
1152                 key_linepos += blen;
1153                 //key_linepos += u8_fromchar(unicode, key_line + key_linepos, sizeof(key_line) - key_linepos - 1);
1154                 //key_line[key_linepos] = ascii;
1155                 //key_linepos++;
1156         }
1157 }
1158
1159 //============================================================================
1160
1161 int chat_mode;
1162 char            chat_buffer[MAX_INPUTLINE];
1163 unsigned int    chat_bufferlen = 0;
1164
1165 extern int Nicks_CompleteChatLine(char *buffer, size_t size, unsigned int pos);
1166
1167 static void
1168 Key_Message (int key, int ascii)
1169 {
1170         if (key == K_ENTER || ascii == 10 || ascii == 13)
1171         {
1172                 if(chat_mode < 0)
1173                         Cmd_ExecuteString(chat_buffer, src_command); // not Cbuf_AddText to allow semiclons in args; however, this allows no variables then. Use aliases!
1174                 else
1175                         Cmd_ForwardStringToServer(va("%s %s", chat_mode ? "say_team" : "say ", chat_buffer));
1176
1177                 key_dest = key_game;
1178                 chat_bufferlen = 0;
1179                 chat_buffer[0] = 0;
1180                 return;
1181         }
1182
1183         // TODO add support for arrow keys and simple editing
1184
1185         if (key == K_ESCAPE) {
1186                 key_dest = key_game;
1187                 chat_bufferlen = 0;
1188                 chat_buffer[0] = 0;
1189                 return;
1190         }
1191
1192         if (key == K_BACKSPACE) {
1193                 if (chat_bufferlen) {
1194                         chat_bufferlen = u8_prevbyte(chat_buffer, chat_bufferlen);
1195                         chat_buffer[chat_bufferlen] = 0;
1196                 }
1197                 return;
1198         }
1199
1200         if(key == K_TAB) {
1201                 chat_bufferlen = Nicks_CompleteChatLine(chat_buffer, sizeof(chat_buffer), chat_bufferlen);
1202                 return;
1203         }
1204
1205         // ctrl+key generates an ascii value < 32 and shows a char from the charmap
1206         if (ascii > 0 && ascii < 32 && utf8_enable.integer)
1207                 ascii = 0xE000 + ascii;
1208
1209         if (chat_bufferlen == sizeof (chat_buffer) - 1)
1210                 return;                                                 // all full
1211
1212         if (!ascii)
1213                 return;                                                 // non printable
1214
1215         chat_bufferlen += u8_fromchar(ascii, chat_buffer+chat_bufferlen, sizeof(chat_buffer) - chat_bufferlen - 1);
1216
1217         //chat_buffer[chat_bufferlen++] = ascii;
1218         //chat_buffer[chat_bufferlen] = 0;
1219 }
1220
1221 //============================================================================
1222
1223
1224 /*
1225 ===================
1226 Returns a key number to be used to index keybindings[] by looking at
1227 the given string.  Single ascii characters return themselves, while
1228 the K_* names are matched up.
1229 ===================
1230 */
1231 int
1232 Key_StringToKeynum (const char *str)
1233 {
1234         const keyname_t  *kn;
1235
1236         if (!str || !str[0])
1237                 return -1;
1238         if (!str[1])
1239                 return tolower(str[0]);
1240
1241         for (kn = keynames; kn->name; kn++) {
1242                 if (!strcasecmp (str, kn->name))
1243                         return kn->keynum;
1244         }
1245         return -1;
1246 }
1247
1248 /*
1249 ===================
1250 Returns a string (either a single ascii char, or a K_* name) for the
1251 given keynum.
1252 FIXME: handle quote special (general escape sequence?)
1253 ===================
1254 */
1255 const char *
1256 Key_KeynumToString (int keynum)
1257 {
1258         const keyname_t  *kn;
1259         static char tinystr[2];
1260
1261         // -1 is an invalid code
1262         if (keynum < 0)
1263                 return "<KEY NOT FOUND>";
1264
1265         // search overrides first, because some characters are special
1266         for (kn = keynames; kn->name; kn++)
1267                 if (keynum == kn->keynum)
1268                         return kn->name;
1269
1270         // if it is printable, output it as a single character
1271         if (keynum > 32 && keynum < 256)
1272         {
1273                 tinystr[0] = keynum;
1274                 tinystr[1] = 0;
1275                 return tinystr;
1276         }
1277
1278         // if it is not overridden and not printable, we don't know what to do with it
1279         return "<UNKNOWN KEYNUM>";
1280 }
1281
1282
1283 qboolean
1284 Key_SetBinding (int keynum, int bindmap, const char *binding)
1285 {
1286         char *newbinding;
1287         size_t l;
1288
1289         if (keynum == -1 || keynum >= MAX_KEYS)
1290                 return false;
1291         if ((bindmap < 0) || (bindmap >= MAX_BINDMAPS))
1292                 return false;
1293
1294 // free old bindings
1295         if (keybindings[bindmap][keynum]) {
1296                 Z_Free (keybindings[bindmap][keynum]);
1297                 keybindings[bindmap][keynum] = NULL;
1298         }
1299         if(!binding[0]) // make "" binds be removed --blub
1300                 return true;
1301 // allocate memory for new binding
1302         l = strlen (binding);
1303         newbinding = (char *)Z_Malloc (l + 1);
1304         memcpy (newbinding, binding, l + 1);
1305         newbinding[l] = 0;
1306         keybindings[bindmap][keynum] = newbinding;
1307         return true;
1308 }
1309
1310 void Key_GetBindMap(int *fg, int *bg)
1311 {
1312         if(fg)
1313                 *fg = key_bmap;
1314         if(bg)
1315                 *bg = key_bmap2;
1316 }
1317
1318 qboolean Key_SetBindMap(int fg, int bg)
1319 {
1320         if(fg >= MAX_BINDMAPS)
1321                 return false;
1322         if(bg >= MAX_BINDMAPS)
1323                 return false;
1324         if(fg >= 0)
1325                 key_bmap = fg;
1326         if(bg >= 0)
1327                 key_bmap2 = bg;
1328         return true;
1329 }
1330
1331 static void
1332 Key_In_Unbind_f (void)
1333 {
1334         int         b, m;
1335         char *errchar = NULL;
1336
1337         if (Cmd_Argc () != 3) {
1338                 Con_Print("in_unbind <bindmap> <key> : remove commands from a key\n");
1339                 return;
1340         }
1341
1342         m = strtol(Cmd_Argv (1), &errchar, 0);
1343         if ((m < 0) || (m >= MAX_BINDMAPS) || (errchar && *errchar)) {
1344                 Con_Printf("%s isn't a valid bindmap\n", Cmd_Argv(1));
1345                 return;
1346         }
1347
1348         b = Key_StringToKeynum (Cmd_Argv (2));
1349         if (b == -1) {
1350                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (2));
1351                 return;
1352         }
1353
1354         if(!Key_SetBinding (b, m, ""))
1355                 Con_Printf("Key_SetBinding failed for unknown reason\n");
1356 }
1357
1358 static void
1359 Key_In_Bind_f (void)
1360 {
1361         int         i, c, b, m;
1362         char        cmd[MAX_INPUTLINE];
1363         char *errchar = NULL;
1364
1365         c = Cmd_Argc ();
1366
1367         if (c != 3 && c != 4) {
1368                 Con_Print("in_bind <bindmap> <key> [command] : attach a command to a key\n");
1369                 return;
1370         }
1371
1372         m = strtol(Cmd_Argv (1), &errchar, 0);
1373         if ((m < 0) || (m >= MAX_BINDMAPS) || (errchar && *errchar)) {
1374                 Con_Printf("%s isn't a valid bindmap\n", Cmd_Argv(1));
1375                 return;
1376         }
1377
1378         b = Key_StringToKeynum (Cmd_Argv (2));
1379         if (b == -1 || b >= MAX_KEYS) {
1380                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (2));
1381                 return;
1382         }
1383
1384         if (c == 3) {
1385                 if (keybindings[m][b])
1386                         Con_Printf("\"%s\" = \"%s\"\n", Cmd_Argv (2), keybindings[m][b]);
1387                 else
1388                         Con_Printf("\"%s\" is not bound\n", Cmd_Argv (2));
1389                 return;
1390         }
1391 // copy the rest of the command line
1392         cmd[0] = 0;                                                     // start out with a null string
1393         for (i = 3; i < c; i++) {
1394                 strlcat (cmd, Cmd_Argv (i), sizeof (cmd));
1395                 if (i != (c - 1))
1396                         strlcat (cmd, " ", sizeof (cmd));
1397         }
1398
1399         if(!Key_SetBinding (b, m, cmd))
1400                 Con_Printf("Key_SetBinding failed for unknown reason\n");
1401 }
1402
1403 static void
1404 Key_In_Bindmap_f (void)
1405 {
1406         int         m1, m2, c;
1407         char *errchar = NULL;
1408
1409         c = Cmd_Argc ();
1410
1411         if (c != 3) {
1412                 Con_Print("in_bindmap <bindmap> <fallback>: set current bindmap and fallback\n");
1413                 return;
1414         }
1415
1416         m1 = strtol(Cmd_Argv (1), &errchar, 0);
1417         if ((m1 < 0) || (m1 >= MAX_BINDMAPS) || (errchar && *errchar)) {
1418                 Con_Printf("%s isn't a valid bindmap\n", Cmd_Argv(1));
1419                 return;
1420         }
1421
1422         m2 = strtol(Cmd_Argv (2), &errchar, 0);
1423         if ((m2 < 0) || (m2 >= MAX_BINDMAPS) || (errchar && *errchar)) {
1424                 Con_Printf("%s isn't a valid bindmap\n", Cmd_Argv(2));
1425                 return;
1426         }
1427
1428         key_bmap = m1;
1429         key_bmap2 = m2;
1430 }
1431
1432 static void
1433 Key_Unbind_f (void)
1434 {
1435         int         b;
1436
1437         if (Cmd_Argc () != 2) {
1438                 Con_Print("unbind <key> : remove commands from a key\n");
1439                 return;
1440         }
1441
1442         b = Key_StringToKeynum (Cmd_Argv (1));
1443         if (b == -1) {
1444                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (1));
1445                 return;
1446         }
1447
1448         if(!Key_SetBinding (b, 0, ""))
1449                 Con_Printf("Key_SetBinding failed for unknown reason\n");
1450 }
1451
1452 static void
1453 Key_Unbindall_f (void)
1454 {
1455         int         i, j;
1456
1457         for (j = 0; j < MAX_BINDMAPS; j++)
1458                 for (i = 0; i < (int)(sizeof(keybindings[0])/sizeof(keybindings[0][0])); i++)
1459                         if (keybindings[j][i])
1460                                 Key_SetBinding (i, j, "");
1461 }
1462
1463 static void
1464 Key_PrintBindList(int j)
1465 {
1466         char bindbuf[MAX_INPUTLINE];
1467         const char *p;
1468         int i;
1469
1470         for (i = 0; i < (int)(sizeof(keybindings[0])/sizeof(keybindings[0][0])); i++)
1471         {
1472                 p = keybindings[j][i];
1473                 if (p)
1474                 {
1475                         Cmd_QuoteString(bindbuf, sizeof(bindbuf), p, "\"\\");
1476                         if (j == 0)
1477                                 Con_Printf("^2%s ^7= \"%s\"\n", Key_KeynumToString (i), bindbuf);
1478                         else
1479                                 Con_Printf("^3bindmap %d: ^2%s ^7= \"%s\"\n", j, Key_KeynumToString (i), bindbuf);
1480                 }
1481         }
1482 }
1483
1484 static void
1485 Key_In_BindList_f (void)
1486 {
1487         int m;
1488         char *errchar = NULL;
1489
1490         if(Cmd_Argc() >= 2)
1491         {
1492                 m = strtol(Cmd_Argv(1), &errchar, 0);
1493                 if ((m < 0) || (m >= MAX_BINDMAPS) || (errchar && *errchar)) {
1494                         Con_Printf("%s isn't a valid bindmap\n", Cmd_Argv(1));
1495                         return;
1496                 }
1497                 Key_PrintBindList(m);
1498         }
1499         else
1500         {
1501                 for (m = 0; m < MAX_BINDMAPS; m++)
1502                         Key_PrintBindList(m);
1503         }
1504 }
1505
1506 static void
1507 Key_BindList_f (void)
1508 {
1509         Key_PrintBindList(0);
1510 }
1511
1512 static void
1513 Key_Bind_f (void)
1514 {
1515         int         i, c, b;
1516         char        cmd[MAX_INPUTLINE];
1517
1518         c = Cmd_Argc ();
1519
1520         if (c != 2 && c != 3) {
1521                 Con_Print("bind <key> [command] : attach a command to a key\n");
1522                 return;
1523         }
1524         b = Key_StringToKeynum (Cmd_Argv (1));
1525         if (b == -1 || b >= MAX_KEYS) {
1526                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (1));
1527                 return;
1528         }
1529
1530         if (c == 2) {
1531                 if (keybindings[0][b])
1532                         Con_Printf("\"%s\" = \"%s\"\n", Cmd_Argv (1), keybindings[0][b]);
1533                 else
1534                         Con_Printf("\"%s\" is not bound\n", Cmd_Argv (1));
1535                 return;
1536         }
1537 // copy the rest of the command line
1538         cmd[0] = 0;                                                     // start out with a null string
1539         for (i = 2; i < c; i++) {
1540                 strlcat (cmd, Cmd_Argv (i), sizeof (cmd));
1541                 if (i != (c - 1))
1542                         strlcat (cmd, " ", sizeof (cmd));
1543         }
1544
1545         if(!Key_SetBinding (b, 0, cmd))
1546                 Con_Printf("Key_SetBinding failed for unknown reason\n");
1547 }
1548
1549 /*
1550 ============
1551 Writes lines containing "bind key value"
1552 ============
1553 */
1554 void
1555 Key_WriteBindings (qfile_t *f)
1556 {
1557         int         i, j;
1558         char bindbuf[MAX_INPUTLINE];
1559         const char *p;
1560
1561         for (j = 0; j < MAX_BINDMAPS; j++)
1562         {
1563                 for (i = 0; i < (int)(sizeof(keybindings[0])/sizeof(keybindings[0][0])); i++)
1564                 {
1565                         p = keybindings[j][i];
1566                         if (p)
1567                         {
1568                                 Cmd_QuoteString(bindbuf, sizeof(bindbuf), p, "\"\\"); // don't need to escape $ because cvars are not expanded inside bind
1569                                 if (j == 0)
1570                                         FS_Printf(f, "bind %s \"%s\"\n", Key_KeynumToString (i), bindbuf);
1571                                 else
1572                                         FS_Printf(f, "in_bind %d %s \"%s\"\n", j, Key_KeynumToString (i), bindbuf);
1573                         }
1574                 }
1575         }
1576 }
1577
1578
1579 void
1580 Key_Init (void)
1581 {
1582         Key_History_Init();
1583         key_line[0] = ']';
1584         key_line[1] = 0;
1585         key_linepos = 1;
1586
1587 //
1588 // register our functions
1589 //
1590         Cmd_AddCommand ("in_bind", Key_In_Bind_f, "binds a command to the specified key in the selected bindmap");
1591         Cmd_AddCommand ("in_unbind", Key_In_Unbind_f, "removes command on the specified key in the selected bindmap");
1592         Cmd_AddCommand ("in_bindlist", Key_In_BindList_f, "bindlist: displays bound keys for all bindmaps, or the given bindmap");
1593         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");
1594
1595         Cmd_AddCommand ("bind", Key_Bind_f, "binds a command to the specified key in bindmap 0");
1596         Cmd_AddCommand ("unbind", Key_Unbind_f, "removes a command on the specified key in bindmap 0");
1597         Cmd_AddCommand ("bindlist", Key_BindList_f, "bindlist: displays bound keys for bindmap 0 bindmaps");
1598         Cmd_AddCommand ("unbindall", Key_Unbindall_f, "removes all commands from all keys in all bindmaps (leaving only shift-escape and escape)");
1599
1600         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)");
1601
1602         Cvar_RegisterVariable (&con_closeontoggleconsole);
1603 }
1604
1605 void
1606 Key_Shutdown (void)
1607 {
1608         Key_History_Shutdown();
1609 }
1610
1611 const char *Key_GetBind (int key, int bindmap)
1612 {
1613         const char *bind;
1614         if (key < 0 || key >= MAX_KEYS)
1615                 return NULL;
1616         if(bindmap >= MAX_BINDMAPS)
1617                 return NULL;
1618         if(bindmap >= 0)
1619         {
1620                 bind = keybindings[bindmap][key];
1621         }
1622         else
1623         {
1624                 bind = keybindings[key_bmap][key];
1625                 if (!bind)
1626                         bind = keybindings[key_bmap2][key];
1627         }
1628         return bind;
1629 }
1630
1631 void Key_FindKeysForCommand (const char *command, int *keys, int numkeys, int bindmap)
1632 {
1633         int             count;
1634         int             j;
1635         const char      *b;
1636
1637         for (j = 0;j < numkeys;j++)
1638                 keys[j] = -1;
1639
1640         if(bindmap >= MAX_BINDMAPS)
1641                 return;
1642
1643         count = 0;
1644
1645         for (j = 0; j < MAX_KEYS; ++j)
1646         {
1647                 b = Key_GetBind(j, bindmap);
1648                 if (!b)
1649                         continue;
1650                 if (!strcmp (b, command) )
1651                 {
1652                         keys[count++] = j;
1653                         if (count == numkeys)
1654                                 break;
1655                 }
1656         }
1657 }
1658
1659 qboolean CL_VM_InputEvent (qboolean down, int key, int ascii);
1660
1661 /*
1662 ===================
1663 Called by the system between frames for both key up and key down events
1664 Should NOT be called during an interrupt!
1665 ===================
1666 */
1667 static char tbl_keyascii[MAX_KEYS];
1668 static keydest_t tbl_keydest[MAX_KEYS];
1669
1670 typedef struct eventqueueitem_s
1671 {
1672         int key;
1673         int ascii;
1674         qboolean down;
1675 }
1676 eventqueueitem_t;
1677 static int events_blocked = 0;
1678 static eventqueueitem_t eventqueue[32];
1679 static unsigned eventqueue_idx = 0;
1680
1681 static void Key_EventQueue_Add(int key, int ascii, qboolean down)
1682 {
1683         if(eventqueue_idx < sizeof(eventqueue) / sizeof(*eventqueue))
1684         {
1685                 eventqueue[eventqueue_idx].key = key;
1686                 eventqueue[eventqueue_idx].ascii = ascii;
1687                 eventqueue[eventqueue_idx].down = down;
1688                 ++eventqueue_idx;
1689         }
1690 }
1691
1692 void Key_EventQueue_Block(void)
1693 {
1694         // block key events until call to Unblock
1695         events_blocked = true;
1696 }
1697
1698 void Key_EventQueue_Unblock(void)
1699 {
1700         // unblocks key events again
1701         unsigned i;
1702         events_blocked = false;
1703         for(i = 0; i < eventqueue_idx; ++i)
1704                 Key_Event(eventqueue[i].key, eventqueue[i].ascii, eventqueue[i].down);
1705         eventqueue_idx = 0;
1706 }
1707
1708 void
1709 Key_Event (int key, int ascii, qboolean down)
1710 {
1711         const char *bind;
1712         qboolean q;
1713         keydest_t keydest = key_dest;
1714
1715         if (key < 0 || key >= MAX_KEYS)
1716                 return;
1717
1718         if(events_blocked)
1719         {
1720                 Key_EventQueue_Add(key, ascii, down);
1721                 return;
1722         }
1723
1724         if (ascii == 0x80 && utf8_enable.integer) // pressing AltGr-5 (or AltGr-e) and for some reason we get windows-1252 encoding?
1725                 ascii = 0x20AC; // we want the Euro currency sign
1726                 // TODO find out which vid_ drivers do it and fix it there
1727                 // but catching U+0080 here is no loss as that char is not useful anyway
1728
1729         // get key binding
1730         bind = keybindings[key_bmap][key];
1731         if (!bind)
1732                 bind = keybindings[key_bmap2][key];
1733
1734         if (developer_insane.integer)
1735                 Con_DPrintf("Key_Event(%i, '%c', %s) keydown %i bind \"%s\"\n", key, ascii ? ascii : '?', down ? "down" : "up", keydown[key], bind ? bind : "");
1736
1737         if(key_consoleactive)
1738                 keydest = key_console;
1739         
1740         if (down)
1741         {
1742                 // increment key repeat count each time a down is received so that things
1743                 // which want to ignore key repeat can ignore it
1744                 keydown[key] = min(keydown[key] + 1, 2);
1745                 if(keydown[key] == 1) {
1746                         tbl_keyascii[key] = ascii;
1747                         tbl_keydest[key] = keydest;
1748                 } else {
1749                         ascii = tbl_keyascii[key];
1750                         keydest = tbl_keydest[key];
1751                 }
1752         }
1753         else
1754         {
1755                 // clear repeat count now that the key is released
1756                 keydown[key] = 0;
1757                 keydest = tbl_keydest[key];
1758                 ascii = tbl_keyascii[key];
1759         }
1760
1761         if(keydest == key_void)
1762                 return;
1763         
1764         // key_consoleactive is a flag not a key_dest because the console is a
1765         // high priority overlay ontop of the normal screen (designed as a safety
1766         // feature so that developers and users can rescue themselves from a bad
1767         // situation).
1768         //
1769         // this also means that toggling the console on/off does not lose the old
1770         // key_dest state
1771
1772         // specially handle escape (togglemenu) and shift-escape (toggleconsole)
1773         // engine bindings, these are not handled as normal binds so that the user
1774         // can recover from a completely empty bindmap
1775         if (key == K_ESCAPE)
1776         {
1777                 // ignore key repeats on escape
1778                 if (keydown[key] > 1)
1779                         return;
1780
1781                 // escape does these things:
1782                 // key_consoleactive - close console
1783                 // key_message - abort messagemode
1784                 // key_menu - go to parent menu (or key_game)
1785                 // key_game - open menu
1786
1787                 // in all modes shift-escape toggles console
1788                 if (keydown[K_SHIFT])
1789                 {
1790                         if(down)
1791                         {
1792                                 Con_ToggleConsole_f ();
1793                                 tbl_keydest[key] = key_void; // esc release should go nowhere (especially not to key_menu or key_game)
1794                         }
1795                         return;
1796                 }
1797
1798                 switch (keydest)
1799                 {
1800                         case key_console:
1801                                 if(down)
1802                                 {
1803                                         if(key_consoleactive & KEY_CONSOLEACTIVE_FORCED)
1804                                         {
1805                                                 key_consoleactive &= ~KEY_CONSOLEACTIVE_USER;
1806                                                 MR_ToggleMenu(1);
1807                                         }
1808                                         else
1809                                                 Con_ToggleConsole_f();
1810                                 }
1811                                 break;
1812
1813                         case key_message:
1814                                 if (down)
1815                                         Key_Message (key, ascii); // that'll close the message input
1816                                 break;
1817
1818                         case key_menu:
1819                         case key_menu_grabbed:
1820                                 MR_KeyEvent (key, ascii, down);
1821                                 break;
1822
1823                         case key_game:
1824                                 // csqc has priority over toggle menu if it wants to (e.g. handling escape for UI stuff in-game.. :sick:)
1825                                 q = CL_VM_InputEvent(down, key, ascii);
1826                                 if (!q && down)
1827                                         MR_ToggleMenu(1);
1828                                 break;
1829
1830                         default:
1831                                 Con_Printf ("Key_Event: Bad key_dest\n");
1832                 }
1833                 return;
1834         }
1835
1836         // send function keydowns to interpreter no matter what mode is (unless the menu has specifically grabbed the keyboard, for rebinding keys)
1837         // VorteX: Omnicide does bind F* keys
1838         if (keydest != key_menu_grabbed)
1839         if (key >= K_F1 && key <= K_F12 && gamemode != GAME_BLOODOMNICIDE)
1840         {
1841                 if (bind)
1842                 {
1843                         if(keydown[key] == 1 && down)
1844                         {
1845                                 // button commands add keynum as a parm
1846                                 if (bind[0] == '+')
1847                                         Cbuf_AddText (va("%s %i\n", bind, key));
1848                                 else
1849                                 {
1850                                         Cbuf_AddText (bind);
1851                                         Cbuf_AddText ("\n");
1852                                 }
1853                         } else if(bind[0] == '+' && !down && keydown[key] == 0)
1854                                 Cbuf_AddText(va("-%s %i\n", bind + 1, key));
1855                 }
1856                 return;
1857         }
1858
1859         // send input to console if it wants it
1860         if (keydest == key_console)
1861         {
1862                 if (!down)
1863                         return;
1864                 // con_closeontoggleconsole enables toggleconsole keys to close the
1865                 // console, as long as they are not the color prefix character
1866                 // (special exemption for german keyboard layouts)
1867                 if (con_closeontoggleconsole.integer && bind && !strncmp(bind, "toggleconsole", strlen("toggleconsole")) && (key_consoleactive & KEY_CONSOLEACTIVE_USER) && ascii != STRING_COLOR_TAG)
1868                 {
1869                         Con_ToggleConsole_f ();
1870                         return;
1871                 }
1872                 Key_Console (key, ascii);
1873                 return;
1874         }
1875
1876         // handle toggleconsole in menu too
1877         if (keydest == key_menu)
1878         {
1879                 if (down && con_closeontoggleconsole.integer && bind && !strncmp(bind, "toggleconsole", strlen("toggleconsole")) && ascii != STRING_COLOR_TAG)
1880                 {
1881                         Con_ToggleConsole_f ();
1882                         tbl_keydest[key] = key_void; // key release should go nowhere (especially not to key_menu or key_game)
1883                         return;
1884                 }
1885         }
1886
1887         // ignore binds while a video is played, let the video system handle the key event
1888         if (cl_videoplaying)
1889         {
1890                 if (gamemode == GAME_BLOODOMNICIDE) // menu controls key events
1891                         MR_KeyEvent(key, ascii, down);
1892                 else
1893                         CL_Video_KeyEvent (key, ascii, keydown[key] != 0);
1894                 return;
1895         }
1896
1897         // anything else is a key press into the game, chat line, or menu
1898         switch (keydest)
1899         {
1900                 case key_message:
1901                         if (down)
1902                                 Key_Message (key, ascii);
1903                         break;
1904                 case key_menu:
1905                 case key_menu_grabbed:
1906                         MR_KeyEvent (key, ascii, down);
1907                         break;
1908                 case key_game:
1909                         q = CL_VM_InputEvent(down, key, ascii);
1910                         // ignore key repeats on binds and only send the bind if the event hasnt been already processed by csqc
1911                         if (!q && bind)
1912                         {
1913                                 if(keydown[key] == 1 && down)
1914                                 {
1915                                         // button commands add keynum as a parm
1916                                         if (bind[0] == '+')
1917                                                 Cbuf_AddText (va("%s %i\n", bind, key));
1918                                         else
1919                                         {
1920                                                 Cbuf_AddText (bind);
1921                                                 Cbuf_AddText ("\n");
1922                                         }
1923                                 } else if(bind[0] == '+' && !down && keydown[key] == 0)
1924                                         Cbuf_AddText(va("-%s %i\n", bind + 1, key));
1925                         }
1926                         break;
1927                 default:
1928                         Con_Printf ("Key_Event: Bad key_dest\n");
1929         }
1930 }
1931
1932 /*
1933 ===================
1934 Key_ClearStates
1935 ===================
1936 */
1937 void
1938 Key_ClearStates (void)
1939 {
1940         memset(keydown, 0, sizeof(keydown));
1941 }