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