]> icculus.org git repositories - taylor/freespace2.git/blob - src/io/key.cpp
start of SDL2 port
[taylor/freespace2.git] / src / io / key.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
4  * All source code herein is the property of Volition, Inc. You may not sell 
5  * or otherwise commercially exploit the source or things you created based on
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/Io/Key.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * <insert description of file here>
16  *
17  * $Log$
18  * Revision 1.12  2004/06/11 01:14:12  tigital
19  * OSX: switched to __APPLE__
20  *
21  * Revision 1.11  2003/05/18 03:57:08  taylor
22  * do not swap German z and y keys if they are already swapped
23  *
24  * Revision 1.9  2003/01/30 19:55:01  relnev
25  * add German keys (this is mostly a patch already sent in by someone else that hasn't made it into cvs yet) (Taylor Richards)
26  *
27  * Revision 1.8  2002/06/17 23:11:39  relnev
28  * enable sdl key repeating.
29  *
30  * swap '/` keys.
31  *
32  * Revision 1.7  2002/06/09 04:41:21  relnev
33  * added copyright header
34  *
35  * Revision 1.6  2002/06/05 04:03:32  relnev
36  * finished cfilesystem.
37  *
38  * removed some old code.
39  *
40  * fixed mouse save off-by-one.
41  *
42  * sound cleanups.
43  *
44  * Revision 1.5  2002/05/31 03:34:02  theoddone33
45  * Fix Keyboard
46  * Add titlebar
47  *
48  * Revision 1.4  2002/05/30 23:46:29  theoddone33
49  * some minor key changes (not necessarily fixes)
50  *
51  * Revision 1.3  2002/05/30 16:50:24  theoddone33
52  * Keyboard partially fixed
53  *
54  * Revision 1.2  2002/05/29 23:17:50  theoddone33
55  * Non working text code and fixed keys
56  *
57  * Revision 1.1.1.1  2002/05/03 03:28:09  root
58  * Initial import.
59  *
60  * 
61  * 6     10/29/99 6:10p Jefff
62  * squashed the damned y/z german issues once and for all
63  * 
64  * 5     6/07/99 1:21p Dave
65  * Fixed debug console scrolling problem. Thread related.
66  * 
67  * 4     6/02/99 6:18p Dave
68  * Fixed TNT lockup problems! Wheeeee!
69  * 
70  * 3     11/05/98 4:18p Dave
71  * First run nebula support. Beefed up localization a bit. Removed all
72  * conditional compiles for foreign versions. Modified mission file
73  * format.
74  * 
75  * 2     10/07/98 10:53a Dave
76  * Initial checkin.
77  * 
78  * 1     10/07/98 10:49a Dave
79  * 
80  * 37    6/19/98 3:50p Lawrance
81  * change GERMAN to GR_BUILD
82  * 
83  * 36    6/17/98 11:05a Lawrance
84  * translate french and german keys
85  * 
86  * 35    6/12/98 4:49p Hoffoss
87  * Added code to remap scancodes for german and french keyboards.
88  * 
89  * 34    5/20/98 12:10a Mike
90  * Remove mprintfs.
91  * 
92  * 33    5/19/98 12:19p Mike
93  * Cheat codes!
94  * 
95  * 32    5/19/98 12:28a Mike
96  * Cheat stuff.
97  * 
98  * 31    5/18/98 11:01p Mike
99  * Adding support for cheat system.
100  * 
101  * 30    5/11/98 12:09a Lawrance
102  * Put in code to turn on/off NumLock key when running under 95
103  * 
104  * 29    5/01/98 4:23p Lawrance
105  * Remap the scancode for the UK "\" key
106  * 
107  * 28    4/18/98 12:42p John
108  * Added code to use DirectInput to read keyboard. Took out because it
109  * didn't differentiate btwn Pause and Numlock and sometimes Ctrl.
110  * 
111  * 27    4/13/98 10:16a John
112  * Switched gettime back to timer_get_milliseconds, which is now thread
113  * safe.
114  * 
115  * 26    4/12/98 11:08p Lawrance
116  * switch back to using gettime() in separate threads
117  * 
118  * 25    4/12/98 5:31p Lawrance
119  * use timer_get_milliseconds() instead of gettime()
120  * 
121  * 24    3/25/98 8:08p John
122  * Restructured software rendering into two modules; One for windowed
123  * debug mode and one for DirectX fullscreen.   
124  * 
125  * 23    1/23/98 3:49p Mike
126  * Fix bug in negative time-down due to latency.
127  * 
128  * 22    1/07/98 6:41p Lawrance
129  * Pass message latency to the keyboard lib.
130  * 
131  * 21    11/17/97 10:42a John
132  * On Debug+Backsp, cleared out keys so that it looks like nothing ever
133  * happened, so they're not stuck down.
134  * 
135  * 20    11/14/97 4:33p Mike
136  * Change Debug key to backquote (from F11).
137  * Balance a ton of subsystems in ships.tbl.
138  * Change "Heavy Laser" to "Disruptor".
139  * 
140  * 19    9/13/97 9:30a Lawrance
141  * added ability to block certain keys from the keyboard
142  * 
143  * 18    9/10/97 6:02p Hoffoss
144  * Added code to check for key-pressed sexp operator in FreeSpace as part
145  * of training mission stuff.
146  * 
147  * 17    9/09/97 11:08a Sandeep
148  * fixed warning level 4
149  * 
150  * 16    7/29/97 5:30p Lawrance
151  * move gettime() to timer module
152  * 
153  * 15    4/22/97 10:56a John
154  * fixed some resource leaks.
155  * 
156  * 14    2/03/97 4:23p Allender
157  * use F11 as debug key now
158  * 
159  * 13    1/10/97 5:15p Mike
160  * Moved ship-specific parameters from obj_subsystem to ship_subsys.
161  * 
162  * Added turret code to AI system.
163  *
164  * $NoKeywords: $
165  */
166
167 #include <ctype.h>      // for toupper
168 #include "pstypes.h"
169 #include "key.h"
170 #include "fix.h"
171 #include "timer.h"
172 #include "osapi.h"
173 #include "localize.h"
174
175 #define KEY_BUFFER_SIZE 16
176
177 //-------- Variable accessed by outside functions ---------
178 ubyte                           keyd_buffer_type;               // 0=No buffer, 1=buffer ASCII, 2=buffer scans
179 ubyte                           keyd_repeat;
180 uint                            keyd_last_pressed;
181 uint                            keyd_last_released;
182 int                             keyd_time_when_last_pressed;
183
184 static bool             keyd_pressed[SDL_NUM_SCANCODES];
185
186 typedef struct keyboard {
187         ushort                  keybuffer[KEY_BUFFER_SIZE];
188         uint                            time_pressed[KEY_BUFFER_SIZE];
189         uint                            TimeKeyWentDown[SDL_NUM_SCANCODES];
190         uint                            TimeKeyHeldDown[SDL_NUM_SCANCODES];
191         uint                            TimeKeyDownChecked[SDL_NUM_SCANCODES];
192         uint                            NumDowns[SDL_NUM_SCANCODES];
193         uint                            NumUps[SDL_NUM_SCANCODES];
194         int                             down_check[SDL_NUM_SCANCODES];  // nonzero if has been pressed yet this mission
195         uint                            keyhead, keytail;
196 } keyboard;
197
198 keyboard key_data;
199
200 int key_inited = 0;
201
202 CRITICAL_SECTION key_lock;
203
204 //int Backspace_debug=1;        // global flag that will enable/disable the backspace key from stopping execution
205                                                                 // This flag was created since the backspace key is also used to correct mistakes
206                                                                 // when typing in your pilots callsign.  This global flag is checked before execution
207                                                                 // is stopped.
208
209 // used to limit the keypresses that are accepted from the keyboard
210 #define MAX_FILTER_KEYS 64
211 int Num_filter_keys;
212 int Key_filter[MAX_FILTER_KEYS];
213
214 static int Key_numlock_was_on = 0;      // Flag to indicate whether NumLock is on at start
215
216 int Cheats_enabled = 0;
217 int Key_normal_game = 0;
218
219
220 bool key_pressed(int keycode)
221 {
222         SDL_Scancode scancode = SDL_GetScancodeFromKey(keycode);
223
224         return keyd_pressed[scancode];
225 }
226
227 int key_numlock_is_on()
228 {
229         const Uint8 *state;
230         state = SDL_GetKeyboardState(NULL);
231         if ( state[SDL_SCANCODE_NUMLOCKCLEAR] ) {
232                 return 1;
233         }
234
235         return 0;
236 }
237
238 void key_turn_off_numlock()
239 {
240 }
241
242 void key_turn_on_numlock()
243 {
244 }
245
246 //      Convert a BIOS scancode to ASCII.
247 //      If scancode >= 127, returns 255, meaning there is no corresponding ASCII code.
248 //      Uses ascii_table and shifted_ascii_table to translate scancode to ASCII.
249 int key_to_ascii(int keycode)
250 {
251         if ( ((keycode >= SDLK_SPACE) && (keycode <= SDLK_AT))
252                         || ((keycode >= SDLK_LEFTBRACKET) && (keycode <= SDLK_z)) )
253         {
254                 return keycode;
255         }
256
257         return 255;
258 }
259
260 //      Flush the keyboard buffer.
261 //      Clear the keyboard array (keyd_pressed).
262 void key_flush()
263 {
264         int i;
265         uint CurTime;
266
267         if ( !key_inited ) return;
268
269         ENTER_CRITICAL_SECTION(&key_lock);      
270
271         key_data.keyhead = key_data.keytail = 0;
272
273         //Clear the keyboard buffer
274         for (i=0; i<KEY_BUFFER_SIZE; i++ )      {
275                 key_data.keybuffer[i] = 0;
276                 key_data.time_pressed[i] = 0;
277         }
278         
279         //Clear the keyboard array
280
281         CurTime = timer_get_milliseconds();
282
283
284         for (i=0; i<SDL_NUM_SCANCODES; i++ )    {
285                 keyd_pressed[i] = false;
286                 key_data.TimeKeyDownChecked[i] = CurTime;
287                 key_data.TimeKeyWentDown[i] = CurTime;
288                 key_data.TimeKeyHeldDown[i] = 0;
289                 key_data.NumDowns[i]=0;
290                 key_data.NumUps[i]=0;
291         }
292
293         LEAVE_CRITICAL_SECTION(&key_lock);      
294 }
295
296 //      A nifty function which performs the function:
297 //              n = (n+1) % KEY_BUFFER_SIZE
298 //      (assuming positive values of n).
299 int add_one( int n )
300 {
301         n++;
302         if ( n >= KEY_BUFFER_SIZE ) n=0;
303         return n;
304 }
305
306 // Returns 1 if character waiting... 0 otherwise
307 int key_checkch()
308 {
309         int is_one_waiting = 0;
310
311         if ( !key_inited ) return 0;
312
313         ENTER_CRITICAL_SECTION(&key_lock);      
314
315         if (key_data.keytail != key_data.keyhead){
316                 is_one_waiting = 1;
317         }
318
319         LEAVE_CRITICAL_SECTION(&key_lock);              
320
321         return is_one_waiting;
322 }
323
324 //      Return keycode if a key has been pressed,
325 //      else return 0.
326 //      Reads keys out of the key buffer and updates keyhead.
327 int key_inkey()
328 {
329         SDL_Scancode scancode;
330
331         if ( !key_inited )
332                 return 0;
333
334         ENTER_CRITICAL_SECTION(&key_lock);      
335
336         if (key_data.keytail != key_data.keyhead) {
337                 scancode = (SDL_Scancode)key_data.keybuffer[key_data.keyhead];
338                 key_data.keyhead = add_one(key_data.keyhead);
339         }
340
341         LEAVE_CRITICAL_SECTION(&key_lock);      
342
343         return (int)SDL_GetKeyFromScancode(scancode);
344 }
345
346 // If not installed, uses BIOS and returns getch();
347 //      Else returns pending key (or waits for one if none waiting).
348 int key_getch()
349 {
350         int dummy=0;
351         int in;
352
353         if ( !key_inited ) return 0;
354         
355         while (!key_checkch()){
356                 os_poll();
357
358                 dummy++;
359         }
360         in = key_inkey();
361
362         return in;
363 }
364
365 //      Set global shift_status with modifier results (shift, ctrl, alt).
366 uint key_get_shift_status()
367 {
368         unsigned int shift_status = 0;
369
370         if ( !key_inited ) return 0;
371
372         ENTER_CRITICAL_SECTION(&key_lock);              
373
374         if ( keyd_pressed[SDL_SCANCODE_LSHIFT] || keyd_pressed[SDL_SCANCODE_RSHIFT] )
375                 shift_status |= KEY_SHIFTED;
376
377         if ( keyd_pressed[SDL_SCANCODE_LALT] || keyd_pressed[SDL_SCANCODE_RALT] )
378                 shift_status |= KEY_ALTED;
379
380         if ( keyd_pressed[SDL_SCANCODE_LCTRL] || keyd_pressed[SDL_SCANCODE_RCTRL] )
381                 shift_status |= KEY_CTRLED;
382
383 #ifndef NDEBUG
384         if (keyd_pressed[KEY_DEBUG_KEY])
385                 shift_status |= KEY_DEBUGGED;
386 #else
387         if (keyd_pressed[KEY_DEBUG_KEY]) {
388                 mprintf(("Cheats_enabled = %i, Key_normal_game = %i\n", Cheats_enabled, Key_normal_game));
389                 if ((Cheats_enabled) && Key_normal_game) {
390                         mprintf(("Debug key\n"));
391                         shift_status |= KEY_DEBUGGED1;
392                 }
393         }
394 #endif
395         LEAVE_CRITICAL_SECTION(&key_lock);              
396
397         return shift_status;
398 }
399
400 //      Returns amount of time key (specified by "keycode") has been down since last call.
401 //      Returns float, unlike key_down_time() which returns a fix.
402 float key_down_timef(int keycode)
403 {
404         uint time_down, time;
405         uint delta_time;
406         SDL_Scancode scancode;
407
408         if ( !key_inited )
409                 return 0.0f;
410
411         scancode = SDL_GetScancodeFromKey(keycode);
412
413         if (scancode == SDL_SCANCODE_UNKNOWN)
414                 return 0.0f;
415
416         ENTER_CRITICAL_SECTION(&key_lock);              
417
418         time = timer_get_milliseconds();
419         delta_time = time - key_data.TimeKeyDownChecked[scancode];
420         key_data.TimeKeyDownChecked[scancode] = time;
421
422         if ( delta_time <= 1 ) {
423                 key_data.TimeKeyWentDown[scancode] = time;
424                 if (keyd_pressed[scancode])     {
425                         LEAVE_CRITICAL_SECTION(&key_lock);              
426                         return 1.0f;
427                 } else  {
428                         LEAVE_CRITICAL_SECTION(&key_lock);              
429                         return 0.0f;
430                 }
431         }
432
433         if ( !keyd_pressed[scancode] )  {
434                 time_down = key_data.TimeKeyHeldDown[scancode];
435                 key_data.TimeKeyHeldDown[scancode] = 0;
436         } else  {
437                 time_down =  time - key_data.TimeKeyWentDown[scancode];
438                 key_data.TimeKeyWentDown[scancode] = time;
439         }
440
441         LEAVE_CRITICAL_SECTION(&key_lock);              
442
443         return i2fl(time_down) / i2fl(delta_time);
444 }
445
446 // Returns number of times key has went from up to down since last call.
447 int key_down_count(int keycode)
448 {
449         int n;
450         SDL_Scancode scancode;
451
452         if ( !key_inited )
453                 return 0;
454
455         scancode = SDL_GetScancodeFromKey(keycode);
456
457         if (scancode == SDL_SCANCODE_UNKNOWN)
458                 return 0;
459
460         ENTER_CRITICAL_SECTION(&key_lock);              
461
462         n = key_data.NumDowns[scancode];
463         key_data.NumDowns[scancode] = 0;
464
465         LEAVE_CRITICAL_SECTION(&key_lock);              
466
467         return n;
468 }
469
470
471 // Returns number of times key has went from down to up since last call.
472 int key_up_count(int keycode)
473 {
474         int n;
475         SDL_Scancode scancode;
476
477         if ( !key_inited )
478                 return 0;
479
480         scancode = SDL_GetScancodeFromKey(keycode);
481
482         if (scancode == SDL_SCANCODE_UNKNOWN)
483                 return 0;
484
485         ENTER_CRITICAL_SECTION(&key_lock);              
486
487         n = key_data.NumUps[scancode];
488         key_data.NumUps[scancode] = 0;
489
490         LEAVE_CRITICAL_SECTION(&key_lock);              
491
492         return n;
493 }
494
495 int key_check(int keycode)
496 {
497         SDL_Scancode scancode = SDL_GetScancodeFromKey(keycode);
498
499         return key_data.down_check[scancode];
500 }
501
502 //      Add a key up or down code to the key buffer.  state=1 -> down, state=0 -> up
503 // latency => time difference in ms between when key was actually pressed and now
504 //void key_mark( uint code, int state )
505 void key_mark(SDL_Scancode scancode, int state, ushort kmod, uint latency )
506 {
507         uint breakbit, temp, event_time;
508         ushort keycode; 
509
510         if ( !key_inited ) return;
511
512         ENTER_CRITICAL_SECTION(&key_lock);              
513
514         Assert( scancode < SDL_NUM_SCANCODES );
515
516         event_time = timer_get_milliseconds() - latency;
517         // event_time = timeGetTime() - latency;
518
519         breakbit = !state;
520         
521         if (breakbit)   {
522                 // Key going up
523                 keyd_last_released = scancode;
524                 keyd_pressed[scancode] = false;
525                 key_data.NumUps[scancode]++;
526
527                 if (event_time < key_data.TimeKeyWentDown[scancode])
528                         key_data.TimeKeyHeldDown[scancode] = 0;
529                 else
530                         key_data.TimeKeyHeldDown[scancode] += event_time - key_data.TimeKeyWentDown[scancode];
531         } else {
532                 // Key going down
533                 keyd_last_pressed = scancode;
534                 keyd_time_when_last_pressed = event_time;
535                 if (!keyd_pressed[scancode])    {
536                         // First time down
537                         key_data.TimeKeyWentDown[scancode] = event_time;
538                         keyd_pressed[scancode] = true;
539                         key_data.NumDowns[scancode]++;
540                         key_data.down_check[scancode]++;
541
542 //                      mprintf(( "Scancode = %x\n", scancode ));
543
544 //                      if ( scancode == KEY_BREAK )
545 //                              Int3();
546                 } 
547
548                 keycode = (unsigned short)scancode;
549
550                 if (kmod & KMOD_SHIFT)
551                         keycode |= KEY_SHIFTED;
552
553                 if (kmod & KMOD_ALT)
554                         keycode |= KEY_ALTED;
555
556                 if (kmod & KMOD_CTRL)
557                         keycode |= KEY_CTRLED;
558
559 #ifndef NDEBUG
560                 if ( keyd_pressed[KEY_DEBUG_KEY] )
561                         keycode |= KEY_DEBUGGED;
562 //                      if ( keycode == (KEY_BACKSP + KEY_DEBUGGED) )   {
563 //                              keycode = 0;
564 //                              keyd_pressed[KEY_DEBUG_KEY] = 0;
565 //                              keyd_pressed[KEY_BACKSP] = 0;
566 //                              Int3();
567 //                      }
568 #else
569                 if ( keyd_pressed[KEY_DEBUG_KEY] ) {
570                         mprintf(("Cheats_enabled = %i, Key_normal_game = %i\n", Cheats_enabled, Key_normal_game));
571                         if (Cheats_enabled && Key_normal_game) {
572                                 keycode |= KEY_DEBUGGED1;
573                         }
574                 }
575
576 #endif
577
578                 if ( keycode )  {
579                         temp = key_data.keytail+1;
580                         if ( temp >= KEY_BUFFER_SIZE ) temp=0;
581
582                         if (temp!=key_data.keyhead)     {
583                                 int i, accept_key = 1;
584                                 // Num_filter_keys will only be non-zero when a key filter has
585                                 // been explicity set up via key_set_filter()
586                                 for ( i = 0; i < Num_filter_keys; i++ ) {
587                                         accept_key = 0;
588                                         if ( Key_filter[i] == keycode ) {
589                                                 accept_key = 1;
590                                                 break;
591                                         }
592                                 }
593
594                                 if ( accept_key ) {
595                                         key_data.keybuffer[key_data.keytail] = keycode;
596                                         key_data.time_pressed[key_data.keytail] = keyd_time_when_last_pressed;
597                                         key_data.keytail = temp;
598                                 }
599                         }
600                 }
601         }
602
603         LEAVE_CRITICAL_SECTION(&key_lock);              
604 }
605
606 void key_close()
607 {
608         if ( !key_inited )
609                 return;
610
611         if ( Key_numlock_was_on ) {
612                 key_turn_on_numlock();
613                 Key_numlock_was_on = 0;
614         }
615
616         key_inited = 0;
617 }
618
619 void key_init()
620 {
621         // Initialize queue
622         if (key_inited)
623                 return;
624
625         key_inited = 1;
626
627         keyd_time_when_last_pressed = timer_get_milliseconds();
628         keyd_buffer_type = 1;
629
630         // Clear the keyboard array
631         key_flush();
632
633         // Clear key filter
634         key_clear_filter();
635
636         atexit(key_close);
637 }
638
639 void key_level_init()
640 {
641         int i;
642
643         for (i=0; i<SDL_NUM_SCANCODES; i++)
644                 key_data.down_check[i] = 0;
645 }
646
647 void key_lost_focus()
648 {
649         if ( !key_inited )
650                 return;
651
652         key_flush();    
653 }
654
655 void key_got_focus()
656 {
657         if ( !key_inited )
658                 return;
659         
660         key_flush();    
661 }
662
663 // Restricts the keys that are accepted from the keyboard
664 //
665 //      filter_array    =>              array of keys to act as a filter
666 //      num                             =>              number of keys in filter_array
667 //
668 void key_set_filter(int *filter_array, int num)
669 {
670         int i;
671
672         if ( num >= MAX_FILTER_KEYS ) {
673                 Int3();
674                 num = MAX_FILTER_KEYS;
675         }
676
677         Num_filter_keys = num;
678
679         for ( i = 0; i < num; i++ ) {
680                 Key_filter[i] = filter_array[i];
681         }
682 }
683
684 // Clear the key filter, so all keypresses are accepted from keyboard 
685 //
686 void key_clear_filter()
687 {
688         int i;
689
690         Num_filter_keys = 0;
691         for ( i = 0; i < MAX_FILTER_KEYS; i++ ) {
692                 Key_filter[i] = -1;
693         }
694 }