Rename all QWindow properties that have "window" in them
[profile/ivi/qtbase.git] / src / plugins / platforms / windows / qwindowskeymapper.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the plugins of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia.  For licensing terms and
14 ** conditions see http://qt.digia.com/licensing.  For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file.  Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights.  These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file.  Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qwindowskeymapper.h"
43 #include "qwindowscontext.h"
44 #include "qwindowswindow.h"
45 #include "qwindowsguieventdispatcher.h"
46
47 #include <QtGui/QWindow>
48 #include <qpa/qwindowsysteminterface.h>
49 #include <QtGui/QKeyEvent>
50
51 QT_BEGIN_NAMESPACE
52
53 /*!
54     \class QWindowsKeyMapper
55     \brief Translates Windows keys to QWindowSystemInterface events.
56     \internal
57     \ingroup qt-lighthouse-win
58
59     In addition, handles some special keys to display system menus, etc.
60     The code originates from \c qkeymapper_win.cpp.
61 */
62
63 QWindowsKeyMapper::QWindowsKeyMapper()
64     : m_useRTLExtensions(false), m_keyGrabber(0)
65 {
66     memset(keyLayout, 0, sizeof(keyLayout));
67 }
68
69 QWindowsKeyMapper::~QWindowsKeyMapper()
70 {
71 }
72
73 #ifndef LANG_PASHTO
74 #define LANG_PASHTO 0x63
75 #endif
76 #ifndef LANG_SYRIAC
77 #define LANG_SYRIAC 0x5a
78 #endif
79 #ifndef LANG_DIVEHI
80 #define LANG_DIVEHI 0x65
81 #endif
82 #ifndef VK_OEM_PLUS
83 #define VK_OEM_PLUS 0xBB
84 #endif
85 #ifndef VK_OEM_3
86 #define VK_OEM_3 0xC0
87 #endif
88
89 // Key recorder ------------------------------------------------------------------------[ start ] --
90 struct KeyRecord {
91     KeyRecord(int c, int a, int s, const QString &t) : code(c), ascii(a), state(s), text(t) {}
92     KeyRecord() {}
93
94     int code;
95     int ascii;
96     int state;
97     QString text;
98 };
99
100 static const int QT_MAX_KEY_RECORDINGS = 64; // User has LOTS of fingers...
101 struct KeyRecorder
102 {
103     KeyRecorder() : nrecs(0) {}
104
105     inline KeyRecord *findKey(int code, bool remove);
106     inline void storeKey(int code, int ascii, int state, const QString& text);
107     inline void clearKeys();
108
109     int nrecs;
110     KeyRecord deleted_record; // A copy of last entry removed from records[]
111     KeyRecord records[QT_MAX_KEY_RECORDINGS];
112 };
113 static KeyRecorder key_recorder;
114
115 KeyRecord *KeyRecorder::findKey(int code, bool remove)
116 {
117     KeyRecord *result = 0;
118     for (int i = 0; i < nrecs; ++i) {
119         if (records[i].code == code) {
120             if (remove) {
121                 deleted_record = records[i];
122                 // Move rest down, and decrease count
123                 while (i + 1 < nrecs) {
124                     records[i] = records[i + 1];
125                     ++i;
126                 }
127                 --nrecs;
128                 result = &deleted_record;
129             } else {
130                 result = &records[i];
131             }
132             break;
133         }
134     }
135     return result;
136 }
137
138 void KeyRecorder::storeKey(int code, int ascii, int state, const QString& text)
139 {
140     Q_ASSERT_X(nrecs != QT_MAX_KEY_RECORDINGS,
141                "Internal KeyRecorder",
142                "Keyboard recorder buffer overflow, consider increasing QT_MAX_KEY_RECORDINGS");
143
144     if (nrecs == QT_MAX_KEY_RECORDINGS) {
145         qWarning("Qt: Internal keyboard buffer overflow");
146         return;
147     }
148     records[nrecs++] = KeyRecord(code,ascii,state,text);
149 }
150
151 void KeyRecorder::clearKeys()
152 {
153     nrecs = 0;
154 }
155 // Key recorder --------------------------------------------------------------------------[ end ] --
156
157
158 // Key translation ---------------------------------------------------------------------[ start ] --
159 // Meaning of values:
160 //             0 = Character output key, needs keyboard driver mapping
161 //   Key_unknown = Unknown Virtual Key, no translation possible, ignore
162 static const uint KeyTbl[] = { // Keyboard mapping table
163                         // Dec |  Hex | Windows Virtual key
164     Qt::Key_unknown,    //   0   0x00
165     Qt::Key_unknown,    //   1   0x01   VK_LBUTTON          | Left mouse button
166     Qt::Key_unknown,    //   2   0x02   VK_RBUTTON          | Right mouse button
167     Qt::Key_Cancel,     //   3   0x03   VK_CANCEL           | Control-Break processing
168     Qt::Key_unknown,    //   4   0x04   VK_MBUTTON          | Middle mouse button
169     Qt::Key_unknown,    //   5   0x05   VK_XBUTTON1         | X1 mouse button
170     Qt::Key_unknown,    //   6   0x06   VK_XBUTTON2         | X2 mouse button
171     Qt::Key_unknown,    //   7   0x07   -- unassigned --
172     Qt::Key_Backspace,  //   8   0x08   VK_BACK             | BackSpace key
173     Qt::Key_Tab,        //   9   0x09   VK_TAB              | Tab key
174     Qt::Key_unknown,    //  10   0x0A   -- reserved --
175     Qt::Key_unknown,    //  11   0x0B   -- reserved --
176     Qt::Key_Clear,      //  12   0x0C   VK_CLEAR            | Clear key
177     Qt::Key_Return,     //  13   0x0D   VK_RETURN           | Enter key
178     Qt::Key_unknown,    //  14   0x0E   -- unassigned --
179     Qt::Key_unknown,    //  15   0x0F   -- unassigned --
180     Qt::Key_Shift,      //  16   0x10   VK_SHIFT            | Shift key
181     Qt::Key_Control,    //  17   0x11   VK_CONTROL          | Ctrl key
182     Qt::Key_Alt,        //  18   0x12   VK_MENU             | Alt key
183     Qt::Key_Pause,      //  19   0x13   VK_PAUSE            | Pause key
184     Qt::Key_CapsLock,   //  20   0x14   VK_CAPITAL          | Caps-Lock
185     Qt::Key_unknown,    //  21   0x15   VK_KANA / VK_HANGUL | IME Kana or Hangul mode
186     Qt::Key_unknown,    //  22   0x16   -- unassigned --
187     Qt::Key_unknown,    //  23   0x17   VK_JUNJA            | IME Junja mode
188     Qt::Key_unknown,    //  24   0x18   VK_FINAL            | IME final mode
189     Qt::Key_unknown,    //  25   0x19   VK_HANJA / VK_KANJI | IME Hanja or Kanji mode
190     Qt::Key_unknown,    //  26   0x1A   -- unassigned --
191     Qt::Key_Escape,     //  27   0x1B   VK_ESCAPE           | Esc key
192     Qt::Key_unknown,    //  28   0x1C   VK_CONVERT          | IME convert
193     Qt::Key_unknown,    //  29   0x1D   VK_NONCONVERT       | IME non-convert
194     Qt::Key_unknown,    //  30   0x1E   VK_ACCEPT           | IME accept
195     Qt::Key_Mode_switch,//  31   0x1F   VK_MODECHANGE       | IME mode change request
196     Qt::Key_Space,      //  32   0x20   VK_SPACE            | Spacebar
197     Qt::Key_PageUp,     //  33   0x21   VK_PRIOR            | Page Up key
198     Qt::Key_PageDown,   //  34   0x22   VK_NEXT             | Page Down key
199     Qt::Key_End,        //  35   0x23   VK_END              | End key
200     Qt::Key_Home,       //  36   0x24   VK_HOME             | Home key
201     Qt::Key_Left,       //  37   0x25   VK_LEFT             | Left arrow key
202     Qt::Key_Up,         //  38   0x26   VK_UP               | Up arrow key
203     Qt::Key_Right,      //  39   0x27   VK_RIGHT            | Right arrow key
204     Qt::Key_Down,       //  40   0x28   VK_DOWN             | Down arrow key
205     Qt::Key_Select,     //  41   0x29   VK_SELECT           | Select key
206     Qt::Key_Printer,    //  42   0x2A   VK_PRINT            | Print key
207     Qt::Key_Execute,    //  43   0x2B   VK_EXECUTE          | Execute key
208     Qt::Key_Print,      //  44   0x2C   VK_SNAPSHOT         | Print Screen key
209     Qt::Key_Insert,     //  45   0x2D   VK_INSERT           | Ins key
210     Qt::Key_Delete,     //  46   0x2E   VK_DELETE           | Del key
211     Qt::Key_Help,       //  47   0x2F   VK_HELP             | Help key
212     0,                  //  48   0x30   (VK_0)              | 0 key
213     0,                  //  49   0x31   (VK_1)              | 1 key
214     0,                  //  50   0x32   (VK_2)              | 2 key
215     0,                  //  51   0x33   (VK_3)              | 3 key
216     0,                  //  52   0x34   (VK_4)              | 4 key
217     0,                  //  53   0x35   (VK_5)              | 5 key
218     0,                  //  54   0x36   (VK_6)              | 6 key
219     0,                  //  55   0x37   (VK_7)              | 7 key
220     0,                  //  56   0x38   (VK_8)              | 8 key
221     0,                  //  57   0x39   (VK_9)              | 9 key
222     Qt::Key_unknown,    //  58   0x3A   -- unassigned --
223     Qt::Key_unknown,    //  59   0x3B   -- unassigned --
224     Qt::Key_unknown,    //  60   0x3C   -- unassigned --
225     Qt::Key_unknown,    //  61   0x3D   -- unassigned --
226     Qt::Key_unknown,    //  62   0x3E   -- unassigned --
227     Qt::Key_unknown,    //  63   0x3F   -- unassigned --
228     Qt::Key_unknown,    //  64   0x40   -- unassigned --
229     0,                  //  65   0x41   (VK_A)              | A key
230     0,                  //  66   0x42   (VK_B)              | B key
231     0,                  //  67   0x43   (VK_C)              | C key
232     0,                  //  68   0x44   (VK_D)              | D key
233     0,                  //  69   0x45   (VK_E)              | E key
234     0,                  //  70   0x46   (VK_F)              | F key
235     0,                  //  71   0x47   (VK_G)              | G key
236     0,                  //  72   0x48   (VK_H)              | H key
237     0,                  //  73   0x49   (VK_I)              | I key
238     0,                  //  74   0x4A   (VK_J)              | J key
239     0,                  //  75   0x4B   (VK_K)              | K key
240     0,                  //  76   0x4C   (VK_L)              | L key
241     0,                  //  77   0x4D   (VK_M)              | M key
242     0,                  //  78   0x4E   (VK_N)              | N key
243     0,                  //  79   0x4F   (VK_O)              | O key
244     0,                  //  80   0x50   (VK_P)              | P key
245     0,                  //  81   0x51   (VK_Q)              | Q key
246     0,                  //  82   0x52   (VK_R)              | R key
247     0,                  //  83   0x53   (VK_S)              | S key
248     0,                  //  84   0x54   (VK_T)              | T key
249     0,                  //  85   0x55   (VK_U)              | U key
250     0,                  //  86   0x56   (VK_V)              | V key
251     0,                  //  87   0x57   (VK_W)              | W key
252     0,                  //  88   0x58   (VK_X)              | X key
253     0,                  //  89   0x59   (VK_Y)              | Y key
254     0,                  //  90   0x5A   (VK_Z)              | Z key
255     Qt::Key_Meta,       //  91   0x5B   VK_LWIN             | Left Windows  - MS Natural kbd
256     Qt::Key_Meta,       //  92   0x5C   VK_RWIN             | Right Windows - MS Natural kbd
257     Qt::Key_Menu,       //  93   0x5D   VK_APPS             | Application key-MS Natural kbd
258     Qt::Key_unknown,    //  94   0x5E   -- reserved --
259     Qt::Key_Sleep,      //  95   0x5F   VK_SLEEP
260     Qt::Key_0,          //  96   0x60   VK_NUMPAD0          | Numeric keypad 0 key
261     Qt::Key_1,          //  97   0x61   VK_NUMPAD1          | Numeric keypad 1 key
262     Qt::Key_2,          //  98   0x62   VK_NUMPAD2          | Numeric keypad 2 key
263     Qt::Key_3,          //  99   0x63   VK_NUMPAD3          | Numeric keypad 3 key
264     Qt::Key_4,          // 100   0x64   VK_NUMPAD4          | Numeric keypad 4 key
265     Qt::Key_5,          // 101   0x65   VK_NUMPAD5          | Numeric keypad 5 key
266     Qt::Key_6,          // 102   0x66   VK_NUMPAD6          | Numeric keypad 6 key
267     Qt::Key_7,          // 103   0x67   VK_NUMPAD7          | Numeric keypad 7 key
268     Qt::Key_8,          // 104   0x68   VK_NUMPAD8          | Numeric keypad 8 key
269     Qt::Key_9,          // 105   0x69   VK_NUMPAD9          | Numeric keypad 9 key
270     Qt::Key_Asterisk,   // 106   0x6A   VK_MULTIPLY         | Multiply key
271     Qt::Key_Plus,       // 107   0x6B   VK_ADD              | Add key
272     Qt::Key_Comma,      // 108   0x6C   VK_SEPARATOR        | Separator key
273     Qt::Key_Minus,      // 109   0x6D   VK_SUBTRACT         | Subtract key
274     Qt::Key_Period,     // 110   0x6E   VK_DECIMAL          | Decimal key
275     Qt::Key_Slash,      // 111   0x6F   VK_DIVIDE           | Divide key
276     Qt::Key_F1,         // 112   0x70   VK_F1               | F1 key
277     Qt::Key_F2,         // 113   0x71   VK_F2               | F2 key
278     Qt::Key_F3,         // 114   0x72   VK_F3               | F3 key
279     Qt::Key_F4,         // 115   0x73   VK_F4               | F4 key
280     Qt::Key_F5,         // 116   0x74   VK_F5               | F5 key
281     Qt::Key_F6,         // 117   0x75   VK_F6               | F6 key
282     Qt::Key_F7,         // 118   0x76   VK_F7               | F7 key
283     Qt::Key_F8,         // 119   0x77   VK_F8               | F8 key
284     Qt::Key_F9,         // 120   0x78   VK_F9               | F9 key
285     Qt::Key_F10,        // 121   0x79   VK_F10              | F10 key
286     Qt::Key_F11,        // 122   0x7A   VK_F11              | F11 key
287     Qt::Key_F12,        // 123   0x7B   VK_F12              | F12 key
288     Qt::Key_F13,        // 124   0x7C   VK_F13              | F13 key
289     Qt::Key_F14,        // 125   0x7D   VK_F14              | F14 key
290     Qt::Key_F15,        // 126   0x7E   VK_F15              | F15 key
291     Qt::Key_F16,        // 127   0x7F   VK_F16              | F16 key
292     Qt::Key_F17,        // 128   0x80   VK_F17              | F17 key
293     Qt::Key_F18,        // 129   0x81   VK_F18              | F18 key
294     Qt::Key_F19,        // 130   0x82   VK_F19              | F19 key
295     Qt::Key_F20,        // 131   0x83   VK_F20              | F20 key
296     Qt::Key_F21,        // 132   0x84   VK_F21              | F21 key
297     Qt::Key_F22,        // 133   0x85   VK_F22              | F22 key
298     Qt::Key_F23,        // 134   0x86   VK_F23              | F23 key
299     Qt::Key_F24,        // 135   0x87   VK_F24              | F24 key
300     Qt::Key_unknown,    // 136   0x88   -- unassigned --
301     Qt::Key_unknown,    // 137   0x89   -- unassigned --
302     Qt::Key_unknown,    // 138   0x8A   -- unassigned --
303     Qt::Key_unknown,    // 139   0x8B   -- unassigned --
304     Qt::Key_unknown,    // 140   0x8C   -- unassigned --
305     Qt::Key_unknown,    // 141   0x8D   -- unassigned --
306     Qt::Key_unknown,    // 142   0x8E   -- unassigned --
307     Qt::Key_unknown,    // 143   0x8F   -- unassigned --
308     Qt::Key_NumLock,    // 144   0x90   VK_NUMLOCK          | Num Lock key
309     Qt::Key_ScrollLock, // 145   0x91   VK_SCROLL           | Scroll Lock key
310                         // Fujitsu/OASYS kbd --------------------
311     0, //Qt::Key_Jisho, // 146   0x92   VK_OEM_FJ_JISHO     | 'Dictionary' key /
312                         //              VK_OEM_NEC_EQUAL  = key on numpad on NEC PC-9800 kbd
313     Qt::Key_Massyo,     // 147   0x93   VK_OEM_FJ_MASSHOU   | 'Unregister word' key
314     Qt::Key_Touroku,    // 148   0x94   VK_OEM_FJ_TOUROKU   | 'Register word' key
315     0, //Qt::Key_Oyayubi_Left,//149   0x95  VK_OEM_FJ_LOYA  | 'Left OYAYUBI' key
316     0, //Qt::Key_Oyayubi_Right,//150  0x96  VK_OEM_FJ_ROYA  | 'Right OYAYUBI' key
317     Qt::Key_unknown,    // 151   0x97   -- unassigned --
318     Qt::Key_unknown,    // 152   0x98   -- unassigned --
319     Qt::Key_unknown,    // 153   0x99   -- unassigned --
320     Qt::Key_unknown,    // 154   0x9A   -- unassigned --
321     Qt::Key_unknown,    // 155   0x9B   -- unassigned --
322     Qt::Key_unknown,    // 156   0x9C   -- unassigned --
323     Qt::Key_unknown,    // 157   0x9D   -- unassigned --
324     Qt::Key_unknown,    // 158   0x9E   -- unassigned --
325     Qt::Key_unknown,    // 159   0x9F   -- unassigned --
326     Qt::Key_Shift,      // 160   0xA0   VK_LSHIFT           | Left Shift key
327     Qt::Key_Shift,      // 161   0xA1   VK_RSHIFT           | Right Shift key
328     Qt::Key_Control,    // 162   0xA2   VK_LCONTROL         | Left Ctrl key
329     Qt::Key_Control,    // 163   0xA3   VK_RCONTROL         | Right Ctrl key
330     Qt::Key_Alt,        // 164   0xA4   VK_LMENU            | Left Menu key
331     Qt::Key_Alt,        // 165   0xA5   VK_RMENU            | Right Menu key
332     Qt::Key_Back,       // 166   0xA6   VK_BROWSER_BACK     | Browser Back key
333     Qt::Key_Forward,    // 167   0xA7   VK_BROWSER_FORWARD  | Browser Forward key
334     Qt::Key_Refresh,    // 168   0xA8   VK_BROWSER_REFRESH  | Browser Refresh key
335     Qt::Key_Stop,       // 169   0xA9   VK_BROWSER_STOP     | Browser Stop key
336     Qt::Key_Search,     // 170   0xAA   VK_BROWSER_SEARCH   | Browser Search key
337     Qt::Key_Favorites,  // 171   0xAB   VK_BROWSER_FAVORITES| Browser Favorites key
338     Qt::Key_HomePage,   // 172   0xAC   VK_BROWSER_HOME     | Browser Start and Home key
339     Qt::Key_VolumeMute, // 173   0xAD   VK_VOLUME_MUTE      | Volume Mute key
340     Qt::Key_VolumeDown, // 174   0xAE   VK_VOLUME_DOWN      | Volume Down key
341     Qt::Key_VolumeUp,   // 175   0xAF   VK_VOLUME_UP        | Volume Up key
342     Qt::Key_MediaNext,  // 176   0xB0   VK_MEDIA_NEXT_TRACK | Next Track key
343     Qt::Key_MediaPrevious, //177 0xB1   VK_MEDIA_PREV_TRACK | Previous Track key
344     Qt::Key_MediaStop,  // 178   0xB2   VK_MEDIA_STOP       | Stop Media key
345     Qt::Key_MediaPlay,  // 179   0xB3   VK_MEDIA_PLAY_PAUSE | Play/Pause Media key
346     Qt::Key_LaunchMail, // 180   0xB4   VK_LAUNCH_MAIL      | Start Mail key
347     Qt::Key_LaunchMedia,// 181   0xB5   VK_LAUNCH_MEDIA_SELECT Select Media key
348     Qt::Key_Launch0,    // 182   0xB6   VK_LAUNCH_APP1      | Start Application 1 key
349     Qt::Key_Launch1,    // 183   0xB7   VK_LAUNCH_APP2      | Start Application 2 key
350     Qt::Key_unknown,    // 184   0xB8   -- reserved --
351     Qt::Key_unknown,    // 185   0xB9   -- reserved --
352     0,                  // 186   0xBA   VK_OEM_1            | ';:' for US
353     0,                  // 187   0xBB   VK_OEM_PLUS         | '+' any country
354     0,                  // 188   0xBC   VK_OEM_COMMA        | ',' any country
355     0,                  // 189   0xBD   VK_OEM_MINUS        | '-' any country
356     0,                  // 190   0xBE   VK_OEM_PERIOD       | '.' any country
357     0,                  // 191   0xBF   VK_OEM_2            | '/?' for US
358     0,                  // 192   0xC0   VK_OEM_3            | '`~' for US
359     Qt::Key_unknown,    // 193   0xC1   -- reserved --
360     Qt::Key_unknown,    // 194   0xC2   -- reserved --
361     Qt::Key_unknown,    // 195   0xC3   -- reserved --
362     Qt::Key_unknown,    // 196   0xC4   -- reserved --
363     Qt::Key_unknown,    // 197   0xC5   -- reserved --
364     Qt::Key_unknown,    // 198   0xC6   -- reserved --
365     Qt::Key_unknown,    // 199   0xC7   -- reserved --
366     Qt::Key_unknown,    // 200   0xC8   -- reserved --
367     Qt::Key_unknown,    // 201   0xC9   -- reserved --
368     Qt::Key_unknown,    // 202   0xCA   -- reserved --
369     Qt::Key_unknown,    // 203   0xCB   -- reserved --
370     Qt::Key_unknown,    // 204   0xCC   -- reserved --
371     Qt::Key_unknown,    // 205   0xCD   -- reserved --
372     Qt::Key_unknown,    // 206   0xCE   -- reserved --
373     Qt::Key_unknown,    // 207   0xCF   -- reserved --
374     Qt::Key_unknown,    // 208   0xD0   -- reserved --
375     Qt::Key_unknown,    // 209   0xD1   -- reserved --
376     Qt::Key_unknown,    // 210   0xD2   -- reserved --
377     Qt::Key_unknown,    // 211   0xD3   -- reserved --
378     Qt::Key_unknown,    // 212   0xD4   -- reserved --
379     Qt::Key_unknown,    // 213   0xD5   -- reserved --
380     Qt::Key_unknown,    // 214   0xD6   -- reserved --
381     Qt::Key_unknown,    // 215   0xD7   -- reserved --
382     Qt::Key_unknown,    // 216   0xD8   -- unassigned --
383     Qt::Key_unknown,    // 217   0xD9   -- unassigned --
384     Qt::Key_unknown,    // 218   0xDA   -- unassigned --
385     0,                  // 219   0xDB   VK_OEM_4            | '[{' for US
386     0,                  // 220   0xDC   VK_OEM_5            | '\|' for US
387     0,                  // 221   0xDD   VK_OEM_6            | ']}' for US
388     0,                  // 222   0xDE   VK_OEM_7            | ''"' for US
389     0,                  // 223   0xDF   VK_OEM_8
390     Qt::Key_unknown,    // 224   0xE0   -- reserved --
391     Qt::Key_unknown,    // 225   0xE1   VK_OEM_AX           | 'AX' key on Japanese AX kbd
392     Qt::Key_unknown,    // 226   0xE2   VK_OEM_102          | "<>" or "\|" on RT 102-key kbd
393     Qt::Key_unknown,    // 227   0xE3   VK_ICO_HELP         | Help key on ICO
394     Qt::Key_unknown,    // 228   0xE4   VK_ICO_00           | 00 key on ICO
395     Qt::Key_unknown,    // 229   0xE5   VK_PROCESSKEY       | IME Process key
396     Qt::Key_unknown,    // 230   0xE6   VK_ICO_CLEAR        |
397     Qt::Key_unknown,    // 231   0xE7   VK_PACKET           | Unicode char as keystrokes
398     Qt::Key_unknown,    // 232   0xE8   -- unassigned --
399                         // Nokia/Ericsson definitions ---------------
400     Qt::Key_unknown,    // 233   0xE9   VK_OEM_RESET
401     Qt::Key_unknown,    // 234   0xEA   VK_OEM_JUMP
402     Qt::Key_unknown,    // 235   0xEB   VK_OEM_PA1
403     Qt::Key_unknown,    // 236   0xEC   VK_OEM_PA2
404     Qt::Key_unknown,    // 237   0xED   VK_OEM_PA3
405     Qt::Key_unknown,    // 238   0xEE   VK_OEM_WSCTRL
406     Qt::Key_unknown,    // 239   0xEF   VK_OEM_CUSEL
407     Qt::Key_unknown,    // 240   0xF0   VK_OEM_ATTN
408     Qt::Key_unknown,    // 241   0xF1   VK_OEM_FINISH
409     Qt::Key_unknown,    // 242   0xF2   VK_OEM_COPY
410     Qt::Key_unknown,    // 243   0xF3   VK_OEM_AUTO
411     Qt::Key_unknown,    // 244   0xF4   VK_OEM_ENLW
412     Qt::Key_unknown,    // 245   0xF5   VK_OEM_BACKTAB
413     Qt::Key_unknown,    // 246   0xF6   VK_ATTN             | Attn key
414     Qt::Key_unknown,    // 247   0xF7   VK_CRSEL            | CrSel key
415     Qt::Key_unknown,    // 248   0xF8   VK_EXSEL            | ExSel key
416     Qt::Key_unknown,    // 249   0xF9   VK_EREOF            | Erase EOF key
417     Qt::Key_Play,       // 250   0xFA   VK_PLAY             | Play key
418     Qt::Key_Zoom,       // 251   0xFB   VK_ZOOM             | Zoom key
419     Qt::Key_unknown,    // 252   0xFC   VK_NONAME           | Reserved
420     Qt::Key_unknown,    // 253   0xFD   VK_PA1              | PA1 key
421     Qt::Key_Clear,      // 254   0xFE   VK_OEM_CLEAR        | Clear key
422     0
423 };
424
425 // Possible modifier states.
426 // NOTE: The order of these states match the order in QWindowsKeyMapper::updatePossibleKeyCodes()!
427 static const Qt::KeyboardModifiers ModsTbl[] = {
428     Qt::NoModifier,                                             // 0
429     Qt::ShiftModifier,                                          // 1
430     Qt::ControlModifier,                                        // 2
431     Qt::ControlModifier | Qt::ShiftModifier,                    // 3
432     Qt::AltModifier,                                            // 4
433     Qt::AltModifier | Qt::ShiftModifier,                        // 5
434     Qt::AltModifier | Qt::ControlModifier,                      // 6
435     Qt::AltModifier | Qt::ShiftModifier | Qt::ControlModifier,  // 7
436     Qt::NoModifier,                                             // Fall-back to raw Key_*
437 };
438 static const size_t NumMods = sizeof ModsTbl / sizeof *ModsTbl;
439 Q_STATIC_ASSERT((NumMods == KeyboardLayoutItem::NumQtKeys));
440
441 /**
442   Remap return or action key to select key for windows mobile.
443 */
444 inline int winceKeyBend(int keyCode)
445 {
446     return KeyTbl[keyCode];
447 }
448
449 #ifdef Q_OS_WINCE
450 QT_BEGIN_INCLUDE_NAMESPACE
451 int ToUnicode(UINT vk, int /*scancode*/, unsigned char* /*kbdBuffer*/, LPWSTR unicodeBuffer, int, int)
452 {
453     QT_USE_NAMESPACE
454     QChar* buf = reinterpret_cast< QChar*>(unicodeBuffer);
455     if (KeyTbl[vk] == 0) {
456         buf[0] = vk;
457         return 1;
458     }
459     return 0;
460 }
461
462 int ToAscii(UINT vk, int scancode, unsigned char *kbdBuffer, LPWORD unicodeBuffer, int flag)
463 {
464     return ToUnicode(vk, scancode, kbdBuffer, (LPWSTR) unicodeBuffer, 0, flag);
465
466 }
467
468 bool GetKeyboardState(unsigned char* kbuffer)
469 {
470     for (int i=0; i< 256; ++i)
471         kbuffer[i] = GetAsyncKeyState(i);
472     return true;
473 }
474 QT_END_INCLUDE_NAMESPACE
475 #endif // Q_OS_WINCE
476
477 // Translate a VK into a Qt key code, or unicode character
478 static inline int toKeyOrUnicode(int vk, int scancode, unsigned char *kbdBuffer, bool *isDeadkey = 0)
479 {
480     Q_ASSERT(vk > 0 && vk < 256);
481     int code = 0;
482     QChar unicodeBuffer[5];
483     int res = ToUnicode(vk, scancode, kbdBuffer, reinterpret_cast<LPWSTR>(unicodeBuffer), 5, 0);
484     if (res)
485         code = unicodeBuffer[0].toUpper().unicode();
486
487     // Qt::Key_*'s are not encoded below 0x20, so try again, and DEL keys (0x7f) is encoded with a
488     // proper Qt::Key_ code
489     if (code < 0x20 || code == 0x7f) // Handles res==0 too
490         code = winceKeyBend(vk);
491
492     if (isDeadkey)
493         *isDeadkey = (res == -1);
494
495     return code == Qt::Key_unknown ? 0 : code;
496 }
497
498 int qt_translateKeyCode(int vk)
499 {
500     int code = winceKeyBend((vk < 0 || vk > 255) ? 0 : vk);
501     return code == Qt::Key_unknown ? 0 : code;
502 }
503
504 static inline int asciiToKeycode(char a, int state)
505 {
506     if (a >= 'a' && a <= 'z')
507         a = toupper(a);
508     if ((state & Qt::ControlModifier) != 0) {
509         if (a >= 0 && a <= 31)              // Ctrl+@..Ctrl+A..CTRL+Z..Ctrl+_
510             a += '@';                       // to @..A..Z.._
511     }
512     return a & 0xff;
513 }
514
515 static inline bool isModifierKey(int code)
516 {
517     return (code >= Qt::Key_Shift) && (code <= Qt::Key_ScrollLock);
518 }
519 // Key translation -----------------------------------------------------------------------[ end ]---
520
521
522 // Keyboard map private ----------------------------------------------------------------[ start ]---
523
524 void QWindowsKeyMapper::deleteLayouts()
525 {
526     for (size_t i = 0; i < NumKeyboardLayoutItems; ++i)
527         keyLayout[i].exists = false;
528 }
529
530 void QWindowsKeyMapper::changeKeyboard()
531 {
532     deleteLayouts();
533
534     /* MAKELCID()'s first argument is a WORD, and GetKeyboardLayout()
535      * returns a DWORD. */
536
537     LCID newLCID = MAKELCID((quintptr)GetKeyboardLayout(0), SORT_DEFAULT);
538 //    keyboardInputLocale = qt_localeFromLCID(newLCID);
539
540     bool bidi = false;
541     wchar_t LCIDFontSig[16];
542     if (GetLocaleInfo(newLCID, LOCALE_FONTSIGNATURE, LCIDFontSig, sizeof(LCIDFontSig) / sizeof(wchar_t))
543         && (LCIDFontSig[7] & (wchar_t)0x0800))
544         bidi = true;
545
546     keyboardInputDirection = bidi ? Qt::RightToLeft : Qt::LeftToRight;
547 }
548
549 void QWindowsKeyMapper::clearRecordedKeys()
550 {
551     key_recorder.clearKeys();
552 }
553
554
555 inline void setKbdState(unsigned char *kbd, bool shift, bool ctrl, bool alt)
556 {
557     kbd[VK_LSHIFT  ] = (shift ? 0x80 : 0);
558     kbd[VK_SHIFT   ] = (shift ? 0x80 : 0);
559     kbd[VK_LCONTROL] = (ctrl ? 0x80 : 0);
560     kbd[VK_CONTROL ] = (ctrl ? 0x80 : 0);
561     kbd[VK_RMENU   ] = (alt ? 0x80 : 0);
562     kbd[VK_MENU    ] = (alt ? 0x80 : 0);
563 }
564
565 void QWindowsKeyMapper::updateKeyMap(const MSG &msg)
566 {
567     unsigned char kbdBuffer[256]; // Will hold the complete keyboard state
568     GetKeyboardState(kbdBuffer);
569     quint32 scancode = (msg.lParam >> 16) & 0xfff;
570     updatePossibleKeyCodes(kbdBuffer, scancode, msg.wParam);
571 }
572
573 void QWindowsKeyMapper::updatePossibleKeyCodes(unsigned char *kbdBuffer, quint32 scancode,
574                                                quint32 vk_key)
575 {
576     if (!vk_key || (keyLayout[vk_key].exists && !keyLayout[vk_key].dirty))
577         return;
578
579     // Copy keyboard state, so we can modify and query output for each possible permutation
580     unsigned char buffer[256];
581     memcpy(buffer, kbdBuffer, sizeof(buffer));
582     // Always 0, as Windows doesn't treat these as modifiers;
583     buffer[VK_LWIN    ] = 0;
584     buffer[VK_RWIN    ] = 0;
585     buffer[VK_CAPITAL ] = 0;
586     buffer[VK_NUMLOCK ] = 0;
587     buffer[VK_SCROLL  ] = 0;
588     // Always 0, since we'll only change the other versions
589     buffer[VK_RSHIFT  ] = 0;
590     buffer[VK_RCONTROL] = 0;
591     buffer[VK_LMENU   ] = 0; // Use right Alt, since left Ctrl + right Alt is considered AltGraph
592
593     bool isDeadKey = false;
594     keyLayout[vk_key].deadkeys = 0;
595     keyLayout[vk_key].dirty = false;
596     keyLayout[vk_key].exists = true;
597     setKbdState(buffer, false, false, false);
598     keyLayout[vk_key].qtKey[0] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
599     keyLayout[vk_key].deadkeys |= isDeadKey ? 0x01 : 0;
600     setKbdState(buffer, true, false, false);
601     keyLayout[vk_key].qtKey[1] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
602     keyLayout[vk_key].deadkeys |= isDeadKey ? 0x02 : 0;
603     setKbdState(buffer, false, true, false);
604     keyLayout[vk_key].qtKey[2] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
605     keyLayout[vk_key].deadkeys |= isDeadKey ? 0x04 : 0;
606     setKbdState(buffer, true, true, false);
607     keyLayout[vk_key].qtKey[3] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
608     keyLayout[vk_key].deadkeys |= isDeadKey ? 0x08 : 0;
609     setKbdState(buffer, false, false, true);
610     keyLayout[vk_key].qtKey[4] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
611     keyLayout[vk_key].deadkeys |= isDeadKey ? 0x10 : 0;
612     setKbdState(buffer, true, false, true);
613     keyLayout[vk_key].qtKey[5] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
614     keyLayout[vk_key].deadkeys |= isDeadKey ? 0x20 : 0;
615     setKbdState(buffer, false, true, true);
616     keyLayout[vk_key].qtKey[6] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
617     keyLayout[vk_key].deadkeys |= isDeadKey ? 0x40 : 0;
618     setKbdState(buffer, true, true, true);
619     keyLayout[vk_key].qtKey[7] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
620     keyLayout[vk_key].deadkeys |= isDeadKey ? 0x80 : 0;
621     // Add a fall back key for layouts which don't do composition and show non-latin1 characters
622     int fallbackKey = winceKeyBend(vk_key);
623     if (!fallbackKey || fallbackKey == Qt::Key_unknown) {
624         fallbackKey = 0;
625         if (vk_key != keyLayout[vk_key].qtKey[0] && vk_key < 0x5B && vk_key > 0x2F)
626             fallbackKey = vk_key;
627     }
628     keyLayout[vk_key].qtKey[8] = fallbackKey;
629
630     // If this vk_key a Dead Key
631     if (MapVirtualKey(vk_key, 2) & 0x80000000) {
632         // Push a Space, then the original key through the low-level ToAscii functions.
633         // We do this because these functions (ToAscii / ToUnicode) will alter the internal state of
634         // the keyboard driver By doing the following, we set the keyboard driver state back to what
635         // it was before we wrecked it with the code above.
636         // We need to push the space with an empty keystate map, since the driver checks the map for
637         // transitions in modifiers, so this helps us capture all possible deadkeys.
638         unsigned char emptyBuffer[256];
639         memset(emptyBuffer, 0, sizeof(emptyBuffer));
640         ::ToAscii(VK_SPACE, 0, emptyBuffer, reinterpret_cast<LPWORD>(&buffer), 0);
641         ::ToAscii(vk_key, scancode, kbdBuffer, reinterpret_cast<LPWORD>(&buffer), 0);
642     }
643
644     if (QWindowsContext::verboseEvents > 1) {
645         qDebug("updatePossibleKeyCodes for virtual key = 0x%02x!", vk_key);
646         for (size_t i = 0; i < NumMods; ++i) {
647             qDebug("    [%d] (%d,0x%02x,'%c')  %s", int(i),
648                    keyLayout[vk_key].qtKey[i],
649                    keyLayout[vk_key].qtKey[i],
650                    keyLayout[vk_key].qtKey[i] ? keyLayout[vk_key].qtKey[i] : 0x03,
651                    keyLayout[vk_key].deadkeys & (1<<i) ? "deadkey" : "");
652         }
653     }
654 }
655
656 bool QWindowsKeyMapper::isADeadKey(unsigned int vk_key, unsigned int modifiers)
657 {
658     if ((vk_key < NumKeyboardLayoutItems) && keyLayout[vk_key].exists) {
659         for (register size_t i = 0; i < NumMods; ++i) {
660             if (uint(ModsTbl[i]) == modifiers)
661                 return bool(keyLayout[vk_key].deadkeys & 1<<i);
662         }
663     }
664     return false;
665 }
666
667 static inline QString messageKeyText(const MSG &msg)
668 {
669     const QChar ch = QChar((ushort)msg.wParam);
670     return ch.isNull() ? QString() : QString(ch);
671 }
672
673 static void showSystemMenu(QWindow* w)
674 {
675     QWindow *topLevel = QWindowsWindow::topLevelOf(w);
676     HWND topLevelHwnd = QWindowsWindow::handleOf(topLevel);
677     HMENU menu = GetSystemMenu(topLevelHwnd, FALSE);
678     if (!menu)
679         return; // no menu for this window
680
681 #ifndef Q_OS_WINCE
682 #define enabled (MF_BYCOMMAND | MF_ENABLED)
683 #define disabled (MF_BYCOMMAND | MF_GRAYED)
684
685     EnableMenuItem(menu, SC_MINIMIZE, (topLevel->flags() & Qt::WindowMinimizeButtonHint)?enabled:disabled);
686     bool maximized = IsZoomed(topLevelHwnd);
687
688     EnableMenuItem(menu, SC_MAXIMIZE, ! (topLevel->flags() & Qt::WindowMaximizeButtonHint) || maximized?disabled:enabled);
689     EnableMenuItem(menu, SC_RESTORE, maximized?enabled:disabled);
690
691     // We should _not_ check with the setFixedSize(x,y) case here, since Windows is not able to check
692     // this and our menu here would be out-of-sync with the menu produced by mouse-click on the
693     // System Menu, or right-click on the title bar.
694     EnableMenuItem(menu, SC_SIZE, (topLevel->flags() & Qt::MSWindowsFixedSizeDialogHint) || maximized?disabled:enabled);
695     EnableMenuItem(menu, SC_MOVE, maximized?disabled:enabled);
696     EnableMenuItem(menu, SC_CLOSE, enabled);
697     // Set bold on close menu item
698     MENUITEMINFO closeItem;
699     closeItem.cbSize = sizeof(MENUITEMINFO);
700     closeItem.fMask = MIIM_STATE;
701     closeItem.fState = MFS_DEFAULT;
702     SetMenuItemInfo(menu, SC_CLOSE, FALSE, &closeItem);
703
704 #undef enabled
705 #undef disabled
706 #endif // !Q_OS_WINCE
707     const int ret = TrackPopupMenuEx(menu,
708                                TPM_LEFTALIGN  | TPM_TOPALIGN | TPM_NONOTIFY | TPM_RETURNCMD,
709                                topLevel->geometry().x(), topLevel->geometry().y(),
710                                topLevelHwnd,
711                                0);
712     if (ret)
713         qWindowsWndProc(topLevelHwnd, WM_SYSCOMMAND, ret, 0);
714 }
715
716 static inline void sendExtendedPressRelease(QWindow *w, int k,
717                                             Qt::KeyboardModifiers mods,
718                                             quint32 nativeScanCode,
719                                             quint32 nativeVirtualKey,
720                                             quint32 nativeModifiers,
721                                             const QString & text = QString(),
722                                             bool autorep = false,
723                                             ushort count = 1)
724 {
725     QWindowSystemInterface::handleExtendedKeyEvent(w, QEvent::KeyPress, k, mods, nativeScanCode, nativeVirtualKey, nativeModifiers, text, autorep, count);
726     QWindowSystemInterface::handleExtendedKeyEvent(w, QEvent::KeyRelease, k, mods, nativeScanCode, nativeVirtualKey, nativeModifiers, text, autorep, count);
727 }
728
729 /*!
730     \brief To be called from the window procedure.
731 */
732
733 bool QWindowsKeyMapper::translateKeyEvent(QWindow *widget, HWND hwnd,
734                                           const MSG &msg, LRESULT *result)
735 {
736     *result = 0;
737     MSG peekedMsg;
738     // consume dead chars?(for example, typing '`','a' resulting in a-accent).
739     if (PeekMessage(&peekedMsg, hwnd, 0, 0, PM_NOREMOVE) && peekedMsg.message == WM_DEADCHAR)
740         return true;
741     if (msg.message == WM_KEYDOWN || msg.message == WM_SYSKEYDOWN)
742         updateKeyMap(msg);
743     return translateKeyEventInternal(widget, msg, false);
744 }
745
746 bool QWindowsKeyMapper::translateKeyEventInternal(QWindow *window, const MSG &msg, bool /* grab */)
747 {
748     const int  msgType = msg.message;
749
750     const quint32 scancode = (msg.lParam >> 16) & 0xfff;
751     const quint32 vk_key = MapVirtualKey(scancode, 1);
752     const bool isNumpad = (msg.wParam >= VK_NUMPAD0 && msg.wParam <= VK_NUMPAD9);
753     quint32 nModifiers = 0;
754
755     QWindow *receiver = m_keyGrabber ? m_keyGrabber : window;
756
757     // Map native modifiers to some bit representation
758     nModifiers |= (GetKeyState(VK_LSHIFT  ) & 0x80 ? ShiftLeft : 0);
759     nModifiers |= (GetKeyState(VK_RSHIFT  ) & 0x80 ? ShiftRight : 0);
760     nModifiers |= (GetKeyState(VK_LCONTROL) & 0x80 ? ControlLeft : 0);
761     nModifiers |= (GetKeyState(VK_RCONTROL) & 0x80 ? ControlRight : 0);
762     nModifiers |= (GetKeyState(VK_LMENU   ) & 0x80 ? AltLeft : 0);
763     nModifiers |= (GetKeyState(VK_RMENU   ) & 0x80 ? AltRight : 0);
764     nModifiers |= (GetKeyState(VK_LWIN    ) & 0x80 ? MetaLeft : 0);
765     nModifiers |= (GetKeyState(VK_RWIN    ) & 0x80 ? MetaRight : 0);
766     // Add Lock keys to the same bits
767     nModifiers |= (GetKeyState(VK_CAPITAL ) & 0x01 ? CapsLock : 0);
768     nModifiers |= (GetKeyState(VK_NUMLOCK ) & 0x01 ? NumLock : 0);
769     nModifiers |= (GetKeyState(VK_SCROLL  ) & 0x01 ? ScrollLock : 0);
770
771     if (msg.lParam & ExtendedKey)
772         nModifiers |= msg.lParam & ExtendedKey;
773
774     // Get the modifier states (may be altered later, depending on key code)
775     int state = 0;
776     state |= (nModifiers & ShiftAny ? int(Qt::ShiftModifier) : 0);
777     state |= (nModifiers & ControlAny ? int(Qt::ControlModifier) : 0);
778     state |= (nModifiers & AltAny ? int(Qt::AltModifier) : 0);
779     state |= (nModifiers & MetaAny ? int(Qt::MetaModifier) : 0);
780
781     // Now we know enough to either have MapVirtualKey or our own keymap tell us if it's a deadkey
782     const bool isDeadKey = isADeadKey(msg.wParam, state)
783                      || MapVirtualKey(msg.wParam, 2) & 0x80000000;
784
785     // A multi-character key or a Input method character
786     // not found by our look-ahead
787     if (msgType == WM_CHAR || msgType == WM_IME_CHAR) {
788         sendExtendedPressRelease(receiver, 0, Qt::KeyboardModifier(state), scancode, vk_key, nModifiers, messageKeyText(msg), false, 0);
789         return true;
790     }
791
792     bool result = false;
793     // handle Directionality changes (BiDi) with RTL extensions
794     if (m_useRTLExtensions) {
795         static int dirStatus = 0;
796         if (!dirStatus && state == Qt::ControlModifier
797                 && msg.wParam == VK_CONTROL
798                 && msgType == WM_KEYDOWN) {
799             if (GetKeyState(VK_LCONTROL) < 0)
800                 dirStatus = VK_LCONTROL;
801             else if (GetKeyState(VK_RCONTROL) < 0)
802                 dirStatus = VK_RCONTROL;
803         } else if (dirStatus) {
804             if (msgType == WM_KEYDOWN) {
805                 if (msg.wParam == VK_SHIFT) {
806                     if (dirStatus == VK_LCONTROL && GetKeyState(VK_LSHIFT) < 0)
807                         dirStatus = VK_LSHIFT;
808                     else if (dirStatus == VK_RCONTROL && GetKeyState(VK_RSHIFT) < 0)
809                         dirStatus = VK_RSHIFT;
810                 } else {
811                     dirStatus = 0;
812                 }
813             } else if (msgType == WM_KEYUP) {
814                 if (dirStatus == VK_LSHIFT
815                         && ((msg.wParam == VK_SHIFT && GetKeyState(VK_LCONTROL))
816                             || (msg.wParam == VK_CONTROL && GetKeyState(VK_LSHIFT)))) {
817                     sendExtendedPressRelease(receiver, Qt::Key_Direction_L, 0, scancode, msg.wParam, nModifiers, QString(), false, 0);
818                     result = true;
819                     dirStatus = 0;
820                 } else if (dirStatus == VK_RSHIFT
821                            && ( (msg.wParam == VK_SHIFT && GetKeyState(VK_RCONTROL))
822                                 || (msg.wParam == VK_CONTROL && GetKeyState(VK_RSHIFT)))) {
823                     sendExtendedPressRelease(receiver, Qt::Key_Direction_R, 0, scancode, msg.wParam, nModifiers, QString(), false, 0);
824                     result = true;
825                     dirStatus = 0;
826                 } else {
827                     dirStatus = 0;
828                 }
829             } else {
830                 dirStatus = 0;
831             }
832         }
833     } // RTL
834
835     // IME will process these keys, so simply return
836     if (msg.wParam == VK_PROCESSKEY)
837         return true;
838
839     // Ignore invalid virtual keycodes (see bugs 127424, QTBUG-3630)
840     if (msg.wParam == 0 || msg.wParam == 0xFF)
841         return true;
842
843     // Translate VK_* (native) -> Key_* (Qt) keys
844     // If it's a dead key, we cannot use the toKeyOrUnicode() function, since that will change
845     // the internal state of the keyboard driver, resulting in that dead keys no longer works.
846     // ..also if we're typing numbers on the keypad, while holding down the Alt modifier.
847     int code = 0;
848     if (isNumpad && (nModifiers & AltAny)) {
849         code = winceKeyBend(msg.wParam);
850     } else if (!isDeadKey) {
851         unsigned char kbdBuffer[256]; // Will hold the complete keyboard state
852         GetKeyboardState(kbdBuffer);
853         code = toKeyOrUnicode(msg.wParam, scancode, kbdBuffer);
854     }
855
856     // Invert state logic:
857     // If the key actually pressed is a modifier key, then we remove its modifier key from the
858     // state, since a modifier-key can't have itself as a modifier
859     if (code == Qt::Key_Control)
860         state = state ^ Qt::ControlModifier;
861     else if (code == Qt::Key_Shift)
862         state = state ^ Qt::ShiftModifier;
863     else if (code == Qt::Key_Alt)
864         state = state ^ Qt::AltModifier;
865
866     // If the bit 24 of lParm is set you received a enter,
867     // otherwise a Return. (This is the extended key bit)
868     if ((code == Qt::Key_Return) && (msg.lParam & 0x1000000))
869         code = Qt::Key_Enter;
870
871     // All cursor keys without extended bit
872     if (!(msg.lParam & 0x1000000)) {
873         switch (code) {
874         case Qt::Key_Left:
875         case Qt::Key_Right:
876         case Qt::Key_Up:
877         case Qt::Key_Down:
878         case Qt::Key_PageUp:
879         case Qt::Key_PageDown:
880         case Qt::Key_Home:
881         case Qt::Key_End:
882         case Qt::Key_Insert:
883         case Qt::Key_Delete:
884         case Qt::Key_Asterisk:
885         case Qt::Key_Plus:
886         case Qt::Key_Minus:
887         case Qt::Key_Period:
888         case Qt::Key_0:
889         case Qt::Key_1:
890         case Qt::Key_2:
891         case Qt::Key_3:
892         case Qt::Key_4:
893         case Qt::Key_5:
894         case Qt::Key_6:
895         case Qt::Key_7:
896         case Qt::Key_8:
897         case Qt::Key_9:
898             state |= ((msg.wParam >= '0' && msg.wParam <= '9')
899                       || (msg.wParam >= VK_OEM_PLUS && msg.wParam <= VK_OEM_3))
900                     ? 0 : int(Qt::KeypadModifier);
901         default:
902             if ((uint)msg.lParam == 0x004c0001 || (uint)msg.lParam == 0xc04c0001)
903                 state |= Qt::KeypadModifier;
904             break;
905         }
906     }
907     // Other keys with with extended bit
908     else {
909         switch (code) {
910         case Qt::Key_Enter:
911         case Qt::Key_Slash:
912         case Qt::Key_NumLock:
913             state |= Qt::KeypadModifier;
914         default:
915             break;
916         }
917     }
918
919     // KEYDOWN ---------------------------------------------------------------------------------
920     if (msgType == WM_KEYDOWN || msgType == WM_IME_KEYDOWN || msgType == WM_SYSKEYDOWN) {
921         // Get the last record of this key press, so we can validate the current state
922         // The record is not removed from the list
923         KeyRecord *rec = key_recorder.findKey(msg.wParam, false);
924
925         // If rec's state doesn't match the current state, something has changed behind our back
926         // (Consumed by modal widget is one possibility) So, remove the record from the list
927         // This will stop the auto-repeat of the key, should a modifier change, for example
928         if (rec && rec->state != state) {
929             key_recorder.findKey(msg.wParam, true);
930             rec = 0;
931         }
932
933         // Find unicode character from Windows Message Queue
934         MSG wm_char;
935         UINT charType = (msgType == WM_KEYDOWN
936                          ? WM_CHAR
937                          : msgType == WM_IME_KEYDOWN ? WM_IME_CHAR : WM_SYSCHAR);
938
939         QChar uch;
940         if (PeekMessage(&wm_char, 0, charType, charType, PM_REMOVE)) {
941             // Found a ?_CHAR
942             uch = QChar((ushort)wm_char.wParam);
943             if (msgType == WM_SYSKEYDOWN && uch.isLetter() && (msg.lParam & KF_ALTDOWN))
944                 uch = uch.toLower(); // (See doc of WM_SYSCHAR) Alt-letter
945             if (!code && !uch.row())
946                 code = asciiToKeycode(uch.cell(), state);
947         }
948
949         // Special handling for the WM_IME_KEYDOWN message. Microsoft IME (Korean) will not
950         // generate a WM_IME_CHAR message corresponding to this message. We might get wrong
951         // results, if we map this virtual key-code directly (for eg '?' US layouts). So try
952         // to find the correct key using the current message parameters & keyboard state.
953         if (uch.isNull() && msgType == WM_IME_KEYDOWN) {
954             BYTE keyState[256];
955             wchar_t newKey[3] = {0};
956             GetKeyboardState(keyState);
957             int val = ToUnicode(vk_key, scancode, keyState, newKey, 2,  0);
958             if (val == 1) {
959                 uch = QChar(newKey[0]);
960             } else {
961                 // If we are still not able to find a unicode key, pass the WM_IME_KEYDOWN
962                 // message to DefWindowProc() for generating a proper WM_KEYDOWN.
963                 return false;
964             }
965         }
966
967         // If no ?_CHAR was found in the queue; deduct character from the ?_KEYDOWN parameters
968         if (uch.isNull()) {
969             if (msg.wParam == VK_DELETE) {
970                 uch = QChar(QLatin1Char(0x7f)); // Windows doesn't know this one.
971             } else {
972                 if (msgType != WM_SYSKEYDOWN || !code) {
973                     UINT map = MapVirtualKey(msg.wParam, 2);
974                     // If the high bit of the return value is set, it's a deadkey
975                     if (!(map & 0x80000000))
976                         uch = QChar((ushort)map);
977                 }
978             }
979             if (!code && !uch.row())
980                 code = asciiToKeycode(uch.cell(), state);
981         }
982
983         // Special handling of global Windows hotkeys
984         if (state == Qt::AltModifier) {
985             switch (code) {
986             case Qt::Key_Escape:
987             case Qt::Key_Tab:
988             case Qt::Key_Enter:
989             case Qt::Key_F4:
990                 return false; // Send the event on to Windows
991             case Qt::Key_Space:
992                 // do not pass this key to windows, we will process it ourselves
993                 showSystemMenu(receiver);
994                 return true;
995             default:
996                 break;
997             }
998         }
999
1000         // Map SHIFT + Tab to SHIFT + BackTab, QShortcutMap knows about this translation
1001         if (code == Qt::Key_Tab && (state & Qt::ShiftModifier) == Qt::ShiftModifier)
1002             code = Qt::Key_Backtab;
1003
1004         // If we have a record, it means that the key is already pressed, the state is the same
1005         // so, we have an auto-repeating key
1006         if (rec) {
1007             if (code < Qt::Key_Shift || code > Qt::Key_ScrollLock) {
1008                 QWindowSystemInterface::handleExtendedKeyEvent(receiver, QEvent::KeyRelease, code,
1009                                                                Qt::KeyboardModifier(state), scancode, msg.wParam, nModifiers, rec->text, true, 0);
1010                 QWindowSystemInterface::handleExtendedKeyEvent(receiver, QEvent::KeyPress, code,
1011                                                                Qt::KeyboardModifier(state), scancode, msg.wParam, nModifiers, rec->text, true, 0);
1012                 result = true;
1013             }
1014         }
1015         // No record of the key being previous pressed, so we now send a QEvent::KeyPress event,
1016         // and store the key data into our records.
1017         else {
1018             const QString text = uch.isNull() ? QString() : QString(uch);
1019             const char a = uch.row() ? 0 : uch.cell();
1020             key_recorder.storeKey(msg.wParam, a, state, text);
1021             QWindowSystemInterface::handleExtendedKeyEvent(receiver, QEvent::KeyPress, code,
1022                                                            Qt::KeyboardModifier(state), scancode, msg.wParam, nModifiers, text, false, 0);
1023             result =true;
1024             bool store = true;
1025 #ifndef Q_OS_WINCE
1026             // Alt+<alphanumerical> go to the Win32 menu system if unhandled by Qt
1027             if (msgType == WM_SYSKEYDOWN && !result && a) {
1028                 HWND parent = GetParent(QWindowsWindow::handleOf(receiver));
1029                 while (parent) {
1030                     if (GetMenu(parent)) {
1031                         SendMessage(parent, WM_SYSCOMMAND, SC_KEYMENU, a);
1032                         store = false;
1033                         result = true;
1034                         break;
1035                     }
1036                     parent = GetParent(parent);
1037                 }
1038             }
1039 #endif // !Q_OS_WINCE
1040             if (!store)
1041                 key_recorder.findKey(msg.wParam, true);
1042         }
1043     }
1044
1045     // KEYUP -----------------------------------------------------------------------------------
1046     else {
1047         // Try to locate the key in our records, and remove it if it exists.
1048         // The key may not be in our records if, for example, the down event was handled by
1049         // win32 natively, or our window gets focus while a key is already press, but now gets
1050         // the key release event.
1051         KeyRecord* rec = key_recorder.findKey(msg.wParam, true);
1052         if (!rec && !(code == Qt::Key_Shift
1053                       || code == Qt::Key_Control
1054                       || code == Qt::Key_Meta
1055                       || code == Qt::Key_Alt)) {
1056             // Someone ate the key down event
1057         } else {
1058             if (!code)
1059                 code = asciiToKeycode(rec->ascii ? rec->ascii : msg.wParam, state);
1060
1061             // Map SHIFT + Tab to SHIFT + BackTab, QShortcutMap knows about this translation
1062             if (code == Qt::Key_Tab && (state & Qt::ShiftModifier) == Qt::ShiftModifier)
1063                 code = Qt::Key_Backtab;
1064             QWindowSystemInterface::handleExtendedKeyEvent(receiver, QEvent::KeyRelease, code,
1065                                                            Qt::KeyboardModifier(state), scancode, msg.wParam, nModifiers,
1066                                                            (rec ? rec->text : QString()), false, 0);
1067             result = true;
1068 #ifndef Q_OS_WINCE
1069             // don't pass Alt to Windows unless we are embedded in a non-Qt window
1070             if (code == Qt::Key_Alt) {
1071                 const QWindowsContext *context = QWindowsContext::instance();
1072                 HWND parent = GetParent(QWindowsWindow::handleOf(receiver));
1073                 while (parent) {
1074                     if (!context->findPlatformWindow(parent) && GetMenu(parent)) {
1075                         result = false;
1076                         break;
1077                     }
1078                     parent = GetParent(parent);
1079                 }
1080             }
1081 #endif
1082         }
1083     }
1084     return result;
1085 }
1086
1087 Qt::KeyboardModifiers QWindowsKeyMapper::queryKeyboardModifiers()
1088 {
1089     Qt::KeyboardModifiers modifiers = Qt::NoModifier;
1090     if (GetKeyState(VK_SHIFT) < 0)
1091         modifiers |= Qt::ShiftModifier;
1092     if (GetKeyState(VK_CONTROL) < 0)
1093         modifiers |= Qt::ControlModifier;
1094     if (GetKeyState(VK_MENU) < 0)
1095         modifiers |= Qt::AltModifier;
1096     return modifiers;
1097 }
1098
1099 QList<int> QWindowsKeyMapper::possibleKeys(const QKeyEvent *e) const
1100 {
1101     QList<int> result;
1102
1103     const KeyboardLayoutItem &kbItem = keyLayout[e->nativeVirtualKey()];
1104     if (!kbItem.exists)
1105         return result;
1106
1107     quint32 baseKey = kbItem.qtKey[0];
1108     Qt::KeyboardModifiers keyMods = e->modifiers();
1109     if (baseKey == Qt::Key_Return && (e->nativeModifiers() & ExtendedKey)) {
1110         result << int(Qt::Key_Enter + keyMods);
1111         return result;
1112     }
1113     result << int(baseKey + keyMods); // The base key is _always_ valid, of course
1114
1115     for (int i = 1; i < NumMods; ++i) {
1116         Qt::KeyboardModifiers neededMods = ModsTbl[i];
1117         quint32 key = kbItem.qtKey[i];
1118         if (key && key != baseKey && ((keyMods & neededMods) == neededMods))
1119             result << int(key + (keyMods & ~neededMods));
1120     }
1121
1122     return result;
1123 }
1124
1125 QT_END_NAMESPACE