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