added -demo and -demolooponly options. -demo starts the wanted demo and then shuts...
[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
25
26 /*
27 key up events are sent even if in console mode
28 */
29
30 #define MAX_INPUTLINE 256
31 int                     edit_line = 31;
32 int                     history_line = 31;
33 char            key_lines[32][MAX_INPUTLINE];
34 int                     key_linepos;
35 static int      ctrl_down = false;
36 static int      key_lastpress;
37 int                     key_insert = true;      // insert key toggle (for editing)
38
39 keydest_t       key_dest;
40 int                     key_consoleactive;
41
42 static int      key_count;                                      // incremented every key event
43 static int      key_bmap, key_bmap2;
44
45 char                            *keybindings[8][1024];
46 static qboolean         consolekeys[1024];      // if true, can't be rebound while in
47                                                                                 // console
48 static qboolean         menubound[1024];                // if true, can't be rebound while in
49                                                                                 // menu
50 static unsigned int     key_repeats[1024];      // if > 1, it is autorepeating
51 static qboolean         keydown[1024];
52
53 typedef struct {
54         const char      *name;
55         int                     keynum;
56 } keyname_t;
57
58 static const keyname_t   keynames[] = {
59         {"TAB", K_TAB},
60         {"ENTER", K_ENTER},
61         {"ESCAPE", K_ESCAPE},
62         {"SPACE", K_SPACE},
63         {"BACKSPACE", K_BACKSPACE},
64         {"UPARROW", K_UPARROW},
65         {"DOWNARROW", K_DOWNARROW},
66         {"LEFTARROW", K_LEFTARROW},
67         {"RIGHTARROW", K_RIGHTARROW},
68
69         {"ALT", K_ALT},
70         {"CTRL", K_CTRL},
71         {"SHIFT", K_SHIFT},
72
73         {"F1", K_F1},
74         {"F2", K_F2},
75         {"F3", K_F3},
76         {"F4", K_F4},
77         {"F5", K_F5},
78         {"F6", K_F6},
79         {"F7", K_F7},
80         {"F8", K_F8},
81         {"F9", K_F9},
82         {"F10", K_F10},
83         {"F11", K_F11},
84         {"F12", K_F12},
85
86         {"INS", K_INS},
87         {"DEL", K_DEL},
88         {"PGDN", K_PGDN},
89         {"PGUP", K_PGUP},
90         {"HOME", K_HOME},
91         {"END", K_END},
92
93         {"PAUSE", K_PAUSE},
94
95         {"MWHEELUP", K_MWHEELUP},
96         {"MWHEELDOWN", K_MWHEELDOWN},
97
98         {"MOUSE1", K_MOUSE1},
99         {"MOUSE2", K_MOUSE2},
100         {"MOUSE3", K_MOUSE3},
101         {"MOUSE4", K_MOUSE4},
102         {"MOUSE5", K_MOUSE5},
103         {"MOUSE6", K_MOUSE6},
104         {"MOUSE7", K_MOUSE7},
105         {"MOUSE8", K_MOUSE8},
106         {"MOUSE9", K_MOUSE9},
107         {"MOUSE10", K_MOUSE10},
108         {"MOUSE11", K_MOUSE11},
109         {"MOUSE12", K_MOUSE12},
110         {"MOUSE13", K_MOUSE13},
111         {"MOUSE14", K_MOUSE14},
112         {"MOUSE15", K_MOUSE15},
113         {"MOUSE16", K_MOUSE16},
114
115         {"NUMLOCK", K_NUMLOCK},
116         {"CAPSLOCK", K_CAPSLOCK},
117         {"SCROLLOCK", K_SCROLLOCK},
118
119         {"KP_HOME",                     K_KP_HOME },
120         {"KP_UPARROW",          K_KP_UPARROW },
121         {"KP_PGUP",                     K_KP_PGUP },
122         {"KP_LEFTARROW",        K_KP_LEFTARROW },
123         {"KP_RIGHTARROW",       K_KP_RIGHTARROW },
124         {"KP_END",                      K_KP_END },
125         {"KP_DOWNARROW",        K_KP_DOWNARROW },
126         {"KP_PGDN",                     K_KP_PGDN },
127         {"KP_INS",                      K_KP_INS },
128         {"KP_DEL",                      K_KP_DEL },
129         {"KP_SLASH",            K_KP_SLASH },
130
131         {"KP_0", K_KP_0},
132         {"KP_1", K_KP_1},
133         {"KP_2", K_KP_2},
134         {"KP_3", K_KP_3},
135         {"KP_4", K_KP_4},
136         {"KP_5", K_KP_5},
137         {"KP_6", K_KP_6},
138         {"KP_7", K_KP_7},
139         {"KP_8", K_KP_8},
140         {"KP_9", K_KP_9},
141         {"KP_PERIOD", K_KP_PERIOD},
142         {"KP_DIVIDE", K_KP_DIVIDE},
143         {"KP_MULTIPLY", K_KP_MULTIPLY},
144         {"KP_MINUS", K_KP_MINUS},
145         {"KP_PLUS", K_KP_PLUS},
146         {"KP_ENTER", K_KP_ENTER},
147         {"KP_EQUALS", K_KP_EQUALS},
148
149         {"JOY1",  K_JOY1},
150         {"JOY2",  K_JOY2},
151         {"JOY3",  K_JOY3},
152         {"JOY4",  K_JOY4},
153         {"JOY5",  K_JOY5},
154         {"JOY6",  K_JOY6},
155         {"JOY7",  K_JOY7},
156         {"JOY8",  K_JOY8},
157         {"JOY9",  K_JOY9},
158         {"JOY10", K_JOY10},
159         {"JOY11", K_JOY11},
160         {"JOY12", K_JOY12},
161         {"JOY13", K_JOY13},
162         {"JOY14", K_JOY14},
163         {"JOY15", K_JOY15},
164         {"JOY16", K_JOY16},
165
166         {"AUX1", K_AUX1},
167         {"AUX2", K_AUX2},
168         {"AUX3", K_AUX3},
169         {"AUX4", K_AUX4},
170         {"AUX5", K_AUX5},
171         {"AUX6", K_AUX6},
172         {"AUX7", K_AUX7},
173         {"AUX8", K_AUX8},
174         {"AUX9", K_AUX9},
175         {"AUX10", K_AUX10},
176         {"AUX11", K_AUX11},
177         {"AUX12", K_AUX12},
178         {"AUX13", K_AUX13},
179         {"AUX14", K_AUX14},
180         {"AUX15", K_AUX15},
181         {"AUX16", K_AUX16},
182         {"AUX17", K_AUX17},
183         {"AUX18", K_AUX18},
184         {"AUX19", K_AUX19},
185         {"AUX20", K_AUX20},
186         {"AUX21", K_AUX21},
187         {"AUX22", K_AUX22},
188         {"AUX23", K_AUX23},
189         {"AUX24", K_AUX24},
190         {"AUX25", K_AUX25},
191         {"AUX26", K_AUX26},
192         {"AUX27", K_AUX27},
193         {"AUX28", K_AUX28},
194         {"AUX29", K_AUX29},
195         {"AUX30", K_AUX30},
196         {"AUX31", K_AUX31},
197         {"AUX32", K_AUX32},
198
199         {"SEMICOLON", ';'},                     // because a raw semicolon seperates commands
200         {"TILDE", '~'},
201         {"BACKQUOTE", '`'},
202         {"QUOTE", '"'},
203         {"APOSTROPHE", '\''},
204
205         {NULL, 0}
206 };
207
208 /*
209 ==============================================================================
210
211                         LINE TYPING INTO THE CONSOLE
212
213 ==============================================================================
214 */
215
216 void
217 Key_ClearEditLine (int edit_line)
218 {
219         memset (key_lines[edit_line], '\0', MAX_INPUTLINE);
220         key_lines[edit_line][0] = ']';
221         key_linepos = 1;
222 }
223
224 /*
225 ====================
226 Interactive line editing and console scrollback
227 ====================
228 */
229 static void
230 Key_Console (int key, char ascii)
231 {
232         // LordHavoc: copied most of this from Q2 to improve keyboard handling
233         switch (key)
234         {
235         case K_KP_SLASH:
236                 key = '/';
237                 break;
238         case K_KP_MINUS:
239                 key = '-';
240                 break;
241         case K_KP_PLUS:
242                 key = '+';
243                 break;
244         case K_KP_HOME:
245                 key = '7';
246                 break;
247         case K_KP_UPARROW:
248                 key = '8';
249                 break;
250         case K_KP_PGUP:
251                 key = '9';
252                 break;
253         case K_KP_LEFTARROW:
254                 key = '4';
255                 break;
256         case K_KP_5:
257                 key = '5';
258                 break;
259         case K_KP_RIGHTARROW:
260                 key = '6';
261                 break;
262         case K_KP_END:
263                 key = '1';
264                 break;
265         case K_KP_DOWNARROW:
266                 key = '2';
267                 break;
268         case K_KP_PGDN:
269                 key = '3';
270                 break;
271         case K_KP_INS:
272                 key = '0';
273                 break;
274         case K_KP_DEL:
275                 key = '.';
276                 break;
277         }
278
279         if ((toupper(key) == 'V' && keydown[K_CTRL]) || ((key == K_INS || key == K_KP_INS) && keydown[K_SHIFT]))
280         {
281                 char *cbd;
282                 if ((cbd = Sys_GetClipboardData()) != 0)
283                 {
284                         int i;
285                         strtok(cbd, "\n\r\b");
286                         i = strlen(cbd);
287                         if (i + key_linepos >= MAX_INPUTLINE)
288                                 i= MAX_INPUTLINE - key_linepos;
289                         if (i > 0)
290                         {
291                                 cbd[i]=0;
292                                 strcat(key_lines[edit_line], cbd);
293                                 key_linepos += i;
294                         }
295                         free(cbd);
296                 }
297                 return;
298         }
299
300         if (key == 'l')
301         {
302                 if (keydown[K_CTRL])
303                 {
304                         Cbuf_AddText ("clear\n");
305                         return;
306                 }
307         }
308
309         if (key == K_ENTER || key == K_KP_ENTER)
310         {
311                 Cbuf_AddText (key_lines[edit_line]+1);  // skip the ]
312                 Cbuf_AddText ("\n");
313                 Con_Printf("%s\n",key_lines[edit_line]);
314                 // LordHavoc: redesigned edit_line/history_line
315                 edit_line = 31;
316                 history_line = edit_line;
317                 memmove(key_lines[0], key_lines[1], sizeof(key_lines[0]) * edit_line);
318                 key_lines[edit_line][0] = ']';
319                 key_lines[edit_line][1] = 0;    // EvilTypeGuy: null terminate
320                 key_linepos = 1;
321                 // force an update, because the command may take some time
322                 if (cls.state == ca_disconnected)
323                         CL_UpdateScreen ();
324                 return;
325         }
326
327         if (key == K_TAB)
328         {
329                 // Enhanced command completion
330                 // by EvilTypeGuy eviltypeguy@qeradiant.com
331                 // Thanks to Fett, Taniwha
332                 Con_CompleteCommandLine();
333                 return;
334         }
335
336         // Advanced Console Editing by Radix radix@planetquake.com
337         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
338
339         // left arrow will just move left one without erasing, backspace will
340         // actually erase charcter
341         if (key == K_LEFTARROW || key == K_KP_LEFTARROW)
342         {
343                 if (key_linepos > 1)
344                         key_linepos--;
345                 return;
346         }
347
348         // delete char before cursor
349         if (key == K_BACKSPACE || (key == 'h' && keydown[K_CTRL]))
350         {
351                 if (key_linepos > 1)
352                 {
353                         strcpy(key_lines[edit_line] + key_linepos - 1, key_lines[edit_line] + key_linepos);
354                         key_linepos--;
355                 }
356                 return;
357         }
358
359         // delete char on cursor
360         if (key == K_DEL || key == K_KP_DEL)
361         {
362                 if ((size_t)key_linepos < strlen(key_lines[edit_line]))
363                         strcpy(key_lines[edit_line] + key_linepos, key_lines[edit_line] + key_linepos + 1);
364                 return;
365         }
366
367
368         // if we're at the end, get one character from previous line,
369         // otherwise just go right one
370         if (key == K_RIGHTARROW || key == K_KP_RIGHTARROW)
371         {
372                 if ((size_t)key_linepos < strlen(key_lines[edit_line]))
373                         key_linepos++;
374
375                 return;
376         }
377
378         if (key == K_INS || key == K_KP_INS) // toggle insert mode
379         {
380                 key_insert ^= 1;
381                 return;
382         }
383
384         // End Advanced Console Editing
385
386         if (key == K_UPARROW || key == K_KP_UPARROW || (key == 'p' && keydown[K_CTRL]))
387         {
388                 if (history_line > 0 && key_lines[history_line-1][1])
389                 {
390                         history_line--;
391                         strcpy(key_lines[edit_line], key_lines[history_line]);
392                         key_linepos = strlen(key_lines[edit_line]);
393                 }
394                 return;
395         }
396
397         if (key == K_DOWNARROW || key == K_KP_DOWNARROW || (key == 'n' && keydown[K_CTRL]))
398         {
399                 history_line++;
400                 if (history_line >= edit_line)
401                 {
402                         history_line = edit_line;
403                         key_lines[edit_line][0] = ']';
404                         key_lines[edit_line][1] = 0;
405                         key_linepos = 1;
406                 }
407                 else
408                 {
409                         strcpy(key_lines[edit_line], key_lines[history_line]);
410                         key_linepos = strlen(key_lines[edit_line]);
411                 }
412                 return;
413         }
414
415         if (key == K_PGUP || key == K_KP_PGUP || key == K_MWHEELUP)
416         {
417                 con_backscroll += ((int) vid_conheight.integer >> 5);
418                 if (con_backscroll > con_totallines - (vid_conheight.integer>>3) - 1)
419                         con_backscroll = con_totallines - (vid_conheight.integer>>3) - 1;
420                 return;
421         }
422
423         if (key == K_PGDN || key == K_KP_PGDN || key == K_MWHEELDOWN)
424         {
425                 con_backscroll -= ((int) vid_conheight.integer >> 5);
426                 if (con_backscroll < 0)
427                         con_backscroll = 0;
428                 return;
429         }
430
431         if (key == K_HOME || key == K_KP_HOME)
432         {
433                 con_backscroll = con_totallines - (vid_conheight.integer>>3) - 1;
434                 return;
435         }
436
437         if (key == K_END || key == K_KP_END)
438         {
439                 con_backscroll = 0;
440                 return;
441         }
442
443         // non printable
444         if (ascii < 32)
445                 return;
446
447         if (key_linepos < MAX_INPUTLINE-1)
448         {
449                 int len;
450                 len = strlen(&key_lines[edit_line][key_linepos]);
451                 // check insert mode, or always insert if at end of line
452                 if (key_insert || len == 0)
453                 {
454                         // can't use strcpy to move string to right
455                         len++;
456                         memmove(&key_lines[edit_line][key_linepos + 1], &key_lines[edit_line][key_linepos], len);
457                 }
458                 key_lines[edit_line][key_linepos] = ascii;
459                 key_linepos++;
460         }
461 }
462
463 //============================================================================
464
465 qboolean        chat_team;
466 char            chat_buffer[MAX_INPUTLINE];
467 unsigned int    chat_bufferlen = 0;
468
469 static void
470 Key_Message (int key, char ascii)
471 {
472
473         if (key == K_ENTER)
474         {
475                 Cmd_ForwardStringToServer(va("%s %s", chat_team ? "say_team" : "say ", chat_buffer));
476
477                 key_dest = key_game;
478                 chat_bufferlen = 0;
479                 chat_buffer[0] = 0;
480                 return;
481         }
482
483         if (key == K_ESCAPE) {
484                 key_dest = key_game;
485                 chat_bufferlen = 0;
486                 chat_buffer[0] = 0;
487                 return;
488         }
489
490         if (key == K_BACKSPACE) {
491                 if (chat_bufferlen) {
492                         chat_bufferlen--;
493                         chat_buffer[chat_bufferlen] = 0;
494                 }
495                 return;
496         }
497
498         if (chat_bufferlen == sizeof (chat_buffer) - 1)
499                 return;                                                 // all full
500
501         if (!ascii)
502                 return;                                                 // non printable
503
504         chat_buffer[chat_bufferlen++] = ascii;
505         chat_buffer[chat_bufferlen] = 0;
506 }
507
508 //============================================================================
509
510
511 /*
512 ===================
513 Returns a key number to be used to index keybindings[] by looking at
514 the given string.  Single ascii characters return themselves, while
515 the K_* names are matched up.
516 ===================
517 */
518 int
519 Key_StringToKeynum (const char *str)
520 {
521         const keyname_t  *kn;
522
523         if (!str || !str[0])
524                 return -1;
525         if (!str[1])
526                 return tolower(str[0]);
527
528         for (kn = keynames; kn->name; kn++) {
529                 if (!strcasecmp (str, kn->name))
530                         return kn->keynum;
531         }
532         return -1;
533 }
534
535 /*
536 ===================
537 Returns a string (either a single ascii char, or a K_* name) for the
538 given keynum.
539 FIXME: handle quote special (general escape sequence?)
540 ===================
541 */
542 const char *
543 Key_KeynumToString (int keynum)
544 {
545         const keyname_t  *kn;
546         static char tinystr[2];
547
548         if (keynum == -1)
549                 return "<KEY NOT FOUND>";
550         if (keynum > 32 && keynum < 127) {      // printable ascii
551                 tinystr[0] = keynum;
552                 tinystr[1] = 0;
553                 return tinystr;
554         }
555
556         for (kn = keynames; kn->name; kn++)
557                 if (keynum == kn->keynum)
558                         return kn->name;
559
560         return "<UNKNOWN KEYNUM>";
561 }
562
563
564 void
565 Key_SetBinding (int keynum, int bindmap, const char *binding)
566 {
567         char       *new;
568         int         l;
569
570         if (keynum == -1)
571                 return;
572
573 // free old bindings
574         if (keybindings[bindmap][keynum]) {
575                 Z_Free (keybindings[bindmap][keynum]);
576                 keybindings[bindmap][keynum] = NULL;
577         }
578 // allocate memory for new binding
579         l = strlen (binding);
580         new = Z_Malloc (l + 1);
581         strcpy (new, binding);
582         new[l] = 0;
583         keybindings[bindmap][keynum] = new;
584 }
585
586 static void
587 Key_In_Unbind_f (void)
588 {
589         int         b, m;
590
591         if (Cmd_Argc () != 3) {
592                 Con_Print("in_unbind <bindmap> <key> : remove commands from a key\n");
593                 return;
594         }
595
596         m = strtol(Cmd_Argv (1), NULL, 0);
597         if ((m < 0) || (m >= 8)) {
598                 Con_Printf("%d isn't a valid bindmap\n", m);
599                 return;
600         }
601
602         b = Key_StringToKeynum (Cmd_Argv (2));
603         if (b == -1) {
604                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (2));
605                 return;
606         }
607
608         Key_SetBinding (b, m, "");
609 }
610
611 static void
612 Key_In_Bind_f (void)
613 {
614         int         i, c, b, m;
615         char        cmd[1024];
616
617         c = Cmd_Argc ();
618
619         if (c != 3 && c != 4) {
620                 Con_Print("in_bind <bindmap> <key> [command] : attach a command to a key\n");
621                 return;
622         }
623
624         m = strtol(Cmd_Argv (1), NULL, 0);
625         if ((m < 0) || (m >= 8)) {
626                 Con_Printf("%d isn't a valid bindmap\n", m);
627                 return;
628         }
629
630         b = Key_StringToKeynum (Cmd_Argv (2));
631         if (b == -1) {
632                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (2));
633                 return;
634         }
635
636         if (c == 3) {
637                 if (keybindings[m][b])
638                         Con_Printf("\"%s\" = \"%s\"\n", Cmd_Argv (2), keybindings[m][b]);
639                 else
640                         Con_Printf("\"%s\" is not bound\n", Cmd_Argv (2));
641                 return;
642         }
643 // copy the rest of the command line
644         cmd[0] = 0;                                                     // start out with a null string
645         for (i = 3; i < c; i++) {
646                 strlcat (cmd, Cmd_Argv (i), sizeof (cmd));
647                 if (i != (c - 1))
648                         strlcat (cmd, " ", sizeof (cmd));
649         }
650
651         Key_SetBinding (b, m, cmd);
652 }
653
654 static void
655 Key_In_Bindmap_f (void)
656 {
657         int         m1, m2, c;
658
659         c = Cmd_Argc ();
660
661         if (c != 3) {
662                 Con_Print("in_bindmap <bindmap> <fallback>: set current bindmap and fallback\n");
663                 return;
664         }
665
666         m1 = strtol(Cmd_Argv (1), NULL, 0);
667         if ((m1 < 0) || (m1 >= 8)) {
668                 Con_Printf("%d isn't a valid bindmap\n", m1);
669                 return;
670         }
671
672         m2 = strtol(Cmd_Argv (2), NULL, 0);
673         if ((m2 < 0) || (m2 >= 8)) {
674                 Con_Printf("%d isn't a valid bindmap\n", m2);
675                 return;
676         }
677
678         key_bmap = m1;
679         key_bmap2 = m2;
680 }
681
682 static void
683 Key_Unbind_f (void)
684 {
685         int         b;
686
687         if (Cmd_Argc () != 2) {
688                 Con_Print("unbind <key> : remove commands from a key\n");
689                 return;
690         }
691
692         b = Key_StringToKeynum (Cmd_Argv (1));
693         if (b == -1) {
694                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (1));
695                 return;
696         }
697
698         Key_SetBinding (b, 0, "");
699 }
700
701 static void
702 Key_Unbindall_f (void)
703 {
704         int         i, j;
705
706         for (j = 0; j < 8; j++)
707                 for (i = 0; i < (int)(sizeof(keybindings[0])/sizeof(keybindings[0][0])); i++)
708                         if (keybindings[j][i])
709                                 Key_SetBinding (i, j, "");
710 }
711
712
713 static void
714 Key_Bind_f (void)
715 {
716         int         i, c, b;
717         char        cmd[1024];
718
719         c = Cmd_Argc ();
720
721         if (c != 2 && c != 3) {
722                 Con_Print("bind <key> [command] : attach a command to a key\n");
723                 return;
724         }
725         b = Key_StringToKeynum (Cmd_Argv (1));
726         if (b == -1) {
727                 Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv (1));
728                 return;
729         }
730
731         if (c == 2) {
732                 if (keybindings[0][b])
733                         Con_Printf("\"%s\" = \"%s\"\n", Cmd_Argv (1), keybindings[0][b]);
734                 else
735                         Con_Printf("\"%s\" is not bound\n", Cmd_Argv (1));
736                 return;
737         }
738 // copy the rest of the command line
739         cmd[0] = 0;                                                     // start out with a null string
740         for (i = 2; i < c; i++) {
741                 strlcat (cmd, Cmd_Argv (i), sizeof (cmd));
742                 if (i != (c - 1))
743                         strlcat (cmd, " ", sizeof (cmd));
744         }
745
746         Key_SetBinding (b, 0, cmd);
747 }
748
749 /*
750 ============
751 Writes lines containing "bind key value"
752 ============
753 */
754 void
755 Key_WriteBindings (qfile_t *f)
756 {
757         int         i, j;
758
759         for (i = 0; i < (int)(sizeof(keybindings[0])/sizeof(keybindings[0][0])); i++)
760                 if (keybindings[0][i])
761                         FS_Printf(f, "bind \"%s\" \"%s\"\n",
762                                         Key_KeynumToString (i), keybindings[0][i]);
763         for (j = 1; j < 8; j++)
764                 for (i = 0; i < (int)(sizeof(keybindings[0])/sizeof(keybindings[0][0])); i++)
765                         if (keybindings[j][i])
766                                 FS_Printf(f, "in_bind %d \"%s\" \"%s\"\n",
767                                                 j, Key_KeynumToString (i), keybindings[j][i]);
768 }
769
770
771 void
772 Key_Init (void)
773 {
774         int         i;
775
776         for (i = 0; i < 32; i++) {
777                 key_lines[i][0] = ']';
778                 key_lines[i][1] = 0;
779         }
780         key_linepos = 1;
781
782 //
783 // init ascii characters in console mode
784 //
785         for (i = 32; i < 128; i++)
786                 consolekeys[i] = true;
787         consolekeys[K_ENTER] = true; consolekeys[K_KP_ENTER] = true;
788         consolekeys[K_TAB] = true;
789         consolekeys[K_LEFTARROW] = true; consolekeys[K_KP_LEFTARROW] = true;
790         consolekeys[K_RIGHTARROW] = true; consolekeys[K_KP_RIGHTARROW] = true;
791         consolekeys[K_UPARROW] = true; consolekeys[K_KP_UPARROW] = true;
792         consolekeys[K_DOWNARROW] = true; consolekeys[K_KP_DOWNARROW] = true;
793         consolekeys[K_BACKSPACE] = true;
794         consolekeys[K_DEL] = true; consolekeys[K_KP_DEL] = true;
795         consolekeys[K_INS] = true; consolekeys[K_KP_INS] = true;
796         consolekeys[K_HOME] = true; consolekeys[K_KP_HOME] = true;
797         consolekeys[K_END] = true; consolekeys[K_KP_END] = true;
798         consolekeys[K_PGUP] = true; consolekeys[K_KP_PGUP] = true;
799         consolekeys[K_PGDN] = true; consolekeys[K_KP_PGDN] = true;
800         consolekeys[K_SHIFT] = true;
801         consolekeys[K_MWHEELUP] = true;
802         consolekeys[K_MWHEELDOWN] = true;
803         consolekeys[K_KP_PLUS] = true;
804         consolekeys[K_KP_MINUS] = true;
805         consolekeys[K_KP_DIVIDE] = true;
806         consolekeys[K_KP_MULTIPLY] = true;
807         consolekeys['`'] = false;
808         consolekeys['~'] = false;
809
810         menubound[K_ESCAPE] = true;
811         for (i = 0; i < 12; i++)
812                 menubound[K_F1 + i] = true;
813
814 //
815 // register our functions
816 //
817         Cmd_AddCommand ("in_bind", Key_In_Bind_f);
818         Cmd_AddCommand ("in_unbind", Key_In_Unbind_f);
819         Cmd_AddCommand ("in_bindmap", Key_In_Bindmap_f);
820
821         Cmd_AddCommand ("bind", Key_Bind_f);
822         Cmd_AddCommand ("unbind", Key_Unbind_f);
823         Cmd_AddCommand ("unbindall", Key_Unbindall_f);
824 }
825
826
827 /*
828 ===================
829 Called by the system between frames for both key up and key down events
830 Should NOT be called during an interrupt!
831 ===================
832 */
833 void
834 Key_Event (int key, char ascii, qboolean down)
835 {
836 #if 1
837 #define USERPLAYING()   ( !key_consoleactive && key_dest == key_game && (cls.state == ca_connected && cls.signon == SIGNONS) )
838         const char *bind;
839         static qboolean shift_down = false;
840
841         // get key binding
842         bind = keybindings[ key_bmap ][ key ];
843         if( !bind ) {
844                 bind = keybindings[ key_bmap2 ][ key ];
845         }
846
847         // set key state
848         keydown[ key ] = down;
849
850         // update key repeats
851         if( down ) {
852                 key_repeats[ key ]++;
853                 if( key_repeats[ key ] > 1 ) {
854                         if( (key_consoleactive && !consolekeys[key]) || USERPLAYING() )
855                                 return;                                         // ignore most autorepeats
856                 }
857         } else {
858                 key_repeats[ key ] = 0;
859         }
860
861         if( key == K_SHIFT ) {
862                 shift_down = down;
863         }
864
865         if( !down ) {
866                 if( bind && bind[ 0 ] == '+') {
867                         Cbuf_AddText( va( "-%s %i\n", bind + 1, key) ); 
868                 }
869         } else {
870                 // handle ESCAPE specially, so unbinding wont help
871                 if( key == K_ESCAPE ) {
872                         // shift-escape is a safety measure for users who cant toggle the console otherwise
873                         if( shift_down ) {
874                                 Con_ToggleConsole_f();
875                                 return;
876                         }
877                         switch( key_dest ) {
878                                 case key_message:
879                                         Key_Message( key, ascii );
880                                         break;
881                                 case key_menu:
882                                         MR_Keydown( key, ascii );
883                                         break;
884                                 case key_game:
885                                         if (COM_CheckParm ("-demolooponly"))
886                                         {
887                                                 CL_Disconnect ();
888                                                 return;
889                                         }
890                                         MR_ToggleMenu_f();
891                                         break;
892                                 default:
893                                         Sys_Error( "Bad key_dest" );
894                         }
895                         return;
896                 }
897
898                 if( !(key_consoleactive && consolekeys[ key ]) && bind && !strncmp( bind, "toggleconsole", strlen( "toggleconsole" ) ) ) {
899                         Cbuf_AddText( bind );
900                         Cbuf_AddText( "\n" );
901                         if( ascii != STRING_COLOR_TAG ) {
902                                 return;
903                         }
904                 } else {
905                         // during demo playback, all keys ingame bring up the main menu
906                         if( cls.demoplayback && !key_consoleactive && key_dest == key_game ) {
907                                 if (!COM_CheckParm ("-demolooponly"))
908                                         MR_ToggleMenu_f ();
909                                 return;
910                         }
911
912                         // menu bind/function keys or normal binds
913                         if( (key_dest == key_menu && menubound[key]) || USERPLAYING() ) {
914                                 if( bind ) {
915                                         if( bind[0] == '+' ) { // button commands add keynum as a parm
916                                                 Cbuf_AddText( va( "%s %i\n", bind, key ) );
917                                         } else {
918                                                 Cbuf_AddText( bind );
919                                                 Cbuf_AddText( "\n" );
920                                         }
921                                 }
922                                 return;
923                         }
924                 }
925
926                 // either console or game state key functions
927                 if( key_consoleactive ) {
928                                 Key_Console( key, ascii );
929                 } else {
930                         switch (key_dest) {
931                                 case key_message:
932                                         Key_Message( key, ascii );
933                                         break;
934                                 case key_menu:
935                                         MR_Keydown( key, ascii );
936                                         break;
937                                 case key_game:                          
938                                         // unbound key
939                                         break;
940                                 default:
941                                         Sys_Error( "Bad key_dest" );
942                         }
943                 }
944         }
945 #else
946         const char      *kb;
947         char            cmd[1024];
948
949         keydown[key] = down;
950
951         if (!down)
952                 key_repeats[key] = 0;
953
954         key_lastpress = key;
955         key_count++;
956         if (key_count <= 0) {
957                 return;                                                 // just catching keys for Con_NotifyBox
958         }
959
960         // update auto-repeat status
961         if (down) {
962                 key_repeats[key]++;
963                 if (key_repeats[key] > 1) {
964                         if ((key_consoleactive && !consolekeys[key]) ||
965                                         (!key_consoleactive && key_dest == key_game &&
966                                          (cls.state == ca_connected && cls.signon == SIGNONS)))
967                                 return;                                         // ignore most autorepeats
968                 }
969         }
970
971         if (key == K_CTRL)
972                 ctrl_down = down;
973
974         //
975         // handle escape specially, so the user can never unbind it
976         //
977         if (key == K_ESCAPE) {
978                 if (!down)
979                         return;
980                 // ctrl-escape is a safety measure
981                 if (ctrl_down)
982                 {
983                         Con_ToggleConsole_f ();
984                         return;
985                 }
986                 switch (key_dest) {
987                         case key_message:
988                                 Key_Message (key, ascii);
989                                 break;
990                         case key_menu:
991                                 MR_Keydown (key, ascii);
992                                 break;
993                         case key_game:
994                                 MR_ToggleMenu_f ();
995                                 break;
996                         default:
997                                 if(UI_Callback_IsSlotUsed(key_dest - 3))
998                                         UI_Callback_KeyDown (key, ascii);
999                                 else
1000                                         Sys_Error ("Bad key_dest");
1001                 }
1002                 return;
1003         }
1004
1005         if (down)
1006         {
1007                 if (!(kb = keybindings[key_bmap][key]))
1008                         kb = keybindings[key_bmap2][key];
1009                 if (kb && !strncmp(kb, "toggleconsole", strlen("toggleconsole")))
1010                 {
1011                         Cbuf_AddText (kb);
1012                         Cbuf_AddText ("\n");
1013                         return;
1014                 }
1015         }
1016
1017         if (key_consoleactive && consolekeys[key] && down)
1018                 Key_Console (key, ascii);
1019         else
1020         {
1021                 //
1022                 // key up events only generate commands if the game key binding is a button
1023                 // command (leading + sign).  These will occur even in console mode, to
1024                 // keep the character from continuing an action started before a console
1025                 // switch.  Button commands include the kenum as a parameter, so multiple
1026                 // downs can be matched with ups
1027                 //
1028                 if (!down) {
1029                         if (!(kb = keybindings[key_bmap][key]))
1030                                 kb = keybindings[key_bmap2][key];
1031
1032                         if (kb && kb[0] == '+') {
1033                                 dpsnprintf (cmd, sizeof(cmd), "-%s %i\n", kb + 1, key);
1034                                 Cbuf_AddText (cmd);
1035                         }
1036                         return;
1037                 }
1038
1039                 //
1040                 // during demo playback, most keys bring up the main menu
1041                 //
1042                 if (cls.demoplayback && down && consolekeys[key] && key_dest == key_game) {
1043                         MR_ToggleMenu_f ();
1044                         return;
1045                 }
1046
1047                 //
1048                 // if not a consolekey, send to the interpreter no matter what mode is
1049                 //
1050                 if ((key_dest == key_menu && menubound[key])
1051                                 || (key_consoleactive && !consolekeys[key])
1052                                 || (key_dest == key_game &&
1053                                         ((cls.state == ca_connected) || !consolekeys[key]))) {
1054                         if (!(kb = keybindings[key_bmap][key]))
1055                                 kb = keybindings[key_bmap2][key];
1056                         if (kb) {
1057                                 if (kb[0] == '+') {                     // button commands add keynum as a parm
1058                                         dpsnprintf (cmd, sizeof(cmd), "%s %i\n", kb, key);
1059                                         Cbuf_AddText (cmd);
1060                                 } else {
1061                                         Cbuf_AddText (kb);
1062                                         Cbuf_AddText ("\n");
1063                                 }
1064                         }
1065                         return;
1066                 }
1067
1068                 if (!down)
1069                         return;                                                 // other systems only care about key
1070                 // down events
1071
1072                 switch (key_dest) {
1073                         case key_message:
1074                                 Key_Message (key, ascii);
1075                                 break;
1076                         case key_menu:
1077                                 MR_Keydown (key, ascii);
1078                                 break;
1079                         case key_game:
1080                                 Key_Console (key, ascii);
1081                                 break;
1082                         default:
1083                                 if(UI_Callback_IsSlotUsed(key_dest - 3))
1084                                         UI_Callback_KeyDown (key, ascii);
1085                                 else
1086                                         Sys_Error ("Bad key_dest");
1087                 }
1088         }
1089 #endif
1090 }
1091
1092 /*
1093 ===================
1094 Key_ClearStates
1095 ===================
1096 */
1097 void
1098 Key_ClearStates (void)
1099 {
1100         int i;
1101
1102         for (i = 0; i < (int)(sizeof(keydown)/sizeof(keydown[0])); i++)
1103         {
1104                 keydown[i] = false;
1105                 key_repeats[i] = 0;
1106         }
1107 }