]> icculus.org git repositories - divverent/darkplaces.git/blob - keys.c
enable optimizations again (oops)
[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 the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 #include "quakedef.h"
21
22 /*
23
24 key up events are sent even if in console mode
25
26 */
27
28
29 #define MAXCMDLINE 256
30 char key_lines[32][MAXCMDLINE];
31 int key_linepos;
32 int shift_down = false;
33 int key_lastpress;
34 int key_insert; // insert key toggle (for editing)
35
36 int edit_line = 0;
37 int history_line = 0;
38
39 int key_consoleactive;
40 keydest_t key_dest;
41
42 int key_count;                  // incremented every key event
43
44 char *keybindings[256];
45 qboolean consolekeys[256];      // if true, can't be rebound while in console
46 qboolean menubound[256];        // if true, can't be rebound while in menu
47 int keyshift[256];              // key to map to if shift held down in console
48 int key_repeats[256];   // if > 1, it is autorepeating
49 qboolean keydown[256];
50
51 typedef struct
52 {
53         char *name;
54         int keynum;
55 } keyname_t;
56
57 keyname_t keynames[] =
58 {
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         {"MOUSE1", K_MOUSE1},
94         {"MOUSE2", K_MOUSE2},
95         {"MOUSE3", K_MOUSE3},
96
97         {"JOY1", K_JOY1},
98         {"JOY2", K_JOY2},
99         {"JOY3", K_JOY3},
100         {"JOY4", K_JOY4},
101
102         {"AUX1", K_AUX1},
103         {"AUX2", K_AUX2},
104         {"AUX3", K_AUX3},
105         {"AUX4", K_AUX4},
106         {"AUX5", K_AUX5},
107         {"AUX6", K_AUX6},
108         {"AUX7", K_AUX7},
109         {"AUX8", K_AUX8},
110         {"AUX9", K_AUX9},
111         {"AUX10", K_AUX10},
112         {"AUX11", K_AUX11},
113         {"AUX12", K_AUX12},
114         {"AUX13", K_AUX13},
115         {"AUX14", K_AUX14},
116         {"AUX15", K_AUX15},
117         {"AUX16", K_AUX16},
118         {"AUX17", K_AUX17},
119         {"AUX18", K_AUX18},
120         {"AUX19", K_AUX19},
121         {"AUX20", K_AUX20},
122         {"AUX21", K_AUX21},
123         {"AUX22", K_AUX22},
124         {"AUX23", K_AUX23},
125         {"AUX24", K_AUX24},
126         {"AUX25", K_AUX25},
127         {"AUX26", K_AUX26},
128         {"AUX27", K_AUX27},
129         {"AUX28", K_AUX28},
130         {"AUX29", K_AUX29},
131         {"AUX30", K_AUX30},
132         {"AUX31", K_AUX31},
133         {"AUX32", K_AUX32},
134
135         {"PAUSE", K_PAUSE},
136
137         {"MWHEELUP", K_MWHEELUP},
138         {"MWHEELDOWN", K_MWHEELDOWN},
139
140         {"SEMICOLON", ';'},     // because a raw semicolon seperates commands
141
142         {NULL,0}
143 };
144
145 /*
146 ==============================================================================
147
148                         LINE TYPING INTO THE CONSOLE
149
150 ==============================================================================
151 */
152
153
154 /*
155 ====================
156 Key_Console
157
158 Interactive line editing and console scrollback
159 ====================
160 */
161 void Key_Console (int key)
162 {
163         if (key == K_ENTER)
164         {
165                 Cbuf_AddText (key_lines[edit_line]+1);  // skip the ]
166                 Cbuf_AddText ("\n");
167                 Con_Printf ("%s\n",key_lines[edit_line]);
168                 edit_line = (edit_line + 1) & 31;
169                 history_line = edit_line;
170                 key_lines[edit_line][0] = ']';
171                 key_lines[edit_line][1] = 0;    // EvilTypeGuy: null terminate
172                 key_linepos = 1;
173                 // force an update, because the command may take some time
174                 if (cls.state == ca_disconnected)
175                 {
176                         CL_UpdateScreen ();
177                         CL_UpdateScreen ();
178                 }
179                 return;
180         }
181
182         if (key == K_TAB)
183         {
184                 // Enhanced command completion
185                 // by EvilTypeGuy eviltypeguy@qeradiant.com
186                 // Thanks to Fett, Taniwha
187                 Con_CompleteCommandLine();
188         }
189
190         // Advanced Console Editing by Radix radix@planetquake.com
191         // Added/Modified by EvilTypeGuy eviltypeguy@qeradiant.com
192
193         // left arrow will just move left one without erasing, backspace will
194         // actually erase charcter
195         if (key == K_LEFTARROW)
196         {
197                 if (key_linepos > 1)
198                         key_linepos--;
199                 return;
200         }
201
202         if (key == K_BACKSPACE) // delete char before cursor
203         {
204                 if (key_linepos > 1)
205                 {
206                         strcpy(key_lines[edit_line] + key_linepos - 1, key_lines[edit_line] + key_linepos);
207                         key_linepos--;
208                 }
209                 return;
210         }
211
212         if (key == K_DEL)               // delete char on cursor
213         {
214                 if (key_linepos < strlen(key_lines[edit_line]))
215                         strcpy(key_lines[edit_line] + key_linepos, key_lines[edit_line] + key_linepos + 1);
216                 return;
217         }
218
219
220         // if we're at the end, get one character from previous line,
221         // otherwise just go right one
222         if (key == K_RIGHTARROW)
223         {
224                 if (strlen(key_lines[edit_line]) == key_linepos)
225                 {
226                         if (strlen(key_lines[(edit_line + 31) & 31]) <= key_linepos)
227                                 return; // no character to get
228
229                         key_lines[edit_line][key_linepos] = key_lines[(edit_line + 31) & 31][key_linepos];
230                         key_linepos++;
231                         key_lines[edit_line][key_linepos] = 0;
232                 }
233                 else
234                         key_linepos++;
235
236                 return;
237         }
238
239         if (key == K_INS) // toggle insert mode
240         {
241                 key_insert ^= 1;
242                 return;
243         }
244
245         // End Advanced Console Editing
246
247         if (key == K_UPARROW)
248         {
249                 do
250                 {
251                         history_line = (history_line - 1) & 31;
252                 } while (history_line != edit_line
253                                 && !key_lines[history_line][1]);
254                 if (history_line == edit_line)
255                         history_line = (edit_line+1)&31;
256                 strcpy(key_lines[edit_line], key_lines[history_line]);
257                 key_linepos = strlen(key_lines[edit_line]);
258                 return;
259         }
260
261         if (key == K_DOWNARROW)
262         {
263                 if (history_line == edit_line) return;
264                 do
265                 {
266                         history_line = (history_line + 1) & 31;
267                 }
268                 while (history_line != edit_line
269                         && !key_lines[history_line][1]);
270                 if (history_line == edit_line)
271                 {
272                         key_lines[edit_line][0] = ']';
273                         key_linepos = 1;
274                 }
275                 else
276                 {
277                         strcpy(key_lines[edit_line], key_lines[history_line]);
278                         key_linepos = strlen(key_lines[edit_line]);
279                 }
280                 return;
281         }
282
283         if (key == K_PGUP || key==K_MWHEELUP)
284         {
285                 con_backscroll += ((int) scr_conlines >> 4);
286                 if (con_backscroll > con_totallines - (vid.conheight>>3) - 1)
287                         con_backscroll = con_totallines - (vid.conheight>>3) - 1;
288                 return;
289         }
290
291         if (key == K_PGDN || key==K_MWHEELDOWN)
292         {
293                 con_backscroll -= ((int) scr_conlines >> 4);
294                 if (con_backscroll < 0)
295                         con_backscroll = 0;
296                 return;
297         }
298
299         if (key == K_HOME)
300         {
301                 con_backscroll = con_totallines - (vid.conheight>>3) - 1;
302                 return;
303         }
304
305         if (key == K_END)
306         {
307                 con_backscroll = 0;
308                 return;
309         }
310
311         if (key < 32 || key > 127)
312                 return; // non printable
313
314
315
316         if (key_linepos < MAXCMDLINE-1)
317         {
318                 int i;
319
320                 if (key_insert) // check insert mode
321                 {
322                         // can't do strcpy to move string to right
323                         i = strlen(key_lines[edit_line]) - 1;
324
325                         if (i == 254)
326                                 i--;
327
328                         for (; i >= key_linepos; i--)
329                                 key_lines[edit_line][i + 1] = key_lines[edit_line][i];
330                 }
331
332                 // only null terminate if at the end
333                 i = key_lines[edit_line][key_linepos];
334                 key_lines[edit_line][key_linepos] = key;
335                 key_linepos++;
336
337                 if (!i)
338                         key_lines[edit_line][key_linepos] = 0;
339         }
340 }
341
342 //============================================================================
343
344 // LordHavoc: increased messagemode length (was 32)
345 char chat_buffer[256];
346 qboolean team_message = false;
347
348 void Key_Message (int key)
349 {
350         static int chat_bufferlen = 0;
351
352         if (key == K_ENTER)
353         {
354                 if (team_message)
355                         Cbuf_AddText ("say_team \"");
356                 else
357                         Cbuf_AddText ("say \"");
358                 Cbuf_AddText(chat_buffer);
359                 Cbuf_AddText("\"\n");
360
361                 key_dest = key_game;
362                 chat_bufferlen = 0;
363                 chat_buffer[0] = 0;
364                 return;
365         }
366
367         if (key == K_ESCAPE)
368         {
369                 key_dest = key_game;
370                 chat_bufferlen = 0;
371                 chat_buffer[0] = 0;
372                 return;
373         }
374
375         if (key < 32 || key > 127)
376                 return; // non printable
377
378         if (key == K_BACKSPACE)
379         {
380                 if (chat_bufferlen)
381                 {
382                         chat_bufferlen--;
383                         chat_buffer[chat_bufferlen] = 0;
384                 }
385                 return;
386         }
387
388         // LordHavoc: increased messagemode length (was 31)
389         if (chat_bufferlen == 240)
390                 return; // all full
391
392         chat_buffer[chat_bufferlen++] = key;
393         chat_buffer[chat_bufferlen] = 0;
394 }
395
396 //============================================================================
397
398
399 /*
400 ===================
401 Key_StringToKeynum
402
403 Returns a key number to be used to index keybindings[] by looking at
404 the given string.  Single ascii characters return themselves, while
405 the K_* names are matched up.
406 ===================
407 */
408 int Key_StringToKeynum (char *str)
409 {
410         keyname_t       *kn;
411
412         if (!str || !str[0])
413                 return -1;
414         if (!str[1])
415                 return str[0];
416
417         for (kn=keynames ; kn->name ; kn++)
418         {
419                 if (!Q_strcasecmp(str,kn->name))
420                         return kn->keynum;
421         }
422         return -1;
423 }
424
425 /*
426 ===================
427 Key_KeynumToString
428
429 Returns a string (either a single ascii char, or a K_* name) for the
430 given keynum.
431 FIXME: handle quote special (general escape sequence?)
432 ===================
433 */
434 char *Key_KeynumToString (int keynum)
435 {
436         keyname_t       *kn;
437         static  char    tinystr[2];
438
439         if (keynum == -1)
440                 return "<KEY NOT FOUND>";
441         if (keynum > 32 && keynum < 127)
442         {       // printable ascii
443                 tinystr[0] = keynum;
444                 tinystr[1] = 0;
445                 return tinystr;
446         }
447         
448         for (kn=keynames ; kn->name ; kn++)
449                 if (keynum == kn->keynum)
450                         return kn->name;
451
452         return "<UNKNOWN KEYNUM>";
453 }
454
455
456 /*
457 ===================
458 Key_SetBinding
459 ===================
460 */
461 void Key_SetBinding (int keynum, char *binding)
462 {
463         char    *new;
464         int             l;
465                         
466         if (keynum == -1)
467                 return;
468
469 // free old bindings
470         if (keybindings[keynum])
471         {
472                 Z_Free (keybindings[keynum]);
473                 keybindings[keynum] = NULL;
474         }
475                         
476 // allocate memory for new binding
477         l = strlen (binding);   
478         new = Z_Malloc (l+1);
479         strcpy (new, binding);
480         new[l] = 0;
481         keybindings[keynum] = new;      
482 }
483
484 /*
485 ===================
486 Key_Unbind_f
487 ===================
488 */
489 void Key_Unbind_f (void)
490 {
491         int             b;
492
493         if (Cmd_Argc() != 2)
494         {
495                 Con_Printf ("unbind <key> : remove commands from a key\n");
496                 return;
497         }
498
499         b = Key_StringToKeynum (Cmd_Argv(1));
500         if (b==-1)
501         {
502                 Con_Printf ("\"%s\" isn't a valid key\n", Cmd_Argv(1));
503                 return;
504         }
505
506         Key_SetBinding (b, "");
507 }
508
509 void Key_Unbindall_f (void)
510 {
511         int             i;
512
513         for (i=0 ; i<256 ; i++)
514                 if (keybindings[i])
515                         Key_SetBinding (i, "");
516 }
517
518
519 /*
520 ===================
521 Key_Bind_f
522 ===================
523 */
524 void Key_Bind_f (void)
525 {
526         int                     i, c, b;
527         char            cmd[1024];
528
529         c = Cmd_Argc();
530
531         if (c != 2 && c != 3)
532         {
533                 Con_Printf ("bind <key> [command] : attach a command to a key\n");
534                 return;
535         }
536         b = Key_StringToKeynum (Cmd_Argv(1));
537         if (b==-1)
538         {
539                 Con_Printf ("\"%s\" isn't a valid key\n", Cmd_Argv(1));
540                 return;
541         }
542
543         if (c == 2)
544         {
545                 if (keybindings[b])
546                         Con_Printf ("\"%s\" = \"%s\"\n", Cmd_Argv(1), keybindings[b] );
547                 else
548                         Con_Printf ("\"%s\" is not bound\n", Cmd_Argv(1) );
549                 return;
550         }
551
552 // copy the rest of the command line
553         cmd[0] = 0;             // start out with a null string
554         for (i=2 ; i< c ; i++)
555         {
556                 if (i > 2)
557                         strcat (cmd, " ");
558                 strcat (cmd, Cmd_Argv(i));
559         }
560
561         Key_SetBinding (b, cmd);
562 }
563
564 /*
565 ============
566 Key_WriteBindings
567
568 Writes lines containing "bind key value"
569 ============
570 */
571 void Key_WriteBindings (QFile *f)
572 {
573         int             i;
574
575         for (i=0 ; i<256 ; i++)
576                 if (keybindings[i])
577                         if (*keybindings[i])
578                                 Qprintf (f, "bind \"%s\" \"%s\"\n", Key_KeynumToString(i), keybindings[i]);
579 }
580
581
582 /*
583 ===================
584 Key_Init
585 ===================
586 */
587 void Key_Init (void)
588 {
589         int             i;
590
591         // LordHavoc: clear keybindings array so bounds checking won't freak
592         for (i = 0;i < 256;i++)
593                 keybindings[i] = NULL;
594
595         for (i=0 ; i<32 ; i++)
596         {
597                 key_lines[i][0] = ']';
598                 key_lines[i][1] = 0;
599         }
600         key_linepos = 1;
601
602 //
603 // init ascii characters in console mode
604 //
605         for (i=32 ; i<128 ; i++)
606                 consolekeys[i] = true;
607         consolekeys[K_ENTER] = true;
608         consolekeys[K_TAB] = true;
609         consolekeys[K_LEFTARROW] = true;
610         consolekeys[K_RIGHTARROW] = true;
611         consolekeys[K_UPARROW] = true;
612         consolekeys[K_DOWNARROW] = true;
613         consolekeys[K_BACKSPACE] = true;
614         consolekeys[K_DEL] = true;
615         consolekeys[K_INS] = true;
616         consolekeys[K_PGUP] = true;
617         consolekeys[K_PGDN] = true;
618         consolekeys[K_SHIFT] = true;
619         consolekeys[K_MWHEELUP] = true;
620         consolekeys[K_MWHEELDOWN] = true;
621         consolekeys['`'] = false;
622         consolekeys['~'] = false;
623
624         for (i=0 ; i<256 ; i++)
625                 keyshift[i] = i;
626         for (i='a' ; i<='z' ; i++)
627                 keyshift[i] = i - 'a' + 'A';
628         keyshift['1'] = '!';
629         keyshift['2'] = '@';
630         keyshift['3'] = '#';
631         keyshift['4'] = '$';
632         keyshift['5'] = '%';
633         keyshift['6'] = '^';
634         keyshift['7'] = '&';
635         keyshift['8'] = '*';
636         keyshift['9'] = '(';
637         keyshift['0'] = ')';
638         keyshift['-'] = '_';
639         keyshift['='] = '+';
640         keyshift[','] = '<';
641         keyshift['.'] = '>';
642         keyshift['/'] = '?';
643         keyshift[';'] = ':';
644         keyshift['\''] = '"';
645         keyshift['['] = '{';
646         keyshift[']'] = '}';
647         keyshift['`'] = '~';
648         keyshift['\\'] = '|';
649
650         menubound[K_ESCAPE] = true;
651         for (i=0 ; i<12 ; i++)
652                 menubound[K_F1+i] = true;
653
654 //
655 // register our functions
656 //
657         Cmd_AddCommand ("bind",Key_Bind_f);
658         Cmd_AddCommand ("unbind",Key_Unbind_f);
659         Cmd_AddCommand ("unbindall",Key_Unbindall_f);
660 }
661
662 /*
663 ===================
664 Key_Event
665
666 Called by the system between frames for both key up and key down events
667 Should NOT be called during an interrupt!
668 ===================
669 */
670 void Key_Event (int key, qboolean down)
671 {
672         char    *kb;
673         char    cmd[1024];
674
675         keydown[key] = down;
676
677         if (!down)
678                 key_repeats[key] = 0;
679
680         key_lastpress = key;
681         key_count++;
682         if (key_count <= 0)
683                 return;         // just catching keys for Con_NotifyBox
684
685 // update auto-repeat status
686         if (down)
687         {
688                 key_repeats[key]++;
689                 if (key != K_BACKSPACE && key != K_PAUSE && key_repeats[key] > 1)
690                         return; // ignore most autorepeats
691
692                 if (key >= 200 && !keybindings[key])
693                         Con_Printf ("%s is unbound, hit F4 to set.\n", Key_KeynumToString (key) );
694         }
695
696         if (key == K_SHIFT)
697                 shift_down = down;
698
699 //
700 // handle escape specialy, so the user can never unbind it
701 //
702         if (key == K_ESCAPE)
703         {
704                 if (!down)
705                         return;
706                 switch (key_dest)
707                 {
708                 case key_message:
709                         Key_Message (key);
710                         break;
711                 case key_menu:
712                         M_Keydown (key);
713                         break;
714                 case key_game:
715                         M_ToggleMenu_f ();
716                         break;
717                 default:
718                         Sys_Error ("Bad key_dest");
719                 }
720                 return;
721         }
722
723         // LordHavoc: hack to make toggleconsole always work
724         if (down)
725         {
726                 kb = keybindings[key];
727                 if (kb && !strncmp(kb, "toggleconsole", strlen("toggleconsole")))
728                 {
729                         Cbuf_AddText (kb);
730                         Cbuf_AddText ("\n");
731                         return;
732                 }
733         }
734
735         if (key_consoleactive && consolekeys[key])
736         {
737                 // console only wants key down events
738                 if (!down)
739                         return;
740
741                 // FIXME: this does not support non-QWERTY keyboards
742                 if (shift_down)
743                         key = keyshift[key];
744
745                 Key_Console (key);
746         }
747         else
748         {
749                 //
750                 // key up events only generate commands if the game key binding is
751                 // a button command (leading + sign).  These will occur even in console mode,
752                 // to keep the character from continuing an action started before a console
753                 // switch.  Button commands include the keynum as a parameter, so multiple
754                 // downs can be matched with ups
755                 //
756                 if (!down)
757                 {
758                         kb = keybindings[key];
759                         if (kb && kb[0] == '+')
760                         {
761                                 sprintf (cmd, "-%s %i\n", kb+1, key);
762                                 Cbuf_AddText (cmd);
763                         }
764                         if (keyshift[key] != key)
765                         {
766                                 kb = keybindings[keyshift[key]];
767                                 if (kb && kb[0] == '+')
768                                 {
769                                         sprintf (cmd, "-%s %i\n", kb+1, key);
770                                         Cbuf_AddText (cmd);
771                                 }
772                         }
773                         return;
774                 }
775
776                 //
777                 // during demo playback, most keys bring up the main menu
778                 //
779                 if (cls.demoplayback && down && consolekeys[key] && key_dest == key_game)
780                 {
781                         M_ToggleMenu_f ();
782                         return;
783                 }
784
785                 //
786                 // if not a consolekey, send to the interpreter no matter what mode is
787                 //
788                 //if ((key_dest == key_console && !consolekeys[key])
789                 if ((key_consoleactive && !consolekeys[key])
790                  || (key_dest == key_menu && menubound[key])
791                  || key_dest == key_game)
792                 {
793                         kb = keybindings[key];
794                         if (kb)
795                         {
796                                 if (kb[0] == '+')
797                                 {       // button commands add keynum as a parm
798                                         sprintf (cmd, "%s %i\n", kb, key);
799                                         Cbuf_AddText (cmd);
800                                 }
801                                 else
802                                 {
803                                         Cbuf_AddText (kb);
804                                         Cbuf_AddText ("\n");
805                                 }
806                         }
807                         return;
808                 }
809
810                 if (!down)
811                         return;         // other systems only care about key down events
812
813                 // FIXME: this does not support non-QWERTY keyboards
814                 if (shift_down)
815                         key = keyshift[key];
816
817                 switch (key_dest)
818                 {
819                 case key_message:
820                         Key_Message (key);
821                         break;
822                 case key_menu:
823                         M_Keydown (key);
824                         break;
825
826                 case key_game:
827                 //case key_console:
828                         Key_Console (key);
829                         break;
830                 default:
831                         Sys_Error ("Bad key_dest");
832                 }
833         }
834 }
835
836
837 /*
838 ===================
839 Key_ClearStates
840 ===================
841 */
842 void Key_ClearStates (void)
843 {
844         int i;
845
846         for (i = 0;i < 256;i++)
847         {
848                 keydown[i] = false;
849                 key_repeats[i] = 0;
850         }
851 }
852