Fixed references to old documentation location.
[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 #include <X11/Xatom.h>
15 #include <X11/keysym.h>
16
17 #include "ts_xlib.h"
18 #include "ts_xresource.h"
19 #include "ts_xutil.h"
20 #ifdef HAVE_XKB
21 #include <X11/XKBlib.h>
22 #endif
23
24 #include <ctype.h>
25 #include <string.h>
26
27 #include "windef.h"
28 #include "wingdi.h"
29 #include "wine/winuser16.h"
30 #include "dinput.h"
31 #include "debugtools.h"
32 #include "user.h"
33 #include "keyboard.h"
34 #include "winnls.h"
35 #include "win.h"
36 #include "x11drv.h"
37
38 DEFAULT_DEBUG_CHANNEL(keyboard);
39 DECLARE_DEBUG_CHANNEL(key);
40 DECLARE_DEBUG_CHANNEL(dinput);
41
42 extern BYTE InputKeyStateTable[256];
43
44 extern LPBYTE pKeyStateTable;
45
46 int min_keycode, max_keycode, keysyms_per_keycode;
47 WORD keyc2vkey[256], keyc2scan[256];
48
49 static int NumLockMask, AltGrMask; /* mask in the XKeyEvent state */
50 static int kcControl, kcAlt, kcShift, kcNumLock, kcCapsLock; /* keycodes */
51 #ifdef HAVE_XKB
52 static int is_xkb, xkb_opcode, xkb_event, xkb_error;
53 #endif
54
55 static char KEYBOARD_MapDeadKeysym(KeySym keysym);
56
57 /* Keyboard translation tables */
58 #define MAIN_LEN 48
59 static const WORD main_key_scan_qwerty[MAIN_LEN] =
60 {
61 /* this is my (102-key) keyboard layout, sorry if it doesn't quite match yours */
62    0x29,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,
63    0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,
64    0x1E,0x1F,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x2B,
65    0x2C,0x2D,0x2E,0x2F,0x30,0x31,0x32,0x33,0x34,0x35,
66    0x56 /* the 102nd key (actually to the right of l-shift) */
67 };
68
69 static const WORD main_key_vkey_qwerty[MAIN_LEN] =
70 {
71 /* NOTE: this layout must concur with the scan codes layout above */
72    VK_OEM_3,VK_1,VK_2,VK_3,VK_4,VK_5,VK_6,VK_7,VK_8,VK_9,VK_0,VK_OEM_MINUS,VK_OEM_PLUS,
73    VK_Q,VK_W,VK_E,VK_R,VK_T,VK_Y,VK_U,VK_I,VK_O,VK_P,VK_OEM_4,VK_OEM_6,
74    VK_A,VK_S,VK_D,VK_F,VK_G,VK_H,VK_J,VK_K,VK_L,VK_OEM_1,VK_OEM_7,VK_OEM_5,
75    VK_Z,VK_X,VK_C,VK_V,VK_B,VK_N,VK_M,VK_OEM_COMMA,VK_OEM_PERIOD,VK_OEM_2,
76    VK_OEM_102 /* the 102nd key (actually to the right of l-shift) */
77 };
78
79 static const WORD main_key_vkey_azerty[MAIN_LEN] =
80 {
81 /* NOTE: this layout must concur with the scan codes layout above */
82    VK_OEM_7,VK_1,VK_2,VK_3,VK_4,VK_5,VK_6,VK_7,VK_8,VK_9,VK_0,VK_OEM_4,VK_OEM_PLUS,
83    VK_A,VK_Z,VK_E,VK_R,VK_T,VK_Y,VK_U,VK_I,VK_O,VK_P,VK_OEM_6,VK_OEM_1,
84    VK_Q,VK_S,VK_D,VK_F,VK_G,VK_H,VK_J,VK_K,VK_L,VK_M,VK_OEM_3,VK_OEM_5,
85    VK_W,VK_X,VK_C,VK_V,VK_B,VK_N,VK_OEM_COMMA,VK_OEM_PERIOD,VK_OEM_2,VK_OEM_8,
86    VK_OEM_102 /* the 102nd key (actually to the right of l-shift) */
87 };
88
89 /* FIXME: add other layouts, such as DVORAK and German QWERTZ */
90
91 /*** DEFINE YOUR NEW LANGUAGE-SPECIFIC MAPPINGS BELOW, SEE EXISTING TABLES */
92
93 /* the VK mappings for the main keyboard will be auto-assigned as before,
94    so what we have here is just the character tables */
95 /* order: Normal, Shift, AltGr, Shift-AltGr */
96 /* We recommend you write just what is guaranteed to be correct (i.e. what's
97    written on the keycaps), not the bunch of special characters behind AltGr
98    and Shift-AltGr if it can vary among different X servers */
99 /* Remember that your 102nd key (to the right of l-shift) should be on a
100    separate line, see existing tables */
101 /* If Wine fails to match your new table, use -debugmsg +key to find out why */
102 /* Remember to also add your new table to the layout index table far below! */
103
104 /*** United States keyboard layout (mostly contributed by Uwe Bonnes) */
105 static const char main_key_US[MAIN_LEN][4] =
106 {
107  "`~","1!","2@","3#","4$","5%","6^","7&","8*","9(","0)","-_","=+",
108  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","[{","]}",
109  "aA","sS","dD","fF","gG","hH","jJ","kK","lL",";:","'\"","\\|",
110  "zZ","xX","cC","vV","bB","nN","mM",",<",".>","/?"
111 };
112
113 /*** United States keyboard layout (phantom key version) */
114 /* (XFree86 reports the <> key even if it's not physically there) */
115 static const char main_key_US_phantom[MAIN_LEN][4] =
116 {
117  "`~","1!","2@","3#","4$","5%","6^","7&","8*","9(","0)","-_","=+",
118  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","[{","]}",
119  "aA","sS","dD","fF","gG","hH","jJ","kK","lL",";:","'\"","\\|",
120  "zZ","xX","cC","vV","bB","nN","mM",",<",".>","/?",
121  "<>" /* the phantom key */
122 };
123
124 /*** British keyboard layout */
125 static const char main_key_UK[MAIN_LEN][4] =
126 {
127  "`","1!","2\"","3£","4$","5%","6^","7&","8*","9(","0)","-_","=+",
128  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","[{","]}",
129  "aA","sS","dD","fF","gG","hH","jJ","kK","lL",";:","'@","#~",
130  "zZ","xX","cC","vV","bB","nN","mM",",<",".>","/?",
131  "\\|"
132 };
133
134 /*** French keyboard layout (contributed by Eric Pouech) */
135 static const char main_key_FR[MAIN_LEN][4] =
136 {
137  "²","&1","é2~","\"3#","'4{","(5[","-6|","è7","_8\\","ç9^±","à0@",")°]","=+}",
138  "aA","zZ","eE","rR","tT","yY","uU","iI","oO","pP","^¨","$£¤",
139  "qQ","sSß","dD","fF","gG","hH","jJ","kK","lL","mM","ù%","*µ",
140  "wW","xX","cC","vV","bB","nN",",?",";.",":/","!§",
141  "<>"
142 };
143
144 /*** Icelandic keyboard layout (contributed by Ríkharður Egilsson) */
145 static const char main_key_IS[MAIN_LEN][4] =
146 {
147  "°","1!","2\"","3#","4$","5%","6&","7/{","8([","9)]","0=}","öÖ\\","-_",
148  "qQ@","wW","eE","rR","tT","yY","uU","iI","oO","pP","ðÐ","'?~",
149  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","æÆ","´^","+*`",
150  "zZ","xX","cC","vV","bB","nN","mM",",;",".:","þÞ",
151  "<>|"
152 };
153
154 /*** German keyboard layout (contributed by Ulrich Weigand) */
155 static const char main_key_DE[MAIN_LEN][4] =
156 {
157  "^°","1!","2\"²","3§³","4$","5%","6&","7/{","8([","9)]","0=}","ß?\\","'`",
158  "qQ@","wW","eE\80","rR","tT","zZ","uU","iI","oO","pP","üÜ","+*~",
159  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","öÖ","äÄ","#´",
160  "yY","xX","cC","vV","bB","nN","mMµ",",;",".:","-_",
161  "<>|"
162 };
163
164 /*** German keyboard layout without dead keys */
165 static const char main_key_DE_nodead[MAIN_LEN][4] =
166 {
167  "^°","1!","2\"","3§","4$","5%","6&","7/{","8([","9)]","0=}","ß?\\","´",
168  "qQ","wW","eE","rR","tT","zZ","uU","iI","oO","pP","üÜ","+*~",
169  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","öÖ","äÄ","#'",
170  "yY","xX","cC","vV","bB","nN","mM",",;",".:","-_",
171  "<>"
172 };
173
174 /*** Swiss German keyboard layout (contributed by Jonathan Naylor) */
175 static const char main_key_SG[MAIN_LEN][4] =
176 {
177  "§°","1+|","2\"@","3*#","4ç","5%","6&¬","7/¦","8(¢","9)","0=","'?´","^`~",
178  "qQ","wW","eE","rR","tT","zZ","uU","iI","oO","pP","üè[","¨!]",
179  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","öé","äà{","$£}",
180  "yY","xX","cC","vV","bB","nN","mM",",;",".:","-_",
181  "<>\\"
182 };
183
184 /*** Swiss French keyboard layout (contributed by Philippe Froidevaux) */
185 static const char main_key_SF[MAIN_LEN][4] =
186 {
187  "§°","1+|","2\"@","3*#","4ç","5%","6&¬","7/¦","8(¢","9)","0=","'?´","^`~",
188  "qQ","wW","eE","rR","tT","zZ","uU","iI","oO","pP","èü[","¨!]",
189  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","éö","àä{","$£}",
190  "yY","xX","cC","vV","bB","nN","mM",",;",".:","-_",
191  "<>\\"
192 };
193
194 /*** Norwegian keyboard layout (contributed by Ove Kåven) */
195 static const char main_key_NO[MAIN_LEN][4] =
196 {
197  "|§","1!","2\"@","3#£","4¤$","5%","6&","7/{","8([","9)]","0=}","+?","\\`´",
198  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","åÅ","¨^~",
199  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","øØ","æÆ","'*",
200  "zZ","xX","cC","vV","bB","nN","mM",",;",".:","-_",
201  "<>"
202 };
203
204 /*** Danish keyboard layout (contributed by Bertho Stultiens) */
205 static const char main_key_DA[MAIN_LEN][4] =
206 {
207  "½§","1!","2\"@","3#£","4¤$","5%","6&","7/{","8([","9)]","0=}","+?","´`|",
208  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","åÅ","¨^~",
209  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","æÆ","øØ","'*",
210  "zZ","xX","cC","vV","bB","nN","mM",",;",".:","-_",
211  "<>\\"
212 };
213
214 /*** Swedish keyboard layout (contributed by Peter Bortas) */
215 static const char main_key_SE[MAIN_LEN][4] =
216 {
217  "§½","1!","2\"@","3#£","4¤$","5%","6&","7/{","8([","9)]","0=}","+?\\","´`",
218  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","åÅ","¨^~",
219  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","öÖ","äÄ","'*",
220  "zZ","xX","cC","vV","bB","nN","mM",",;",".:","-_",
221  "<>|"
222 };
223
224 /*** Canadian French keyboard layout */
225 static const char main_key_CF[MAIN_LEN][4] =
226 {
227  "#|\\","1!±","2\"@","3/£","4$¢","5%¤","6?¬","7&¦","8*²","9(³","0)¼","-_½","=+¾",
228  "qQ","wW","eE","rR","tT","yY","uU","iI","oO§","pP¶","^^[","¸¨]",
229  "aA","sS","dD","fF","gG","hH","jJ","kK","lL",";:~","``{","<>}",
230  "zZ","xX","cC","vV","bB","nN","mM",",'-",".","éÉ",
231  "«»°"
232 };
233
234 /*** Portuguese keyboard layout */
235 static const char main_key_PT[MAIN_LEN][4] =
236 {
237  "\\¦","1!","2\"@","3#£","4$§","5%","6&","7/{","8([","9)]","0=}","'?","«»",
238  "qQ",  "wW","eE",  "rR", "tT", "yY", "uU", "iI", "oO", "pP", "+*\\¨","\\'\\`",
239  "aA",  "sS","dD",  "fF", "gG", "hH", "jJ", "kK", "lL", "çÇ", "ºª", "\\~\\^",
240  "zZ",  "xX","cC",  "vV", "bB", "nN", "mM", ",;", ".:", "-_",
241  "<>"
242 };
243
244 /*** Italian keyboard layout */
245 static const char main_key_IT[MAIN_LEN][4] =
246 {
247  "\\|","1!¹","2\"²","3£³","4$¼","5%½","6&¾","7/{","8([","9)]","0=}","'?`","ì^~",
248  "qQ@","wW","eE","rR","tT","yY","uU","iI","oOø","pPþ","èé[","+*]",
249  "aA","sSß","dDð","fF","gG","hH","jJ","kK","lL","òç@","à°#","ù§",
250  "zZ","xX","cC","vV","bB","nN","mMµ",",;",".:·","-_",
251  "<>|"
252 };
253
254 /*** Finnish keyboard layout */
255 static const char main_key_FI[MAIN_LEN][4] =
256 {
257  "","1!","2\"@","3#","4$","5%","6&","7/{","8([","9)]","0=}","+?\\","\'`",
258  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","","\"^~",
259  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","","","'*",
260  "zZ","xX","cC","vV","bB","nN","mM",",;",".:","-_",
261  "<>|"
262 };
263
264 /*** Russian keyboard layout (contributed by Pavel Roskin) */
265 static const char main_key_RU[MAIN_LEN][4] =
266 {
267  "`~","1!","2@","3#","4$","5%","6^","7&","8*","9(","0)","-_","=+",
268  "qQÊê","wWÃã","eEÕõ","rRËë","tTÅå","yYÎî","uUÇç","iIÛû","oOÝý","pPÚú","[{Èè","]}ßÿ",
269  "aAÆæ","sSÙù","dD×÷","fFÁá","gGÐð","hHÒò","jJÏï","kKÌì","lLÄä",";:Öö","'\"Üü","\\|",
270  "zZÑñ","xXÞþ","cCÓó","vVÍí","bBÉé","nNÔô","mMØø",",<Ââ",".>Àà","/?"
271 };
272
273 /*** Russian keyboard layout KOI8-R */
274 static const char main_key_RU_koi8r[MAIN_LEN][4] =
275 {
276  "()","1!","2\"","3/","4$","5:","6,","7.","8;","9?","0%","-_","=+",
277  "Êê","Ãã","Õõ","Ëë","Åå","Îî","Çç","Ûû","Ýý","Úú","Èè","ßÿ",
278  "Ææ","Ùù","×÷","Áá","Ðð","Òò","Ïï","Ìì","Ää","Öö","Üü","\\|",
279  "Ññ","Þþ","Óó","Íí","Éé","Ôô","Øø","Ââ","Àà","/?",
280  "<>" /* the phantom key */
281 };
282
283 /*** Ukrainian keyboard layout KOI8-U */
284 static const char main_key_UA[MAIN_LEN][4] =
285 {
286  "`~­½","1!1!","2@2\"","3#3'","4$4*","5%5:","6^6,","7&7.","8*8;","9(9(","0)0)","-_-_","=+=+",
287  "qQÊê","wWÃã","eEÕõ","rRËë","tTÅå","yYÎî","uUÇç","iIÛû","oOÝý","pPÚú","[{Èè","]}§·",
288  "aAÆæ","sS¦¶","dD×÷","fFÁá","gGÐð","hHÒò","jJÏï","kKÌì","lLÄä",";:Öö","'\"¤´","\\|\\|",
289  "zZÑñ","xXÞþ","cCÓó","vVÍí","bBÉé","nNÔô","mMØø",",<Ââ",".>Àà","/?/?",
290  "<>" /* the phantom key */
291 };
292
293 /*** Spanish keyboard layout (contributed by José Marcos López) */
294 static const char main_key_ES[MAIN_LEN][4] =
295 {
296  "ºª\\","1!|","2\"@","3·#","4$","5%","6&¬","7/","8(","9)","0=","'?","¡¿",
297  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","`^[","+*]",
298  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","ñÑ","'¨{","çÇ}",
299  "zZ","xX","cC","vV","bB","nN","mM",",;",".:","-_",
300  "<>"
301 };
302
303 /*** Belgian keyboard layout ***/
304 static const char main_key_BE[MAIN_LEN][4] =
305 {
306  "","&1|","é2@","\"3#","'4","(5","§6^","è7","!8","ç9{","à0}",")°","-_",
307  "aA","zZ","eE¤","rR","tT","yY","uU","iI","oO","pP","^¨[","$*]",
308  "qQ","sSß","dD","fF","gG","hH","jJ","kK","lL","mM","ù%´","µ£`",
309  "wW","xX","cC","vV","bB","nN",",?",";.",":/","=+~",
310  "<>\\"
311 };
312
313 /*** Hungarian keyboard layout (contributed by Zoltán Kovács) */
314 static const char main_key_HU[MAIN_LEN][4] =
315 {
316  "0§","1'~","2\"·","3+^","4!¢","5%°","6/²","7=`","8(ÿ","9)´","öÖ½","üܨ","óÓ¸",
317  "qQ\\","wW|","eE","rR","tT","zZ","uU","iIÍ","oOø","pP","õÕ÷","úÚ×",
318  "aA","sSð","dDÐ","fF[","gG]","hH","jJí","kK³","lL£","éÉ$","áÁß","ûÛ¤",
319  "yY>","xX#","cC&","vV@","bB{","nN}","mM",",?;",".:·","-_*",
320  "íÍ<"
321 };
322
323 /*** Polish (programmer's) keyboard layout ***/
324 static const char main_key_PL[MAIN_LEN][4] =
325 {
326  "`~","1!","2@","3#","4$","5%","6^","7&§","8*","9(","0)","-_","=+",
327  "qQ","wW","eEêÊ","rR","tT","yY","uU","iI","oOóÓ","pP","[{","]}",
328  "aA±¡","sS¶¦","dD","fF","gG","hH","jJ","kK","lL³£",";:","'\"","\\|",
329  "zZ¿¯","xX¼¬","cCæÆ","vV","bB","nNñÑ","mM",",<",".>","/?",
330  "<>|"
331 };
332
333 /*** Croatian keyboard layout specific for me <jelly@srk.fer.hr> ***/
334 static const char main_key_HR_jelly[MAIN_LEN][4] =
335 {
336  "`~","1!","2@","3#","4$","5%","6^","7&","8*","9(","0)","-_","=+",
337  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","[{¹©","]}ðÐ",
338  "aA","sS","dD","fF","gG","hH","jJ","kK","lL",";:èÈ","'\"æÆ","\\|¾®",
339  "zZ","xX","cC","vV","bB","nN","mM",",<",".>","/?",
340  "<>|"
341 };
342
343 /*** Croatian keyboard layout ***/
344 static const char main_key_HR[MAIN_LEN][4] =
345 {
346  "¸¨","1!","2\"·","3#^","4$¢","5%°","6&²","7/`","8(ÿ","9)´","0=½","'?¨","+*¸",
347  "qQ\\","wW|","eE","rR","tT","zZ","uU","iI","oO","pP","¹©÷","ðÐ×",
348  "aA","sS","dD","fF[","gG]","hH","jJ","kK³","lL£","èÈ","æÆß","¾®¤",
349  "yY","xX","cC","vV@","bB{","nN}","mM§",",;",".:","-_/",
350  "<>"
351 };
352
353 /*** Japanese 106 keyboard layout ***/
354 static const char main_key_JA_jp106[MAIN_LEN][4] =
355 {
356  "1!","2\"","3#","4$","5%","6&","7'","8(","9)","0~","-=","^~","\\|",
357  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","@`","[{",
358  "aA","sS","dD","fF","gG","hH","jJ","kK","lL",";+",":*","]}",
359  "zZ","xX","cC","vV","bB","nN","mM",",<",".>","/?",
360  "\\_",
361 };
362
363 /*** Japanese pc98x1 keyboard layout ***/
364 static const char main_key_JA_pc98x1[MAIN_LEN][4] =
365 {
366  "1!","2\"","3#","4$","5%","6&","7'","8(","9)","0","-=","^`","\\|",
367  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","@~","[{",
368  "aA","sS","dD","fF","gG","hH","jJ","kK","lL",";+",":*","]}",
369  "zZ","xX","cC","vV","bB","nN","mM",",<",".>","/?",
370  "\\_",
371 };
372
373 /*** Brazilian ABNT-2 keyboard layout (contributed by Raul Gomes Fernandes) */
374 static const char main_key_PT_br[MAIN_LEN][4] =
375 {
376  "'\"","1!","2@","3#","4$","5%","6\"","7&","8*","9(","0)","-_","=+",
377  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","'`","[{",
378  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","çÇ","~^","]}",
379  "zZ","xX","cC","vV","bB","nN","mM",",<",".>","/?"
380 };
381
382 /*** US international keyboard layout (contributed by Gustavo Noronha (kov@debian.org)) */
383 static const char main_key_US_intl[MAIN_LEN][4] =
384 {
385   "`~", "1!", "2@", "3#", "4$", "5%", "6^", "7&", "8*", "9(", "0)", "-_", "=+", "\\|",
386   "qQ", "wW", "eE", "rR", "tT", "yY", "uU", "iI", "oO", "pP", "[{", "]}",
387   "aA", "sS", "dD", "fF", "gG", "hH", "jJ", "kK", "lL", ";:", "'\"",
388   "zZ", "xX", "cC", "vV", "bB", "nN", "mM", ",<", ".>", "/?"
389 };
390
391 /*** Slovak keyboard layout (see cssk_ibm(sk_qwerty) in xkbsel)
392   - dead_abovering replaced with degree - no symbol in iso8859-2
393   - brokenbar replaced with bar                                 */
394 static const char main_key_SK[MAIN_LEN][4] =
395 {
396  ";°`'","+1","µ2","¹3","è4","»5","¾6","ý7","á8","í9","é0)","=%","",
397  "qQ\\","wW|","eE","rR","tT","yY","uU","iI","oO","pP","ú/÷","ä(×",
398  "aA","sSð","dDÐ","fF[","gG]","hH","jJ","kK³","lL£","ô\"$","§!ß","ò)¤",
399  "zZ>","xX#","cC&","vV@","bB{","nN}","mM",",?<",".:>","-_*",
400  "<>\\|"
401 };
402
403 /*** Slovak and Czech (programmer's) keyboard layout (see cssk_dual(cs_sk_ucw)) */
404 static const char main_key_SK_prog[MAIN_LEN][4] =
405 {
406  "`~","1!","2@","3#","4$","5%","6^","7&","8*","9(","0)","-_","=+",
407  "qQäÄ","wWìÌ","eEéÉ","rRøØ","tT»«","yYýÝ","uUùÙ","iIíÍ","oOóÓ","pPöÖ","[{","]}",
408  "aAáÁ","sS¹©","dDïÏ","fFëË","gGàÀ","hHúÚ","jJüÜ","kKôÔ","lLµ¥",";:","'\"","\\|",
409  "zZ¾®","xX¤","cCèÈ","vVçÇ","bB","nNòÒ","mMåÅ",",<",".>","/?",
410  "<>"
411 };
412
413 /*** Czech keyboard layout (see cssk_ibm(cs_qwerty) in xkbsel) */
414 static const char main_key_CS[MAIN_LEN][4] =
415 {
416  ";","+1","ì2","¹3","è4","ø5","¾6","ý7","á8","í9","é0½)","=%","",
417  "qQ\\","wW|","eE","rR","tT","yY","uU","iI","oO","pP","ú/[{",")(]}",
418  "aA","sSð","dDÐ","fF[","gG]","hH","jJ","kK³","lL£","ù\"$","§!ß","¨'",
419  "zZ>","xX#","cC&","vV@","bB{","nN}","mM",",?<",".:>","-_*",
420  "<>\\|"
421 };
422
423 /*** Latin American keyboard layout (contributed by Gabriel Orlando Garcia) */
424 static const char main_key_LA[MAIN_LEN][4] =
425 {
426  "|°¬","1!","2\"","3#","4$","5%","6&","7/","8(","9)","0=","'?\\","¡¿",
427  "qQ@","wW","eE","rR","tT","yY","uU","iI","oO","pP","´¨","+*~",
428  "aA","sS","dD","fF","gG","hH","jJ","kK","lL","ñÑ","{[^","}]`",
429  "zZ","xX","cC","vV","bB","nN","mM",",;",".:","-_",
430  "<>"
431 };
432
433 /*** Lithuanian (Baltic) keyboard layout (contributed by Nerijus Baliûnas) */
434 static const char main_key_LT_B[MAIN_LEN][4] =
435 {
436  "`~","àÀ","èÈ","æÆ","ëË","áÁ","ðÐ","øØ","ûÛ","((","))","-_","þÞ",
437  "qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","[{","]}",
438  "aA","sS","dD","fF","gG","hH","jJ","kK","lL",";:","'\"","\\|",
439  "zZ","xX","cC","vV","bB","nN","mM",",<",".>","/?"
440 };
441
442 /*** Turkish keyboard Layout */
443 static const char main_key_TK[MAIN_LEN][4] =
444 {
445 "\"é","1!","2'","3^#","4+$","5%","6&","7/{","8([","9)]","0=}","*?\\","-_",
446 "qQ@","wW","eE","rR","tT","yY","uU","ýIî","oO","pP","ðÐ","üÜ~",
447 "aAæ","sSß","dD","fF","gG","hH","jJ","kK","lL","þÞ","iÝ",",;`",
448 "zZ","xX","cC","vV","bB","nN","mM","öÖ","çÇ",".:"
449 };
450
451 /*** Layout table. Add your keyboard mappings to this list */
452 static const struct {
453     const char *comment;
454     const UINT layout_cp; /* Code page for this layout */
455     const char (*key)[MAIN_LEN][4];
456     const WORD (*scan)[MAIN_LEN]; /* scan codes mapping */
457     const WORD (*vkey)[MAIN_LEN]; /* virtual key codes mapping */
458 } main_key_tab[]={
459  {"United States keyboard layout", 28591, &main_key_US, &main_key_scan_qwerty, &main_key_vkey_qwerty},
460  {"United States keyboard layout (phantom key version)", 28591, &main_key_US_phantom, &main_key_scan_qwerty, &main_key_vkey_qwerty},
461  {"British keyboard layout", 28591, &main_key_UK, &main_key_scan_qwerty, &main_key_vkey_qwerty},
462  {"German keyboard layout", 28591, &main_key_DE, &main_key_scan_qwerty, &main_key_vkey_qwerty},
463  {"German keyboard layout without dead keys", 28591, &main_key_DE_nodead, &main_key_scan_qwerty, &main_key_vkey_qwerty},
464  {"Swiss German keyboard layout", 28591, &main_key_SG, &main_key_scan_qwerty, &main_key_vkey_qwerty},
465  {"Swedish keyboard layout", 28591, &main_key_SE, &main_key_scan_qwerty, &main_key_vkey_qwerty},
466  {"Norwegian keyboard layout", 28591, &main_key_NO, &main_key_scan_qwerty, &main_key_vkey_qwerty},
467  {"Danish keyboard layout", 28591, &main_key_DA, &main_key_scan_qwerty, &main_key_vkey_qwerty},
468  {"French keyboard layout", 28591, &main_key_FR, &main_key_scan_qwerty, &main_key_vkey_azerty},
469  {"Canadian French keyboard layout", 28591, &main_key_CF, &main_key_scan_qwerty, &main_key_vkey_qwerty},
470  {"Belgian keyboard layout", 28591, &main_key_BE, &main_key_scan_qwerty, &main_key_vkey_azerty},
471  {"Swiss French keyboard layout", 28591, &main_key_SF, &main_key_scan_qwerty, &main_key_vkey_qwerty},
472  {"Portuguese keyboard layout", 28591, &main_key_PT, &main_key_scan_qwerty, &main_key_vkey_qwerty},
473  {"Brazilian ABNT-2 keyboard layout", 28591, &main_key_PT_br, &main_key_scan_qwerty, &main_key_vkey_qwerty},
474  {"United States International keyboard layout", 28591, &main_key_US_intl, &main_key_scan_qwerty, &main_key_vkey_qwerty},
475  {"Finnish keyboard layout", 28591, &main_key_FI, &main_key_scan_qwerty, &main_key_vkey_qwerty},
476  {"Russian keyboard layout", 20866, &main_key_RU, &main_key_scan_qwerty, &main_key_vkey_qwerty},
477  {"Russian keyboard layout KOI8-R", 20866, &main_key_RU_koi8r, &main_key_scan_qwerty, &main_key_vkey_qwerty},
478  {"Ukrainian keyboard layout KOI8-U", 20866, &main_key_UA, &main_key_scan_qwerty, &main_key_vkey_qwerty},
479  {"Spanish keyboard layout", 28591, &main_key_ES, &main_key_scan_qwerty, &main_key_vkey_qwerty},
480  {"Italian keyboard layout", 28591, &main_key_IT, &main_key_scan_qwerty, &main_key_vkey_qwerty},
481  {"Icelandic keyboard layout", 28591, &main_key_IS, &main_key_scan_qwerty, &main_key_vkey_qwerty},
482  {"Hungarian keyboard layout", 28592, &main_key_HU, &main_key_scan_qwerty, &main_key_vkey_qwerty},
483  {"Polish (programmer's) keyboard layout", 28592, &main_key_PL, &main_key_scan_qwerty, &main_key_vkey_qwerty},
484  {"Croatian keyboard layout", 28592, &main_key_HR, &main_key_scan_qwerty, &main_key_vkey_qwerty},
485  {"Croatian keyboard layout (specific)", 28592, &main_key_HR_jelly, &main_key_scan_qwerty, &main_key_vkey_qwerty},
486  {"Japanese 106 keyboard layout", 932, &main_key_JA_jp106, &main_key_scan_qwerty, &main_key_vkey_qwerty},
487  {"Japanese pc98x1 keyboard layout", 932, &main_key_JA_pc98x1, &main_key_scan_qwerty, &main_key_vkey_qwerty},
488  {"Slovak keyboard layout", 28592, &main_key_SK, &main_key_scan_qwerty, &main_key_vkey_qwerty},
489  {"Slovak and Czech keyboard layout without dead keys", 28592, &main_key_SK_prog, &main_key_scan_qwerty, &main_key_vkey_qwerty},
490  {"Czech keyboard layout", 28592, &main_key_CS, &main_key_scan_qwerty, &main_key_vkey_qwerty},
491  {"Latin American keyboard layout", 28591, &main_key_LA, &main_key_scan_qwerty, &main_key_vkey_qwerty},
492  {"Lithuanian (Baltic) keyboard layout", 28603, &main_key_LT_B, &main_key_scan_qwerty, &main_key_vkey_qwerty},
493  {"Turkish keyboard layout", 28599, &main_key_TK, &main_key_scan_qwerty, &main_key_vkey_qwerty},
494
495  {NULL, 0, NULL, NULL, NULL} /* sentinel */
496 };
497 static unsigned kbd_layout=0; /* index into above table of layouts */
498
499 /* maybe more of these scancodes should be extended? */
500                 /* extended must be set for ALT_R, CTRL_R,
501                    INS, DEL, HOME, END, PAGE_UP, PAGE_DOWN, ARROW keys,
502                    keypad / and keypad ENTER (SDK 3.1 Vol.3 p 138) */
503                 /* FIXME should we set extended bit for NumLock ? My
504                  * Windows does ... DF */
505                 /* Yes, to distinguish based on scan codes, also
506                    for PrtScn key ... GA */
507
508 static const WORD special_key_vkey[] =
509 {
510     VK_BACK, VK_TAB, 0, VK_CLEAR, 0, VK_RETURN, 0, 0,           /* FF08 */
511     0, 0, 0, VK_PAUSE, VK_SCROLL, 0, 0, 0,                      /* FF10 */
512     0, 0, 0, VK_ESCAPE                                          /* FF18 */
513 };
514 static const WORD special_key_scan[] =
515 {
516     0x0E, 0x0F, 0, /*?*/ 0, 0, 0x1C, 0, 0,                      /* FF08 */
517     0,    0,    0, 0x45, 0x46, 0   , 0, 0,                      /* FF10 */
518     0,    0,    0, 0x01                                         /* FF18 */
519 };
520
521 static const WORD cursor_key_vkey[] =
522 {
523     VK_HOME, VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN, VK_PRIOR, 
524                                        VK_NEXT, VK_END          /* FF50 */
525 };
526 static const WORD cursor_key_scan[] =
527 {
528     0x147, 0x14B, 0x148, 0x14D, 0x150, 0x149, 0x151, 0x14F      /* FF50 */
529 };
530
531 static const WORD misc_key_vkey[] =
532 {
533     VK_SELECT, VK_SNAPSHOT, VK_EXECUTE, VK_INSERT, 0, 0, 0, 0,  /* FF60 */
534     VK_CANCEL, VK_HELP, VK_CANCEL, VK_CANCEL                    /* FF68 */
535 };
536 static const WORD misc_key_scan[] =
537 {
538     /*?*/ 0, 0x137, /*?*/ 0, 0x152, 0, 0, 0, 0,                 /* FF60 */
539     /*?*/ 0, /*?*/ 0, 0x38, 0x146                               /* FF68 */
540 };
541
542 static const WORD keypad_key_vkey[] =
543 {
544     0, VK_NUMLOCK,                                              /* FF7E */
545     0, 0, 0, 0, 0, 0, 0, 0,                                     /* FF80 */
546     0, 0, 0, 0, 0, VK_RETURN, 0, 0,                             /* FF88 */
547     0, 0, 0, 0, 0, VK_HOME, VK_LEFT, VK_UP,                     /* FF90 */
548     VK_RIGHT, VK_DOWN, VK_PRIOR, VK_NEXT, VK_END, 0,
549                                  VK_INSERT, VK_DELETE,          /* FF98 */
550     0, 0, 0, 0, 0, 0, 0, 0,                                     /* FFA0 */
551     0, 0, VK_MULTIPLY, VK_ADD, VK_SEPARATOR, VK_SUBTRACT, 
552                                VK_DECIMAL, VK_DIVIDE,           /* FFA8 */
553     VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4,
554                             VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, /* FFB0 */
555     VK_NUMPAD8, VK_NUMPAD9                                      /* FFB8 */
556 };
557 static const WORD keypad_key_scan[] =
558 {
559     0x138, 0x145,                                               /* FF7E */
560     0, 0, 0, 0, 0, 0, 0, 0,                                     /* FF80 */
561     0, 0, 0, 0, 0, 0x11C, 0, 0,                                 /* FF88 */
562     0, 0, 0, 0, 0, 0x47, 0x4B, 0x48,                            /* FF90 */
563     0x4D, 0x50, 0x49, 0x51, 0x4F, 0x4C, 0x52, 0x53,             /* FF98 */
564     0, 0, 0, 0, 0, 0, 0, 0,                                     /* FFA0 */
565     0, 0, 0x37, 0x4E, /*?*/ 0, 0x4A, 0x53, 0x135,               /* FFA8 */
566     0x52, 0x4F, 0x50, 0x51, 0x4B, 0x4C, 0x4D, 0x47,             /* FFB0 */
567     0x48, 0x49                                                  /* FFB8 */
568 };
569     
570 static const WORD function_key_vkey[] =
571 {
572     VK_F1, VK_F2,                                               /* FFBE */
573     VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_F10,    /* FFC0 */
574     VK_F11, VK_F12, VK_F13, VK_F14, VK_F15, VK_F16              /* FFC8 */
575 };
576 static const WORD function_key_scan[] =
577 {
578     0x3B, 0x3C,                                                 /* FFBE */
579     0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44,             /* FFC0 */
580     0x57, 0x58, 0, 0, 0, 0                                      /* FFC8 */
581 };
582
583 static const WORD modifier_key_vkey[] =
584 {
585     VK_SHIFT, VK_SHIFT, VK_CONTROL, VK_CONTROL, VK_CAPITAL, 0, /* FFE1 */
586     VK_MENU, VK_MENU, VK_MENU, VK_MENU                         /* FFE7 */
587 };
588 static const WORD modifier_key_scan[] =
589 {
590     0x2A, 0x36, 0x1D, 0x11D, 0x3A, 0,                          /* FFE1 */
591     0x38, 0x138, 0x38, 0x138                                   /* FFE7 */
592 };
593
594 /* Returns the Windows virtual key code associated with the X event <e> */
595 static WORD EVENT_event_to_vkey( XKeyEvent *e)
596 {
597     KeySym keysym;
598
599     TSXLookupString(e, NULL, 0, &keysym, NULL);
600
601     if ((keysym >= 0xFFAE) && (keysym <= 0xFFB9) && (keysym != 0xFFAF) 
602         && (e->state & NumLockMask)) 
603         /* Only the Keypad keys 0-9 and . send different keysyms
604          * depending on the NumLock state */
605         return keypad_key_vkey[(keysym & 0xFF) - 0x7E];
606
607     return keyc2vkey[e->keycode];
608 }
609
610 static BOOL NumState=FALSE, CapsState=FALSE, AltGrState=FALSE;
611
612 /**********************************************************************
613  *              KEYBOARD_GenerateMsg
614  *
615  * Generate Down+Up messages when NumLock or CapsLock is pressed.
616  *
617  * Convention : called with vkey only VK_NUMLOCK or VK_CAPITAL
618  *
619  */
620 static void KEYBOARD_GenerateMsg( WORD vkey, WORD scan, int Evtype, INT event_x, INT event_y,
621                            DWORD event_time )
622 {
623   BOOL * State = (vkey==VK_NUMLOCK? &NumState : &CapsState);
624   DWORD up, down;
625
626   if (*State) {
627     /* The INTERMEDIARY state means : just after a 'press' event, if a 'release' event comes,
628        don't treat it. It's from the same key press. Then the state goes to ON.
629        And from there, a 'release' event will switch off the toggle key. */
630     *State=FALSE;
631     TRACE("INTERM : don\'t treat release of toggle key. InputKeyStateTable[%#x] = %#x\n",vkey,pKeyStateTable[vkey]);
632   } else
633     {
634         down = (vkey==VK_NUMLOCK ? KEYEVENTF_EXTENDEDKEY : 0);
635         up = (vkey==VK_NUMLOCK ? KEYEVENTF_EXTENDEDKEY : 0) | KEYEVENTF_KEYUP;
636         if ( pKeyStateTable[vkey] & 0x1 ) /* it was ON */
637           {
638             if (Evtype!=KeyPress)
639               {
640                 TRACE("ON + KeyRelease => generating DOWN and UP messages.\n");
641                 KEYBOARD_SendEvent( vkey, scan, down,
642                                     event_x, event_y, event_time );
643                 KEYBOARD_SendEvent( vkey, scan, up, 
644                                     event_x, event_y, event_time );
645                 *State=FALSE;
646                 pKeyStateTable[vkey] &= ~0x01; /* Toggle state to off. */ 
647               } 
648           }
649         else /* it was OFF */
650           if (Evtype==KeyPress)
651             {
652               TRACE("OFF + Keypress => generating DOWN and UP messages.\n");
653               KEYBOARD_SendEvent( vkey, scan, down,
654                                   event_x, event_y, event_time );
655               KEYBOARD_SendEvent( vkey, scan, up, 
656                                   event_x, event_y, event_time );
657               *State=TRUE; /* Goes to intermediary state before going to ON */
658               pKeyStateTable[vkey] |= 0x01; /* Toggle state to on. */
659             }
660     }
661 }
662
663 /***********************************************************************
664  *           KEYBOARD_UpdateOneState
665  *
666  * Updates internal state for <vkey>, depending on key <state> under X
667  *
668  */
669 static void KEYBOARD_UpdateOneState ( int vkey, int state )
670 {
671     /* Do something if internal table state != X state for keycode */
672     if (((pKeyStateTable[vkey] & 0x80)!=0) != state)
673     {
674         TRACE("Adjusting state for vkey %#.2x. State before %#.2x \n",
675               vkey, pKeyStateTable[vkey]);
676
677         /* Fake key being pressed inside wine */
678         KEYBOARD_SendEvent( vkey, 0, state? 0 : KEYEVENTF_KEYUP, 
679                             0, 0, GetTickCount() );
680
681         TRACE("State after %#.2x \n",pKeyStateTable[vkey]);
682     }
683 }
684
685 /***********************************************************************
686  *           X11DRV_KEYBOARD_UpdateState
687  *
688  * Update modifiers state (Ctrl, Alt, Shift)
689  * when window is activated (called by EVENT_FocusIn in event.c)
690  *
691  * This handles the case where one uses Ctrl+... Alt+... or Shift+.. to switch
692  * from wine to another application and back.
693  * Toggle keys are handled in HandleEvent. (because XQueryKeymap says nothing
694  *  about them)
695  */
696 void X11DRV_KEYBOARD_UpdateState ( void )
697 {
698 /* extract a bit from the char[32] bit suite */
699 #define KeyState(keycode) ((keys_return[keycode/8] & (1<<(keycode%8)))!=0)
700
701     char keys_return[32];
702
703     TRACE("called\n");
704     if (!TSXQueryKeymap(thread_display(), keys_return)) {
705         ERR("Error getting keymap !\n");
706         return;
707     }
708
709     /* Adjust the ALT and CONTROL state if any has been changed outside wine */
710     KEYBOARD_UpdateOneState(VK_MENU, KeyState(kcAlt));
711     KEYBOARD_UpdateOneState(VK_CONTROL, KeyState(kcControl));
712     KEYBOARD_UpdateOneState(VK_SHIFT, KeyState(kcShift));
713 #undef KeyState
714 }
715
716 /***********************************************************************
717  *           X11DRV_KEYBOARD_HandleEvent
718  *
719  * Handle a X key event
720  */
721 void X11DRV_KEYBOARD_HandleEvent( XKeyEvent *event, int x, int y )
722 {
723     char Str[24]; 
724     KeySym keysym;
725     WORD vkey = 0, bScan;
726     DWORD dwFlags;
727     static BOOL force_extended = FALSE; /* hack for AltGr translation */
728     int ascii_chars;
729
730     DWORD event_time = event->time - X11DRV_server_startticks;
731
732     /* this allows support for dead keys */
733     if ((event->keycode >> 8) == 0x10)
734         event->keycode=(event->keycode & 0xff);
735
736     ascii_chars = TSXLookupString(event, Str, sizeof(Str), &keysym, NULL);
737
738     TRACE_(key)("state = %X\n", event->state);
739
740     /* If XKB extensions is used, the state mask for AltGr will used the group
741        index instead of the modifier mask. The group index is set in bits
742        13-14 of the state field in the XKeyEvent structure. So if AltGr is
743        pressed, look if the group index is diferent than 0. From XKB
744        extension documentation, the group index should for AltGr should 
745        be 2 (event->state = 0x2000). It's probably better to not assume a
746        predefined group index and find it dynamically
747
748        Ref: X Keyboard Extension: Library specification (section 14.1.1 and 17.1.1) */
749     if ( AltGrState && (event->state & 0x6000) )
750         AltGrMask = event->state & 0x6000;
751
752     if (keysym == XK_Mode_switch)
753         {
754         TRACE_(key)("Alt Gr key event received\n");
755         event->keycode = kcControl; /* Simulate Control */
756         X11DRV_KEYBOARD_HandleEvent( event, x, y );
757
758         event->keycode = kcAlt; /* Simulate Alt */
759         force_extended = TRUE;
760         X11DRV_KEYBOARD_HandleEvent( event, x, y );
761         force_extended = FALSE;
762     
763     /* Here we save the pressed/released state of the AltGr key, to be able to 
764        identify the group index associated with AltGr on the next key pressed *
765        see comment above. */
766     AltGrState = (event->type == KeyPress) ? TRUE : FALSE;
767     
768         return;
769         }
770
771     Str[ascii_chars] = '\0';
772     if (TRACE_ON(key)){
773         char    *ksname;
774
775         ksname = TSXKeysymToString(keysym);
776         if (!ksname)
777           ksname = "No Name";
778         TRACE_(key)("%s : keysym=%lX (%s), ascii chars=%u / %X / '%s'\n", 
779                     (event->type == KeyPress) ? "KeyPress" : "KeyRelease",
780                     keysym, ksname, ascii_chars, Str[0] & 0xff, Str);
781     }
782
783     vkey = EVENT_event_to_vkey(event);
784     if (force_extended) vkey |= 0x100;
785
786     TRACE_(key)("keycode 0x%x converted to vkey 0x%x\n",
787                 event->keycode, vkey);
788
789    if (vkey)
790    {
791     switch (vkey & 0xff)
792     {
793     case VK_NUMLOCK:    
794       KEYBOARD_GenerateMsg( VK_NUMLOCK, 0x45, event->type, x, y, event_time );
795       break;
796     case VK_CAPITAL:
797       TRACE("Caps Lock event. (type %d). State before : %#.2x\n",event->type,pKeyStateTable[vkey]);
798       KEYBOARD_GenerateMsg( VK_CAPITAL, 0x3A, event->type, x, y, event_time );
799       TRACE("State after : %#.2x\n",pKeyStateTable[vkey]);
800       break;
801     default:
802         /* Adjust the NUMLOCK state if it has been changed outside wine */
803         if (!(pKeyStateTable[VK_NUMLOCK] & 0x01) != !(event->state & NumLockMask))
804           { 
805             TRACE("Adjusting NumLock state. \n");
806             KEYBOARD_GenerateMsg( VK_NUMLOCK, 0x45, KeyPress, x, y, event_time );
807             KEYBOARD_GenerateMsg( VK_NUMLOCK, 0x45, KeyRelease, x, y, event_time );
808           }
809         /* Adjust the CAPSLOCK state if it has been changed outside wine */
810         if (!(pKeyStateTable[VK_CAPITAL] & 0x01) != !(event->state & LockMask))
811           {
812               TRACE("Adjusting Caps Lock state.\n");
813             KEYBOARD_GenerateMsg( VK_CAPITAL, 0x3A, KeyPress, x, y, event_time );
814             KEYBOARD_GenerateMsg( VK_CAPITAL, 0x3A, KeyRelease, x, y, event_time );
815           }
816         /* Not Num nor Caps : end of intermediary states for both. */
817         NumState = FALSE;
818         CapsState = FALSE;
819
820         bScan = keyc2scan[event->keycode] & 0xFF;
821         TRACE_(key)("bScan = 0x%02x.\n", bScan);
822
823         dwFlags = 0;
824         if ( event->type == KeyRelease ) dwFlags |= KEYEVENTF_KEYUP;
825         if ( vkey & 0x100 )              dwFlags |= KEYEVENTF_EXTENDEDKEY;
826         if ( force_extended )            dwFlags |= KEYEVENTF_WINE_FORCEEXTENDED;
827
828         KEYBOARD_SendEvent( vkey & 0xff, bScan, dwFlags, x, y, event_time );
829     }
830    }
831 }
832
833 /**********************************************************************
834  *              X11DRV_KEYBOARD_DetectLayout
835  *
836  * Called from X11DRV_InitKeyboard
837  *  This routine walks through the defined keyboard layouts and selects
838  *  whichever matches most closely.
839  */
840 static void
841 X11DRV_KEYBOARD_DetectLayout (void)
842 {
843   Display *display = thread_display();
844   unsigned current, match, mismatch, seq;
845   int score, keyc, i, key, pkey, ok, syms;
846   KeySym keysym;
847   const char (*lkey)[MAIN_LEN][4];
848   unsigned max_seq = 0;
849   int max_score = 0, ismatch = 0;
850   char ckey[4] =
851   {0, 0, 0, 0};
852
853   syms = keysyms_per_keycode;
854   if (syms > 4) {
855     WARN("%d keysyms per keycode not supported, set to 4\n", syms);
856     syms = 4;
857   }
858   for (current = 0; main_key_tab[current].comment; current++) {
859     TRACE("Attempting to match against \"%s\"\n", main_key_tab[current].comment);
860     match = 0;
861     mismatch = 0;
862     score = 0;
863     seq = 0;
864     lkey = main_key_tab[current].key;
865     pkey = -1;
866     for (keyc = min_keycode; keyc <= max_keycode; keyc++) {
867       /* get data for keycode from X server */
868       for (i = 0; i < syms; i++) {
869         keysym = TSXKeycodeToKeysym (display, keyc, i);
870         /* Allow both one-byte and two-byte national keysyms */
871         if ((keysym < 0x800) && (keysym != ' '))
872           ckey[i] = keysym & 0xFF;
873         else {
874           ckey[i] = KEYBOARD_MapDeadKeysym(keysym);
875         }
876       }
877       if (ckey[0]) {
878         /* search for a match in layout table */
879         /* right now, we just find an absolute match for defined positions */
880         /* (undefined positions are ignored, so if it's defined as "3#" in */
881         /* the table, it's okay that the X server has "3#£", for example) */
882         /* however, the score will be higher for longer matches */
883         for (key = 0; key < MAIN_LEN; key++) {
884           for (ok = 0, i = 0; (ok >= 0) && (i < syms); i++) {
885             if ((*lkey)[key][i] && ((*lkey)[key][i] == ckey[i]))
886               ok++;
887             if ((*lkey)[key][i] && ((*lkey)[key][i] != ckey[i]))
888               ok = -1;
889           }
890           if (ok > 0) {
891             score += ok;
892             break;
893           }
894         }
895         /* count the matches and mismatches */
896         if (ok > 0) {
897           match++;
898           /* and how much the keycode order matches */
899           if (key > pkey) seq++;
900           pkey = key;
901         } else {
902           TRACE_(key)("mismatch for keycode %d, character %c\n", keyc,
903                  ckey[0]);
904           mismatch++;
905           score -= syms;
906         }
907       }
908     }
909     TRACE("matches=%d, mismatches=%d, score=%d\n",
910            match, mismatch, score);
911     if ((score > max_score) ||
912         ((score == max_score) && (seq > max_seq))) {
913       /* best match so far */
914       kbd_layout = current;
915       max_score = score;
916       max_seq = seq;
917       ismatch = !mismatch;
918     }
919   }
920   /* we're done, report results if necessary */
921   if (!ismatch) {
922     FIXME(
923            "Your keyboard layout was not found!\n"
924            "Using closest match instead (%s) for scancode mapping.\n"
925            "Please define your layout in windows/x11drv/keyboard.c and submit them\n"
926            "to us for inclusion into future Wine releases.\n"
927            "See the Wine User Guide, chapter \"Keyboard\" for more information.\n",
928            main_key_tab[kbd_layout].comment);
929   }
930
931   TRACE("detected layout is \"%s\"\n", main_key_tab[kbd_layout].comment);
932 }
933
934 /**********************************************************************
935  *              InitKeyboard (X11DRV.@)
936  */
937 void X11DRV_InitKeyboard(void)
938 {
939 #ifdef HAVE_XKB
940     int xkb_major = XkbMajorVersion, xkb_minor = XkbMinorVersion;
941 #endif
942     Display *display = thread_display();
943     KeySym *ksp;
944     XModifierKeymap *mmp;
945     KeySym keysym;
946     KeyCode *kcp;
947     XKeyEvent e2;
948     WORD scan, vkey, OEMvkey;
949     int keyc, i, keyn, syms;
950     char ckey[4]={0,0,0,0};
951     const char (*lkey)[MAIN_LEN][4];
952
953 #ifdef HAVE_XKB
954     wine_tsx11_lock();
955     is_xkb = XkbQueryExtension(display,
956                                &xkb_opcode, &xkb_event, &xkb_error,
957                                &xkb_major, &xkb_minor);
958     if (is_xkb) {
959         /* we have XKB, approximate Windows behaviour */
960         XkbSetDetectableAutoRepeat(display, True, NULL);
961     }
962     wine_tsx11_unlock();
963 #endif
964     TSXDisplayKeycodes(display, &min_keycode, &max_keycode);
965     ksp = TSXGetKeyboardMapping(display, min_keycode,
966                               max_keycode + 1 - min_keycode, &keysyms_per_keycode);
967     /* We are only interested in keysyms_per_keycode.
968        There is no need to hold a local copy of the keysyms table */
969     TSXFree(ksp);
970     mmp = TSXGetModifierMapping(display);
971     kcp = mmp->modifiermap;
972     for (i = 0; i < 8; i += 1) /* There are 8 modifier keys */
973     {
974         int j;
975         
976         for (j = 0; j < mmp->max_keypermod; j += 1, kcp += 1)
977             if (*kcp)
978             {
979                 int k;
980                 
981                 for (k = 0; k < keysyms_per_keycode; k += 1)
982                     if (TSXKeycodeToKeysym(display, *kcp, k) == XK_Mode_switch)
983                     {
984                         AltGrMask = 1 << i;
985                         TRACE_(key)("AltGrMask is %x\n", AltGrMask);
986                     }
987                     else if (TSXKeycodeToKeysym(display, *kcp, k) == XK_Num_Lock)
988                     {
989                         NumLockMask = 1 << i;
990                         TRACE_(key)("NumLockMask is %x\n", NumLockMask);
991                     }
992             }
993     }
994     TSXFreeModifiermap(mmp);
995
996     /* Detect the keyboard layout */
997     X11DRV_KEYBOARD_DetectLayout();
998     lkey = main_key_tab[kbd_layout].key;
999     syms = (keysyms_per_keycode > 4) ? 4 : keysyms_per_keycode;
1000
1001     /* Now build two conversion arrays :
1002      * keycode -> vkey + scancode + extended
1003      * vkey + extended -> keycode */
1004
1005     e2.display = display;
1006     e2.state = 0;
1007
1008     OEMvkey = VK_OEM_7; /* next is available.  */
1009     for (keyc = min_keycode; keyc <= max_keycode; keyc++)
1010     {
1011         e2.keycode = (KeyCode)keyc;
1012         TSXLookupString(&e2, NULL, 0, &keysym, NULL);
1013         vkey = 0; scan = 0;
1014         if (keysym)  /* otherwise, keycode not used */
1015         {
1016             if ((keysym >> 8) == 0xFF)         /* non-character key */
1017             {
1018                 int key = keysym & 0xff;
1019                 
1020                 if (key >= 0x08 && key <= 0x1B) {        /* special key */
1021                     vkey = special_key_vkey[key - 0x08];
1022                     scan = special_key_scan[key - 0x08];
1023                 } else if (key >= 0x50 && key <= 0x57) { /* cursor key */
1024                     vkey = cursor_key_vkey[key - 0x50];
1025                     scan = cursor_key_scan[key - 0x50];
1026                 } else if (key >= 0x60 && key <= 0x6B) { /* miscellaneous key */
1027                     vkey = misc_key_vkey[key - 0x60];
1028                     scan = misc_key_scan[key - 0x60];
1029                 } else if (key >= 0x7E && key <= 0xB9) { /* keypad key */
1030                     vkey = keypad_key_vkey[key - 0x7E];
1031                     scan = keypad_key_scan[key - 0x7E];
1032                 } else if (key >= 0xBE && key <= 0xCD) { /* function key */
1033                     vkey = function_key_vkey[key - 0xBE] | 0x100; /* set extended bit */
1034                     scan = function_key_scan[key - 0xBE];
1035                 } else if (key >= 0xE1 && key <= 0xEA) { /* modifier key */
1036                     vkey = modifier_key_vkey[key - 0xE1];
1037                     scan = modifier_key_scan[key - 0xE1];
1038                 } else if (key == 0xFF) {                /* DEL key */
1039                     vkey = VK_DELETE;
1040                     scan = 0x153;
1041                 }
1042                 /* set extended bit when necessary */
1043                 if (scan & 0x100) vkey |= 0x100;
1044             } else if (keysym == 0x20) {                 /* Spacebar */
1045                 vkey = VK_SPACE;
1046                 scan = 0x39;
1047             } else {
1048               /* we seem to need to search the layout-dependent scancodes */
1049               int maxlen=0,maxval=-1,ok;
1050               for (i=0; i<syms; i++) {
1051                 keysym = TSXKeycodeToKeysym(display, keyc, i);
1052                 if ((keysym<0x800) && (keysym!=' ')) {
1053                   ckey[i] = keysym & 0xFF;
1054                 } else {
1055                   ckey[i] = KEYBOARD_MapDeadKeysym(keysym);
1056                 }
1057               }
1058               /* find key with longest match streak */
1059               for (keyn=0; keyn<MAIN_LEN; keyn++) {
1060                 for (ok=(*lkey)[keyn][i=0]; ok&&(i<4); i++)
1061                   if ((*lkey)[keyn][i] && (*lkey)[keyn][i]!=ckey[i]) ok=0;
1062                 if (ok||(i>maxlen)) {
1063                   maxlen=i; maxval=keyn;
1064                 }
1065                 if (ok) break;
1066               }
1067               if (maxval>=0) {
1068                 /* got it */
1069                 const WORD (*lscan)[MAIN_LEN] = main_key_tab[kbd_layout].scan;
1070                 const WORD (*lvkey)[MAIN_LEN] = main_key_tab[kbd_layout].vkey;
1071                 scan = (*lscan)[maxval];
1072                 vkey = (*lvkey)[maxval];
1073               }
1074             }
1075
1076             /* find a suitable layout-dependent VK code */
1077             /* (most Winelib apps ought to be able to work without layout tables!) */
1078             for (i = 0; (i < keysyms_per_keycode) && (!vkey); i++)
1079             {
1080                 keysym = TSXLookupKeysym(&e2, i);
1081                 if ((keysym >= VK_0 && keysym <= VK_9)
1082                     || (keysym >= VK_A && keysym <= VK_Z)) {
1083                     vkey = keysym;
1084                 }
1085             }
1086
1087             for (i = 0; (i < keysyms_per_keycode) && (!vkey); i++)
1088             {
1089                 keysym = TSXLookupKeysym(&e2, i);
1090                 switch (keysym)
1091                 {
1092                 case ';':             vkey = VK_OEM_1; break;
1093                 case '/':             vkey = VK_OEM_2; break;
1094                 case '`':             vkey = VK_OEM_3; break;
1095                 case '[':             vkey = VK_OEM_4; break;
1096                 case '\\':            vkey = VK_OEM_5; break;
1097                 case ']':             vkey = VK_OEM_6; break;
1098                 case '\'':            vkey = VK_OEM_7; break;
1099                 case ',':             vkey = VK_OEM_COMMA; break;
1100                 case '.':             vkey = VK_OEM_PERIOD; break;
1101                 case '-':             vkey = VK_OEM_MINUS; break;
1102                 case '+':             vkey = VK_OEM_PLUS; break;
1103                 }
1104             }
1105
1106             if (!vkey)
1107             {
1108                 /* Others keys: let's assign OEM virtual key codes in the allowed range,
1109                  * that is ([0xba,0xc0], [0xdb,0xe4], 0xe6 (given up) et [0xe9,0xf5]) */
1110                 switch (++OEMvkey)
1111                 {
1112                 case 0xc1 : OEMvkey=0xdb; break;
1113                 case 0xe5 : OEMvkey=0xe9; break;
1114                 case 0xf6 : OEMvkey=0xf5; WARN("No more OEM vkey available!\n");
1115                 }
1116
1117                 vkey = OEMvkey;
1118                   
1119                 if (TRACE_ON(keyboard))
1120                 {
1121                     TRACE("OEM specific virtual key %X assigned to keycode %X:\n",
1122                                      OEMvkey, e2.keycode);
1123                     TRACE("(");
1124                     for (i = 0; i < keysyms_per_keycode; i += 1)
1125                     {
1126                         char    *ksname;
1127                         
1128                         keysym = TSXLookupKeysym(&e2, i);
1129                         ksname = TSXKeysymToString(keysym);
1130                         if (!ksname)
1131                             ksname = "NoSymbol";
1132                         DPRINTF( "%lX (%s) ", keysym, ksname);
1133                     }
1134                     DPRINTF(")\n");
1135                 }
1136             }
1137         }
1138         keyc2vkey[e2.keycode] = vkey;
1139         keyc2scan[e2.keycode] = scan;
1140     } /* for */
1141
1142     /* If some keys still lack scancodes, assign some arbitrary ones to them now */
1143     for (scan = 0x60, keyc = min_keycode; keyc <= max_keycode; keyc++)
1144       if (keyc2vkey[keyc]&&!keyc2scan[keyc]) {
1145         char *ksname;
1146         keysym = TSXKeycodeToKeysym(display, keyc, 0);
1147         ksname = TSXKeysymToString(keysym);
1148         if (!ksname) ksname = "NoSymbol";
1149
1150         /* should make sure the scancode is unassigned here, but >=0x60 currently always is */
1151
1152         TRACE_(key)("assigning scancode %02x to unidentified keycode %02x (%s)\n",scan,keyc,ksname);
1153         keyc2scan[keyc]=scan++;
1154       }
1155
1156     /* Now store one keycode for each modifier. Used to simulate keypresses. */
1157     kcControl = TSXKeysymToKeycode(display, XK_Control_L);
1158     kcAlt = TSXKeysymToKeycode(display, XK_Alt_L);
1159     if (!kcAlt) kcAlt = TSXKeysymToKeycode(display, XK_Meta_L);
1160     kcShift = TSXKeysymToKeycode(display, XK_Shift_L);
1161     kcNumLock = TSXKeysymToKeycode(display, XK_Num_Lock);
1162     kcCapsLock = TSXKeysymToKeycode(display, XK_Caps_Lock);
1163 }
1164
1165 /***********************************************************************
1166  *              VkKeyScan (X11DRV.@)
1167  */
1168 WORD X11DRV_VkKeyScan(CHAR cChar)
1169 {
1170         Display *display = thread_display();
1171         KeyCode keycode;
1172         KeySym keysym;          
1173         int i,index;
1174         int highbyte=0;
1175
1176         /* char->keysym (same for ANSI chars) */
1177         keysym=(unsigned char) cChar;/* (!) cChar is signed */
1178         if (keysym<=27) keysym+=0xFF00;/*special chars : return, backspace...*/
1179         
1180         keycode = TSXKeysymToKeycode(display, keysym);  /* keysym -> keycode */
1181         if (!keycode)
1182         { /* It didn't work ... let's try with deadchar code. */
1183           keycode = TSXKeysymToKeycode(display, keysym | 0xFE00);
1184         }
1185
1186         TRACE("VkKeyScan '%c'(%#lx, %lu): got keycode %#.2x\n",
1187               cChar,keysym,keysym,keycode);
1188         
1189         if (keycode)
1190           {
1191             for (index=-1, i=0; (i<8) && (index<0); i++) /* find shift state */
1192               if (TSXKeycodeToKeysym(display,keycode,i)==keysym) index=i;
1193             switch (index) {
1194             case -1 :
1195               WARN("Keysym %lx not found while parsing the keycode table\n",keysym); break;
1196             case 0 : break;
1197             case 1 : highbyte = 0x0100; break;
1198             case 2 : highbyte = 0x0600; break;
1199             case 3 : highbyte = 0x0700; break;
1200             default : ERR("index %d found by XKeycodeToKeysym. please report! \n",index);
1201             }
1202             /*
1203               index : 0     adds 0x0000
1204               index : 1     adds 0x0100 (shift)
1205               index : ?     adds 0x0200 (ctrl)
1206               index : 2     adds 0x0600 (ctrl+alt)
1207               index : 3     adds 0x0700 (ctrl+alt+shift)
1208              */
1209           }
1210         TRACE(" ... returning %#.2x\n", keyc2vkey[keycode]+highbyte);
1211         return keyc2vkey[keycode]+highbyte;   /* keycode -> (keyc2vkey) vkey */
1212 }
1213
1214 /***********************************************************************
1215  *              MapVirtualKey (X11DRV.@)
1216  */
1217 UINT16 X11DRV_MapVirtualKey(UINT16 wCode, UINT16 wMapType)
1218 {
1219     Display *display = thread_display();
1220
1221 #define returnMVK(value) { TRACE("returning 0x%x.\n",value); return value; }
1222
1223         TRACE("MapVirtualKey wCode=0x%x wMapType=%d ... \n", wCode,wMapType);
1224         switch(wMapType) {
1225                 case 0: { /* vkey-code to scan-code */
1226                         /* let's do vkey -> keycode -> scan */
1227                         int keyc;
1228                         for (keyc=min_keycode; keyc<=max_keycode; keyc++)
1229                                 if ((keyc2vkey[keyc] & 0xFF) == wCode)
1230                                         returnMVK (keyc2scan[keyc] & 0xFF);
1231                         TRACE("returning no scan-code.\n");
1232                         return 0; }
1233
1234                 case 1: { /* scan-code to vkey-code */
1235                         /* let's do scan -> keycode -> vkey */
1236                         int keyc;
1237                         for (keyc=min_keycode; keyc<=max_keycode; keyc++)
1238                                 if ((keyc2scan[keyc] & 0xFF) == (wCode & 0xFF))
1239                                         returnMVK (keyc2vkey[keyc] & 0xFF);
1240                         TRACE("returning no vkey-code.\n");
1241                         return 0; }
1242
1243                 case 2: { /* vkey-code to unshifted ANSI code */
1244                         /* (was FIXME) : what does unshifted mean ? 'a' or 'A' ? */
1245                         /* My Windows returns 'A'. */
1246                         /* let's do vkey -> keycode -> (XLookupString) ansi char */
1247                         XKeyEvent e;
1248                         KeySym keysym;
1249                         int keyc;
1250                         char s[2];
1251                         e.display = display;
1252                         e.state = 0; /* unshifted */
1253
1254                         e.keycode = 0;
1255                         /* We exit on the first keycode found, to speed up the thing. */
1256                         for (keyc=min_keycode; (keyc<=max_keycode) && (!e.keycode) ; keyc++)
1257                         { /* Find a keycode that could have generated this virtual key */
1258                             if  ((keyc2vkey[keyc] & 0xFF) == wCode)
1259                             { /* We filter the extended bit, we don't know it */
1260                                 e.keycode = keyc; /* Store it temporarily */
1261                                 if ((EVENT_event_to_vkey(&e) & 0xFF) != wCode) {
1262                                     e.keycode = 0; /* Wrong one (ex: because of the NumLock
1263                                          state), so set it to 0, we'll find another one */
1264                                 }
1265                             }
1266                         }
1267
1268                         if ((wCode>=VK_NUMPAD0) && (wCode<=VK_NUMPAD9))
1269                           e.keycode = TSXKeysymToKeycode(e.display, wCode-VK_NUMPAD0+XK_KP_0);
1270           
1271                         if (wCode==VK_DECIMAL)
1272                           e.keycode = TSXKeysymToKeycode(e.display, XK_KP_Decimal);
1273
1274                         if (!e.keycode)
1275                         {
1276                           WARN("Unknown virtual key %X !!! \n", wCode);
1277                           return 0; /* whatever */
1278                         }
1279                         TRACE("Found keycode %d (0x%2X)\n",e.keycode,e.keycode);
1280
1281                         if (TSXLookupString(&e, s, 2, &keysym, NULL))
1282                           returnMVK (*s);
1283                         
1284                         TRACE("returning no ANSI.\n");
1285                         return 0;
1286                         }
1287
1288                 case 3:   /* **NT only** scan-code to vkey-code but distinguish between  */
1289                           /*             left and right  */
1290                           FIXME(" stub for NT\n");
1291                           return 0;
1292
1293                 default: /* reserved */
1294                         WARN("Unknown wMapType %d !\n", wMapType);
1295                         return 0;       
1296         }
1297         return 0;
1298 }
1299
1300 /***********************************************************************
1301  *              GetKeyNameText (X11DRV.@)
1302  */
1303 INT16 X11DRV_GetKeyNameText(LONG lParam, LPSTR lpBuffer, INT16 nSize)
1304 {
1305   int vkey, ansi, scanCode;
1306   KeyCode keyc;
1307   KeySym keys;
1308   char *name;
1309         
1310   scanCode = lParam >> 16;
1311   scanCode &= 0x1ff;  /* keep "extended-key" flag with code */
1312
1313   /* FIXME: should use MVK type 3 (NT version that distinguishes right and left */
1314   vkey = X11DRV_MapVirtualKey(scanCode, 1);
1315
1316   /*  handle "don't care" bit (0x02000000) */
1317   if (!(lParam & 0x02000000)) {
1318     switch (vkey) {
1319          case VK_LSHIFT:
1320          case VK_RSHIFT:
1321                           vkey = VK_SHIFT;
1322                           break;
1323        case VK_LCONTROL:
1324        case VK_RCONTROL:
1325                           vkey = VK_CONTROL;
1326                           break;
1327           case VK_LMENU:
1328           case VK_RMENU:
1329                           vkey = VK_MENU;
1330                           break;
1331                default:
1332                           break;
1333     }
1334   }
1335
1336   ansi = X11DRV_MapVirtualKey(vkey, 2);
1337   TRACE("scan 0x%04x, vkey 0x%04x, ANSI 0x%04x\n", scanCode, vkey, ansi);
1338
1339   /* first get the name of the "regular" keys which is the Upper case
1340      value of the keycap imprint.                                     */
1341   if ( ((ansi >= 0x21) && (ansi <= 0x7e)) &&
1342        (scanCode != 0x137) &&   /* PrtScn   */
1343        (scanCode != 0x135) &&   /* numpad / */
1344        (scanCode != 0x37 ) &&   /* numpad * */
1345        (scanCode != 0x4a ) &&   /* numpad - */
1346        (scanCode != 0x4e ) )    /* numpad + */
1347       {
1348         if ((nSize >= 2) && lpBuffer)
1349         {
1350         *lpBuffer = toupper((char)ansi);
1351           *(lpBuffer+1) = 0;
1352           return 1;
1353         } 
1354      else
1355         return 0;
1356   }
1357
1358   /* FIXME: horrible hack to fix function keys. Windows reports scancode
1359             without "extended-key" flag. However Wine generates scancode
1360             *with* "extended-key" flag. Seems to occur *only* for the
1361             function keys. Soooo.. We will leave the table alone and
1362             fudge the lookup here till the other part is found and fixed!!! */
1363
1364   if ( ((scanCode >= 0x13b) && (scanCode <= 0x144)) ||
1365        (scanCode == 0x157) || (scanCode == 0x158))
1366     scanCode &= 0xff;   /* remove "extended-key" flag for Fx keys */
1367
1368   /* let's do scancode -> keycode -> keysym -> String */
1369
1370   for (keyc=min_keycode; keyc<=max_keycode; keyc++)
1371       if ((keyc2scan[keyc]) == scanCode)
1372          break;
1373   if (keyc <= max_keycode)
1374   {
1375       keys = TSXKeycodeToKeysym(thread_display(), keyc, 0);
1376       name = TSXKeysymToString(keys);
1377       TRACE("found scan=%04x keyc=%04x keysym=%04x string=%s\n",
1378             scanCode, keyc, (int)keys, name);
1379       if (lpBuffer && nSize && name)
1380       {
1381           lstrcpynA(lpBuffer, name, nSize);
1382           return 1;
1383       }
1384   }
1385
1386   /* Finally issue FIXME for unknown keys   */
1387
1388   FIXME("(%08lx,%p,%d): unsupported key, vkey=%04x, ansi=%04x\n",lParam,lpBuffer,nSize,vkey,ansi);
1389   if (lpBuffer && nSize)
1390     *lpBuffer = 0;
1391   return 0;
1392 }
1393
1394 /***********************************************************************
1395  *              X11DRV_KEYBOARD_MapDeadKeysym
1396  */
1397 static char KEYBOARD_MapDeadKeysym(KeySym keysym)
1398 {
1399         switch (keysym)
1400             {
1401         /* symbolic ASCII is the same as defined in rfc1345 */
1402 #ifdef XK_dead_tilde
1403             case XK_dead_tilde :
1404 #endif
1405             case 0x1000FE7E : /* Xfree's XK_Dtilde */
1406                 return '~';     /* '? */
1407 #ifdef XK_dead_acute
1408             case XK_dead_acute :
1409 #endif
1410             case 0x1000FE27 : /* Xfree's XK_Dacute_accent */
1411                 return 0xb4;    /* '' */
1412 #ifdef XK_dead_circumflex
1413             case XK_dead_circumflex:
1414 #endif
1415             case 0x1000FE5E : /* Xfree's XK_Dcircumflex_accent */
1416                 return '^';     /* '> */
1417 #ifdef XK_dead_grave
1418             case XK_dead_grave :
1419 #endif
1420             case 0x1000FE60 : /* Xfree's XK_Dgrave_accent */
1421                 return '`';     /* '! */
1422 #ifdef XK_dead_diaeresis
1423             case XK_dead_diaeresis :
1424 #endif
1425             case 0x1000FE22 : /* Xfree's XK_Ddiaeresis */
1426                 return 0xa8;    /* ': */
1427 #ifdef XK_dead_cedilla
1428             case XK_dead_cedilla :
1429                 return 0xb8;    /* ', */
1430 #endif
1431 #ifdef XK_dead_macron
1432             case XK_dead_macron :
1433                 return '-';     /* 'm isn't defined on iso-8859-x */
1434 #endif
1435 #ifdef XK_dead_breve
1436             case XK_dead_breve :
1437                 return 0xa2;    /* '( */
1438 #endif
1439 #ifdef XK_dead_abovedot
1440             case XK_dead_abovedot :
1441                 return 0xff;    /* '. */
1442 #endif
1443 #ifdef XK_dead_abovering
1444             case XK_dead_abovering :
1445                 return '0';     /* '0 isn't defined on iso-8859-x */
1446 #endif
1447 #ifdef XK_dead_doubleacute
1448             case XK_dead_doubleacute :
1449                 return 0xbd;    /* '" */
1450 #endif
1451 #ifdef XK_dead_caron
1452             case XK_dead_caron :
1453                 return 0xb7;    /* '< */
1454 #endif
1455 #ifdef XK_dead_ogonek
1456             case XK_dead_ogonek :
1457                 return 0xb2;    /* '; */
1458 #endif
1459 /* FIXME: I don't know this three.
1460             case XK_dead_iota :
1461                 return 'i';      
1462             case XK_dead_voiced_sound :
1463                 return 'v';
1464             case XK_dead_semivoiced_sound :
1465                 return 's';
1466 */
1467             }
1468         TRACE("no character for dead keysym 0x%08lx\n",keysym);
1469         return 0;
1470 }
1471
1472 /***********************************************************************
1473  *              ToUnicode (X11DRV.@)
1474  *
1475  * The ToUnicode function translates the specified virtual-key code and keyboard
1476  * state to the corresponding Windows character or characters.
1477  *
1478  * If the specified key is a dead key, the return value is negative. Otherwise,
1479  * it is one of the following values:
1480  * Value        Meaning
1481  * 0    The specified virtual key has no translation for the current state of the keyboard.
1482  * 1    One Windows character was copied to the buffer.
1483  * 2    Two characters were copied to the buffer. This usually happens when a
1484  *      dead-key character (accent or diacritic) stored in the keyboard layout cannot
1485  *      be composed with the specified virtual key to form a single character.
1486  *
1487  * FIXME : should do the above (return 2 for non matching deadchar+char combinations)
1488  *
1489  */
1490 INT X11DRV_ToUnicode(UINT virtKey, UINT scanCode, LPBYTE lpKeyState,
1491                      LPWSTR bufW, int bufW_size, UINT flags)
1492 {
1493     Display *display = thread_display();
1494     XKeyEvent e;
1495     KeySym keysym;
1496     INT ret;
1497     int keyc;
1498     BYTE lpChar[2];
1499
1500     if (scanCode==0) {
1501         /* This happens when doing Alt+letter : a fake 'down arrow' key press
1502            event is generated by windows. Just ignore it. */
1503         TRACE("scanCode=0, doing nothing\n");
1504         return 0;
1505     }
1506     if (scanCode & 0x8000)
1507     {
1508         TRACE("Key UP, doing nothing\n" );
1509         return 0;
1510     }
1511     e.display = display;
1512     e.keycode = 0;
1513     e.state = 0;
1514     if (lpKeyState[VK_SHIFT] & 0x80)
1515         e.state |= ShiftMask;
1516     if (lpKeyState[VK_CAPITAL] & 0x01)
1517         e.state |= LockMask;
1518     if (lpKeyState[VK_CONTROL] & 0x80)
1519     {
1520         if (lpKeyState[VK_MENU] & 0x80)
1521             e.state |= AltGrMask;
1522         else
1523             e.state |= ControlMask;
1524     }
1525     if (lpKeyState[VK_NUMLOCK] & 0x01)
1526         e.state |= NumLockMask;
1527     TRACE_(key)("(%04X, %04X) : faked state = %X\n",
1528                 virtKey, scanCode, e.state);
1529     /* We exit on the first keycode found, to speed up the thing. */
1530     for (keyc=min_keycode; (keyc<=max_keycode) && (!e.keycode) ; keyc++)
1531       { /* Find a keycode that could have generated this virtual key */
1532           if  ((keyc2vkey[keyc] & 0xFF) == virtKey)
1533           { /* We filter the extended bit, we don't know it */
1534               e.keycode = keyc; /* Store it temporarily */
1535               if ((EVENT_event_to_vkey(&e) & 0xFF) != virtKey) {
1536                   e.keycode = 0; /* Wrong one (ex: because of the NumLock
1537                          state), so set it to 0, we'll find another one */
1538               }
1539           }
1540       }
1541
1542     if ((virtKey>=VK_NUMPAD0) && (virtKey<=VK_NUMPAD9))
1543         e.keycode = TSXKeysymToKeycode(e.display, virtKey-VK_NUMPAD0+XK_KP_0);
1544           
1545     if (virtKey==VK_DECIMAL)
1546         e.keycode = TSXKeysymToKeycode(e.display, XK_KP_Decimal);
1547
1548     if (!e.keycode)
1549       {
1550         WARN("Unknown virtual key %X !!! \n",virtKey);
1551         return virtKey; /* whatever */
1552       }
1553     else TRACE("Found keycode %d (0x%2X)\n",e.keycode,e.keycode);
1554
1555     ret = TSXLookupString(&e, (LPVOID)lpChar, 2, &keysym, NULL);
1556     if (ret == 0)
1557         {
1558         BYTE dead_char;
1559
1560         dead_char = KEYBOARD_MapDeadKeysym(keysym);
1561         if (dead_char)
1562             {
1563             MultiByteToWideChar(main_key_tab[kbd_layout].layout_cp, 0, &dead_char, 1, bufW, bufW_size);
1564             ret = -1;
1565             }
1566         else
1567             {
1568             char        *ksname;
1569
1570             ksname = TSXKeysymToString(keysym);
1571             if (!ksname)
1572                 ksname = "No Name";
1573             if ((keysym >> 8) != 0xff)
1574                 {
1575                 ERR("Please report: no char for keysym %04lX (%s) :\n",
1576                     keysym, ksname);
1577                 ERR("(virtKey=%X,scanCode=%X,keycode=%X,state=%X)\n",
1578                     virtKey, scanCode, e.keycode, e.state);
1579                 }
1580             }
1581         }
1582     else {  /* ret != 0 */
1583         /* We have a special case to handle : Shift + arrow, shift + home, ...
1584            X returns a char for it, but Windows doesn't. Let's eat it. */
1585         if (!(e.state & NumLockMask)  /* NumLock is off */
1586             && (e.state & ShiftMask) /* Shift is pressed */
1587             && (keysym>=XK_KP_0) && (keysym<=XK_KP_9))
1588         {
1589             *(char*)lpChar = 0;
1590             ret = 0;
1591         }
1592
1593         /* more areas where X returns characters but Windows does not 
1594            CTRL + number or CTRL + symbol*/
1595         if (e.state & ControlMask)
1596         {
1597             if (((keysym>=33) && (keysym < 'A')) ||
1598                 ((keysym > 'Z') && (keysym < 'a')))
1599             {
1600                 *(char*)lpChar = 0;
1601                 ret = 0;
1602             }
1603         }
1604
1605         /* We have another special case for delete key (XK_Delete) on an
1606          extended keyboard. X returns a char for it, but Windows doesn't */
1607         if (keysym == XK_Delete)
1608         {
1609             *(char*)lpChar = 0;
1610             ret = 0;
1611         }
1612         else if((lpKeyState[VK_SHIFT] & 0x80) /* Shift is pressed */
1613                 && (keysym == XK_KP_Decimal))
1614         {
1615             *(char*)lpChar = 0;
1616             ret = 0;
1617         }
1618
1619         /* perform translation to unicode */
1620         if(ret)
1621         {
1622             TRACE_(key)("Translating char 0x%02x from code page %d to unicode\n",
1623                 *(BYTE *)lpChar, main_key_tab[kbd_layout].layout_cp);
1624             ret = MultiByteToWideChar(main_key_tab[kbd_layout].layout_cp, 0, (LPCSTR)lpChar, ret, bufW, bufW_size);
1625         }
1626     }
1627
1628     TRACE_(key)("ToUnicode about to return %d with char %x %s\n",
1629                 ret, bufW ? bufW[0] : 0, bufW ? "" : "(no buffer)");
1630     return ret;
1631 }
1632
1633 /***********************************************************************
1634  *              Beep (X11DRV.@)
1635  */
1636 void X11DRV_Beep(void)
1637 {
1638   TSXBell(thread_display(), 0);
1639 }
1640
1641 /***********************************************************************
1642  *              GetDIState (X11DRV.@)
1643  */
1644 BOOL X11DRV_GetDIState(DWORD len, LPVOID ptr)
1645 {
1646   if (len==256) {
1647     int keyc,vkey;
1648     
1649     memset(ptr,0,256);
1650     for (keyc=min_keycode;keyc<max_keycode;keyc++)
1651       {
1652         /* X keycode to virtual key */
1653         vkey = keyc2vkey[keyc] & 0xFF;
1654         /* The windows scancode is keyc-min_keycode */
1655         if (InputKeyStateTable[vkey]&0x80) {
1656           ((LPBYTE)ptr)[keyc-min_keycode]=0x80;
1657           ((LPBYTE)ptr)[(keyc-min_keycode)|0x80]=0x80;
1658         }
1659       }
1660     return TRUE;
1661   }
1662   WARN("whoops, got len %ld?\n", len);
1663   return TRUE;
1664 }
1665
1666 /***********************************************************************
1667  *              GetDIData (X11DRV.@)
1668  */
1669 BOOL X11DRV_GetDIData(
1670   BYTE *keystate,
1671   DWORD dodsize, LPDIDEVICEOBJECTDATA dod,
1672   LPDWORD entries, DWORD flags)
1673 {
1674   int keyc,n,vkey,xentries;
1675     
1676   /* FIXME !!! */
1677   
1678   if (entries)
1679     xentries = *entries; 
1680   else
1681     xentries = 1;
1682   
1683   n = 0;
1684   
1685   for (keyc=min_keycode;(keyc<max_keycode) && (n<*entries);keyc++)
1686     {
1687       /* X keycode to virtual key */
1688       vkey = keyc2vkey[keyc] & 0xFF;
1689       if (keystate[vkey] == (InputKeyStateTable[vkey]&0x80))
1690         continue;
1691       if (dod) {
1692         /* add an entry */
1693         dod[n].dwOfs            = keyc-min_keycode; /* scancode */
1694         dod[n].dwData           = InputKeyStateTable[vkey]&0x80;
1695         dod[n].dwTimeStamp      = 0; /* umm */
1696         dod[n].dwSequence       = 0; /* umm */
1697         n++;
1698       }
1699       if (!(flags & DIGDD_PEEK))
1700         keystate[vkey] = InputKeyStateTable[vkey]&0x80;
1701       
1702     }
1703   
1704   if (n) TRACE_(dinput)("%d entries\n",n);
1705   *entries = n;
1706
1707   return TRUE;
1708 }