Release 970120
[wine] / windows / keyboard.c
1 /*
2  * Keyboard related functions
3  *
4  * Copyright 1993 Bob Amstadt
5  * Copyright 1996 Albrecht Kleine 
6  * Copyright 1997 David Faure
7  *
8  */
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <ctype.h>
13 #include <X11/keysym.h>
14 #include <X11/Xlib.h>
15 #include <X11/Xresource.h>
16 #include <X11/Xutil.h>
17 #include <X11/Xatom.h>
18
19 #include "windows.h"
20 #include "win.h"
21 #include "gdi.h"
22 #include "keyboard.h"
23 #include "message.h"
24 #include "stddebug.h"
25 /* #define DEBUG_KEYBOARD */
26 #include "debug.h"
27 #include "xmalloc.h"
28 #include "accel.h"
29
30 BOOL32 MouseButtonsStates[3];
31 BOOL32 AsyncMouseButtonsStates[3];
32 BYTE InputKeyStateTable[256];
33 BYTE QueueKeyStateTable[256];
34 BYTE AsyncKeyStateTable[256];
35
36 static int NumLockMask;
37 static int AltGrMask;
38 static int min_keycode, max_keycode;
39 static int keyc2vkey[256];
40
41 typedef union
42 {
43     struct
44     {
45         unsigned long count : 16;
46         unsigned long code : 8;
47         unsigned long extended : 1;
48         unsigned long unused : 2;
49         unsigned long win_internal : 2;
50         unsigned long context : 1;
51         unsigned long previous : 1;
52         unsigned long transition : 1;
53     } lp1;
54     unsigned long lp2;
55 } KEYLP;
56
57 typedef enum {OFF,INTERM,ON} ToggleKeyState;
58
59 /* Keyboard translation tables */
60 static const int special_key[] =
61 {
62     VK_BACK, VK_TAB, 0, VK_CLEAR, 0, VK_RETURN, 0, 0,           /* FF08 */
63     0, 0, 0, VK_PAUSE, VK_SCROLL, 0, 0, 0,                      /* FF10 */
64     0, 0, 0, VK_ESCAPE                                          /* FF18 */
65 };
66
67 static const int cursor_key[] =
68 {
69     VK_HOME, VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN, VK_PRIOR, 
70                                        VK_NEXT, VK_END          /* FF50 */
71 };
72
73 static const int misc_key[] =
74 {
75     VK_SELECT, VK_SNAPSHOT, VK_EXECUTE, VK_INSERT, 0, 0, 0, 0,  /* FF60 */
76     VK_CANCEL, VK_HELP, VK_CANCEL, VK_MENU                      /* FF68 */
77 };
78
79 static const int keypad_key[] =
80 {
81     0, VK_NUMLOCK,                                              /* FF7E */
82     0, 0, 0, 0, 0, 0, 0, 0,                                     /* FF80 */
83     0, 0, 0, 0, 0, VK_RETURN, 0, 0,                             /* FF88 */
84     0, 0, 0, 0, 0, VK_HOME, VK_LEFT, VK_UP,                     /* FF90 */
85     VK_RIGHT, VK_DOWN, VK_PRIOR, VK_NEXT, VK_END, 0,
86                                  VK_INSERT, VK_DELETE,          /* FF98 */
87     0, 0, 0, 0, 0, 0, 0, 0,                                     /* FFA0 */
88     0, 0, VK_MULTIPLY, VK_ADD, VK_SEPARATOR, VK_SUBTRACT, 
89                                VK_DECIMAL, VK_DIVIDE,           /* FFA8 */
90     VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4,
91                             VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, /* FFB0 */
92     VK_NUMPAD8, VK_NUMPAD9                                      /* FFB8 */
93 };
94     
95 static const int function_key[] =
96 {
97     VK_F1, VK_F2,                                               /* FFBE */
98     VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_F10,    /* FFC0 */
99     VK_F11, VK_F12, VK_F13, VK_F14, VK_F15, VK_F16              /* FFC8 */
100 };
101
102 static const int modifier_key[] =
103 {
104     VK_SHIFT, VK_SHIFT, VK_CONTROL, VK_CONTROL, VK_CAPITAL, 0, /* FFE1 */
105     VK_MENU, VK_MENU, VK_MENU, VK_MENU                         /* FFE7 */
106 };
107
108
109 static WORD EVENT_event_to_vkey( XKeyEvent *e)
110 {
111     KeySym keysym;
112
113     XLookupString(e, NULL, 0, &keysym, NULL);
114
115     if ((keysym >= 0xFFAE) && (keysym <= 0xFFB9) && (e->state & NumLockMask)) 
116         /* Only the Keypad keys 0-9 and . send different keysyms
117          * depending on the NumLock state */
118         return keypad_key[(keysym & 0xFF) - 0x7E];
119
120     return keyc2vkey[e->keycode];
121 }
122
123 /**********************************************************************
124  *              KEYBOARD_Init
125  */
126 BOOL32 KEYBOARD_Init(void)
127 {
128     int i, keysyms_per_keycode;
129     KeySym *ksp;
130     XModifierKeymap *mmp;
131     KeySym keysym;
132     KeyCode *kcp;
133     XKeyEvent e2;
134     WORD vkey, OEMvkey;
135
136     XDisplayKeycodes(display, &min_keycode, &max_keycode);
137     ksp = XGetKeyboardMapping(display, min_keycode,
138                               max_keycode + 1 - min_keycode, &keysyms_per_keycode);
139     /* We are only interested in keysyms_per_keycode.
140        There is no need to hold a local copy of the keysyms table */
141     XFree(ksp);
142     mmp = XGetModifierMapping(display);
143     kcp = mmp->modifiermap;
144     for (i = 0; i < 8; i += 1) /* There are 8 modifier keys */
145     {
146         int j;
147         
148         for (j = 0; j < mmp->max_keypermod; j += 1, kcp += 1)
149             if (*kcp)
150             {
151                 int k;
152                 
153                 for (k = 0; k < keysyms_per_keycode; k += 1)
154                     if (XKeycodeToKeysym(display, *kcp, k) == XK_Mode_switch)
155                     {
156                         AltGrMask = 1 << i;
157                         dprintf_key(stddeb, "AltGrMask is %x\n", AltGrMask);
158                     }
159                     else if (XKeycodeToKeysym(display, *kcp, k) == XK_Num_Lock)
160                     {
161                         NumLockMask = 1 << i;
162                         dprintf_key(stddeb, "NumLockMask is %x\n", NumLockMask);
163                     }
164             }
165     }
166     XFreeModifiermap(mmp);
167
168     /* Now build two conversion arrays :
169      * keycode -> vkey + extended
170      * vkey + extended -> keycode */
171
172     e2.display = display;
173     e2.state = 0;
174
175     OEMvkey = 0xb9; /* first OEM virtual key available is ba */
176     for (e2.keycode=min_keycode; e2.keycode<=max_keycode; e2.keycode++)
177     {
178         XLookupString(&e2, NULL, 0, &keysym, NULL);
179         vkey = 0;
180         if (keysym)  /* otherwise, keycode not used */
181         {
182             if ((keysym >> 8) == 0xFF)         /* non-character key */
183             {
184                 int key = keysym & 0xff;
185                 
186                 if (key >= 0x08 && key <= 0x1B)         /* special key */
187                     vkey = special_key[key - 0x08];
188                 else if (key >= 0x50 && key <= 0x57)    /* cursor key */
189                     vkey = cursor_key[key - 0x50];
190                 else if (key >= 0x60 && key <= 0x6B)    /* miscellaneous key */
191                     vkey = misc_key[key - 0x60];
192                 else if (key >= 0x7E && key <= 0xB9)    /* keypad key */
193                     vkey = keypad_key[key - 0x7E];
194                 else if (key >= 0xBE && key <= 0xCD)    /* function key */
195                 {
196                     vkey = function_key[key - 0xBE];
197                     vkey |= 0x100; /* set extended bit */
198                 }
199                 else if (key >= 0xE1 && key <= 0xEA)    /* modifier key */
200                     vkey = modifier_key[key - 0xE1];
201                 else if (key == 0xFF)                   /* DEL key */
202                     vkey = VK_DELETE;
203                 /* extended must also be set for ALT_R, CTRL_R,
204                    INS, DEL, HOME, END, PAGE_UP, PAGE_DOWN, ARROW keys,
205                    keypad / and keypad ENTER (SDK 3.1 Vol.3 p 138) */
206                 /* FIXME should we set extended bit for NumLock ? My
207                  * Windows does ... DF */
208                 switch (keysym)
209                 {
210                 case XK_Control_R :
211                 case XK_Alt_R :
212                 case XK_Insert :
213                 case XK_Delete :
214                 case XK_Home :
215                 case XK_End :
216                 case XK_Prior :
217                 case XK_Next :
218                 case XK_Left :
219                 case XK_Up :
220                 case XK_Right :
221                 case XK_Down :
222                 case XK_KP_Divide :
223                 case XK_KP_Enter :
224                     vkey |= 0x100;
225                 }
226             }
227             for (i = 0; (i < keysyms_per_keycode) && (!vkey); i++)
228             {
229                 keysym = XLookupKeysym(&e2, i);
230                 if ((keysym >= VK_0 && keysym <= VK_9)
231                     || (keysym >= VK_A && keysym <= VK_Z)
232                     || keysym == VK_SPACE)
233                     vkey = keysym;
234             }
235
236             if (!vkey)
237             {
238                 /* Others keys: let's assign OEM virtual key codes in the allowed range,
239                  * that is ([0xba,0xc0], [0xdb,0xe4], 0xe6 (given up) et [0xe9,0xf5]) */
240                 switch (++OEMvkey)
241                 {
242                 case 0xc1 : OEMvkey=0xdb; break;
243                 case 0xe5 : OEMvkey=0xe9; break;
244                 case 0xf6 : OEMvkey=0xf5; fprintf(stderr,"No more OEM vkey available!\n");
245                 }
246
247                 vkey = OEMvkey;
248                   
249                 if (debugging_keyboard)
250                 {
251                     fprintf(stddeb,"OEM specific virtual key %X assigned to keycode %X :\n ("
252                             ,OEMvkey,e2.keycode);
253                     for (i = 0; i < keysyms_per_keycode; i += 1)
254                     {
255                         char    *ksname;
256                         
257                         keysym = XLookupKeysym(&e2, i);
258                         ksname = XKeysymToString(keysym);
259                         if (!ksname)
260                             ksname = "NoSymbol";
261                         fprintf(stddeb, "%lX (%s) ", keysym, ksname);
262                     }
263                     fprintf(stddeb, ")\n");
264                 }
265             }
266         }
267         keyc2vkey[e2.keycode] = vkey;
268     } /* for */
269     return TRUE;
270 }
271
272
273 /***********************************************************************
274  *           KEYBOARD_HandleEvent
275  *
276  * Handle a X key event
277  */
278 void KEYBOARD_HandleEvent( XKeyEvent *event )
279 {
280     char Str[24]; 
281     XComposeStatus cs; 
282     KeySym keysym;
283     WORD vkey = 0;
284     KEYLP keylp;
285     WORD message;
286     static BOOL force_extended = FALSE; /* hack for AltGr translation */
287     BOOL DontPropagate;
288     ToggleKeyState * State;
289     static ToggleKeyState NumState=OFF, CapsState=OFF;
290
291     int ascii_chars = XLookupString(event, Str, 1, &keysym, &cs);
292
293     dprintf_key(stddeb, "EVENT_key : state = %X\n", event->state);
294     if (keysym == XK_Mode_switch)
295         {
296         dprintf_key(stddeb, "Alt Gr key event received\n");
297         event->keycode = XKeysymToKeycode(event->display, XK_Control_L);
298         dprintf_key(stddeb, "Control_L is keycode 0x%x\n", event->keycode);
299         KEYBOARD_HandleEvent(event);
300         event->keycode = XKeysymToKeycode(event->display, XK_Alt_L);
301         dprintf_key(stddeb, "Alt_L is keycode 0x%x\n", event->keycode);
302         force_extended = TRUE;
303         KEYBOARD_HandleEvent(event);
304         force_extended = FALSE;
305         return;
306         }
307
308     Str[ascii_chars] = '\0';
309     if (debugging_key)
310         {
311         char    *ksname;
312
313         ksname = XKeysymToString(keysym);
314         if (!ksname)
315             ksname = "No Name";
316         fprintf(stddeb, "%s : keysym=%lX (%s), ascii chars=%u / %X / '%s'\n", 
317                 (event->type == KeyPress) ? "KeyPress" : "KeyRelease",
318                 keysym, ksname, ascii_chars, Str[0] & 0xff, Str);
319         }
320
321 #if 0
322     /* Ctrl-Alt-Return enters the debugger */
323     if ((keysym == XK_Return) && (event->type == KeyPress) &&
324         (event->state & ControlMask) && (event->state & Mod1Mask))
325         DEBUG_EnterDebugger();
326 #endif
327
328     vkey = EVENT_event_to_vkey(event);
329     if (force_extended) vkey |= 0x100;
330
331     dprintf_key(stddeb, "keycode 0x%x converted to vkey 0x%x\n",
332                     event->keycode, vkey);
333
334     if (vkey)
335     {
336     keylp.lp1.count = 1;
337     keylp.lp1.code = LOBYTE(event->keycode) - 8;
338     keylp.lp1.extended = (vkey & 0x100 ? 1 : 0);
339     keylp.lp1.win_internal = 0; /* this has something to do with dialogs, 
340                                 * don't remember where I read it - AK */
341                                 /* it's '1' under windows, when a dialog box appears
342                                  * and you press one of the underlined keys - DF*/
343     vkey &= 0xff;
344     if (event->type == KeyPress)
345     {
346         keylp.lp1.previous = (InputKeyStateTable[vkey] & 0x80) != 0;
347         if (!(InputKeyStateTable[vkey] & 0x80))
348             InputKeyStateTable[vkey] ^= 0x01;
349         InputKeyStateTable[vkey] |= 0x80;
350         keylp.lp1.transition = 0;
351         message = (InputKeyStateTable[VK_MENU] & 0x80)
352                     && !(InputKeyStateTable[VK_CONTROL] & 0x80)
353                          ? WM_SYSKEYDOWN : WM_KEYDOWN;
354     }
355     else
356     {
357         UINT sysKey = (InputKeyStateTable[VK_MENU] & 0x80)
358                         && !(InputKeyStateTable[VK_CONTROL] & 0x80)
359                         && (force_extended == FALSE); /* for Alt from AltGr */
360
361         InputKeyStateTable[vkey] &= ~0x80; 
362         keylp.lp1.previous = 1;
363         keylp.lp1.transition = 1;
364         message = sysKey ? WM_SYSKEYUP : WM_KEYUP;
365     }
366     keylp.lp1.context = ( (event->state & Mod1Mask)  || 
367                           (InputKeyStateTable[VK_MENU] & 0x80)) ? 1 : 0;
368     DontPropagate = FALSE;
369     if ((vkey==VK_NUMLOCK) || (vkey==VK_CAPITAL))
370       {
371         
372         switch (*( State = (vkey==VK_NUMLOCK? &NumState : &CapsState))) {
373         case OFF:if (event->type==KeyPress)
374           {
375             dprintf_keyboard(stddeb,"OFF + Keypress => DOWN and UP generated. \n");
376             hardware_event( message, vkey, keylp.lp2, event->x_root - desktopX,
377                             event->y_root - desktopY, event->time - MSG_WineStartTicks, 0);
378             message += WM_KEYUP - WM_KEYDOWN; /* create a *UP message from the *DOWN one */
379             keylp.lp1.previous = 1;
380             keylp.lp1.transition = 1;
381             *State = INTERM;
382           } break;
383         case INTERM:
384           /* The 'INTERM' state means : just after a 'press' event, if a 'release' event comes,
385              don't "propagate" it. It's from the same key press. Then the state goes to ON.
386              And from there, a 'release' event will switch off the toggle key. */
387           DontPropagate = TRUE;
388           *State=ON;
389           InputKeyStateTable[vkey] |= 0x01; /* force to 'on' event if a release event was received */
390           dprintf_keyboard(stddeb,"INTERM : don\'t propagate press/release of toggle key. InputKeyStateTable[%#x] = %#x",vkey,InputKeyStateTable[vkey]);
391           break;
392         case ON: if (event->type==KeyPress) DontPropagate = TRUE; else
393           {
394             KEYLP downkeylp = keylp;
395             dprintf_keyboard(stddeb,"ON + KeyRelease => generating DOWN msg before the UP\n");
396             message += WM_KEYDOWN - WM_KEYUP; /* create the *DOWN from the *UP */
397             downkeylp.lp1.previous = 0; /* ? */
398             downkeylp.lp1.transition = 0;
399             hardware_event( message, vkey, downkeylp.lp2, event->x_root - desktopX,
400                             event->y_root - desktopY, event->time - MSG_WineStartTicks, 0);
401             message += WM_KEYUP - WM_KEYDOWN; /* back to the UP message */
402             *State=OFF;
403           } break;
404         }
405         dprintf_keyboard(stddeb,"Internal State : %d (0=OFF 1=INTERM 2=ON). InputTable state : %#x \n",*State,InputKeyStateTable[vkey]);
406       } else {
407         if (NumState == INTERM) NumState = ON;
408         if (CapsState == INTERM) CapsState = ON;
409       }
410     
411     if (!DontPropagate)
412       {
413         dprintf_key(stddeb,"            wParam=%04X, lParam=%08lX\n", 
414                     vkey, keylp.lp2 );
415         dprintf_key(stddeb,"            InputKeyState=%X\n",
416                     InputKeyStateTable[vkey]);
417
418         hardware_event( message, vkey, keylp.lp2, event->x_root - desktopX,
419                         event->y_root - desktopY, event->time - MSG_WineStartTicks, 0 );
420       }
421     }
422 }
423
424
425 /**********************************************************************
426  *              GetKeyState                     [USER.106]
427  * An application calls the GetKeyState function in response to a
428  * keyboard-input message.  This function retrieves the state of the key
429  * at the time the input message was generated.  (SDK 3.1 Vol 2. p 390)
430  */
431 INT GetKeyState(INT vkey)
432 {
433     INT retval;
434
435     switch (vkey)
436         {
437         case VK_LBUTTON : /* VK_LBUTTON is 1 */
438             retval = MouseButtonsStates[0];
439             break;
440         case VK_MBUTTON : /* VK_MBUTTON is 4 */
441             retval = MouseButtonsStates[1];
442             break;
443         case VK_RBUTTON : /* VK_RBUTTON is 2 */
444             retval = MouseButtonsStates[2];
445             break;
446         default :
447             if (vkey >= 'a' && vkey <= 'z')
448                 vkey += 'A' - 'a';
449             retval = ( (INT)(QueueKeyStateTable[vkey] & 0x80) << 8 ) |
450                        (INT)(QueueKeyStateTable[vkey] & 0x01);
451         }
452     dprintf_key(stddeb, "GetKeyState(0x%x) -> %x\n", vkey, retval);
453     return retval;
454 }
455
456 /**********************************************************************
457  *              GetKeyboardState                        [USER.222]
458  * An application calls the GetKeyboardState function in response to a
459  * keyboard-input message.  This function retrieves the state of the keyboard
460  * at the time the input message was generated.  (SDK 3.1 Vol 2. p 387)
461  */
462 void GetKeyboardState(BYTE *lpKeyState)
463 {
464     dprintf_key(stddeb, "GetKeyboardState()\n");
465     if (lpKeyState != NULL) {
466         QueueKeyStateTable[VK_LBUTTON] = MouseButtonsStates[0] >> 8;
467         QueueKeyStateTable[VK_MBUTTON] = MouseButtonsStates[1] >> 8;
468         QueueKeyStateTable[VK_RBUTTON] = MouseButtonsStates[2] >> 8;
469         memcpy(lpKeyState, QueueKeyStateTable, 256);
470     }
471 }
472
473 /**********************************************************************
474  *      SetKeyboardState            [USER.223]
475  */
476 void SetKeyboardState(BYTE *lpKeyState)
477 {
478     dprintf_key(stddeb, "SetKeyboardState()\n");
479     if (lpKeyState != NULL) {
480         memcpy(QueueKeyStateTable, lpKeyState, 256);
481         MouseButtonsStates[0] = QueueKeyStateTable[VK_LBUTTON]? 0x8000: 0;
482         MouseButtonsStates[1] = QueueKeyStateTable[VK_MBUTTON]? 0x8000: 0;
483         MouseButtonsStates[2] = QueueKeyStateTable[VK_RBUTTON]? 0x8000: 0;
484     }
485 }
486
487 /**********************************************************************
488  *            GetAsyncKeyState        (USER.249)
489  *
490  *      Determine if a key is or was pressed.  retval has high-order 
491  * bit set to 1 if currently pressed, low-order bit set to 1 if key has
492  * been pressed.
493  *
494  *      This uses the variable AsyncMouseButtonsStates and
495  * AsyncKeyStateTable (set in event.c) which have the mouse button
496  * number or key number (whichever is applicable) set to true if the
497  * mouse or key had been depressed since the last call to 
498  * GetAsyncKeyState.
499  */
500 int GetAsyncKeyState(int nKey)
501 {
502     short retval;       
503
504     switch (nKey) {
505      case VK_LBUTTON:
506         retval = AsyncMouseButtonsStates[0] | 
507         MouseButtonsStates[0]? 0x0001: 0;
508         break;
509      case VK_MBUTTON:
510         retval = AsyncMouseButtonsStates[1] |
511         MouseButtonsStates[1]? 0x0001: 0;
512         break;
513      case VK_RBUTTON:
514         retval = AsyncMouseButtonsStates[2] |
515         MouseButtonsStates[2]? 0x0001: 0;
516         break;
517      default:
518         retval = AsyncKeyStateTable[nKey] | 
519         (InputKeyStateTable[nKey] ? 0x8000 : 0);
520         break;
521     }
522
523     memset( AsyncMouseButtonsStates, 0, 3 );  /* all states to false */
524     memset( AsyncKeyStateTable, 0, 256 );
525
526     dprintf_key(stddeb, "GetAsyncKeyState(%x) -> %x\n", nKey, retval);
527     return retval;
528 }
529
530
531 /**********************************************************************
532  *                      TranslateAccelerator    [USER.178]
533  *
534  * FIXME: should send some WM_INITMENU or/and WM_INITMENUPOPUP  -messages
535  */
536 INT16 TranslateAccelerator(HWND hWnd, HACCEL16 hAccel, LPMSG16 msg)
537 {
538     ACCELHEADER *lpAccelTbl;
539     int         i;
540     BOOL sendmsg;
541     
542     if (hAccel == 0 || msg == NULL) return 0;
543     if (msg->message != WM_KEYDOWN &&
544         msg->message != WM_KEYUP &&
545         msg->message != WM_SYSKEYDOWN &&
546         msg->message != WM_SYSKEYUP &&
547         msg->message != WM_CHAR) return 0;
548
549     dprintf_accel(stddeb, "TranslateAccelerators hAccel=%04x, hWnd=%04x,\
550 msg->hwnd=%04x, msg->message=%04x\n", hAccel,hWnd,msg->hwnd,msg->message);
551
552     lpAccelTbl = (LPACCELHEADER)GlobalLock16(hAccel);
553     for (sendmsg= i = 0; i < lpAccelTbl->wCount; i++) 
554     {
555      if(msg->wParam == lpAccelTbl->tbl[i].wEvent) 
556      {
557       if (msg->message == WM_CHAR) 
558       {
559         if ( !(lpAccelTbl->tbl[i].type & ALT_ACCEL) && 
560              !(lpAccelTbl->tbl[i].type & VIRTKEY_ACCEL) )
561         {
562           dprintf_accel(stddeb,"found accel for WM_CHAR: ('%c')",msg->wParam&0xff);
563           sendmsg=TRUE;
564         }  
565       }
566       else
567       {
568        if(lpAccelTbl->tbl[i].type & VIRTKEY_ACCEL) 
569        {
570         INT mask = 0;
571         dprintf_accel(stddeb,"found accel for virt_key %04x (scan %04x)",
572                                msg->wParam,0xff & HIWORD(msg->lParam));                
573         if(GetKeyState(VK_SHIFT) & 0x8000) mask |= SHIFT_ACCEL;
574         if(GetKeyState(VK_CONTROL) & 0x8000) mask |= CONTROL_ACCEL;
575         if(GetKeyState(VK_MENU) & 0x8000) mask |= ALT_ACCEL;
576         if(mask == (lpAccelTbl->tbl[i].type &
577                             (SHIFT_ACCEL | CONTROL_ACCEL | ALT_ACCEL)))
578           sendmsg=TRUE;                     
579         else
580           dprintf_accel(stddeb,", but incorrect SHIFT/CTRL/ALT-state\n");
581        }
582        else
583        {
584          if (!(msg->lParam & 0x01000000))  /* no special_key */
585          {
586            if ((lpAccelTbl->tbl[i].type & ALT_ACCEL) && (msg->lParam & 0x20000000))
587            {                                                   /* ^^ ALT pressed */
588             dprintf_accel(stddeb,"found accel for Alt-%c", msg->wParam&0xff);
589             sendmsg=TRUE;           
590            } 
591          } 
592        }
593       } 
594
595       if (sendmsg)      /* found an accelerator, but send a message... ? */
596       {
597         INT16  iSysStat,iStat,mesg=0;
598         HMENU16 hSysMenu,hMenu;
599         
600         if (msg->message == WM_KEYUP || msg->message == WM_SYSKEYUP)
601           mesg=1;
602         else 
603          if (GetCapture16())
604            mesg=2;
605          else
606           if (!IsWindowEnabled16(hWnd))
607             mesg=3;
608           else
609           {
610             hMenu=GetMenu32(hWnd);
611             hSysMenu=GetSystemMenu32(hWnd,FALSE);
612             if (hSysMenu)
613               iSysStat=GetMenuState32(hSysMenu,lpAccelTbl->tbl[i].wIDval,MF_BYCOMMAND);
614             else
615               iSysStat=-1;
616             if (hMenu)
617               iStat=GetMenuState32(hMenu,lpAccelTbl->tbl[i].wIDval,MF_BYCOMMAND);
618             else
619               iStat=-1;
620             if (iSysStat!=-1)
621             {
622               if (iSysStat & (MF_DISABLED|MF_GRAYED))
623                 mesg=4;
624               else
625                 mesg=WM_SYSCOMMAND;
626             }
627             else
628             {
629               if (iStat!=-1)
630               {
631                 if (IsIconic32(hWnd))
632                   mesg=5;
633                 else
634                 {
635                  if (iStat & (MF_DISABLED|MF_GRAYED))
636                    mesg=6;
637                  else
638                    mesg=WM_COMMAND;  
639                 }   
640               }
641               else
642                mesg=WM_COMMAND;  
643             }
644           }
645           if ( mesg==WM_COMMAND || mesg==WM_SYSCOMMAND )
646           {
647               dprintf_accel(stddeb,", sending %s, wParam=%0x\n",
648                   mesg==WM_COMMAND ? "WM_COMMAND" : "WM_SYSCOMMAND",
649                   lpAccelTbl->tbl[i].wIDval);
650               SendMessage16(hWnd, mesg, lpAccelTbl->tbl[i].wIDval,0x00010000L);
651           }
652           else
653           {
654            /*  some reasons for NOT sending the WM_{SYS}COMMAND message: 
655             *   #0: unknown (please report!)
656             *   #1: for WM_KEYUP,WM_SYSKEYUP
657             *   #2: mouse is captured
658             *   #3: window is disabled 
659             *   #4: it's a disabled system menu option
660             *   #5: it's a menu option, but window is iconic
661             *   #6: it's a menu option, but disabled
662             */
663             dprintf_accel(stddeb,", but won't send WM_{SYS}COMMAND, reason is #%d\n",mesg);
664           }          
665           GlobalUnlock16(hAccel);
666           return 1;         
667       }
668      }
669     }
670     GlobalUnlock16(hAccel);
671     return 0;
672 }
673
674
675 DWORD OemKeyScan(WORD wOemChar)
676 {
677     dprintf_keyboard(stddeb,"*OemKeyScan (%d)\n",wOemChar);
678
679     return wOemChar;
680 }
681
682 /* VkKeyScan translates an ANSI character to a virtual-key and shift code
683  * for the current keyboard.
684  * FIXME high-order byte should yield :
685  *      0       Unshifted
686  *      1       Shift
687  *      2       Ctrl
688  *      3-5     Shift-key combinations that are not used for characters
689  *      6       Ctrl-Alt
690  *      7       Ctrl-Alt-Shift
691  *      I.e. :  Shift = 1, Ctrl = 2, Alt = 4.
692  */
693
694 WORD VkKeyScan(WORD cChar)
695 {
696         KeyCode keycode;
697         dprintf_keyboard(stddeb,"VkKeyScan '%c'(%d) ",cChar,cChar);
698         
699 /* let's do this : char = keysym (for ANSI chars) -> keyc [ + shift ... (?? how ??)]
700 keyc -> (keyc2vkey) vkey */
701
702         keycode = XKeysymToKeycode(display, cChar & 0xFF);
703         
704         dprintf_keyboard(stddeb," ... got keycode 0x%x ... returning 0x%x\n",
705                          keycode,keyc2vkey[keycode]);
706         return keyc2vkey[keycode];
707 }
708
709 WORD VkKeyScan32W(WORD cChar)
710 {
711         /* lower part of cChar is used anyway */
712         return VkKeyScan(cChar);
713 }
714
715 int GetKeyboardType(int nTypeFlag)
716 {
717   dprintf_keyboard(stddeb,"GetKeyboardType(%d)\n",nTypeFlag);
718   switch(nTypeFlag)
719     {
720     case 0:      /* Keyboard type */
721       return 4;    /* AT-101 */
722       break;
723     case 1:      /* Keyboard Subtype */
724       return 0;    /* There are no defined subtypes */
725       break;
726     case 2:      /* Number of F-keys */
727       return 12;   /* We're doing an 101 for now, so return 12 F-keys */
728       break;
729     default:     
730       fprintf(stderr, "Unknown type on GetKeyboardType\n");
731       return 0;    /* The book says 0 here, so 0 */
732     }
733 }
734
735 /* MapVirtualKey translates keycodes from one format to another. */
736
737 WORD MapVirtualKey(WORD wCode, WORD wMapType)
738 {
739 #define returnMVK(value) { dprintf_keyboard(stddeb,"returning 0x%x.\n",value); return value; }
740
741         dprintf_keyboard(stddeb,"MapVirtualKey wCode=0x%x wMapType=%d ... ",wCode,wMapType);
742         switch(wMapType) {
743                 case 0: { /* vkey-code to scan-code */
744                         /* let's do vkey -> keycode -> scan */
745                         KeyCode keyc;
746                         for (keyc=min_keycode; keyc<=max_keycode; keyc++) /* see event.c */
747                                 if ((keyc2vkey[keyc] & 0xFF)== wCode)
748                                         returnMVK (keyc - 8);
749                         return 0; }
750
751                 case 1: /* scan-code to vkey-code */
752                         /* let's do scan -> keycode -> vkey */
753
754                         returnMVK (keyc2vkey[(wCode & 0xFF) + 8]);
755
756                 case 2: { /* vkey-code to unshifted ANSI code */
757                         /* (was FIXME) : what does unshifted mean ? 'a' or 'A' ? */
758                         /* My Windows returns 'A'. */
759                         /* let's do vkey -> keycode -> (XLookupString) ansi char */
760                         XKeyEvent e;
761                         KeySym keysym;
762                         char s[2];
763                         e.display = display;
764                         e.state = 0; /* unshifted */
765                         e.keycode = MapVirtualKey( wCode, 0);
766                         if (!XLookupString(&e, s , 2 , &keysym, NULL))
767                           returnMVK (*s);
768                         
769                         return 0;
770                         }
771                 default: /* reserved */
772                         fprintf(stderr, "MapVirtualKey: unknown wMapType %d !\n",
773                                 wMapType);
774                         return 0;       
775         }
776         return 0;
777 }
778
779 int GetKbCodePage(void)
780 {
781         dprintf_keyboard(stddeb,"GetKbCodePage()\n");
782         return 850;
783 }
784
785 /****************************************************************************
786  *      GetKeyNameText32W   (USER32.247)
787  */
788 INT32 GetKeyNameText32W(LONG lParam, LPWSTR lpBuffer, INT32 nSize)
789 {
790         LPSTR buf = xmalloc(nSize);
791         int     res = GetKeyNameText32A(lParam,buf,nSize);
792
793         lstrcpynAtoW(lpBuffer,buf,nSize);
794         free(buf);
795         return res;
796 }
797
798 /****************************************************************************
799  *      GetKeyNameText32A   (USER32.246)
800  */
801 INT32 GetKeyNameText32A(LONG lParam, LPSTR lpBuffer, INT32 nSize)
802 {
803         return GetKeyNameText16(lParam,lpBuffer,nSize);
804 }
805
806 /****************************************************************************
807  *      GetKeyNameText16   (KEYBOARD.133)
808  */
809 INT16 GetKeyNameText16(LONG lParam, LPSTR lpBuffer, INT16 nSize)
810 {
811   /*    int i; */
812         
813         dprintf_keyboard(stddeb,"GetKeyNameText(%ld,<ptr>,%d)\n",lParam,nSize);
814
815         lParam >>= 16;
816         lParam &= 0xff;
817
818         /*      for (i = 0 ; i != KeyTableSize ; i++) 
819                 if (KeyTable[i].scancode == lParam)  {
820                         lstrcpyn32A( lpBuffer, KeyTable[i].name, nSize );
821                         return strlen(lpBuffer);
822                 }
823                 */
824         /* FIXME ! GetKeyNameText is still to do...
825  */
826         *lpBuffer = 0;
827         return 0;
828 }
829
830 int ToAscii(WORD wVirtKey, WORD wScanCode, LPSTR lpKeyState, 
831         LPVOID lpChar, WORD wFlags) 
832 {
833     XKeyEvent e;
834     KeySym keysym;
835     static XComposeStatus cs;
836     int ret;
837     WORD keyc;
838
839     e.display = display;
840     e.keycode = 0;
841     for (keyc=min_keycode; keyc<=max_keycode; keyc++)
842       { /* this could be speeded up by making another table, an array of struct vkey,keycode
843          * (vkey -> keycode) with vkeys sorted .... but it takes memory (512*3 bytes)!  DF */
844         if ((keyc2vkey[keyc] & 0xFF)== wVirtKey) /* no need to make a more precise test (with the extended bit correctly set above wVirtKey ... VK* are different enough... */
845           {
846             if ((e.keycode) && ((wVirtKey<0x10) || (wVirtKey>0x12))) 
847                 /* it's normal to have 2 shift, control, and alt ! */
848                 dprintf_keyboard(stddeb,"ToAscii : The keycodes %X and %X are matching the same vkey %X\n",
849                                  e.keycode,keyc,wVirtKey);
850             e.keycode = keyc;
851           }
852       }
853     if ((!e.keycode) && (lpKeyState[VK_NUMLOCK] & 0x01)) 
854       {
855         if ((wVirtKey>=VK_NUMPAD0) && (wVirtKey<=VK_NUMPAD9))
856           e.keycode = XKeysymToKeycode(e.display, wVirtKey-VK_NUMPAD0+XK_KP_0);
857         if (wVirtKey==VK_DECIMAL)
858           e.keycode = XKeysymToKeycode(e.display, XK_KP_Decimal);
859       }
860     if (!e.keycode)
861       {
862         fprintf(stderr,"ToAscii : Unknown virtual key %X !!! \n",wVirtKey);
863         return wVirtKey; /* whatever */
864       }
865     e.state = 0;
866     if (lpKeyState[VK_SHIFT] & 0x80)
867         e.state |= ShiftMask;
868     dprintf_keyboard(stddeb,"ToAscii : lpKeyState[0x14(VK_CAPITAL)]=%#x\n",lpKeyState[VK_CAPITAL]);
869     if (lpKeyState[VK_CAPITAL] & 0x01)
870         e.state |= LockMask;
871     if (lpKeyState[VK_CONTROL] & 0x80)
872         if (lpKeyState[VK_MENU] & 0x80)
873             e.state |= AltGrMask;
874         else
875             e.state |= ControlMask;
876     if (lpKeyState[VK_NUMLOCK] & 0x01)
877         e.state |= NumLockMask;
878     dprintf_key(stddeb, "ToAscii(%04X, %04X) : faked state = %X\n",
879                 wVirtKey, wScanCode, e.state);
880     ret = XLookupString(&e, lpChar, 2, &keysym, &cs);
881     if (ret == 0)
882         {
883         BYTE dead_char = 0;
884
885         ((char*)lpChar)[1] = '\0';
886         switch (keysym)
887             {
888             case XK_dead_tilde :
889             case 0x1000FE7E : /* Xfree's XK_Dtilde */
890                 dead_char = '~';
891                 break;
892             case XK_dead_acute :
893             case 0x1000FE27 : /* Xfree's XK_Dacute_accent */
894                 dead_char = 0xb4;
895                 break;
896             case XK_dead_circumflex :
897             case 0x1000FE5E : /* Xfree's XK_Dcircumflex_accent */
898                 dead_char = '^';
899                 break;
900             case XK_dead_grave :
901             case 0x1000FE60 : /* Xfree's XK_Dgrave_accent */
902                 dead_char = '`';
903                 break;
904             case XK_dead_diaeresis :
905             case 0x1000FE22 : /* Xfree's XK_Ddiaeresis */
906                 dead_char = 0xa8;
907                 break;
908             }
909         if (dead_char)
910             {
911             *(char*)lpChar = dead_char;
912             ret = -1;
913             }
914         else
915             {
916             char        *ksname;
917
918             ksname = XKeysymToString(keysym);
919             if (!ksname)
920                 ksname = "No Name";
921             if ((keysym >> 8) != 0xff)
922                 {
923                 fprintf(stderr, "Please report : no char for keysym %04lX (%s) :\n",
924                         keysym, ksname);
925                 fprintf(stderr, "  wVirtKey = %X, wScanCode = %X, keycode = %X, state = %X\n",
926                         wVirtKey, wScanCode, e.keycode, e.state);
927                 }
928             }
929         }
930     dprintf_key(stddeb, "ToAscii about to return %d with char %x\n",
931                 ret, *(char*)lpChar);
932     return ret;
933 }