Moved code to the X11 driver.
[wine] / windows / x11drv / keyboard.c
1 /*
2  * X11 keyboard driver
3  *
4  * Copyright 1993 Bob Amstadt
5  * Copyright 1996 Albrecht Kleine 
6  * Copyright 1997 David Faure
7  * Copyright 1998 Morten Welinder
8  * Copyright 1998 Ulrich Weigand
9  * Copyright 1999 Ove Kåven
10  */
11
12 #include "config.h"
13
14 #ifndef X_DISPLAY_MISSING
15
16 #include <ctype.h>
17 #include <X11/Xatom.h>
18 #include <X11/keysym.h>
19 #include "ts_xlib.h"
20 #include "ts_xresource.h"
21 #include "ts_xutil.h"
22
23 #include "wine/winuser16.h"
24 #include "dinput.h"
25 #include "debugtools.h"
26 #include "keyboard.h"
27 #include "message.h"
28 #include "windef.h"
29 #include "winnls.h"
30 #include "x11drv.h"
31
32 DECLARE_DEBUG_CHANNEL(key)
33 DECLARE_DEBUG_CHANNEL(keyboard)
34 DECLARE_DEBUG_CHANNEL(x11drv)
35
36 extern BYTE InputKeyStateTable[256];
37
38 extern LPBYTE pKeyStateTable;
39
40 int min_keycode, max_keycode, keysyms_per_keycode;
41 WORD keyc2vkey[256], keyc2scan[256];
42
43 static int NumLockMask, AltGrMask; /* mask in the XKeyEvent state */
44 static int kcControl, kcAlt, kcShift, kcNumLock, kcCapsLock; /* keycodes */
45
46 static char KEYBOARD_MapDeadKeysym(KeySym keysym);
47
48 /* Keyboard translation tables */
49 #define MAIN_LEN 48
50 static const int main_key_scan[MAIN_LEN] =
51 {
52 /* this is my (102-key) keyboard layout, sorry if it doesn't quite match yours */
53    0x29,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,
54    0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,
55    0x1E,0x1F,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x2B,
56    0x2C,0x2D,0x2E,0x2F,0x30,0x31,0x32,0x33,0x34,0x35,
57    0x56 /* the 102nd key (actually to the right of l-shift) */
58 };
59
60 /*** DEFINE YOUR NEW LANGUAGE-SPECIFIC MAPPINGS BELOW, SEE EXISTING TABLES */
61
62 /* the VK mappings for the main keyboard will be auto-assigned as before,
63    so what we have here is just the character tables */
64 /* order: Normal, Shift, AltGr, Shift-AltGr */
65 /* We recommend you write just what is guaranteed to be correct (i.e. what's
66    written on the keycaps), not the bunch of special characters behind AltGr
67    and Shift-AltGr if it can vary among different X servers */
68 /* Remember that your 102nd key (to the right of l-shift) should be on a
69    separate line, see existing tables */
70 /* If Wine fails to match your new table, use -debugmsg +key to find out why */
71 /* Remember to also add your new table to the layout index table far below! */
72
73 /*** United States keyboard layout (mostly contributed by Uwe Bonnes) */
74 static const char main_key_US[MAIN_LEN][4] =
75 {
76  "`~","1!","2@","3#","4$","5%","6^","7&","8*","9(","0)","-_","=+",
77  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","[{","]}",
78  "aA","sS","dD","fF","gG","hH","jJ","kK","lL",";:","'\"","\\|",
79  "zZ","xX","cC","vV","bB","nN","mM",",<",".>","/?"
80 };
81
82 /*** British keyboard layout */
83 static const char main_key_UK[MAIN_LEN][4] =
84 {
85  "`","1!","2\"","3£","4$","5%","6^","7&","8*","9(","0)","-_","=+",
86  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","[{","]}",
87  "aA","sS","dD","fF","gG","hH","jJ","kK","lL",";:","'@","#~",
88  "zZ","xX","cC","vV","bB","nN","mM",",<",".>","/?",
89  "\\|"
90 };
91
92 /*** French keyboard layout (contributed by Eric Pouech) */
93 static const char main_key_FR[MAIN_LEN][4] =
94 {
95  "²","&1","é2~","\"3#","'4{","(5[","-6|","è7","_8\\","ç9^±","à0@",")°]","=+}",
96  "aA","zZ","eE","rR","tT","yY","uU","iI","oO","pP","^¨","$£¤",
97  "qQ","sSß","dD","fF","gG","hH","jJ","kK","lL","mM","ù%","*µ",
98  "wW","xX","cC","vV","bB","nN",",?",";.",":/","!§",
99  "<>"
100 };
101
102 /*** Icelandic keyboard layout (contributed by Ríkharður Egilsson) */
103 static const char main_key_IS[MAIN_LEN][4] =
104 {
105  "°","1!","2\"","3#","4$","5%","6&","7/{","8([","9)]","0=}","öÖ\\","-_",
106  "qQ@","wW","eE","rR","tT","yY","uU","iI","oO","pP","ðÐ","'?~",
107  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","æÆ","´^","+*`",
108  "zZ","xX","cC","vV","bB","nN","mM",",;",".:","þÞ",
109  "<>|"
110 };
111
112 /*** German keyboard layout (contributed by Ulrich Weigand) */
113 static const char main_key_DE[MAIN_LEN][4] =
114 {
115  "^°","1!","2\"","3§","4$","5%","6&","7/{","8([","9)]","0=}","ß?\\","'",
116  "qQ","wW","eE","rR","tT","zZ","uU","iI","oO","pP","üÜ","+*~",
117  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","öÖ","äÄ","#´",
118  "yY","xX","cC","vV","bB","nN","mM",",;",".:","-_",
119  "<>"
120 };
121
122 /*** Swiss German keyboard layout (contributed by Jonathan Naylor) */
123 static const char main_key_SG[MAIN_LEN][4] =
124 {
125  "§°","1+|","2\"@","3*#","4ç","5%","6&¬","7/¦","8(¢","9)","0=","'?´","^`~",
126  "qQ","wW","eE","rR","tT","zZ","uU","iI","oO","pP","üè[","¨!]",
127  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","öé","äà{","$£}",
128  "yY","xX","cC","vV","bB","nN","mM",",;",".:","-_",
129  "<>\\"
130 };
131
132 /*** Swiss French keyboard layout (contributed by Philippe Froidevaux) */
133 static const char main_key_SF[MAIN_LEN][4] =
134 {
135  "§°","1+|","2\"@","3*#","4ç","5%","6&¬","7/¦","8(¢","9)","0=","'?´","^`~",
136  "qQ","wW","eE","rR","tT","zZ","uU","iI","oO","pP","èü[","¨!]",
137  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","éö","àä{","$£}",
138  "yY","xX","cC","vV","bB","nN","mM",",;",".:","-_",
139  "<>\\"
140 };
141
142 /*** Norwegian keyboard layout (contributed by Ove Kåven) */
143 static const char main_key_NO[MAIN_LEN][4] =
144 {
145  "|§","1!","2\"@","3#£","4¤$","5%","6&","7/{","8([","9)]","0=}","+?","\\`´",
146  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","åÅ","¨^~",
147  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","øØ","æÆ","'*",
148  "zZ","xX","cC","vV","bB","nN","mM",",;",".:","-_",
149  "<>"
150 };
151
152 /*** Danish keyboard layout (contributed by Bertho Stultiens) */
153 static const char main_key_DA[MAIN_LEN][4] =
154 {
155  "½§","1!","2\"@","3#£","4¤$","5%","6&","7/{","8([","9)]","0=}","+?","´`|",
156  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","åÅ","¨^~",
157  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","æÆ","øØ","'*",
158  "zZ","xX","cC","vV","bB","nN","mM",",;",".:","-_",
159  "<>\\"
160 };
161
162 /*** Swedish keyboard layout (contributed by Peter Bortas) */
163 static const char main_key_SE[MAIN_LEN][4] =
164 {
165  "§½","1!","2\"@","3#£","4¤$","5%","6&","7/{","8([","9)]","0=}","+?\\","´`",
166  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","åÅ","¨^~",
167  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","öÖ","äÄ","'*",
168  "zZ","xX","cC","vV","bB","nN","mM",",;",".:","-_",
169  "<>|"
170 };
171
172 /*** Canadian French keyboard layout */
173 static const char main_key_CF[MAIN_LEN][4] =
174 {
175  "#|\\","1!±","2\"@","3/£","4$¢","5%¤","6?¬","7&¦","8*²","9(³","0)³","-_½","=+¾",
176  "qQ","wW","eE","rR","tT","yY","uU","iI","oO§","pP¶","^^[","¨]",
177  "aA","sS","dD","fF","gG","hH","jJ","kK","lL",";:~","``{","<>}",
178  "zZ","xX","cC","vV","bB","nN","mM",",'_",".","éÉ",
179  "«»°"
180 };
181
182 /*** Portuguese keyboard layout */
183 static const char main_key_PT[MAIN_LEN][4] =
184 {
185  "\\¦","1!","2\"@","3#£","4$§","5%","6&","7/{","8([","9)]","0=}","'?","«»",
186  "qQ",  "wW","eE",  "rR", "tT", "yY", "uU", "iI", "oO", "pP", "+*\\¨","\\'\\`",
187  "aA",  "sS","dD",  "fF", "gG", "hH", "jJ", "kK", "lL", "çÇ", "ºª", "\\~\\^",
188  "zZ",  "xX","cC",  "vV", "bB", "nN", "mM", ",;", ".:", "-_",
189  "<>"
190 };
191
192 /*** Italian keyboard layout */
193 static const char main_key_IT[MAIN_LEN][4] =
194 {
195  "\\|","1!1","2\"2","3?3","4$","5%½","6&¾","7/{","8([","9)]","0=}","'?`","i^~",
196  "qQ@","wW","eE","rR?","tT","yY","uU","iI","oOo","pP?","ee[","+*]",
197  "aAae","sS?","dD?","fF","gG","hH","jJ","kK","lL","oc@","a?#","u?",
198  "zZ<","xX>","cC","vV","bB","nN","mM?",",;",".:*","-_","<>|"
199 };
200
201 /*** Finnish keyboard layout */
202 static const char main_key_FI[MAIN_LEN][4] =
203 {
204  "","1!","2\"@","3#","4$","5%","6&","7/{","8([","9)]","0=}","+?\\","\'`",
205  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","","\"^~",
206  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","","","'*",
207  "zZ","xX","cC","vV","bB","nN","mM",",;",".:","-_",
208  "<>|"
209 };
210
211 /*** Russian keyboard layout (contributed by Pavel Roskin) */
212 static const char main_key_RU[MAIN_LEN][4] =
213 {
214  "`~","1!","2@","3#","4$","5%","6^","7&","8*","9(","0)","-_","=+",
215  "qQÊê","wWÃã","eEÕõ","rRËë","tTÅå","yYÎî","uUÇç","iIÛû","oOÝý","pPÚú","[{Èè","]}ßÿ",
216  "aAÆæ","sSÙù","dD×÷","fFÁá","gGÐð","hHÒò","jJÏï","kKÌì","lLÄä",";:Öö","'\"Üü","\\|",
217  "zZÑñ","xXÞþ","cCÓó","vVÍí","bBÉé","nNÔô","mMØø",",<Ââ",".>Àà","/?"
218 };
219
220 /*** Spanish keyboard layout (contributed by José Marcos López) */
221 static const char main_key_ES[MAIN_LEN][4] =
222 {
223  "ºª\\","1!|","2\"@","3·#","4$","5%","6&¬","7/","8(","9)","0=","'?","¡¿",
224  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","`^[","+*]",
225  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","ñÑ","'¨{","çÇ}",
226  "zZ","xX","cC","vV","bB","nN","mM",",;",".:","-_",
227  "<>"
228 };
229
230 /*** Belgian keyboard layout ***/
231 static const char main_key_BE[MAIN_LEN][4] =
232 {
233  "","&1|","é2@","\"3#","'4","(5","§6^","è7","!8","ç9{","à0}",")°","-_",
234  "aA","zZ","eE¤","rR","tT","yY","uU","iI","oO","pP","^¨[","$*]",
235  "qQ","sSß","dD","fF","gG","hH","jJ","kK","lL","mM","ù%´","µ£`",
236  "wW","xX","cC","vV","bB","nN",",?",";.",":/","=+~",
237  "<>\\"
238 };
239
240 /*** Layout table. Add your keyboard mappings to this list */
241 static struct {
242  WORD lang, ansi_codepage, oem_codepage;
243  const char (*key)[MAIN_LEN][4];
244 } main_key_tab[]={
245  {MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),     1252, 437, &main_key_US},
246  {MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_UK),     1252, 850, &main_key_UK},
247  {MAKELANGID(LANG_GERMAN,SUBLANG_DEFAULT),         1252, 850, &main_key_DE},
248  {MAKELANGID(LANG_GERMAN,SUBLANG_GERMAN_SWISS),    1252, 850, &main_key_SG},
249  {MAKELANGID(LANG_SWEDISH,SUBLANG_SWEDISH),        1252, 850, &main_key_SE},
250  {MAKELANGID(LANG_NORWEGIAN,SUBLANG_DEFAULT),      1252, 865, &main_key_NO},
251  {MAKELANGID(LANG_DANISH,SUBLANG_DEFAULT),         1252, 865, &main_key_DA},
252  {MAKELANGID(LANG_FRENCH,SUBLANG_DEFAULT),         1252, 850, &main_key_FR},
253  {MAKELANGID(LANG_FRENCH,SUBLANG_FRENCH_CANADIAN), 1252, 863, &main_key_CF},
254  {MAKELANGID(LANG_FRENCH,SUBLANG_FRENCH_BELGIAN),  1252, 850, &main_key_BE},
255  {MAKELANGID(LANG_FRENCH,SUBLANG_FRENCH_SWISS),    1252, 850, &main_key_SF},
256  {MAKELANGID(LANG_WALON,SUBLANG_DEFAULT),          1252, 850, &main_key_BE},
257  {MAKELANGID(LANG_PORTUGUESE,SUBLANG_DEFAULT),     1252, 860, &main_key_PT},
258  {MAKELANGID(LANG_FINNISH,SUBLANG_DEFAULT),        1252, 850, &main_key_FI},
259  {MAKELANGID(LANG_RUSSIAN,SUBLANG_DEFAULT),        1251, 866, &main_key_RU},
260  {MAKELANGID(LANG_SPANISH,SUBLANG_DEFAULT),        1252, 850, &main_key_ES},
261  {MAKELANGID(LANG_DUTCH,SUBLANG_DUTCH_BELGIAN),    1252, 850, &main_key_BE},
262  {MAKELANGID(LANG_ITALIAN,SUBLANG_DEFAULT),        1252, 850, &main_key_IT},
263  {MAKELANGID(LANG_ICELANDIC,SUBLANG_DEFAULT),      1252, 850, &main_key_IS},
264
265  {0} /* sentinel */
266 };
267 static unsigned kbd_layout=0; /* index into above table of layouts */
268
269 /* maybe more of these scancodes should be extended? */
270                 /* extended must be set for ALT_R, CTRL_R,
271                    INS, DEL, HOME, END, PAGE_UP, PAGE_DOWN, ARROW keys,
272                    keypad / and keypad ENTER (SDK 3.1 Vol.3 p 138) */
273                 /* FIXME should we set extended bit for NumLock ? My
274                  * Windows does ... DF */
275 static const int special_key_vkey[] =
276 {
277     VK_BACK, VK_TAB, 0, VK_CLEAR, 0, VK_RETURN, 0, 0,           /* FF08 */
278     0, 0, 0, VK_PAUSE, VK_SCROLL, 0, 0, 0,                      /* FF10 */
279     0, 0, 0, VK_ESCAPE                                          /* FF18 */
280 };
281 static const int special_key_scan[] =
282 {
283     0x0E, 0x0F, 0, /*?*/ 0, 0, 0x1C, 0, 0,                      /* FF08 */
284     0,    0,    0, 0x45, 0x46, 0   , 0, 0,                      /* FF10 */
285     0,    0,    0, 0x01                                         /* FF18 */
286 };
287
288 static const int cursor_key_vkey[] =
289 {
290     VK_HOME, VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN, VK_PRIOR, 
291                                        VK_NEXT, VK_END          /* FF50 */
292 };
293 static const int cursor_key_scan[] =
294 {
295     0x147, 0x14B, 0x148, 0x14D, 0x150, 0x149, 0x151, 0x14F      /* FF50 */
296 };
297
298 static const int misc_key_vkey[] =
299 {
300     VK_SELECT, VK_SNAPSHOT, VK_EXECUTE, VK_INSERT, 0, 0, 0, 0,  /* FF60 */
301     VK_CANCEL, VK_HELP, VK_CANCEL, VK_MENU                      /* FF68 */
302 };
303 static const int misc_key_scan[] =
304 {
305     /*?*/ 0, 0x37, /*?*/ 0, 0x152, 0, 0, 0, 0,                  /* FF60 */
306     /*?*/ 0, /*?*/ 0, 0x38                                      /* FF68 */
307 };
308
309 static const int keypad_key_vkey[] =
310 {
311     0, VK_NUMLOCK,                                              /* FF7E */
312     0, 0, 0, 0, 0, 0, 0, 0,                                     /* FF80 */
313     0, 0, 0, 0, 0, VK_RETURN, 0, 0,                             /* FF88 */
314     0, 0, 0, 0, 0, VK_HOME, VK_LEFT, VK_UP,                     /* FF90 */
315     VK_RIGHT, VK_DOWN, VK_PRIOR, VK_NEXT, VK_END, 0,
316                                  VK_INSERT, VK_DELETE,          /* FF98 */
317     0, 0, 0, 0, 0, 0, 0, 0,                                     /* FFA0 */
318     0, 0, VK_MULTIPLY, VK_ADD, VK_SEPARATOR, VK_SUBTRACT, 
319                                VK_DECIMAL, VK_DIVIDE,           /* FFA8 */
320     VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4,
321                             VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, /* FFB0 */
322     VK_NUMPAD8, VK_NUMPAD9                                      /* FFB8 */
323 };
324 static const int keypad_key_scan[] =
325 {
326     0x138, 0x45,                                                /* FF7E */
327     0, 0, 0, 0, 0, 0, 0, 0,                                     /* FF80 */
328     0, 0, 0, 0, 0, 0x11C, 0, 0,                                 /* FF88 */
329     0, 0, 0, 0, 0, 0x47, 0x4B, 0x48,                            /* FF90 */
330     0x4D, 0x50, 0x49, 0x51, 0x4F, 0x4C, 0x52, 0x53,             /* FF98 */
331     0, 0, 0, 0, 0, 0, 0, 0,                                     /* FFA0 */
332     0, 0, 0x37, 0x4E, /*?*/ 0, 0x4A, 0x53, 0x135,               /* FFA8 */
333     0x52, 0x4F, 0x50, 0x51, 0x4B, 0x4C, 0x4D, 0x47,             /* FFB0 */
334     0x48, 0x49                                                  /* FFB8 */
335 };
336     
337 static const int function_key_vkey[] =
338 {
339     VK_F1, VK_F2,                                               /* FFBE */
340     VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_F10,    /* FFC0 */
341     VK_F11, VK_F12, VK_F13, VK_F14, VK_F15, VK_F16              /* FFC8 */
342 };
343 static const int function_key_scan[] =
344 {
345     0x3B, 0x3C,                                                 /* FFBE */
346     0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44,             /* FFC0 */
347     0x57, 0x58, 0, 0, 0, 0                                      /* FFC8 */
348 };
349
350 static const int modifier_key_vkey[] =
351 {
352     VK_SHIFT, VK_SHIFT, VK_CONTROL, VK_CONTROL, VK_CAPITAL, 0, /* FFE1 */
353     VK_MENU, VK_MENU, VK_MENU, VK_MENU                         /* FFE7 */
354 };
355 static const int modifier_key_scan[] =
356 {
357     0x2A, 0x36, 0x1D, 0x11D, 0x3A, 0,                          /* FFE1 */
358     0x38, 0x138, 0x38, 0x138                                   /* FFE7 */
359 };
360
361 /* Returns the Windows virtual key code associated with the X event <e> */
362 static WORD EVENT_event_to_vkey( XKeyEvent *e)
363 {
364     KeySym keysym;
365
366     TSXLookupString(e, NULL, 0, &keysym, NULL);
367
368     if ((keysym >= 0xFFAE) && (keysym <= 0xFFB9) && (keysym != 0xFFAF) 
369         && (e->state & NumLockMask)) 
370         /* Only the Keypad keys 0-9 and . send different keysyms
371          * depending on the NumLock state */
372         return keypad_key_vkey[(keysym & 0xFF) - 0x7E];
373
374     return keyc2vkey[e->keycode];
375 }
376
377 static BOOL NumState=FALSE, CapsState=FALSE;
378
379 /**********************************************************************
380  *              KEYBOARD_GenerateMsg
381  *
382  * Generate Down+Up messages when NumLock or CapsLock is pressed.
383  *
384  * Convention : called with vkey only VK_NUMLOCK or VK_CAPITAL
385  *
386  */
387 static void KEYBOARD_GenerateMsg( WORD vkey, WORD scan, int Evtype, INT event_x, INT event_y,
388                            DWORD event_time )
389 {
390   BOOL * State = (vkey==VK_NUMLOCK? &NumState : &CapsState);
391   DWORD up, down;
392
393   if (*State) {
394     /* The INTERMEDIARY state means : just after a 'press' event, if a 'release' event comes,
395        don't treat it. It's from the same key press. Then the state goes to ON.
396        And from there, a 'release' event will switch off the toggle key. */
397     *State=FALSE;
398     TRACE_(keyboard)("INTERM : don\'t treat release of toggle key. InputKeyStateTable[%#x] = %#x\n",vkey,pKeyStateTable[vkey]);
399   } else
400     {
401         down = (vkey==VK_NUMLOCK ? KEYEVENTF_EXTENDEDKEY : 0);
402         up = (vkey==VK_NUMLOCK ? KEYEVENTF_EXTENDEDKEY : 0) | KEYEVENTF_KEYUP;
403         if ( pKeyStateTable[vkey] & 0x1 ) /* it was ON */
404           {
405             if (Evtype!=KeyPress)
406               {
407                 TRACE_(keyboard)("ON + KeyRelease => generating DOWN and UP messages.\n");
408                 KEYBOARD_SendEvent( vkey, scan, down,
409                                     event_x, event_y, event_time );
410                 KEYBOARD_SendEvent( vkey, scan, up, 
411                                     event_x, event_y, event_time );
412                 *State=FALSE;
413                 pKeyStateTable[vkey] &= ~0x01; /* Toggle state to off. */ 
414               } 
415           }
416         else /* it was OFF */
417           if (Evtype==KeyPress)
418             {
419               TRACE_(keyboard)("OFF + Keypress => generating DOWN and UP messages.\n");
420               KEYBOARD_SendEvent( vkey, scan, down,
421                                   event_x, event_y, event_time );
422               KEYBOARD_SendEvent( vkey, scan, up, 
423                                   event_x, event_y, event_time );
424               *State=TRUE; /* Goes to intermediary state before going to ON */
425               pKeyStateTable[vkey] |= 0x01; /* Toggle state to on. */
426             }
427     }
428 }
429
430 /***********************************************************************
431  *           KEYBOARD_UpdateOneState
432  *
433  * Updates internal state for <vkey>, depending on key <state> under X
434  *
435  */
436 static void KEYBOARD_UpdateOneState ( int vkey, int state )
437 {
438     /* Do something if internal table state != X state for keycode */
439     if (((pKeyStateTable[vkey] & 0x80)!=0) != state)
440     {
441         TRACE_(keyboard)("Adjusting state for vkey %#.2x. State before %#.2x \n",
442               vkey, pKeyStateTable[vkey]);
443
444         /* Fake key being pressed inside wine */
445         KEYBOARD_SendEvent( vkey, 0, state? 0 : KEYEVENTF_KEYUP, 
446                             0, 0, GetTickCount() );
447
448         TRACE_(keyboard)("State after %#.2x \n",pKeyStateTable[vkey]);
449     }
450 }
451
452 /***********************************************************************
453  *           X11DRV_KEYBOARD_UpdateState
454  *
455  * Update modifiers state (Ctrl, Alt, Shift)
456  * when window is activated (called by EVENT_FocusIn in event.c)
457  *
458  * This handles the case where one uses Ctrl+... Alt+... or Shift+.. to switch
459  * from wine to another application and back.
460  * Toggle keys are handled in HandleEvent. (because XQueryKeymap says nothing
461  *  about them)
462  */
463 void X11DRV_KEYBOARD_UpdateState ( void )
464 {
465 /* extract a bit from the char[32] bit suite */
466 #define KeyState(keycode) ((keys_return[keycode/8] & (1<<(keycode%8)))!=0)
467
468     char keys_return[32];
469
470     TRACE_(keyboard)("called\n");
471     if (!TSXQueryKeymap(display, keys_return)) {
472         ERR_(keyboard)("Error getting keymap !");
473         return;
474     }
475
476     /* Adjust the ALT and CONTROL state if any has been changed outside wine */
477     KEYBOARD_UpdateOneState(VK_MENU, KeyState(kcAlt));
478     KEYBOARD_UpdateOneState(VK_CONTROL, KeyState(kcControl));
479     KEYBOARD_UpdateOneState(VK_SHIFT, KeyState(kcShift));
480 #undef KeyState
481 }
482
483 /***********************************************************************
484  *           X11DRV_KEYBOARD_HandleEvent
485  *
486  * Handle a X key event
487  */
488 void X11DRV_KEYBOARD_HandleEvent( WND *pWnd, XKeyEvent *event )
489 {
490     char Str[24]; 
491     XComposeStatus cs; 
492     KeySym keysym;
493     WORD vkey = 0, bScan;
494     DWORD dwFlags;
495     static BOOL force_extended = FALSE; /* hack for AltGr translation */
496     
497     int ascii_chars;
498
499     INT event_x = (pWnd? pWnd->rectWindow.left : 0) + event->x;
500     INT event_y = (pWnd? pWnd->rectWindow.top  : 0) + event->y;
501     DWORD event_time = event->time - MSG_WineStartTicks;
502
503     /* this allows support for dead keys */
504     if ((event->keycode >> 8) == 0x10)
505         event->keycode=(event->keycode & 0xff);
506
507     ascii_chars = TSXLookupString(event, Str, 1, &keysym, &cs);
508
509     TRACE_(key)("EVENT_key : state = %X\n", event->state);
510     if (keysym == XK_Mode_switch)
511         {
512         TRACE_(key)("Alt Gr key event received\n");
513         event->keycode = kcControl; /* Simulate Control */
514         X11DRV_KEYBOARD_HandleEvent( pWnd, event );
515
516         event->keycode = kcAlt; /* Simulate Alt */
517         force_extended = TRUE;
518         X11DRV_KEYBOARD_HandleEvent( pWnd, event );
519         force_extended = FALSE;
520         return;
521         }
522
523     Str[ascii_chars] = '\0';
524     if (TRACE_ON(key)){
525         char    *ksname;
526
527         ksname = TSXKeysymToString(keysym);
528         if (!ksname)
529           ksname = "No Name";
530         TRACE_(key)("%s : keysym=%lX (%s), ascii chars=%u / %X / '%s'\n", 
531                      (event->type == KeyPress) ? "KeyPress" : "KeyRelease",
532                      keysym, ksname, ascii_chars, Str[0] & 0xff, Str);
533     }
534
535     vkey = EVENT_event_to_vkey(event);
536     if (force_extended) vkey |= 0x100;
537
538     TRACE_(key)("keycode 0x%x converted to vkey 0x%x\n",
539                     event->keycode, vkey);
540
541    if (vkey)
542    {
543     switch (vkey & 0xff)
544     {
545     case VK_NUMLOCK:    
546       KEYBOARD_GenerateMsg( VK_NUMLOCK, 0x45, event->type, event_x, event_y,
547                             event_time );
548       break;
549     case VK_CAPITAL:
550       TRACE_(keyboard)("Caps Lock event. (type %d). State before : %#.2x\n",event->type,pKeyStateTable[vkey]);
551       KEYBOARD_GenerateMsg( VK_CAPITAL, 0x3A, event->type, event_x, event_y,
552                             event_time ); 
553       TRACE_(keyboard)("State after : %#.2x\n",pKeyStateTable[vkey]);
554       break;
555     default:
556         /* Adjust the NUMLOCK state if it has been changed outside wine */
557         if (!(pKeyStateTable[VK_NUMLOCK] & 0x01) != !(event->state & NumLockMask))
558           { 
559             TRACE_(keyboard)("Adjusting NumLock state. \n");
560             KEYBOARD_GenerateMsg( VK_NUMLOCK, 0x45, KeyPress, event_x, event_y,
561                                   event_time );
562             KEYBOARD_GenerateMsg( VK_NUMLOCK, 0x45, KeyRelease, event_x, event_y,
563                                   event_time );
564           }
565         /* Adjust the CAPSLOCK state if it has been changed outside wine */
566         if (!(pKeyStateTable[VK_CAPITAL] & 0x01) != !(event->state & LockMask))
567           {
568               TRACE_(keyboard)("Adjusting Caps Lock state.\n");
569             KEYBOARD_GenerateMsg( VK_CAPITAL, 0x3A, KeyPress, event_x, event_y,
570                                   event_time );
571             KEYBOARD_GenerateMsg( VK_CAPITAL, 0x3A, KeyRelease, event_x, event_y,
572                                   event_time );
573           }
574         /* Not Num nor Caps : end of intermediary states for both. */
575         NumState = FALSE;
576         CapsState = FALSE;
577
578         bScan = keyc2scan[event->keycode] & 0xFF;
579         TRACE_(key)("bScan = 0x%02x.\n", bScan);
580
581         dwFlags = 0;
582         if ( event->type == KeyRelease ) dwFlags |= KEYEVENTF_KEYUP;
583         if ( vkey & 0x100 )              dwFlags |= KEYEVENTF_EXTENDEDKEY;
584         if ( force_extended )            dwFlags |= KEYEVENTF_WINE_FORCEEXTENDED;
585
586         KEYBOARD_SendEvent( vkey & 0xff, bScan, dwFlags, 
587                             event_x, event_y, event_time );
588     }
589    }
590 }
591
592 /**********************************************************************
593  *              X11DRV_KEYBOARD_DetectLayout
594  *
595  * Called from X11DRV_KEYBOARD_Init
596  *  This routine walks through the defined keyboard layouts and selects
597  *  whichever matches most closely.
598  */
599 static void
600 X11DRV_KEYBOARD_DetectLayout (void)
601 {
602   unsigned current, match, mismatch, seq;
603   int score, keyc, i, key, pkey, ok, syms;
604   KeySym keysym;
605   const char (*lkey)[MAIN_LEN][4];
606   unsigned max_seq = 0;
607   int max_score = 0, ismatch = 0;
608   char ckey[4] =
609   {0, 0, 0, 0};
610
611   syms = keysyms_per_keycode;
612   if (syms > 4) {
613     WARN_(keyboard)("%d keysyms per keycode not supported, set to 4", syms);
614     syms = 4;
615   }
616   for (current = 0; main_key_tab[current].lang; current++) {
617     TRACE_(keyboard)("Attempting to match against layout %04x\n",
618            main_key_tab[current].lang);
619     match = 0;
620     mismatch = 0;
621     score = 0;
622     seq = 0;
623     lkey = main_key_tab[current].key;
624     pkey = -1;
625     for (keyc = min_keycode; keyc <= max_keycode; keyc++) {
626       /* get data for keycode from X server */
627       for (i = 0; i < syms; i++) {
628         keysym = TSXKeycodeToKeysym (display, keyc, i);
629         /* Allow both one-byte and two-byte national keysyms */
630         if ((keysym < 0x800) && (keysym != ' '))
631           ckey[i] = keysym & 0xFF;
632         else {
633           ckey[i] = KEYBOARD_MapDeadKeysym(keysym);
634         }
635       }
636       if (ckey[0]) {
637         /* search for a match in layout table */
638         /* right now, we just find an absolute match for defined positions */
639         /* (undefined positions are ignored, so if it's defined as "3#" in */
640         /* the table, it's okay that the X server has "3#£", for example) */
641         /* however, the score will be higher for longer matches */
642         for (key = 0; key < MAIN_LEN; key++) {
643           for (ok = 0, i = 0; (ok >= 0) && (i < syms); i++) {
644             if ((*lkey)[key][i] && ((*lkey)[key][i] == ckey[i]))
645               ok++;
646             if ((*lkey)[key][i] && ((*lkey)[key][i] != ckey[i]))
647               ok = -1;
648           }
649           if (ok > 0) {
650             score += ok;
651             break;
652           }
653         }
654         /* count the matches and mismatches */
655         if (ok > 0) {
656           match++;
657           /* and how much the keycode order matches */
658           if (key > pkey) seq++;
659           pkey = key;
660         } else {
661           TRACE_(key)("mismatch for keycode %d, character %c\n", keyc,
662                  ckey[0]);
663           mismatch++;
664           score -= syms;
665         }
666       }
667     }
668     TRACE_(keyboard)("matches=%d, mismatches=%d, score=%d\n",
669            match, mismatch, score);
670     if ((score > max_score) ||
671         ((score == max_score) && (seq > max_seq))) {
672       /* best match so far */
673       kbd_layout = current;
674       max_score = score;
675       max_seq = seq;
676       ismatch = !mismatch;
677     }
678   }
679   /* we're done, report results if necessary */
680   if (!ismatch) {
681     FIXME_(keyboard)(
682            "Your keyboard layout was not found!\n"
683            "Instead using closest match (%04x) for scancode mapping.\n"
684            "Please define your layout in windows/x11drv/keyboard.c and submit them\n"
685            "to us for inclusion into future Wine releases.\n"
686            "See documentation/keyboard for more information.\n",
687            main_key_tab[kbd_layout].lang);
688   }
689   TRACE_(keyboard)("detected layout is %04x\n", main_key_tab[kbd_layout].lang);
690 }
691
692 /**********************************************************************
693  *              X11DRV_KEYBOARD_Init
694  */
695 void X11DRV_KEYBOARD_Init(void)
696 {
697     KeySym *ksp;
698     XModifierKeymap *mmp;
699     KeySym keysym;
700     KeyCode *kcp;
701     XKeyEvent e2;
702     WORD scan, vkey, OEMvkey;
703     int keyc, i, keyn, syms;
704     char ckey[4]={0,0,0,0};
705     const char (*lkey)[MAIN_LEN][4];
706
707     TSXDisplayKeycodes(display, &min_keycode, &max_keycode);
708     ksp = TSXGetKeyboardMapping(display, min_keycode,
709                               max_keycode + 1 - min_keycode, &keysyms_per_keycode);
710     /* We are only interested in keysyms_per_keycode.
711        There is no need to hold a local copy of the keysyms table */
712     TSXFree(ksp);
713     mmp = TSXGetModifierMapping(display);
714     kcp = mmp->modifiermap;
715     for (i = 0; i < 8; i += 1) /* There are 8 modifier keys */
716     {
717         int j;
718         
719         for (j = 0; j < mmp->max_keypermod; j += 1, kcp += 1)
720             if (*kcp)
721             {
722                 int k;
723                 
724                 for (k = 0; k < keysyms_per_keycode; k += 1)
725                     if (TSXKeycodeToKeysym(display, *kcp, k) == XK_Mode_switch)
726                     {
727                         AltGrMask = 1 << i;
728                         TRACE_(key)("AltGrMask is %x\n", AltGrMask);
729                     }
730                     else if (TSXKeycodeToKeysym(display, *kcp, k) == XK_Num_Lock)
731                     {
732                         NumLockMask = 1 << i;
733                         TRACE_(key)("NumLockMask is %x\n", NumLockMask);
734                     }
735             }
736     }
737     TSXFreeModifiermap(mmp);
738
739     /* Detect the keyboard layout */
740     X11DRV_KEYBOARD_DetectLayout();
741     lkey = main_key_tab[kbd_layout].key;
742     syms = (keysyms_per_keycode > 4) ? 4 : keysyms_per_keycode;
743
744     /* Now build two conversion arrays :
745      * keycode -> vkey + scancode + extended
746      * vkey + extended -> keycode */
747
748     e2.display = display;
749     e2.state = 0;
750
751     OEMvkey = VK_OEM_7; /* next is available.  */
752     for (keyc = min_keycode; keyc <= max_keycode; keyc++)
753     {
754         e2.keycode = (KeyCode)keyc;
755         TSXLookupString(&e2, NULL, 0, &keysym, NULL);
756         vkey = 0; scan = 0;
757         if (keysym)  /* otherwise, keycode not used */
758         {
759             if ((keysym >> 8) == 0xFF)         /* non-character key */
760             {
761                 int key = keysym & 0xff;
762                 
763                 if (key >= 0x08 && key <= 0x1B) {        /* special key */
764                     vkey = special_key_vkey[key - 0x08];
765                     scan = special_key_scan[key - 0x08];
766                 } else if (key >= 0x50 && key <= 0x57) { /* cursor key */
767                     vkey = cursor_key_vkey[key - 0x50];
768                     scan = cursor_key_scan[key - 0x50];
769                 } else if (key >= 0x60 && key <= 0x6B) { /* miscellaneous key */
770                     vkey = misc_key_vkey[key - 0x60];
771                     scan = misc_key_scan[key - 0x60];
772                 } else if (key >= 0x7E && key <= 0xB9) { /* keypad key */
773                     vkey = keypad_key_vkey[key - 0x7E];
774                     scan = keypad_key_scan[key - 0x7E];
775                 } else if (key >= 0xBE && key <= 0xCD) { /* function key */
776                     vkey = function_key_vkey[key - 0xBE] | 0x100; /* set extended bit */
777                     scan = function_key_scan[key - 0xBE];
778                 } else if (key >= 0xE1 && key <= 0xEA) { /* modifier key */
779                     vkey = modifier_key_vkey[key - 0xE1];
780                     scan = modifier_key_scan[key - 0xE1];
781                 } else if (key == 0xFF) {                /* DEL key */
782                     vkey = VK_DELETE;
783                     scan = 0x153;
784                 }
785                 /* set extended bit when necessary */
786                 if (scan & 0x100) vkey |= 0x100;
787             } else if (keysym == 0x20) {                 /* Spacebar */
788                 vkey = VK_SPACE;
789                 scan = 0x39;
790             } else {
791               /* we seem to need to search the layout-dependent scancodes */
792               int maxlen=0,maxval=-1,ok;
793               for (i=0; i<syms; i++) {
794                 keysym = TSXKeycodeToKeysym(display, keyc, i);
795                 if ((keysym<0x800) && (keysym!=' ')) {
796                   ckey[i] = keysym & 0xFF;
797                 } else {
798                   ckey[i] = KEYBOARD_MapDeadKeysym(keysym);
799                 }
800               }
801               /* find key with longest match streak */
802               for (keyn=0; keyn<MAIN_LEN; keyn++) {
803                 for (ok=(*lkey)[keyn][i=0]; ok&&(i<4); i++)
804                   if ((*lkey)[keyn][i] && (*lkey)[keyn][i]!=ckey[i]) ok=0;
805                 if (ok||(i>maxlen)) {
806                   maxlen=i; maxval=keyn;
807                 }
808                 if (ok) break;
809               }
810               if (maxval>=0) {
811                 /* got it */
812                 scan = main_key_scan[maxval];
813               }
814             }
815
816             /* find a suitable layout-dependent VK code */
817             /* (most Winelib apps ought to be able to work without layout tables!) */
818             for (i = 0; (i < keysyms_per_keycode) && (!vkey); i++)
819             {
820                 keysym = TSXLookupKeysym(&e2, i);
821                 if ((keysym >= VK_0 && keysym <= VK_9)
822                     || (keysym >= VK_A && keysym <= VK_Z)) {
823                     vkey = keysym;
824                 }
825             }
826
827             for (i = 0; (i < keysyms_per_keycode) && (!vkey); i++)
828             {
829                 keysym = TSXLookupKeysym(&e2, i);
830                 switch (keysym)
831                 {
832                 case ';':             vkey = VK_OEM_1; break;
833                 case '/':             vkey = VK_OEM_2; break;
834                 case '`':             vkey = VK_OEM_3; break;
835                 case '[':             vkey = VK_OEM_4; break;
836                 case '\\':            vkey = VK_OEM_5; break;
837                 case ']':             vkey = VK_OEM_6; break;
838                 case '\'':            vkey = VK_OEM_7; break;
839                 case ',':             vkey = VK_OEM_COMMA; break;
840                 case '.':             vkey = VK_OEM_PERIOD; break;
841                 case '-':             vkey = VK_OEM_MINUS; break;
842                 case '+':             vkey = VK_OEM_PLUS; break;
843                 }
844             }
845
846             if (!vkey)
847             {
848                 /* Others keys: let's assign OEM virtual key codes in the allowed range,
849                  * that is ([0xba,0xc0], [0xdb,0xe4], 0xe6 (given up) et [0xe9,0xf5]) */
850                 switch (++OEMvkey)
851                 {
852                 case 0xc1 : OEMvkey=0xdb; break;
853                 case 0xe5 : OEMvkey=0xe9; break;
854                 case 0xf6 : OEMvkey=0xf5; WARN_(keyboard)("No more OEM vkey available!\n");
855                 }
856
857                 vkey = OEMvkey;
858                   
859                 if (TRACE_ON(keyboard))
860                 {
861                     dbg_decl_str(keyboard, 1024);
862
863                     TRACE_(keyboard)("OEM specific virtual key %X assigned "
864                                  "to keycode %X:\n", OEMvkey, e2.keycode);
865                     for (i = 0; i < keysyms_per_keycode; i += 1)
866                     {
867                         char    *ksname;
868                         
869                         keysym = TSXLookupKeysym(&e2, i);
870                         ksname = TSXKeysymToString(keysym);
871                         if (!ksname)
872                             ksname = "NoSymbol";
873                         dsprintf(keyboard, "%lX (%s) ", keysym, ksname);
874                     }
875                     TRACE_(keyboard)("(%s)\n", dbg_str(keyboard));
876                 }
877             }
878         }
879         keyc2vkey[e2.keycode] = vkey;
880         keyc2scan[e2.keycode] = scan;
881     } /* for */
882
883     /* If some keys still lack scancodes, assign some arbitrary ones to them now */
884     for (scan = 0x60, keyc = min_keycode; keyc <= max_keycode; keyc++)
885       if (keyc2vkey[keyc]&&!keyc2scan[keyc]) {
886         char *ksname;
887         keysym = TSXKeycodeToKeysym(display, keyc, 0);
888         ksname = TSXKeysymToString(keysym);
889         if (!ksname) ksname = "NoSymbol";
890
891         /* should make sure the scancode is unassigned here, but >=0x60 currently always is */
892
893         TRACE_(key)("assigning scancode %02x to unidentified keycode %02x (%s)\n",scan,keyc,ksname);
894         keyc2scan[keyc]=scan++;
895       }
896
897     /* Now store one keycode for each modifier. Used to simulate keypresses. */
898     kcControl = TSXKeysymToKeycode(display, XK_Control_L);
899     kcAlt = TSXKeysymToKeycode(display, XK_Alt_L);
900     if (!kcAlt) kcAlt = TSXKeysymToKeycode(display, XK_Meta_L);
901     kcShift = TSXKeysymToKeycode(display, XK_Shift_L);
902     kcNumLock = TSXKeysymToKeycode(display, XK_Num_Lock);
903     kcCapsLock = TSXKeysymToKeycode(display, XK_Caps_Lock);
904 }
905
906 /***********************************************************************
907  *              X11DRV_KEYBOARD_VkKeyScan
908  */
909 WORD X11DRV_KEYBOARD_VkKeyScan(CHAR cChar)
910 {
911         KeyCode keycode;
912         KeySym keysym;          
913         int i,index;
914         int highbyte=0;
915
916         /* char->keysym (same for ANSI chars) */
917         keysym=(unsigned char) cChar;/* (!) cChar is signed */
918         if (keysym<=27) keysym+=0xFF00;/*special chars : return, backspace...*/
919         
920         keycode = TSXKeysymToKeycode(display, keysym);  /* keysym -> keycode */
921         if (!keycode)
922         { /* It didn't work ... let's try with deadchar code. */
923           keycode = TSXKeysymToKeycode(display, keysym | 0xFE00);
924         }
925
926         TRACE_(keyboard)("VkKeyScan '%c'(%#lx, %lu): got keycode %#.2x\n",
927                          cChar,keysym,keysym,keycode);
928         
929         if (keycode)
930           {
931             for (index=-1, i=0; (i<8) && (index<0); i++) /* find shift state */
932               if (TSXKeycodeToKeysym(display,keycode,i)==keysym) index=i;
933             switch (index) {
934             case -1 :
935               WARN_(keyboard)("Keysym %lx not found while parsing the keycode table\n",keysym); break;
936             case 0 : break;
937             case 1 : highbyte = 0x0100; break;
938             case 2 : highbyte = 0x0600; break;
939             case 3 : highbyte = 0x0700; break;
940             default : ERR_(keyboard)("index %d found by XKeycodeToKeysym. please report! \n",index);
941             }
942             /*
943               index : 0     adds 0x0000
944               index : 1     adds 0x0100 (shift)
945               index : ?     adds 0x0200 (ctrl)
946               index : 2     adds 0x0600 (ctrl+alt)
947               index : 3     adds 0x0700 (ctrl+alt+shift)
948              */
949           }
950         TRACE_(keyboard)(" ... returning %#.2x\n", keyc2vkey[keycode]+highbyte);
951         return keyc2vkey[keycode]+highbyte;   /* keycode -> (keyc2vkey) vkey */
952 }
953
954 /***********************************************************************
955  *              X11DRV_KEYBOARD_MapVirtualKey
956  */
957 UINT16 X11DRV_KEYBOARD_MapVirtualKey(UINT16 wCode, UINT16 wMapType)
958 {
959 #define returnMVK(value) { TRACE_(keyboard)("returning 0x%x.\n",value); return value; }
960
961         TRACE_(keyboard)("MapVirtualKey wCode=0x%x wMapType=%d ... \n",
962                          wCode,wMapType);
963         switch(wMapType) {
964                 case 0: { /* vkey-code to scan-code */
965                         /* let's do vkey -> keycode -> scan */
966                         int keyc;
967                         for (keyc=min_keycode; keyc<=max_keycode; keyc++)
968                                 if ((keyc2vkey[keyc] & 0xFF) == wCode)
969                                         returnMVK (keyc2scan[keyc] & 0xFF);
970                         TRACE_(keyboard)("returning no scan-code.\n");
971                         return 0; }
972
973                 case 1: { /* scan-code to vkey-code */
974                         /* let's do scan -> keycode -> vkey */
975                         int keyc;
976                         for (keyc=min_keycode; keyc<=max_keycode; keyc++)
977                                 if ((keyc2scan[keyc] & 0xFF) == (wCode & 0xFF))
978                                         returnMVK (keyc2vkey[keyc] & 0xFF);
979                         TRACE_(keyboard)("returning no vkey-code.\n");
980                         return 0; }
981
982                 case 2: { /* vkey-code to unshifted ANSI code */
983                         /* (was FIXME) : what does unshifted mean ? 'a' or 'A' ? */
984                         /* My Windows returns 'A'. */
985                         /* let's do vkey -> keycode -> (XLookupString) ansi char */
986                         XKeyEvent e;
987                         KeySym keysym;
988                         int keyc;
989                         char s[2];
990                         e.display = display;
991                         e.state = 0; /* unshifted */
992
993                         e.keycode = 0;
994                         /* We exit on the first keycode found, to speed up the thing. */
995                         for (keyc=min_keycode; (keyc<=max_keycode) && (!e.keycode) ; keyc++)
996                         { /* Find a keycode that could have generated this virtual key */
997                             if  ((keyc2vkey[keyc] & 0xFF) == wCode)
998                             { /* We filter the extended bit, we don't know it */
999                                 e.keycode = keyc; /* Store it temporarily */
1000                                 if ((EVENT_event_to_vkey(&e) & 0xFF) != wCode) {
1001                                     e.keycode = 0; /* Wrong one (ex: because of the NumLock
1002                                          state), so set it to 0, we'll find another one */
1003                                 }
1004                             }
1005                         }
1006
1007                         if ((wCode>=VK_NUMPAD0) && (wCode<=VK_NUMPAD9))
1008                           e.keycode = TSXKeysymToKeycode(e.display, wCode-VK_NUMPAD0+XK_KP_0);
1009           
1010                         if (wCode==VK_DECIMAL)
1011                           e.keycode = TSXKeysymToKeycode(e.display, XK_KP_Decimal);
1012
1013                         if (!e.keycode)
1014                         {
1015                           WARN_(keyboard)("Unknown virtual key %X !!! \n", wCode);
1016                           return 0; /* whatever */
1017                         }
1018                         TRACE_(keyboard)("Found keycode %d (0x%2X)\n",e.keycode,e.keycode);
1019
1020                         if (TSXLookupString(&e, s, 2, &keysym, NULL))
1021                           returnMVK (*s);
1022                         
1023                         TRACE_(keyboard)("returning no ANSI.\n");
1024                         return 0;
1025                         }
1026
1027                 case 3:   /* **NT only** scan-code to vkey-code but distinguish between  */
1028                           /*             left and right  */
1029                           FIXME_(keyboard)(" stub for NT\n");
1030                           return 0;
1031
1032                 default: /* reserved */
1033                         WARN_(keyboard)("Unknown wMapType %d !\n",
1034                                 wMapType);
1035                         return 0;       
1036         }
1037         return 0;
1038 }
1039
1040 /***********************************************************************
1041  *              X11DRV_KEYBOARD_GetKeyNameText
1042  */
1043 INT16 X11DRV_KEYBOARD_GetKeyNameText(LONG lParam, LPSTR lpBuffer, INT16 nSize)
1044 {
1045   int vkey, ansi, scanCode;
1046         
1047   scanCode = lParam >> 16;
1048   scanCode &= 0x1ff;  /* keep "extended-key" flag with code */
1049
1050   /* FIXME: should use MVK type 3 (NT version that distinguishes right and left */
1051   vkey = X11DRV_KEYBOARD_MapVirtualKey(scanCode, 1);
1052
1053   /*  handle "don't care" bit (0x02000000) */
1054   if (!(lParam & 0x02000000)) {
1055     switch (vkey) {
1056          case VK_LSHIFT:
1057          case VK_RSHIFT:
1058                           vkey = VK_SHIFT;
1059                           break;
1060        case VK_LCONTROL:
1061        case VK_RCONTROL:
1062                           vkey = VK_CONTROL;
1063                           break;
1064           case VK_LMENU:
1065           case VK_RMENU:
1066                           vkey = VK_MENU;
1067                           break;
1068                default:
1069                           break;
1070     }
1071   }
1072
1073   ansi = X11DRV_KEYBOARD_MapVirtualKey(vkey, 2);
1074   TRACE_(keyboard)("scan 0x%04x, vkey 0x%04x, ANSI 0x%04x\n",
1075           scanCode, vkey, ansi);
1076
1077   if ( ((vkey >= 0x30) && (vkey <= 0x39)) ||
1078       ( (vkey >= 0x41) && (vkey <= 0x5a)) ) /* Windows VK_* are ANSI codes */
1079       {
1080         if ((nSize >= 2) && lpBuffer)
1081         {
1082         *lpBuffer = toupper((char)ansi);
1083           *(lpBuffer+1) = 0;
1084           return 1;
1085         } 
1086      else
1087         return 0;
1088   }
1089
1090   /* use vkey values to construct names */
1091
1092   FIXME_(keyboard)("(%08lx,%p,%d): unsupported key\n",lParam,lpBuffer,nSize);
1093
1094   if (lpBuffer && nSize)
1095     *lpBuffer = 0;
1096   return 0;
1097 }
1098
1099 /***********************************************************************
1100  *              X11DRV_KEYBOARD_MapDeadKeysym
1101  */
1102 static char KEYBOARD_MapDeadKeysym(KeySym keysym)
1103 {
1104         switch (keysym)
1105             {
1106         /* symbolic ASCII is the same as defined in rfc1345 */
1107 #ifdef XK_dead_tilde
1108             case XK_dead_tilde :
1109 #endif
1110             case 0x1000FE7E : /* Xfree's XK_Dtilde */
1111                 return '~';     /* '? */
1112 #ifdef XK_dead_acute
1113             case XK_dead_acute :
1114 #endif
1115             case 0x1000FE27 : /* Xfree's XK_Dacute_accent */
1116                 return 0xb4;    /* '' */
1117 #ifdef XK_dead_circumflex
1118             case XK_dead_circumflex:
1119 #endif
1120             case 0x1000FE5E : /* Xfree's XK_Dcircumflex_accent */
1121                 return '^';     /* '> */
1122 #ifdef XK_dead_grave
1123             case XK_dead_grave :
1124 #endif
1125             case 0x1000FE60 : /* Xfree's XK_Dgrave_accent */
1126                 return '`';     /* '! */
1127 #ifdef XK_dead_diaeresis
1128             case XK_dead_diaeresis :
1129 #endif
1130             case 0x1000FE22 : /* Xfree's XK_Ddiaeresis */
1131                 return 0xa8;    /* ': */
1132 #ifdef XK_dead_cedilla
1133             case XK_dead_cedilla :
1134                 return 0xb8;    /* ', */
1135 #endif
1136 #ifdef XK_dead_macron
1137             case XK_dead_macron :
1138                 return '-';     /* 'm isn't defined on iso-8859-x */
1139 #endif
1140 #ifdef XK_dead_breve
1141             case XK_dead_breve :
1142                 return 0xa2;    /* '( */
1143 #endif
1144 #ifdef XK_dead_abovedot
1145             case XK_dead_abovedot :
1146                 return 0xff;    /* '. */
1147 #endif
1148 #ifdef XK_dead_abovering
1149             case XK_dead_abovering :
1150                 return '0';     /* '0 isn't defined on iso-8859-x */
1151 #endif
1152 #ifdef XK_dead_doubleacute
1153             case XK_dead_doubleacute :
1154                 return 0xbd;    /* '" */
1155 #endif
1156 #ifdef XK_dead_caron
1157             case XK_dead_caron :
1158                 return 0xb7;    /* '< */
1159 #endif
1160 #ifdef XK_dead_ogonek
1161             case XK_dead_ogonek :
1162                 return 0xb2;    /* '; */
1163 #endif
1164 /* FIXME: I don't know this three.
1165             case XK_dead_iota :
1166                 return 'i';      
1167             case XK_dead_voiced_sound :
1168                 return 'v';
1169             case XK_dead_semivoiced_sound :
1170                 return 's';
1171 */
1172             }
1173         TRACE_(keyboard)("no character for dead keysym 0x%08lx\n",keysym);
1174         return 0;
1175 }
1176
1177 /***********************************************************************
1178  *              X11DRV_KEYBOARD_ToAscii
1179  *
1180  * The ToAscii function translates the specified virtual-key code and keyboard
1181  * state to the corresponding Windows character or characters.
1182  *
1183  * If the specified key is a dead key, the return value is negative. Otherwise,
1184  * it is one of the following values:
1185  * Value        Meaning
1186  * 0    The specified virtual key has no translation for the current state of the keyboard.
1187  * 1    One Windows character was copied to the buffer.
1188  * 2    Two characters were copied to the buffer. This usually happens when a
1189  *      dead-key character (accent or diacritic) stored in the keyboard layout cannot
1190  *      be composed with the specified virtual key to form a single character.
1191  *
1192  * FIXME : should do the above (return 2 for non matching deadchar+char combinations)
1193  *
1194  */
1195 INT16 X11DRV_KEYBOARD_ToAscii(
1196     UINT16 virtKey,UINT16 scanCode, LPBYTE lpKeyState, 
1197     LPVOID lpChar, UINT16 flags)
1198 {
1199     XKeyEvent e;
1200     KeySym keysym;
1201     static XComposeStatus cs;
1202     INT ret;
1203     int keyc;
1204
1205     if (scanCode==0) {
1206         /* This happens when doing Alt+letter : a fake 'down arrow' key press
1207            event is generated by windows. Just ignore it. */
1208         TRACE_(keyboard)("scanCode=0, doing nothing\n");
1209         return 0;
1210     }
1211     if (scanCode & 0x8000)
1212     {
1213         TRACE_(keyboard)("Key UP, doing nothing\n" );
1214         return 0;
1215     }
1216     e.display = display;
1217     e.keycode = 0;
1218     e.state = 0;
1219     if (lpKeyState[VK_SHIFT] & 0x80)
1220         e.state |= ShiftMask;
1221     if (lpKeyState[VK_CAPITAL] & 0x01)
1222         e.state |= LockMask;
1223     if (lpKeyState[VK_CONTROL] & 0x80)
1224     {
1225         if (lpKeyState[VK_MENU] & 0x80)
1226             e.state |= AltGrMask;
1227         else
1228             e.state |= ControlMask;
1229     }
1230     if (lpKeyState[VK_NUMLOCK] & 0x01)
1231         e.state |= NumLockMask;
1232     TRACE_(key)("(%04X, %04X) : faked state = %X\n",
1233                 virtKey, scanCode, e.state);
1234     /* We exit on the first keycode found, to speed up the thing. */
1235     for (keyc=min_keycode; (keyc<=max_keycode) && (!e.keycode) ; keyc++)
1236       { /* Find a keycode that could have generated this virtual key */
1237           if  ((keyc2vkey[keyc] & 0xFF) == virtKey)
1238           { /* We filter the extended bit, we don't know it */
1239               e.keycode = keyc; /* Store it temporarily */
1240               if ((EVENT_event_to_vkey(&e) & 0xFF) != virtKey) {
1241                   e.keycode = 0; /* Wrong one (ex: because of the NumLock
1242                          state), so set it to 0, we'll find another one */
1243               }
1244           }
1245       }
1246
1247     if ((virtKey>=VK_NUMPAD0) && (virtKey<=VK_NUMPAD9))
1248         e.keycode = TSXKeysymToKeycode(e.display, virtKey-VK_NUMPAD0+XK_KP_0);
1249           
1250     if (virtKey==VK_DECIMAL)
1251         e.keycode = TSXKeysymToKeycode(e.display, XK_KP_Decimal);
1252
1253     if (!e.keycode)
1254       {
1255         WARN_(keyboard)("Unknown virtual key %X !!! \n",virtKey);
1256         return virtKey; /* whatever */
1257       }
1258     else TRACE_(keyboard)("Found keycode %d (0x%2X)\n",e.keycode,e.keycode);
1259
1260     ret = TSXLookupString(&e, (LPVOID)lpChar, 2, &keysym, &cs);
1261     if (ret == 0)
1262         {
1263         BYTE dead_char = 0;
1264
1265         ((char*)lpChar)[1] = '\0';
1266         dead_char = KEYBOARD_MapDeadKeysym(keysym);
1267         if (dead_char)
1268             {
1269             *(char*)lpChar = dead_char;
1270             ret = -1;
1271             }
1272         else
1273             {
1274             char        *ksname;
1275
1276             ksname = TSXKeysymToString(keysym);
1277             if (!ksname)
1278                 ksname = "No Name";
1279             if ((keysym >> 8) != 0xff)
1280                 {
1281                 ERR_(keyboard)("Please report: no char for keysym %04lX (%s) :\n",
1282                         keysym, ksname);
1283                 ERR_(keyboard)("(virtKey=%X,scanCode=%X,keycode=%X,state=%X)\n",
1284                         virtKey, scanCode, e.keycode, e.state);
1285                 }
1286             }
1287         }
1288     else {  /* ret = 1 */
1289         /* We have a special case to handle : Shift + arrow, shift + home, ...
1290            X returns a char for it, but Windows doesn't. Let's eat it. */
1291         if (!(lpKeyState[VK_NUMLOCK] & 0x01)  /* NumLock is off */
1292             && (lpKeyState[VK_SHIFT] & 0x80) /* Shift is pressed */
1293             && (keysym>=XK_KP_0) && (keysym<=XK_KP_9))
1294         {
1295             *(char*)lpChar = 0;
1296             ret = 0;
1297         }
1298     }
1299
1300     TRACE_(key)("ToAscii about to return %d with char %x\n",
1301                 ret, *(char*)lpChar);
1302     return ret;
1303 }
1304
1305 /***********************************************************************
1306  *              X11DRV_KEYBOARD_GetBeepActive
1307  */
1308 BOOL X11DRV_KEYBOARD_GetBeepActive()
1309 {
1310   XKeyboardState  keyboard_state;
1311
1312   TSXGetKeyboardControl(display, &keyboard_state);
1313
1314   return keyboard_state.bell_percent != 0;
1315 }
1316
1317 /***********************************************************************
1318  *              X11DRV_KEYBOARD_SetBeepActive
1319  */
1320 void X11DRV_KEYBOARD_SetBeepActive(BOOL bActivate)
1321 {
1322   XKeyboardControl keyboard_value;
1323   
1324   if(bActivate)
1325     keyboard_value.bell_percent = -1;
1326   else
1327     keyboard_value.bell_percent = 0;
1328   
1329   TSXChangeKeyboardControl(display, KBBellPercent, &keyboard_value);
1330 }
1331
1332 /***********************************************************************
1333  *              X11DRV_KEYBOARD_Beep
1334  */
1335 void X11DRV_KEYBOARD_Beep()
1336 {
1337   TSXBell(display, 0);
1338 }
1339
1340 /***********************************************************************
1341  *              X11DRV_KEYBOARD_GetDIState
1342  */
1343 BOOL X11DRV_KEYBOARD_GetDIState(DWORD len, LPVOID ptr)
1344 {
1345   if (len==256) {
1346     int keyc,vkey;
1347     
1348     memset(ptr,0,256);
1349     for (keyc=min_keycode;keyc<max_keycode;keyc++)
1350       {
1351         /* X keycode to virtual key */
1352         vkey = keyc2vkey[keyc] & 0xFF;
1353         /* The windows scancode is keyc-min_keycode */
1354         if (InputKeyStateTable[vkey]&0x80) {
1355           ((LPBYTE)ptr)[keyc-min_keycode]=0x80;
1356           ((LPBYTE)ptr)[(keyc-min_keycode)|0x80]=0x80;
1357         }
1358       }
1359     return TRUE;
1360   }
1361   WARN_(x11drv)("whoops, X11DRV_KEYBOARD_GetState got len %ld?\n", len);
1362   return TRUE;
1363 }
1364
1365 /***********************************************************************
1366  *              X11DRV_KEYBOARD_GetDIData
1367  */
1368 BOOL X11DRV_KEYBOARD_GetDIData(
1369   BYTE *keystate,
1370   DWORD dodsize, LPDIDEVICEOBJECTDATA dod,
1371   LPDWORD entries, DWORD flags)
1372 {
1373   int keyc,n,vkey,xentries;
1374     
1375   /* FIXME !!! */
1376   
1377   EVENT_Synchronize( FALSE );
1378   
1379   if (entries)
1380     xentries = *entries; 
1381   else
1382     xentries = 1;
1383   
1384   n = 0;
1385   
1386   for (keyc=min_keycode;(keyc<max_keycode) && (n<*entries);keyc++)
1387     {
1388       /* X keycode to virtual key */
1389       vkey = keyc2vkey[keyc] & 0xFF;
1390       if (keystate[vkey] == (InputKeyStateTable[vkey]&0x80))
1391         continue;
1392       if (dod) {
1393         /* add an entry */
1394         dod[n].dwOfs            = keyc-min_keycode; /* scancode */
1395         dod[n].dwData           = InputKeyStateTable[vkey]&0x80;
1396         dod[n].dwTimeStamp      = 0; /* umm */
1397         dod[n].dwSequence       = 0; /* umm */
1398         n++;
1399       }
1400       if (!(flags & DIGDD_PEEK))
1401         keystate[vkey] = InputKeyStateTable[vkey]&0x80;
1402       
1403     }
1404   
1405   if (n) fprintf(stderr,"%d entries\n",n);
1406   *entries = n;
1407
1408   return TRUE;
1409 }
1410
1411 #endif /* !defined(X_DISPLAY_MISSING) */
1412