1 /****************************************************************************
2 **
3 ** Copyright (C) 2015 The Qt Company Ltd.
4 ** Contact: http://www.qt.io/licensing/
5 **
6 ** This file is part of the QtGui module 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 The Qt Company. For licensing terms
14 ** and conditions see http://www.qt.io/terms-conditions. For further
15 ** information use the contact form at http://www.qt.io/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 or version 3 as published by the Free
20 ** Software Foundation and appearing in the file LICENSE.LGPLv21 and
21 ** LICENSE.LGPLv3 included in the packaging of this file. Please review the
22 ** following information to ensure the GNU Lesser General Public License
23 ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
24 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 **
26 ** As a special exception, The Qt Company gives you certain additional
27 ** rights. These rights are described in The Qt Company LGPL Exception
28 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 **
30 ** GNU General Public License Usage
31 ** Alternatively, this file may be used under the terms of the GNU
32 ** General Public License version 3.0 as published by the Free Software
33 ** Foundation and appearing in the file LICENSE.GPL included in the
34 ** packaging of this file.  Please review the following information to
35 ** ensure the GNU General Public License version 3.0 requirements will be
36 ** met: http://www.gnu.org/copyleft/gpl.html.
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41 
42 #ifdef Q_WS_WINCE
43 #include "qguifunctions_wince.h"
44 #include "qmenubar.h"
45 extern bool qt_wince_is_mobile();             //defined in qguifunctions_wince.cpp
46 extern bool qt_wince_is_high_dpi();           //defined in qguifunctions_wince.cpp
47 extern bool qt_wince_is_smartphone();         //defined in qguifunctions_wince.cpp
48 extern bool qt_wince_is_pocket_pc();          //defined in qguifunctions_wince.cpp
49 extern void qt_wince_hide_taskbar(HWND hwnd); //defined in qguifunctions_wince.cpp
50 #endif
51 #ifdef Q_WS_WINCE_WM
52 #include <windowsm.h>
53 #include <tpcshell.h>
54 #ifdef QT_WINCE_GESTURES
55 #ifndef QT_NO_GESTURES
56 #include <gesture.h>
57 #endif
58 #endif
59 #endif
60 
61 #include "qapplication.h"
62 #include "qdesktopwidget.h"
63 #include "qevent.h"
64 #include "private/qeventdispatcher_win_p.h"
65 #include "qeventloop.h"
66 #include "qclipboard.h"
67 #include "qcursor.h"
68 #include "qdatetime.h"
69 #include "qpointer.h"
70 #include "qhash.h"
71 #include "qmetaobject.h"
72 #include "qmime.h"
73 #include "qpainter.h"
74 #include "qpixmapcache.h"
75 #include "qsessionmanager.h"
76 #include "qstyle.h"
77 #include "qwhatsthis.h" // ######## dependency
78 #include "qwidget.h"
79 #include "qcolormap.h"
80 #include "qlayout.h"
81 #include "qtooltip.h"
82 #include "qt_windows.h"
83 #include "qscrollbar.h"
84 #if defined(QT_NON_COMMERCIAL)
85 #include "qnc_win.h"
86 #endif
87 #include "private/qwininputcontext_p.h"
88 #include "private/qcursor_p.h"
89 #include "private/qmath_p.h"
90 #include "private/qapplication_p.h"
91 #include "private/qbackingstore_p.h"
92 #include "private/qwindowsurface_raster_p.h"
93 #include "qdebug.h"
94 #include <private/qkeymapper_p.h>
95 #include <private/qlocale_p.h>
96 #include <private/qsystemlibrary_p.h>
97 #include "qevent_p.h"
98 
99 //#define ALIEN_DEBUG
100 
101 #ifndef QT_NO_THREAD
102 #include "qmutex.h"
103 #endif
104 
105 #ifndef QT_NO_ACCESSIBILITY
106 #include "qaccessible.h"
107 
108 #include <oleacc.h>
109 #ifndef WM_GETOBJECT
110 #define WM_GETOBJECT                    0x003D
111 #endif
112 #endif // QT_NO_ACCESSIBILITY
113 
114 #if !defined(WINABLEAPI)
115 #  if defined(Q_WS_WINCE)
116 #    include <bldver.h>
117 #  endif
118 #  if !defined(Q_WS_WINCE)
119 #    include <winable.h>
120 #  endif
121 #endif
122 
123 #ifndef QT_NO_GESTURES
124 #  ifndef GID_ZOOM
125 #    define GID_ZOOM              3
126 #    define GID_TWOFINGERTAP      6
127 #    define GID_PRESSANDTAP       7
128 #    define GID_ROLLOVER          GID_PRESSANDTAP
129 #  endif
130 #endif
131 
132 #ifndef WM_TOUCH
133 #  define WM_TOUCH 0x0240
134 #endif
135 
136 #ifndef TOUCHEVENTF_MOVE
137 #  define TOUCHEVENTF_MOVE       0x0001
138 #  define TOUCHEVENTF_DOWN       0x0002
139 #  define TOUCHEVENTF_UP         0x0004
140 #  define TOUCHEVENTF_INRANGE    0x0008
141 #  define TOUCHEVENTF_PRIMARY    0x0010
142 #  define TOUCHEVENTF_NOCOALESCE 0x0020
143 #  define TOUCHEVENTF_PEN        0x0040
144 #  define TOUCHEVENTF_PALM       0x0080
145 
146 #  define TOUCHINPUTMASKF_TIMEFROMSYSTEM 0x0001
147 #  define TOUCHINPUTMASKF_EXTRAINFO      0x0002
148 #  define TOUCHINPUTMASKF_CONTACTAREA    0x0004
149 
150 typedef struct tagTOUCHINPUT
151 {
152     LONG x;
153     LONG y;
154     HANDLE hSource;
155     DWORD dwID;
156     DWORD dwFlags;
157     DWORD dwMask;
158     DWORD dwTime;
159     ULONG_PTR dwExtraInfo;
160     DWORD cxContact;
161     DWORD cyContact;
162 } TOUCHINPUT, *PTOUCHINPUT;
163 
164 #endif
165 
166 #include <windowsx.h>
167 #include <limits.h>
168 #include <string.h>
169 #include <ctype.h>
170 #include <stdio.h>
171 #include <math.h>
172 
173 #define PACKETDATA  (PK_X | PK_Y | PK_BUTTONS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE \
174                      | PK_ORIENTATION | PK_CURSOR | PK_Z)
175 #define PACKETMODE  0
176 
177 #include <wintab.h>
178 #ifndef CSR_TYPE
179 #define CSR_TYPE 20 // Some old Wacom wintab.h may not provide this constant.
180 #endif
181 #include <pktdef.h>
182 
183 #if defined(__CYGWIN32__)
184 #define __INSIDE_CYGWIN32__
185 #include <mywinsock.h>
186 #endif
187 
188 #ifndef IMR_RECONVERTSTRING
189 #define IMR_RECONVERTSTRING 4
190 #endif
191 
192 #ifndef IMR_CONFIRMRECONVERTSTRING
193 #define IMR_CONFIRMRECONVERTSTRING 0x0005
194 #endif
195 QT_BEGIN_NAMESPACE
196 
197 #ifdef Q_WS_WINCE
198 #ifndef SHRG_RETURNCMD
199 struct SHRGINFO {
200     DWORD cbSize;
201     HWND hwndClient;
202     POINT ptDown;
203     DWORD dwFlags;
204 };
205 #define  GN_CONTEXTMENU       1000
206 #define  SHRG_RETURNCMD       0x00000001
207 #define  SHRG_NOANIMATION     0x00000010
208 #endif
209 
210 #ifndef SPI_SETSIPINFO
211 #define SPI_SETSIPINFO        224
212 #endif
213 
214 #ifndef QT_NO_GESTURES
215 typedef DWORD (API *AygRecognizeGesture)(SHRGINFO*);
216 static AygRecognizeGesture ptrRecognizeGesture = 0;
217 static bool aygResolved = false;
resolveAygLibs()218 static void resolveAygLibs()
219 {
220     if (!aygResolved) {
221         QSystemLibrary ayglib(QLatin1String("aygshell"));
222         ptrRecognizeGesture = (AygRecognizeGesture) ayglib.resolve("SHRecognizeGesture");
223         aygResolved = true;
224     }
225 }
226 #endif // QT_NO_GESTURES
227 
228 #endif
229 
230 #ifndef SPI_SETFONTSMOOTHINGTYPE
231 #  define SPI_SETFONTSMOOTHINGTYPE 0x200B
232 #endif
233 #ifndef SPI_GETFONTSMOOTHINGTYPE
234 #  define SPI_GETFONTSMOOTHINGTYPE 0x200A
235 #endif
236 #ifndef FE_FONTSMOOTHINGCLEARTYPE
237 #  define FE_FONTSMOOTHINGCLEARTYPE 0x0002
238 #endif
239 
240 Q_GUI_EXPORT qreal qt_fontsmoothing_gamma;
241 Q_GUI_EXPORT bool qt_cleartype_enabled;
242 Q_GUI_EXPORT bool qt_win_owndc_required; // CS_OWNDC is required if we use the GL graphicssystem as default
243 
244 typedef HCTX (API *PtrWTOpen)(HWND, LPLOGCONTEXT, BOOL);
245 typedef BOOL (API *PtrWTClose)(HCTX);
246 typedef UINT (API *PtrWTInfo)(UINT, UINT, LPVOID);
247 typedef BOOL (API *PtrWTEnable)(HCTX, BOOL);
248 typedef BOOL (API *PtrWTOverlap)(HCTX, BOOL);
249 typedef int  (API *PtrWTPacketsGet)(HCTX, int, LPVOID);
250 typedef BOOL (API *PtrWTGet)(HCTX, LPLOGCONTEXT);
251 typedef int  (API *PtrWTQueueSizeGet)(HCTX);
252 typedef BOOL (API *PtrWTQueueSizeSet)(HCTX, int);
253 
254 static PtrWTInfo ptrWTInfo = 0;
255 static PtrWTEnable ptrWTEnable = 0;
256 static PtrWTOverlap ptrWTOverlap = 0;
257 static PtrWTPacketsGet ptrWTPacketsGet = 0;
258 static PtrWTGet ptrWTGet = 0;
259 
260 static PACKET localPacketBuf[QT_TABLET_NPACKETQSIZE];  // our own tablet packet queue.
261 HCTX qt_tablet_context;  // the hardware context for the tablet (like a window handle)
262 bool qt_tablet_tilt_support;
263 QPointF oldHiResTabletGlobalPosF;
264 
265 // flags for extensions for special Languages, currently only for RTL languages
266 bool qt_use_rtl_extensions = false;
267 
268 #ifndef QT_NO_TABLETEVENT
269 static void tabletInit(const quint64 uniqueId, const UINT csr_type, HCTX hTab);
270 static void tabletUpdateCursor(QTabletDeviceData &tdd, const UINT currentCursor);
271 static void initWinTabFunctions();        // resolve the WINTAB api functions
272 #endif // QT_NO_TABLETEVENT
273 
274 
275 #ifndef QT_NO_ACCESSIBILITY
276 extern IAccessible *qt_createWindowsAccessible(QAccessibleInterface *object);
277 #endif // QT_NO_ACCESSIBILITY
278 
279 extern bool qt_tabletChokeMouse;
280 extern QWidget* qt_get_tablet_widget();
281 extern bool qt_sendSpontaneousEvent(QObject*, QEvent*);
282 extern QRegion qt_dirtyRegion(QWidget *);
283 
284 typedef QHash<quint64, QTabletDeviceData> QTabletCursorInfo;
285 Q_GLOBAL_STATIC(QTabletCursorInfo, tCursorInfo)
286 QTabletDeviceData currentTabletPointer;
287 
288 // from qregion_win.cpp
289 extern HRGN qt_tryCreateRegion(QRegion::RegionType type, int left, int top, int right, int bottom);
290 
291 // support for on-the-fly changes of the XP theme engine
292 #ifndef WM_THEMECHANGED
293 #define WM_THEMECHANGED                 0x031A
294 #endif
295 #ifndef COLOR_MENUHILIGHT
296 #define COLOR_MENUHILIGHT                29
297 #define COLOR_MENUBAR                        30
298 #endif
299 
300 // support for xbuttons
301 #ifndef WM_XBUTTONDOWN
302 #define WM_XBUTTONDOWN                  0x020B
303 #define WM_XBUTTONUP                    0x020C
304 #define WM_XBUTTONDBLCLK                0x020D
305 #endif
306 #ifndef GET_KEYSTATE_WPARAM
307 #define GET_KEYSTATE_WPARAM(wParam)     (LOWORD(wParam))
308 #define GET_XBUTTON_WPARAM(wParam)      (HIWORD(wParam))
309 #define XBUTTON1      0x0001
310 #define XBUTTON2      0x0002
311 #endif
312 #ifndef MK_XBUTTON1
313 #define MK_XBUTTON1         0x0020
314 #define MK_XBUTTON2         0x0040
315 #endif
316 
317 // support for multi-media-keys
318 #ifndef WM_APPCOMMAND
319 #define WM_APPCOMMAND                   0x0319
320 #endif
321 
322 #ifndef FAPPCOMMAND_MOUSE
323 #define FAPPCOMMAND_MOUSE 0x8000
324 #define FAPPCOMMAND_KEY   0
325 #define FAPPCOMMAND_OEM   0x1000
326 #define FAPPCOMMAND_MASK  0xF000
327 #define GET_APPCOMMAND_LPARAM(lParam) ((short)(HIWORD(lParam) & ~FAPPCOMMAND_MASK))
328 #define GET_DEVICE_LPARAM(lParam)     ((WORD)(HIWORD(lParam) & FAPPCOMMAND_MASK))
329 #define GET_MOUSEORKEY_LPARAM         GET_DEVICE_LPARAM
330 #define GET_FLAGS_LPARAM(lParam)      (LOWORD(lParam))
331 #define GET_KEYSTATE_LPARAM(lParam)   GET_FLAGS_LPARAM(lParam)
332 
333 #define APPCOMMAND_BROWSER_BACKWARD       1
334 #define APPCOMMAND_BROWSER_FORWARD        2
335 #define APPCOMMAND_BROWSER_REFRESH        3
336 #define APPCOMMAND_BROWSER_STOP           4
337 #define APPCOMMAND_BROWSER_SEARCH         5
338 #define APPCOMMAND_BROWSER_FAVORITES      6
339 #define APPCOMMAND_BROWSER_HOME           7
340 #define APPCOMMAND_VOLUME_MUTE            8
341 #define APPCOMMAND_VOLUME_DOWN            9
342 #define APPCOMMAND_VOLUME_UP              10
343 #define APPCOMMAND_MEDIA_NEXTTRACK        11
344 #define APPCOMMAND_MEDIA_PREVIOUSTRACK    12
345 #define APPCOMMAND_MEDIA_STOP             13
346 #define APPCOMMAND_MEDIA_PLAY_PAUSE       14
347 #define APPCOMMAND_LAUNCH_MAIL            15
348 #define APPCOMMAND_LAUNCH_MEDIA_SELECT    16
349 #define APPCOMMAND_LAUNCH_APP1            17
350 #define APPCOMMAND_LAUNCH_APP2            18
351 #define APPCOMMAND_BASS_DOWN              19
352 #define APPCOMMAND_BASS_BOOST             20
353 #define APPCOMMAND_BASS_UP                21
354 #define APPCOMMAND_TREBLE_DOWN            22
355 #define APPCOMMAND_TREBLE_UP              23
356 #endif // FAPPCOMMAND_MOUSE
357 
358 // New commands from Windows XP (some even Sp1)
359 #ifndef APPCOMMAND_MICROPHONE_VOLUME_MUTE
360 #define APPCOMMAND_MICROPHONE_VOLUME_MUTE 24
361 #define APPCOMMAND_MICROPHONE_VOLUME_DOWN 25
362 #define APPCOMMAND_MICROPHONE_VOLUME_UP   26
363 #define APPCOMMAND_HELP                   27
364 #define APPCOMMAND_FIND                   28
365 #define APPCOMMAND_NEW                    29
366 #define APPCOMMAND_OPEN                   30
367 #define APPCOMMAND_CLOSE                  31
368 #define APPCOMMAND_SAVE                   32
369 #define APPCOMMAND_PRINT                  33
370 #define APPCOMMAND_UNDO                   34
371 #define APPCOMMAND_REDO                   35
372 #define APPCOMMAND_COPY                   36
373 #define APPCOMMAND_CUT                    37
374 #define APPCOMMAND_PASTE                  38
375 #define APPCOMMAND_REPLY_TO_MAIL          39
376 #define APPCOMMAND_FORWARD_MAIL           40
377 #define APPCOMMAND_SEND_MAIL              41
378 #define APPCOMMAND_SPELL_CHECK            42
379 #define APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE    43
380 #define APPCOMMAND_MIC_ON_OFF_TOGGLE      44
381 #define APPCOMMAND_CORRECTION_LIST        45
382 #define APPCOMMAND_MEDIA_PLAY             46
383 #define APPCOMMAND_MEDIA_PAUSE            47
384 #define APPCOMMAND_MEDIA_RECORD           48
385 #define APPCOMMAND_MEDIA_FAST_FORWARD     49
386 #define APPCOMMAND_MEDIA_REWIND           50
387 #define APPCOMMAND_MEDIA_CHANNEL_UP       51
388 #define APPCOMMAND_MEDIA_CHANNEL_DOWN     52
389 #endif // APPCOMMAND_MICROPHONE_VOLUME_MUTE
390 
391 #if (_WIN32_WINNT < 0x0400)
392 // This struct is defined in winuser.h if the _WIN32_WINNT >= 0x0400 -- in the
393 // other cases we have to define it on our own.
394 typedef struct tagTRACKMOUSEEVENT {
395     DWORD cbSize;
396     DWORD dwFlags;
397     HWND  hwndTrack;
398     DWORD dwHoverTime;
399 } TRACKMOUSEEVENT, *LPTRACKMOUSEEVENT;
400 #endif
401 #ifndef WM_MOUSELEAVE
402 #define WM_MOUSELEAVE                   0x02A3
403 #endif
404 
405 QT_BEGIN_INCLUDE_NAMESPACE
406 #include "private/qwidget_p.h"
407 QT_END_INCLUDE_NAMESPACE
408 
409 static int translateButtonState(int s, int type, int button);
410 
411 // ##### get rid of this!
qt_colorref2qrgb(COLORREF col)412 QRgb qt_colorref2qrgb(COLORREF col)
413 {
414     return qRgb(GetRValue(col),GetGValue(col),GetBValue(col));
415 }
416 
417 
418 /*****************************************************************************
419   Internal variables and functions
420  *****************************************************************************/
421 
422 static HWND         curWin                = 0;                // current window
423 static HDC         displayDC        = 0;                // display device context
424 
425 // Session management
426 static bool        sm_blockUserInput    = false;
427 static bool        sm_smActive             = false;
428 extern QSessionManager* qt_session_manager_self;
429 static bool        sm_cancel;
430 
431 static bool replayPopupMouseEvent = false; // replay handling when popups close
432 
433 // ignore the next release event if return from a modal widget
434 Q_GUI_EXPORT bool qt_win_ignoreNextMouseReleaseEvent = false;
435 
436 
437 #if defined(QT_DEBUG)
438 static bool        appNoGrab        = false;        // mouse/keyboard grabbing
439 #endif
440 
441 static bool        app_do_modal           = false;        // modal mode
442 extern QWidgetList *qt_modal_stack;
443 extern QDesktopWidget *qt_desktopWidget;
444 static QPointer<QWidget> popupButtonFocus;
445 static bool        qt_try_modal(QWidget *, MSG *, int& ret);
446 
447 QWidget               *qt_button_down = 0;                // widget got last button-down
448 QPointer<QWidget> qt_last_mouse_receiver = 0;
449 
450 static HWND        autoCaptureWnd = 0;
451 static HWND        imeParentWnd = 0;
452 static void        setAutoCapture(HWND);                // automatic capture
453 static void        releaseAutoCapture();
454 
455 static void     unregWinClasses();
456 
457 extern QCursor *qt_grab_cursor();
458 
459 #if defined(Q_WS_WIN)
460 #define __export
461 #endif
462 
463 extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND, UINT, WPARAM, LPARAM);
464 
465 class QETWidget : public QWidget                // event translator widget
466 {
467 public:
xtra()468     QWExtra    *xtra() { return d_func()->extraData(); }
topData()469     QTLWExtra  *topData() { return d_func()->topData(); }
maybeTopData()470     QTLWExtra  *maybeTopData() { return d_func()->maybeTopData(); }
syncBackingStore(const QRegion & rgn)471     void syncBackingStore(const QRegion &rgn) { d_func()->syncBackingStore(rgn); }
syncBackingStore()472     void syncBackingStore() { d_func()->syncBackingStore(); }
dataPtr()473     QWidgetData *dataPtr() { return data; }
dptr()474     QWidgetPrivate *dptr() { return d_func(); }
frameStrut() const475     QRect frameStrut() const { return d_func()->frameStrut(); }
winEvent(MSG * m,long * r)476     bool        winEvent(MSG *m, long *r)        { return QWidget::winEvent(m, r); }
markFrameStrutDirty()477     void        markFrameStrutDirty()        { data->fstrut_dirty = 1; }
478     bool        translateMouseEvent(const MSG &msg);
479     bool        translateWheelEvent(const MSG &msg);
480     bool        translatePaintEvent(const MSG &msg);
481     bool        translateConfigEvent(const MSG &msg);
482     bool        translateCloseEvent(const MSG &msg);
483     bool        translateTabletEvent(const MSG &msg, PACKET *localPacketBuf, int numPackets);
484 #ifndef QT_NO_GESTURES
485     bool        translateGestureEvent(const MSG &msg, const GESTUREINFO &gi);
486 #endif
487     void        repolishStyle(QStyle &style);
showChildren(bool spontaneous)488     inline void showChildren(bool spontaneous) { d_func()->showChildren(spontaneous); }
hideChildren(bool spontaneous)489     inline void hideChildren(bool spontaneous) { d_func()->hideChildren(spontaneous); }
testWindowState(uint teststate)490     inline uint testWindowState(uint teststate){ return dataPtr()->window_state & teststate; }
setWindowTitle_helper(const QString & title)491     inline void setWindowTitle_helper(const QString &title) { d_func()->setWindowTitle_helper(title); }
forceUpdate()492     inline void forceUpdate() {
493         QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
494         if (tlwExtra && tlwExtra->backingStore)
495             tlwExtra->backingStore->markDirty(rect(), this, true, true);
496     }
497 };
498 
499 // need to get default font?
500 extern bool qt_app_has_font;
501 
502 extern QFont qt_LOGFONTtoQFont(LOGFONT& lf,bool scale);
503 
qt_set_windows_color_resources()504 static void qt_set_windows_color_resources()
505 {
506     // Do the color settings
507     QPalette pal;
508     pal.setColor(QPalette::WindowText,
509                  QColor(qt_colorref2qrgb(GetSysColor(COLOR_WINDOWTEXT))));
510     pal.setColor(QPalette::Button,
511                  QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNFACE))));
512     pal.setColor(QPalette::Light,
513                  QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNHIGHLIGHT))));
514     pal.setColor(QPalette::Dark,
515                  QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNSHADOW))));
516     pal.setColor(QPalette::Mid, pal.button().color().darker(150));
517     pal.setColor(QPalette::Text,
518                  QColor(qt_colorref2qrgb(GetSysColor(COLOR_WINDOWTEXT))));
519     pal.setColor(QPalette::BrightText,
520                  QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNHIGHLIGHT))));
521     pal.setColor(QPalette::Base,
522                  QColor(qt_colorref2qrgb(GetSysColor(COLOR_WINDOW))));
523     pal.setColor(QPalette::Window,
524                  QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNFACE))));
525     pal.setColor(QPalette::ButtonText,
526                  QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNTEXT))));
527     pal.setColor(QPalette::Midlight,
528                  QColor(qt_colorref2qrgb(GetSysColor(COLOR_3DLIGHT))));
529     pal.setColor(QPalette::Shadow,
530                  QColor(qt_colorref2qrgb(GetSysColor(COLOR_3DDKSHADOW))));
531     pal.setColor(QPalette::Highlight,
532                  QColor(qt_colorref2qrgb(GetSysColor(COLOR_HIGHLIGHT))));
533     pal.setColor(QPalette::HighlightedText,
534                  QColor(qt_colorref2qrgb(GetSysColor(COLOR_HIGHLIGHTTEXT))));
535 
536 #if defined(Q_WS_WINCE)
537     // ### hardcoded until I find out how to get it from the system settings.
538     pal.setColor(QPalette::LinkVisited, pal.highlight().color().dark(150));
539     pal.setColor(QPalette::Link, pal.highlight().color().light(130));
540     // Background == Base on Windows CE
541     if (qt_wince_is_smartphone() || qt_wince_is_pocket_pc())
542       pal.setColor(QPalette::Background, pal.base().color());
543 #else
544     pal.setColor(QPalette::Link, Qt::blue);
545     pal.setColor(QPalette::LinkVisited, Qt::magenta);
546 #endif
547 
548 
549 
550     pal.setColor(QPalette::Inactive, QPalette::Button, pal.button().color());
551     pal.setColor(QPalette::Inactive, QPalette::Window, pal.background().color());
552     pal.setColor(QPalette::Inactive, QPalette::Light, pal.light().color());
553     pal.setColor(QPalette::Inactive, QPalette::Dark, pal.dark().color());
554 
555     if (pal.midlight() == pal.button())
556         pal.setColor(QPalette::Midlight, pal.button().color().lighter(110));
557     if (pal.background() != pal.base()) {
558         pal.setColor(QPalette::Inactive, QPalette::Highlight, pal.color(QPalette::Inactive, QPalette::Window));
559         pal.setColor(QPalette::Inactive, QPalette::HighlightedText, pal.color(QPalette::Inactive, QPalette::Text));
560     }
561 
562     const QColor bg = pal.background().color();
563     const QColor fg = pal.foreground().color(), btn = pal.button().color();
564     QColor disabled((fg.red()+btn.red())/2,(fg.green()+btn.green())/2,
565                      (fg.blue()+btn.blue())/2);
566     pal.setColorGroup(QPalette::Disabled, pal.foreground(), pal.button(), pal.light(),
567         pal.dark(), pal.mid(), pal.text(), pal.brightText(), pal.base(), pal.background() );
568     pal.setColor(QPalette::Disabled, QPalette::WindowText, disabled);
569     pal.setColor(QPalette::Disabled, QPalette::Text, disabled);
570     pal.setColor(QPalette::Disabled, QPalette::ButtonText, disabled);
571     pal.setColor(QPalette::Disabled, QPalette::Highlight,
572                   QColor(qt_colorref2qrgb(GetSysColor(COLOR_HIGHLIGHT))));
573     pal.setColor(QPalette::Disabled, QPalette::HighlightedText,
574                   QColor(qt_colorref2qrgb(GetSysColor(COLOR_HIGHLIGHTTEXT))));
575     pal.setColor(QPalette::Disabled, QPalette::Base, bg);
576 
577     QApplicationPrivate::setSystemPalette(pal);
578 
579     QApplicationPrivate::initializeWidgetPaletteHash();
580 
581     QColor ttip(qt_colorref2qrgb(GetSysColor(COLOR_INFOBK)));
582 
583     QColor ttipText(qt_colorref2qrgb(GetSysColor(COLOR_INFOTEXT)));
584     {
585 #ifndef QT_NO_TOOLTIP
586         QPalette tiplabel(pal);
587         tiplabel.setColor(QPalette::All, QPalette::Button, ttip);
588         tiplabel.setColor(QPalette::All, QPalette::Window, ttip);
589         tiplabel.setColor(QPalette::All, QPalette::ToolTipBase, ttip);
590         tiplabel.setColor(QPalette::All, QPalette::Text, ttipText);
591         tiplabel.setColor(QPalette::All, QPalette::WindowText, ttipText);
592         tiplabel.setColor(QPalette::All, QPalette::ButtonText, ttipText);
593         tiplabel.setColor(QPalette::All, QPalette::Button, ttip);
594         tiplabel.setColor(QPalette::All, QPalette::Window, ttip);
595         tiplabel.setColor(QPalette::All, QPalette::Text, ttipText);
596         tiplabel.setColor(QPalette::All, QPalette::WindowText, ttipText);
597         tiplabel.setColor(QPalette::All, QPalette::ButtonText, ttipText);
598         tiplabel.setColor(QPalette::All, QPalette::ToolTipText, ttipText);
599         const QColor fg = tiplabel.foreground().color(), btn = tiplabel.button().color();
600         QColor disabled((fg.red()+btn.red())/2,(fg.green()+btn.green())/2,
601                          (fg.blue()+btn.blue())/2);
602         tiplabel.setColor(QPalette::Disabled, QPalette::WindowText, disabled);
603         tiplabel.setColor(QPalette::Disabled, QPalette::ToolTipText, disabled);
604         tiplabel.setColor(QPalette::Disabled, QPalette::Text, disabled);
605         tiplabel.setColor(QPalette::Disabled, QPalette::Base, Qt::white);
606         tiplabel.setColor(QPalette::Disabled, QPalette::ToolTipBase, Qt::white);
607         tiplabel.setColor(QPalette::Disabled, QPalette::BrightText, Qt::white);
608         QToolTip::setPalette(tiplabel);
609 #endif //QT_NO_TOOLTIP
610     }
611 }
612 
qt_set_windows_font_resources()613 static void qt_set_windows_font_resources()
614 {
615 #ifndef Q_WS_WINCE
616     NONCLIENTMETRICS ncm;
617     ncm.cbSize = FIELD_OFFSET(NONCLIENTMETRICS, lfMessageFont) + sizeof(LOGFONT);
618     SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncm.cbSize , &ncm, 0);
619 
620     QFont menuFont = qt_LOGFONTtoQFont(ncm.lfMenuFont, true);
621     QFont messageFont = qt_LOGFONTtoQFont(ncm.lfMessageFont, true);
622     QFont statusFont = qt_LOGFONTtoQFont(ncm.lfStatusFont, true);
623     QFont titleFont = qt_LOGFONTtoQFont(ncm.lfCaptionFont, true);
624 
625     LOGFONT lfIconTitleFont;
626     SystemParametersInfo(SPI_GETICONTITLELOGFONT, sizeof(lfIconTitleFont), &lfIconTitleFont, 0);
627     QFont iconTitleFont = qt_LOGFONTtoQFont(lfIconTitleFont, true);
628 
629     QApplication::setFont(menuFont, "QMenu");
630     QApplication::setFont(menuFont, "QMenuBar");
631     QApplication::setFont(messageFont, "QMessageBox");
632     QApplication::setFont(statusFont, "QTipLabel");
633     QApplication::setFont(statusFont, "QStatusBar");
634     QApplication::setFont(titleFont, "Q3TitleBar");
635     QApplication::setFont(titleFont, "QWorkspaceTitleBar");
636     QApplication::setFont(iconTitleFont, "QAbstractItemView");
637     QApplication::setFont(iconTitleFont, "QDockWidgetTitle");
638 
639 #else
640     LOGFONT lf;
641     HGDIOBJ stockFont = GetStockObject(SYSTEM_FONT);
642     GetObject(stockFont, sizeof(lf), &lf);
643     QFont systemFont = qt_LOGFONTtoQFont(lf, true);
644     QApplicationPrivate::setSystemFont(systemFont);
645     QFont smallerFont = systemFont;
646     if (qt_wince_is_mobile()) {
647         smallerFont.setPointSize(systemFont.pointSize()-1);
648         QApplication::setFont(smallerFont, "QTabBar");
649         smallerFont.setBold(true);
650         QApplication::setFont(smallerFont, "QAbstractButton");
651     }
652 #endif// Q_WS_WINCE
653 }
654 
qt_win_read_cleartype_settings()655 static void qt_win_read_cleartype_settings()
656 {
657     UINT result = 0;
658 #ifdef Q_OS_WINCE
659     if (SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &result, 0))
660         qt_cleartype_enabled = result;
661 #else
662     if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &result, 0))
663         qt_cleartype_enabled = (result == FE_FONTSMOOTHINGCLEARTYPE);
664 #endif
665 
666     int winSmooth;
667     if (SystemParametersInfo(0x200C /* SPI_GETFONTSMOOTHINGCONTRAST */, 0, &winSmooth, 0)) {
668         qt_fontsmoothing_gamma = winSmooth / qreal(1000.0);
669     } else {
670         qt_fontsmoothing_gamma = 1.0;
671     }
672 
673     // Safeguard ourselves against corrupt registry values...
674     if (qt_fontsmoothing_gamma > 5 || qt_fontsmoothing_gamma < 1)
675         qt_fontsmoothing_gamma = qreal(1.4);
676 }
677 
qt_set_windows_resources()678 static void qt_set_windows_resources()
679 {
680     if (QApplication::type() != QApplication::Tty)
681         (void) QApplication::style(); // trigger creation of application style
682     qt_set_windows_font_resources();
683     qt_set_windows_color_resources();
684 }
685 
initializeWidgetPaletteHash()686 void QApplicationPrivate::initializeWidgetPaletteHash()
687 {
688     QPalette pal = *QApplicationPrivate::sys_pal;
689     QColor menuCol(qt_colorref2qrgb(GetSysColor(COLOR_MENU)));
690     QColor menuText(qt_colorref2qrgb(GetSysColor(COLOR_MENUTEXT)));
691     BOOL isFlat = false;
692     if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP
693         && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)))
694         SystemParametersInfo(SPI_GETFLATMENU, 0, &isFlat, 0);
695     QPalette menu(pal);
696     // we might need a special color group for the menu.
697     menu.setColor(QPalette::Active, QPalette::Button, menuCol);
698     menu.setColor(QPalette::Active, QPalette::Text, menuText);
699     menu.setColor(QPalette::Active, QPalette::WindowText, menuText);
700     menu.setColor(QPalette::Active, QPalette::ButtonText, menuText);
701     QColor disabled(qt_colorref2qrgb(GetSysColor(COLOR_GRAYTEXT)));
702     menu.setColor(QPalette::Disabled, QPalette::WindowText, disabled);
703     menu.setColor(QPalette::Disabled, QPalette::Text, disabled);
704     menu.setColor(QPalette::Disabled, QPalette::Highlight,
705                     QColor(qt_colorref2qrgb(GetSysColor(
706                                             (QSysInfo::WindowsVersion >= QSysInfo::WV_XP
707                                             && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based))
708                                             && isFlat ? COLOR_MENUHILIGHT : COLOR_HIGHLIGHT))));
709     menu.setColor(QPalette::Disabled, QPalette::HighlightedText, disabled);
710     menu.setColor(QPalette::Disabled, QPalette::Button,
711                     menu.color(QPalette::Active, QPalette::Button));
712     menu.setColor(QPalette::Inactive, QPalette::Button,
713                     menu.color(QPalette::Active, QPalette::Button));
714     menu.setColor(QPalette::Inactive, QPalette::Text,
715                     menu.color(QPalette::Active, QPalette::Text));
716     menu.setColor(QPalette::Inactive, QPalette::WindowText,
717                     menu.color(QPalette::Active, QPalette::WindowText));
718     menu.setColor(QPalette::Inactive, QPalette::ButtonText,
719                     menu.color(QPalette::Active, QPalette::ButtonText));
720     menu.setColor(QPalette::Inactive, QPalette::Highlight,
721                     menu.color(QPalette::Active, QPalette::Highlight));
722     menu.setColor(QPalette::Inactive, QPalette::HighlightedText,
723                     menu.color(QPalette::Active, QPalette::HighlightedText));
724     menu.setColor(QPalette::Inactive, QPalette::ButtonText,
725                     pal.color(QPalette::Inactive, QPalette::Dark));
726     QApplication::setPalette(menu, "QMenu");
727 
728     if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP
729         && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)) && isFlat) {
730         QColor menubar(qt_colorref2qrgb(GetSysColor(COLOR_MENUBAR)));
731         menu.setColor(QPalette::Active, QPalette::Button, menubar);
732         menu.setColor(QPalette::Disabled, QPalette::Button, menubar);
733         menu.setColor(QPalette::Inactive, QPalette::Button, menubar);
734     }
735     QApplication::setPalette(menu, "QMenuBar");
736 }
737 
qt_set_windows_updateScrollBar(QWidget * widget)738 static void qt_set_windows_updateScrollBar(QWidget *widget)
739 {
740     QList<QObject*> children = widget->children();
741     for (int i = 0; i < children.size(); ++i) {
742         QObject *o = children.at(i);
743         if(!o->isWidgetType())
744             continue;
745         if (QWidget *w = static_cast<QWidget *>(o))
746             qt_set_windows_updateScrollBar(w);
747     }
748 #ifndef QT_NO_SCROLLBAR
749     if (qobject_cast<QScrollBar*>(widget))
750         widget->updateGeometry();
751 #endif
752 }
753 
754 
755 /*****************************************************************************
756   qt_init() - initializes Qt for Windows
757  *****************************************************************************/
758 
759 typedef BOOL (WINAPI *PtrSetProcessDPIAware) (VOID);
760 static PtrSetProcessDPIAware ptrSetProcessDPIAware = 0;
761 PtrUpdateLayeredWindow ptrUpdateLayeredWindow = 0;
762 PtrUpdateLayeredWindowIndirect ptrUpdateLayeredWindowIndirect = 0;
qt_updateLayeredWindowIndirect(HWND hwnd,const Q_UPDATELAYEREDWINDOWINFO * info)763 static BOOL WINAPI qt_updateLayeredWindowIndirect(HWND hwnd, const Q_UPDATELAYEREDWINDOWINFO *info)
764 {
765     return (*ptrUpdateLayeredWindow)(hwnd, info->hdcDst, info->pptDst, info->psize, info->hdcSrc,
766                                      info->pptSrc, info->crKey, info->pblend, info->dwFlags);
767 }
768 
qt_init(QApplicationPrivate * priv,int)769 void qt_init(QApplicationPrivate *priv, int)
770 {
771 
772     int argc = priv->argc;
773     char **argv = priv->argv;
774     int i, j;
775 
776   // Get command line params
777 
778     j = argc ? 1 : 0;
779     for (i=1; i<argc; i++) {
780         if (argv[i] && *argv[i] != '-') {
781             argv[j++] = argv[i];
782             continue;
783         }
784 #if defined(QT_DEBUG)
785         if (qstrcmp(argv[i], "-nograb") == 0)
786             appNoGrab = !appNoGrab;
787         else
788 #endif // QT_DEBUG
789             argv[j++] = argv[i];
790     }
791     if(j < priv->argc) {
792         priv->argv[j] = 0;
793         priv->argc = j;
794     }
795 
796 #ifndef Q_WS_WINCE
797     // No message boxes but important ones
798     SetErrorMode(SetErrorMode(0) | SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX);
799 #endif
800 
801 #ifndef Q_WS_WINCE
802     // Initialize OLE/COM
803     //         S_OK means success and S_FALSE means that it has already
804     //         been initialized
805     HRESULT r;
806     r = OleInitialize(0);
807     if (r != S_OK && r != S_FALSE) {
808         qWarning("Qt: Could not initialize OLE (error %x)", (unsigned int)r);
809     }
810 #endif
811 
812     // Misc. initialization
813 #if defined(QT_DEBUG) && !defined(Q_WS_WINCE)
814     GdiSetBatchLimit(1);
815 #endif
816 
817     // initialize key mapper
818     QKeyMapper::changeKeyboard();
819 
820     QColormap::initialize();
821     QFont::initialize();
822 #ifndef QT_NO_CURSOR
823     if (QApplication::type() != QApplication::Tty)
824         QCursorData::initialize();
825 #endif
826     qApp->setObjectName(priv->appName());
827 
828     // default font
829 #ifndef Q_WS_WINCE
830     HGDIOBJ stockFont = GetStockObject(DEFAULT_GUI_FONT);
831 #else
832     HGDIOBJ stockFont = GetStockObject(SYSTEM_FONT);
833 #endif
834 
835     LOGFONT lf;
836     GetObject(stockFont, sizeof(lf), &lf);
837     QFont systemFont = qt_LOGFONTtoQFont(lf, true);
838 
839 #ifndef Q_WS_WINCE
840     if (systemFont.family() == QLatin1String("MS Shell Dlg")) {
841         systemFont.setFamily(QLatin1String("MS Shell Dlg 2"));
842     }
843 #endif
844 
845     QApplicationPrivate::setSystemFont(systemFont);
846 
847     // QFont::locale_init();  ### Uncomment when it does something on Windows
848 
849     if (QApplication::desktopSettingsAware())
850         qt_set_windows_resources();
851 
852 #ifndef QT_NO_TABLETEVENT
853     initWinTabFunctions();
854 #endif // QT_NO_TABLETEVENT
855 
856 #ifndef QT_NO_IM
857     QApplicationPrivate::inputContext = new QWinInputContext(0);
858 #endif
859 
860     // Read the initial cleartype settings...
861     qt_win_read_cleartype_settings();
862     qt_win_owndc_required = false;
863 
864     extern void qt_win_initialize_directdraw();
865     qt_win_initialize_directdraw();
866 
867 #ifndef Q_OS_WINCE
868     QSystemLibrary user32(QLatin1String("user32"));
869     ptrUpdateLayeredWindowIndirect = (PtrUpdateLayeredWindowIndirect)user32.resolve("UpdateLayeredWindowIndirect");
870     ptrUpdateLayeredWindow = (PtrUpdateLayeredWindow)user32.resolve("UpdateLayeredWindow");
871 
872     if (ptrUpdateLayeredWindow && !ptrUpdateLayeredWindowIndirect)
873         ptrUpdateLayeredWindowIndirect = qt_updateLayeredWindowIndirect;
874 
875     // Notify Vista and Windows 7 that we support highter DPI settings
876     ptrSetProcessDPIAware = (PtrSetProcessDPIAware)user32.resolve("SetProcessDPIAware");
877     if (ptrSetProcessDPIAware)
878         ptrSetProcessDPIAware();
879 #endif
880 
881 #ifndef QT_NO_GESTURES
882     priv->GetGestureInfo = 0;
883     priv->GetGestureExtraArgs = 0;
884     priv->CloseGestureInfoHandle = 0;
885     priv->SetGestureConfig = 0;
886     priv->GetGestureConfig = 0;
887     priv->BeginPanningFeedback = 0;
888     priv->UpdatePanningFeedback = 0;
889     priv->EndPanningFeedback = 0;
890 
891 #if defined(Q_WS_WINCE_WM) && defined(QT_WINCE_GESTURES)
892     priv->GetGestureInfo = (PtrGetGestureInfo) &TKGetGestureInfo;
893     priv->GetGestureExtraArgs = (PtrGetGestureExtraArgs) &TKGetGestureExtraArguments;
894 #elif !defined(Q_WS_WINCE)
895   #if !defined(QT_NO_NATIVE_GESTURES)
896     priv->GetGestureInfo = (PtrGetGestureInfo)user32.resolve("GetGestureInfo");
897     priv->GetGestureExtraArgs = (PtrGetGestureExtraArgs)user32.resolve("GetGestureExtraArgs");
898     priv->CloseGestureInfoHandle = (PtrCloseGestureInfoHandle)user32.resolve("CloseGestureInfoHandle");
899     priv->SetGestureConfig = (PtrSetGestureConfig)user32.resolve("SetGestureConfig");
900     priv->GetGestureConfig = (PtrGetGestureConfig)user32.resolve("GetGestureConfig");
901   #endif // QT_NO_NATIVE_GESTURES
902     QSystemLibrary libTheme(QLatin1String("uxtheme"));
903     priv->BeginPanningFeedback = (PtrBeginPanningFeedback)libTheme.resolve("BeginPanningFeedback");
904     priv->UpdatePanningFeedback = (PtrUpdatePanningFeedback)libTheme.resolve("UpdatePanningFeedback");
905     priv->EndPanningFeedback = (PtrEndPanningFeedback)libTheme.resolve("EndPanningFeedback");
906 #endif
907 #endif // QT_NO_GESTURES
908 }
909 
910 /*****************************************************************************
911   qt_cleanup() - cleans up when the application is finished
912  *****************************************************************************/
913 
qt_cleanup()914 void qt_cleanup()
915 {
916     unregWinClasses();
917     QPixmapCache::clear();
918 
919 #ifndef QT_NO_CURSOR
920     if (QApplication::type() != QApplication::Tty)
921         QCursorData::cleanup();
922 #endif
923     QFont::cleanup();
924     QColormap::cleanup();
925     if (displayDC) {
926         ReleaseDC(0, displayDC);
927         displayDC = 0;
928     }
929 
930 #ifndef QT_NO_IM
931     delete QApplicationPrivate::inputContext;
932     QApplicationPrivate::inputContext = 0;
933 #endif
934 
935 #ifndef Q_WS_WINCE
936   // Deinitialize OLE/COM
937     OleUninitialize();
938 #endif
939 }
940 
941 
942 /*****************************************************************************
943   Platform specific global and internal functions
944  *****************************************************************************/
945 
qt_win_display_dc()946 Q_GUI_EXPORT HDC qt_win_display_dc()                        // get display DC
947 {
948     Q_ASSERT(qApp && qApp->thread() == QThread::currentThread());
949     if (!displayDC)
950         displayDC = GetDC(0);
951     return displayDC;
952 }
953 
qt_nograb()954 bool qt_nograb()                                // application no-grab option
955 {
956 #if defined(QT_DEBUG)
957     return appNoGrab;
958 #else
959     return false;
960 #endif
961 }
962 
963 typedef QHash<QString, int> WinClassNameHash;
Q_GLOBAL_STATIC(WinClassNameHash,winclassNames) const964 Q_GLOBAL_STATIC(WinClassNameHash, winclassNames)
965 
966 //
967 // If 0 is passed as the widget pointer, register a window class
968 // for QWidget as default. This is used in QGLTemporaryContext
969 // during GL initialization, where we don't want to use temporary
970 // QWidgets or QGLWidgets, neither do we want to have separate code
971 // to register window classes.
972 //
973 const QString qt_reg_winclass(QWidget *w)        // register window class
974 {
975     Qt::WindowFlags flags = w ? w->windowFlags() : (Qt::WindowFlags)0;
976     Qt::WindowFlags type = flags & Qt::WindowType_Mask;
977 
978     uint style;
979     bool icon;
980     QString cname;
981     if (w && qt_widget_private(w)->isGLWidget) {
982         cname = QLatin1String("QGLWidget");
983         style = CS_DBLCLKS;
984 #ifndef Q_WS_WINCE
985         style |= CS_OWNDC;
986 #endif
987         icon  = true;
988     } else if (w && (flags & Qt::MSWindowsOwnDC)) {
989         cname = QLatin1String("QWidgetOwnDC");
990         style = CS_DBLCLKS;
991 #ifndef Q_WS_WINCE
992         style |= CS_OWNDC;
993 #endif
994         icon  = true;
995     } else if (w && (type == Qt::Tool || type == Qt::ToolTip)) {
996         style = CS_DBLCLKS;
997         if (type == Qt::ToolTip || w->inherits("QTipLabel") || w->inherits("QAlphaWidget")) {
998             if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP
999                 && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based))) {
1000                 style |= CS_DROPSHADOW;
1001             }
1002             cname = QLatin1String("QToolTip");
1003         } else {
1004             cname = QLatin1String("QTool");
1005         }
1006 #ifndef Q_WS_WINCE
1007         style |= CS_SAVEBITS;
1008 #endif
1009         icon = false;
1010     } else if (w && (type == Qt::Popup)) {
1011         cname = QLatin1String("QPopup");
1012         style = CS_DBLCLKS;
1013 #ifndef Q_WS_WINCE
1014         style |= CS_SAVEBITS;
1015 #endif
1016         if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP
1017             && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)))
1018             style |= CS_DROPSHADOW;
1019         icon = false;
1020     } else {
1021         cname = QLatin1String("QWidget");
1022         style = CS_DBLCLKS;
1023         icon  = true;
1024     }
1025 
1026 #ifndef Q_WS_WINCE
1027     // force CS_OWNDC when the GL graphics system is
1028     // used as the default renderer
1029     if (qt_win_owndc_required)
1030         style |= CS_OWNDC;
1031 #endif
1032 
1033 #ifdef Q_OS_WINCE
1034     // We need to register the classes with the
1035     // unique ID on WinCE to make sure we can
1036     // move the windows to the front when starting
1037     // a second instance.
1038     wchar_t uniqueAppID[MAX_PATH];
1039     GetModuleFileName(0, uniqueAppID, MAX_PATH);
1040     cname = QString::number(RegisterWindowMessage(
1041               (const wchar_t *) QString::fromWCharArray(uniqueAppID).toLower().replace(QLatin1Char('\\'),
1042               QLatin1Char('_')).utf16()));
1043 #endif
1044 
1045     // since multiple Qt versions can be used in one process
1046     // each one has to have window class names with a unique name
1047     // The first instance gets the unmodified name; if the class
1048     // has already been registered by another instance of Qt then
1049     // add an instance-specific ID, the address of the window proc.
1050     static int classExists = -1;
1051 
1052     if (classExists == -1) {
1053         WNDCLASS wcinfo;
1054         classExists = GetClassInfo((HINSTANCE)qWinAppInst(), (wchar_t*)cname.utf16(), &wcinfo);
1055         classExists = classExists && wcinfo.lpfnWndProc != QtWndProc;
1056     }
1057 
1058     if (classExists)
1059         cname += QString::number((quintptr)QtWndProc);
1060 
1061     if (winclassNames()->contains(cname))        // already registered in our list
1062         return cname;
1063 
1064 #ifndef Q_WS_WINCE
1065     WNDCLASSEX wc;
1066     wc.cbSize       = sizeof(WNDCLASSEX);
1067 #else
1068     WNDCLASS wc;
1069 #endif
1070     wc.style        = style;
1071     wc.lpfnWndProc  = (WNDPROC)QtWndProc;
1072     wc.cbClsExtra   = 0;
1073     wc.cbWndExtra   = 0;
1074     wc.hInstance    = qWinAppInst();
1075     if (icon) {
1076         wc.hIcon = (HICON)LoadImage(qWinAppInst(), L"IDI_ICON1", IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
1077 #ifndef Q_WS_WINCE
1078         if (wc.hIcon) {
1079             int sw = GetSystemMetrics(SM_CXSMICON);
1080             int sh = GetSystemMetrics(SM_CYSMICON);
1081             wc.hIconSm = (HICON)LoadImage(qWinAppInst(), L"IDI_ICON1", IMAGE_ICON, sw, sh, 0);
1082         } else {
1083             wc.hIcon = (HICON)LoadImage(0, IDI_APPLICATION, IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_SHARED);
1084             wc.hIconSm = 0;
1085         }
1086 #endif
1087     } else {
1088         wc.hIcon    = 0;
1089 #ifndef Q_WS_WINCE
1090         wc.hIconSm  = 0;
1091 #endif
1092     }
1093     wc.hCursor      = 0;
1094 #ifndef Q_WS_WINCE
1095     HBRUSH brush = 0;
1096     if (w && !qt_widget_private(w)->isGLWidget)
1097         brush = (HBRUSH)GetSysColorBrush(COLOR_WINDOW);
1098     wc.hbrBackground = brush;
1099 #else
1100     wc.hbrBackground = 0;
1101 #endif
1102     wc.lpszMenuName  = 0;
1103     wc.lpszClassName = (wchar_t*)cname.utf16();
1104 
1105 #ifndef Q_WS_WINCE
1106     ATOM atom = RegisterClassEx(&wc);
1107 #else
1108     ATOM atom = RegisterClass(&wc);
1109 #endif
1110 
1111 #ifndef QT_NO_DEBUG
1112     if (!atom)
1113         qErrnoWarning("QApplication::regClass: Registering window class failed.");
1114 #else
1115     Q_UNUSED(atom);
1116 #endif
1117 
1118     winclassNames()->insert(cname, 1);
1119     return cname;
1120 }
1121 
qt_getRegisteredWndClass()1122 Q_GUI_EXPORT const QString qt_getRegisteredWndClass()
1123 {
1124     return qt_reg_winclass(0);
1125 }
1126 
unregWinClasses()1127 static void unregWinClasses()
1128 {
1129     WinClassNameHash *hash = winclassNames();
1130     QHash<QString, int>::ConstIterator it = hash->constBegin();
1131     while (it != hash->constEnd()) {
1132         UnregisterClass((wchar_t*)it.key().utf16(), qWinAppInst());
1133         ++it;
1134     }
1135     hash->clear();
1136 }
1137 
1138 
1139 /*****************************************************************************
1140   Safe configuration (move,resize,setGeometry) mechanism to avoid
1141   recursion when processing messages.
1142  *****************************************************************************/
1143 
1144 struct QWinConfigRequest {
1145     WId         id;                                        // widget to be configured
1146     int         req;                                        // 0=move, 1=resize, 2=setGeo
1147     int         x, y, w, h;                                // request parameters
1148 };
1149 
1150 static QList<QWinConfigRequest*> *configRequests = 0;
1151 
qWinRequestConfig(WId id,int req,int x,int y,int w,int h)1152 void qWinRequestConfig(WId id, int req, int x, int y, int w, int h)
1153 {
1154     if (!configRequests)                        // create queue
1155         configRequests = new QList<QWinConfigRequest*>;
1156     QWinConfigRequest *r = new QWinConfigRequest;
1157     r->id = id;                                        // create new request
1158     r->req = req;
1159     r->x = x;
1160     r->y = y;
1161     r->w = w;
1162     r->h = h;
1163     configRequests->append(r);                // store request in queue
1164 }
1165 
qWinProcessConfigRequests()1166 static void qWinProcessConfigRequests()                // perform requests in queue
1167 {
1168     if (!configRequests)
1169         return;
1170     QWinConfigRequest *r;
1171     for (;;) {
1172         if (configRequests->isEmpty())
1173             break;
1174         r = configRequests->takeLast();
1175         QWidget *w = QWidget::find(r->id);
1176         QRect rect(r->x, r->y, r->w, r->h);
1177         int req = r->req;
1178         delete r;
1179 
1180         if ( w ) {                              // widget exists
1181             if (w->testAttribute(Qt::WA_WState_ConfigPending))
1182                 return;                         // biting our tail
1183             if (req == 0)
1184                 w->move(rect.topLeft());
1185             else if (req == 1)
1186                 w->resize(rect.size());
1187             else
1188                 w->setGeometry(rect);
1189         }
1190     }
1191     delete configRequests;
1192     configRequests = 0;
1193 }
1194 
1195 
1196 /*****************************************************************************
1197     GUI event dispatcher
1198  *****************************************************************************/
1199 
1200 class QGuiEventDispatcherWin32 : public QEventDispatcherWin32
1201 {
1202     Q_DECLARE_PRIVATE(QEventDispatcherWin32)
1203 public:
1204     QGuiEventDispatcherWin32(QObject *parent = 0);
1205     bool processEvents(QEventLoop::ProcessEventsFlags flags);
1206 };
1207 
QGuiEventDispatcherWin32(QObject * parent)1208 QGuiEventDispatcherWin32::QGuiEventDispatcherWin32(QObject *parent)
1209     : QEventDispatcherWin32(parent)
1210 {
1211     createInternalHwnd();
1212 }
1213 
processEvents(QEventLoop::ProcessEventsFlags flags)1214 bool QGuiEventDispatcherWin32::processEvents(QEventLoop::ProcessEventsFlags flags)
1215 {
1216     if (!QEventDispatcherWin32::processEvents(flags))
1217         return false;
1218 
1219     if (configRequests)                        // any pending configs?
1220         qWinProcessConfigRequests();
1221 
1222     return true;
1223 }
1224 
createEventDispatcher()1225 void QApplicationPrivate::createEventDispatcher()
1226 {
1227     Q_Q(QApplication);
1228     if (q->type() != QApplication::Tty)
1229         eventDispatcher = new QGuiEventDispatcherWin32(q);
1230     else
1231         eventDispatcher = new QEventDispatcherWin32(q);
1232 }
1233 
1234 /*****************************************************************************
1235   Platform specific QApplication members
1236  *****************************************************************************/
1237 
1238 #ifdef QT3_SUPPORT
setMainWidget(QWidget * mainWidget)1239 void QApplication::setMainWidget(QWidget *mainWidget)
1240 {
1241     QApplicationPrivate::main_widget = mainWidget;
1242     if (QApplicationPrivate::main_widget && windowIcon().isNull()
1243         && QApplicationPrivate::main_widget->testAttribute(Qt::WA_SetWindowIcon))
1244         setWindowIcon(QApplicationPrivate::main_widget->windowIcon());
1245 }
1246 #endif
1247 
1248 #ifndef QT_NO_CURSOR
1249 
1250 /*****************************************************************************
1251   QApplication cursor stack
1252  *****************************************************************************/
1253 
setOverrideCursor(const QCursor & cursor)1254 void QApplication::setOverrideCursor(const QCursor &cursor)
1255 {
1256     qApp->d_func()->cursor_list.prepend(cursor);
1257     SetCursor(qApp->d_func()->cursor_list.first().handle());
1258 }
1259 
restoreOverrideCursor()1260 void QApplication::restoreOverrideCursor()
1261 {
1262     if (qApp->d_func()->cursor_list.isEmpty())
1263         return;
1264     qApp->d_func()->cursor_list.removeFirst();
1265 
1266     if (!qApp->d_func()->cursor_list.isEmpty()) {
1267         SetCursor(qApp->d_func()->cursor_list.first().handle());
1268     } else {
1269         QWidget *w = QWidget::find(curWin);
1270         if (w)
1271             SetCursor(w->cursor().handle());
1272         else
1273             SetCursor(QCursor(Qt::ArrowCursor).handle());
1274     }
1275 }
1276 
1277 #endif
1278 
1279 /*
1280   Internal function called from QWidget::setCursor()
1281    force is true if this function is called from dispatchEnterLeave, it means that the
1282    mouse is actually directly under this widget.
1283 */
1284 
1285 #ifndef QT_NO_CURSOR
qt_win_set_cursor(QWidget * w,bool force)1286 void qt_win_set_cursor(QWidget *w, bool force)
1287 {
1288     static QPointer<QWidget> lastUnderMouse = 0;
1289     if (force) {
1290         lastUnderMouse = w;
1291     } else if (w->testAttribute(Qt::WA_WState_Created) && lastUnderMouse
1292                && lastUnderMouse->effectiveWinId() == w->effectiveWinId()) {
1293         w = lastUnderMouse;
1294     }
1295 
1296     if (!curWin && w && w->internalWinId())
1297         return;
1298     QWidget* cW = w && !w->internalWinId() ? w : QWidget::find(curWin);
1299     if (!cW || cW->window() != w->window() ||
1300          !cW->isVisible() || !cW->underMouse() || QApplication::overrideCursor())
1301         return;
1302 
1303     SetCursor(cW->cursor().handle());
1304 }
1305 #endif // QT_NO_CURSOR
1306 
qt_win_getKeyboardModifiers()1307 Qt::KeyboardModifiers qt_win_getKeyboardModifiers()
1308 {
1309     Qt::KeyboardModifiers modifiers = Qt::NoModifier;
1310     if (GetKeyState(VK_SHIFT) < 0)
1311         modifiers |= Qt::ShiftModifier;
1312     if (GetKeyState(VK_CONTROL) < 0)
1313         modifiers |= Qt::ControlModifier;
1314     if (GetKeyState(VK_MENU) < 0)
1315         modifiers |= Qt::AltModifier;
1316     return modifiers;
1317 }
1318 
queryKeyboardModifiers()1319 Qt::KeyboardModifiers QApplication::queryKeyboardModifiers()
1320 {
1321     return qt_win_getKeyboardModifiers();
1322 }
1323 
1324 /*****************************************************************************
1325   Routines to find a Qt widget from a screen position
1326  *****************************************************************************/
1327 
topLevelAt(const QPoint & pos)1328 QWidget *QApplication::topLevelAt(const QPoint &pos)
1329 {
1330     POINT p;
1331     HWND  win;
1332     QWidget *w;
1333     p.x = pos.x();
1334     p.y = pos.y();
1335     win = WindowFromPoint(p);
1336     if (!win)
1337         return 0;
1338 
1339     w = QWidget::find(win);
1340     while (!w && win) {
1341         win = GetParent(win);
1342         w = QWidget::find(win);
1343     }
1344     return w ? w->window() : 0;
1345 }
1346 
beep()1347 void QApplication::beep()
1348 {
1349     MessageBeep(MB_OK);
1350 }
1351 
alert_widget(QWidget * widget,int duration)1352 static void alert_widget(QWidget *widget, int duration)
1353 {
1354 #ifdef Q_OS_WINCE
1355     Q_UNUSED(widget);
1356     Q_UNUSED(duration);
1357 #else
1358     bool stopFlash = duration < 0;
1359 
1360     if (widget && (!widget->isActiveWindow() || stopFlash)) {
1361         DWORD timeOut = GetCaretBlinkTime();
1362         if (timeOut <= 0)
1363             timeOut = 250;
1364 
1365         UINT flashCount;
1366         if (duration == 0)
1367             flashCount = 10;
1368         else
1369             flashCount = duration/timeOut;
1370 
1371         FLASHWINFO info;
1372         info.cbSize = sizeof(info);
1373         info.hwnd = widget->window()->winId();
1374         info.dwFlags = stopFlash ? FLASHW_STOP : FLASHW_TRAY;
1375         info.dwTimeout = stopFlash ? 0 : timeOut;
1376         info.uCount = stopFlash ? 0 : flashCount;
1377 
1378         FlashWindowEx(&info);
1379     }
1380 #endif
1381 }
1382 
alert(QWidget * widget,int duration)1383 void QApplication::alert(QWidget *widget, int duration)
1384 {
1385     if (!QApplicationPrivate::checkInstance("alert"))
1386         return;
1387 
1388     if (widget) {
1389         alert_widget(widget, duration);
1390     } else {
1391         const QWidgetList toplevels(topLevelWidgets());
1392         for (int i = 0; i < toplevels.count(); ++i) {
1393             QWidget *topLevel = toplevels.at(i);
1394             alert_widget(topLevel, duration);
1395         }
1396     }
1397 }
1398 
appName() const1399 QString QApplicationPrivate::appName() const
1400 {
1401     return QCoreApplicationPrivate::appName();
1402 }
1403 
1404 
1405 /*****************************************************************************
1406   Main event loop
1407  *****************************************************************************/
1408 
1409 extern uint qGlobalPostedEventsCount();
1410 
winFocus(QWidget * widget,bool gotFocus)1411 void QApplication::winFocus(QWidget *widget, bool gotFocus)
1412 {
1413     if (d_func()->inPopupMode()) // some delayed focus event to ignore
1414         return;
1415     if (gotFocus) {
1416         setActiveWindow(widget);
1417         if (QApplicationPrivate::active_window
1418             && (QApplicationPrivate::active_window->windowType() == Qt::Dialog)) {
1419             // raise the entire application, not just the dialog
1420             QWidget* mw = QApplicationPrivate::active_window;
1421 #ifndef Q_WS_WINCE
1422             while(mw->parentWidget() && (mw->windowType() == Qt::Dialog))
1423                 mw = mw->parentWidget()->window();
1424             if (mw->testAttribute(Qt::WA_WState_Created) && mw != QApplicationPrivate::active_window)
1425                 SetWindowPos(mw->internalWinId(), HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
1426 #else
1427             // On Desktop Windows, we set the first parent of the dialog on top
1428             // Child windows will be automatically set above again.
1429             // On Windows CE we pass no parent in CreateWindowEx as otherwise
1430             // dialogs get embedded into the parent window. Thus we need to
1431             // manually iterate and reactivate all windows from bottom up.
1432             QList<QWidget*> raiseList;
1433             raiseList.push_back(mw);
1434             while(mw->parentWidget() && (mw->windowType() == Qt::Dialog)) {
1435                 mw = mw->parentWidget()->window();
1436                 raiseList.push_back(mw);
1437             }
1438             while(!raiseList.isEmpty()) {
1439                 mw = raiseList.takeLast();
1440                 if (mw->testAttribute(Qt::WA_WState_Created)) {
1441                     HWND state = HWND_TOP;
1442                     if (mw->windowFlags() & Qt::WindowStaysOnBottomHint)
1443                         state = HWND_BOTTOM;
1444                     else if (mw->windowFlags() & Qt::WindowStaysOnTopHint)
1445                         state = HWND_TOPMOST;
1446                     SetWindowPos(mw->internalWinId(), state, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
1447                 }
1448             }
1449 #endif
1450         }
1451     } else {
1452         setActiveWindow(0);
1453     }
1454 }
1455 
1456 
1457 //
1458 // QtWndProc() receives all messages from the main event loop
1459 //
1460 
1461 static bool inLoop = false;
1462 static int inputcharset = CP_ACP;
1463 
1464 #define RETURN(x) { inLoop=false;return x; }
1465 
qt_is_translatable_mouse_event(UINT message)1466 static bool qt_is_translatable_mouse_event(UINT message)
1467 {
1468     return (((message >= WM_MOUSEFIRST && message <= WM_MOUSELAST) ||
1469                 (message >= WM_XBUTTONDOWN && message <= WM_XBUTTONDBLCLK))
1470             && message != WM_MOUSEWHEEL
1471             && message != WM_MOUSEHWHEEL)
1472 
1473 #ifndef Q_WS_WINCE
1474             || (message >= WM_NCMOUSEMOVE && message <= WM_NCMBUTTONDBLCLK)
1475 #endif
1476             ;
1477 }
1478 
QtWndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam)1479 extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
1480 {
1481     bool result = true;
1482     QEvent::Type evt_type = QEvent::None;
1483     QETWidget *widget = 0;
1484 
1485         // there is no need to process pakcets from tablet unless
1486         // it is actually on the tablet, a flag to let us know...
1487         int nPackets;        // the number of packets we get from the queue
1488 
1489     long res = 0;
1490     if (!qApp)                                // unstable app state
1491 #ifndef QT_NO_IM
1492         RETURN(QWinInputContext::DefWindowProc(hwnd,message,wParam,lParam))
1493 #else
1494         return res;
1495 #endif // QT_NO_IM
1496     QScopedLoopLevelCounter loopLevelCounter(QThreadData::get2(qApp->thread()));
1497 
1498 #if 0
1499     // make sure we update widgets also when the user resizes
1500     if (inLoop && qApp->loopLevel())
1501         qApp->sendPostedEvents(0, QEvent::Paint);
1502 #endif
1503 
1504     inLoop = true;
1505 
1506     MSG msg;
1507     msg.hwnd = hwnd;                                // create MSG structure
1508     msg.message = message;                        // time and pt fields ignored
1509     msg.wParam = wParam;
1510     msg.lParam = lParam;
1511     msg.pt.x = GET_X_LPARAM(lParam);
1512     msg.pt.y = GET_Y_LPARAM(lParam);
1513     // If it's a non-client-area message the coords are screen coords, otherwise they are
1514     // client coords.
1515 #ifndef Q_WS_WINCE
1516     if (message < WM_NCMOUSEMOVE || message > WM_NCMBUTTONDBLCLK)
1517 #endif
1518         ClientToScreen(msg.hwnd, &msg.pt);
1519 
1520     /*
1521     // sometimes the autograb is not released, so the clickevent is sent
1522     // to the wrong window. We ignore this for now, because it doesn't
1523     // cause any problems.
1524     if (msg.message == WM_LBUTTONDOWN || msg.message == WM_RBUTTONDOWN || msg.message == WM_MBUTTONDOWN) {
1525         HWND handle = WindowFromPoint(msg.pt);
1526         if (msg.hwnd != handle) {
1527             msg.hwnd = handle;
1528             hwnd = handle;
1529         }
1530     }
1531     */
1532 
1533 #if defined(QT_NON_COMMERCIAL)
1534     QT_NC_WNDPROC
1535 #endif
1536 
1537     // send through app filter
1538     if (qApp->filterEvent(&msg, &res))
1539         return res;
1540 
1541     // close any opened ime candidate window (enabled only on a popup widget)
1542     if (imeParentWnd  && QApplication::activePopupWidget()
1543         && (message == WM_MBUTTONDOWN || message == WM_XBUTTONDOWN
1544         || message == WM_LBUTTONDOWN || message == WM_RBUTTONDOWN
1545 #ifndef Q_WS_WINCE
1546         || message == WM_NCMBUTTONDOWN || message == WM_NCLBUTTONDOWN
1547         || message == WM_NCRBUTTONDOWN)) {
1548 #else
1549                                       )) {
1550 #endif
1551             ::SendMessage(imeParentWnd, WM_IME_ENDCOMPOSITION, 0, 0);
1552     }
1553 
1554     switch (message) {
1555 #ifndef Q_WS_WINCE
1556 #ifndef QT_NO_SESSIONMANAGER
1557     case WM_QUERYENDSESSION: {
1558         if (sm_smActive) // bogus message from windows
1559             RETURN(true);
1560 
1561         sm_smActive = true;
1562         sm_blockUserInput = true; // prevent user-interaction outside interaction windows
1563         sm_cancel = false;
1564         if (qt_session_manager_self)
1565             qApp->commitData(*qt_session_manager_self);
1566         if (lParam & ENDSESSION_LOGOFF) {
1567             _flushall();
1568         }
1569         RETURN(!sm_cancel);
1570     }
1571     case WM_ENDSESSION: {
1572         sm_smActive = false;
1573         sm_blockUserInput = false;
1574         bool endsession = (bool) wParam;
1575 
1576         // we receive the message for each toplevel window included internal hidden ones,
1577         // but the aboutToQuit signal should be emitted only once.
1578         QApplicationPrivate *qAppPriv = QApplicationPrivate::instance();
1579         if (endsession && !qAppPriv->aboutToQuitEmitted) {
1580             qAppPriv->aboutToQuitEmitted = true;
1581             int index = QApplication::staticMetaObject.indexOfSignal("aboutToQuit()");
1582             qApp->qt_metacall(QMetaObject::InvokeMetaMethod, index,0);
1583             // since the process will be killed immediately quit() has no real effect
1584             QApplication::quit();
1585         }
1586 
1587         RETURN(0);
1588     }
1589 #endif
1590     case WM_DISPLAYCHANGE:
1591         if (QApplication::type() == QApplication::Tty)
1592             break;
1593         if (qt_desktopWidget) {
1594             qt_desktopWidget->move(GetSystemMetrics(76), GetSystemMetrics(77));
1595             QSize sz(GetSystemMetrics(78), GetSystemMetrics(79));
1596             if (sz == qt_desktopWidget->size()) {
1597                  // a screen resized without changing size of the virtual desktop
1598                 QResizeEvent rs(sz, qt_desktopWidget->size());
1599                 QApplication::sendEvent(qt_desktopWidget, &rs);
1600             } else {
1601                 qt_desktopWidget->resize(sz);
1602             }
1603         }
1604         break;
1605 #endif
1606 
1607     case WM_SETTINGCHANGE:
1608 #ifdef Q_WS_WINCE
1609         // CE SIP hide/show
1610         if (qt_desktopWidget && wParam == SPI_SETSIPINFO) {
1611             QResizeEvent re(QSize(0, 0), QSize(0, 0)); // Calculated by QDesktopWidget
1612             QApplication::sendEvent(qt_desktopWidget, &re);
1613             break;
1614         }
1615 #endif
1616         // ignore spurious XP message when user logs in again after locking
1617         if (QApplication::type() == QApplication::Tty)
1618             break;
1619         if (QApplication::desktopSettingsAware() && wParam != SPI_SETWORKAREA) {
1620             widget = (QETWidget*)QWidget::find(hwnd);
1621             if (widget) {
1622                 if (wParam == SPI_SETNONCLIENTMETRICS)
1623                     widget->markFrameStrutDirty();
1624             }
1625         }
1626         else if (qt_desktopWidget && wParam == SPI_SETWORKAREA) {
1627             qt_desktopWidget->move(GetSystemMetrics(76), GetSystemMetrics(77));
1628             QSize sz(GetSystemMetrics(78), GetSystemMetrics(79));
1629             if (sz == qt_desktopWidget->size()) {
1630                  // a screen resized without changing size of the virtual desktop
1631                 QResizeEvent rs(sz, qt_desktopWidget->size());
1632                 QApplication::sendEvent(qt_desktopWidget, &rs);
1633             } else {
1634                 qt_desktopWidget->resize(sz);
1635             }
1636         }
1637 
1638         if (wParam == SPI_SETFONTSMOOTHINGTYPE) {
1639             qt_win_read_cleartype_settings();
1640             foreach (QWidget *w, QApplication::topLevelWidgets()) {
1641                 if (!w->isVisible())
1642                     continue;
1643                 ((QETWidget *) w)->forceUpdate();
1644             }
1645         }
1646 
1647         break;
1648     case WM_SYSCOLORCHANGE:
1649         if (QApplication::type() == QApplication::Tty)
1650             break;
1651         if (QApplication::desktopSettingsAware()) {
1652             widget = (QETWidget*)QWidget::find(hwnd);
1653             if (widget && !widget->parentWidget())
1654                 qt_set_windows_color_resources();
1655         }
1656         break;
1657 
1658     case WM_LBUTTONDOWN:
1659     case WM_MBUTTONDOWN:
1660     case WM_RBUTTONDOWN:
1661     case WM_XBUTTONDOWN:
1662     case WM_LBUTTONDBLCLK:
1663     case WM_RBUTTONDBLCLK:
1664     case WM_MBUTTONDBLCLK:
1665     case WM_XBUTTONDBLCLK:
1666         if (qt_win_ignoreNextMouseReleaseEvent)
1667             qt_win_ignoreNextMouseReleaseEvent = false;
1668         break;
1669 
1670     case WM_LBUTTONUP:
1671     case WM_MBUTTONUP:
1672     case WM_RBUTTONUP:
1673     case WM_XBUTTONUP:
1674         if (qt_win_ignoreNextMouseReleaseEvent) {
1675             qt_win_ignoreNextMouseReleaseEvent = false;
1676             if (qt_button_down && qt_button_down->internalWinId() == autoCaptureWnd) {
1677                 releaseAutoCapture();
1678                 qt_button_down = 0;
1679             }
1680 
1681             RETURN(0);
1682         }
1683         break;
1684 
1685     default:
1686         break;
1687     }
1688 
1689     if (!widget)
1690         widget = (QETWidget*)QWidget::find(hwnd);
1691     if (!widget)                                // don't know this widget
1692         goto do_default;
1693 
1694     if (app_do_modal)        {                        // modal event handling
1695         int ret = 0;
1696         if (!qt_try_modal(widget, &msg, ret))
1697             RETURN(ret);
1698     }
1699 
1700     res = 0;
1701     if (widget->winEvent(&msg, &res))                // send through widget filter
1702         RETURN(res);
1703 
1704     if (qt_is_translatable_mouse_event(message)) {
1705         if (QApplication::activePopupWidget() != 0) { // in popup mode
1706             POINT curPos = msg.pt;
1707             QWidget* w = QApplication::widgetAt(curPos.x, curPos.y);
1708             if (w)
1709                 widget = (QETWidget*)w;
1710         }
1711 
1712         if (!qt_tabletChokeMouse) {
1713             result = widget->translateMouseEvent(msg);        // mouse event
1714 #if defined(Q_WS_WINCE) && !defined(QT_NO_CONTEXTMENU)
1715             if (message == WM_LBUTTONDOWN && widget != QApplication::activePopupWidget()) {
1716                 QWidget* alienWidget = widget;
1717                 if ((alienWidget != QApplication::activePopupWidget()) && (alienWidget->contextMenuPolicy() != Qt::PreventContextMenu)) {
1718                     QPoint pos(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
1719                     QPoint globalPos(msg.pt.x, msg.pt.y);
1720                     // In case we are using Alien, then the widget to
1721                     // send the context menu event is a different one
1722                     if (!alienWidget->testAttribute(Qt::WA_NativeWindow) && !alienWidget->testAttribute(Qt::WA_PaintOnScreen)) {
1723                         alienWidget = QApplication::widgetAt(globalPos);
1724                         if (alienWidget)
1725                             pos = alienWidget->mapFromGlobal(globalPos);
1726                     }
1727                     if (alienWidget) {
1728                         SHRGINFO shrg;
1729                         shrg.cbSize = sizeof(shrg);
1730                         shrg.hwndClient = hwnd;
1731                         shrg.ptDown.x = GET_X_LPARAM(lParam);
1732                         shrg.ptDown.y = GET_Y_LPARAM(lParam);
1733                         shrg.dwFlags = SHRG_RETURNCMD | SHRG_NOANIMATION;
1734 #ifndef QT_NO_GESTURES
1735                         resolveAygLibs();
1736                         if (ptrRecognizeGesture && (ptrRecognizeGesture(&shrg) == GN_CONTEXTMENU)) {
1737                             if (QApplication::activePopupWidget())
1738                                 QApplication::activePopupWidget()->close();
1739                             QContextMenuEvent e(QContextMenuEvent::Mouse, pos, globalPos);
1740                             result = qt_sendSpontaneousEvent(alienWidget, &e);
1741                         }
1742 #endif // QT_NO_GESTURES
1743                     }
1744                 }
1745             }
1746 #endif
1747         } else {
1748             // Sometimes we only get a WM_MOUSEMOVE message
1749             // and sometimes we get both a WM_MOUSEMOVE and
1750             // a WM_LBUTTONDOWN/UP, this creates a spurious mouse
1751             // press/release event, using the PeekMessage
1752             // will help us fix this.  This leaves us with a
1753             // question:
1754             //    This effectively kills using the mouse AND the
1755             //    tablet simultaneously, well creates wacky input.
1756             //    Is this going to be a problem? (probably not)
1757             bool next_is_button = false;
1758             bool is_mouse_move = (message == WM_MOUSEMOVE);
1759             if (is_mouse_move) {
1760                 MSG msg1;
1761                 if (PeekMessage(&msg1, msg.hwnd, WM_MOUSEFIRST,
1762                                 WM_MOUSELAST, PM_NOREMOVE))
1763                     next_is_button = (msg1.message == WM_LBUTTONUP
1764                                        || msg1.message == WM_LBUTTONDOWN);
1765             }
1766             if (!is_mouse_move || (is_mouse_move && !next_is_button))
1767                 qt_tabletChokeMouse = false;
1768         }
1769     } else {
1770         switch (message) {
1771         case WM_TOUCH:
1772             result = QApplicationPrivate::instance()->translateTouchEvent(msg);
1773             break;
1774         case WM_KEYDOWN:                        // keyboard event
1775         case WM_SYSKEYDOWN:
1776             qt_keymapper_private()->updateKeyMap(msg);
1777             // fall-through intended
1778         case WM_KEYUP:
1779         case WM_SYSKEYUP:
1780 #if Q_OS_WINCE_WM
1781         case WM_HOTKEY:
1782             if(HIWORD(msg.lParam) == VK_TBACK) {
1783                 const bool hotKeyDown = !(LOWORD(msg.lParam) & MOD_KEYUP);
1784                 msg.lParam = 0x69 << 16;
1785                 msg.wParam = VK_BACK;
1786                 if (hotKeyDown) {
1787                     msg.message = WM_KEYDOWN;
1788                     qt_keymapper_private()->updateKeyMap(msg);
1789                 } else {
1790                     msg.message = WM_KEYUP;
1791                 }
1792             }
1793             // fall-through intended
1794 #endif
1795         case WM_IME_CHAR:
1796         case WM_IME_KEYDOWN:
1797         case WM_CHAR: {
1798             MSG msg1;
1799             bool anyMsg = PeekMessage(&msg1, msg.hwnd, 0, 0, PM_NOREMOVE);
1800             if (anyMsg && msg1.message == WM_DEADCHAR) {
1801                 result = true; // consume event since there is a dead char next
1802                 break;
1803             }
1804             QWidget *g = QWidget::keyboardGrabber();
1805             if (g && qt_get_tablet_widget() && hwnd == qt_get_tablet_widget()->winId()) {
1806                 // if we get an event for the internal tablet widget,
1807                 // then don't send it to the keyboard grabber, but
1808                 // send it to the widget itself (we don't use it right
1809                 // now, just in case).
1810                 g = 0;
1811             }
1812             if (g)
1813                 widget = (QETWidget*)g;
1814             else if (QApplication::activePopupWidget())
1815                 widget = (QETWidget*)QApplication::activePopupWidget()->focusWidget()
1816                        ? (QETWidget*)QApplication::activePopupWidget()->focusWidget()
1817                        : (QETWidget*)QApplication::activePopupWidget();
1818             else if (QApplication::focusWidget())
1819                 widget = (QETWidget*)QApplication::focusWidget();
1820             else if (!widget || widget->internalWinId() == GetFocus()) // We faked the message to go to exactly that widget.
1821                 widget = (QETWidget*)widget->window();
1822             if (widget->isEnabled())
1823                 result = sm_blockUserInput
1824                             ? true
1825                             : qt_keymapper_private()->translateKeyEvent(widget, msg, g != 0);
1826             break;
1827         }
1828         case WM_SYSCHAR:
1829             result = true;                        // consume event
1830             break;
1831 
1832         case WM_MOUSEWHEEL:
1833         case WM_MOUSEHWHEEL:
1834             result = widget->translateWheelEvent(msg);
1835             break;
1836 
1837         case WM_APPCOMMAND:
1838             {
1839                 uint cmd = GET_APPCOMMAND_LPARAM(lParam);
1840                 uint uDevice = GET_DEVICE_LPARAM(lParam);
1841                 uint dwKeys = GET_KEYSTATE_LPARAM(lParam);
1842 
1843                 int state = translateButtonState(dwKeys, QEvent::KeyPress, 0);
1844 
1845                 switch (uDevice) {
1846                 case FAPPCOMMAND_KEY:
1847                     {
1848                         int key = 0;
1849 
1850                         switch(cmd) {
1851                         case APPCOMMAND_BASS_BOOST:
1852                             key = Qt::Key_BassBoost;
1853                             break;
1854                         case APPCOMMAND_BASS_DOWN:
1855                             key = Qt::Key_BassDown;
1856                             break;
1857                         case APPCOMMAND_BASS_UP:
1858                             key = Qt::Key_BassUp;
1859                             break;
1860                         case APPCOMMAND_TREBLE_DOWN:
1861                             key = Qt::Key_TrebleDown;
1862                             break;
1863                         case APPCOMMAND_TREBLE_UP:
1864                             key = Qt::Key_TrebleUp;
1865                             break;
1866                         case APPCOMMAND_HELP:
1867                             key = Qt::Key_Help;
1868                             break;
1869                         case APPCOMMAND_FIND:
1870                             key = Qt::Key_Search;
1871                             break;
1872                         default:
1873                             break;
1874                         }
1875                         if (key) {
1876                             bool res = false;
1877                             QWidget *g = QWidget::keyboardGrabber();
1878                             if (g)
1879                                 widget = (QETWidget*)g;
1880                             else if (QApplication::focusWidget())
1881                                 widget = (QETWidget*)QApplication::focusWidget();
1882                             else
1883                                 widget = (QETWidget*)widget->window();
1884                             if (widget->isEnabled()) {
1885                                 res = QKeyMapper::sendKeyEvent(widget, g != 0, QEvent::KeyPress, key,
1886                                                                Qt::KeyboardModifier(state),
1887                                                                QString(), false, 0, 0, 0, 0);
1888                             }
1889                             if (res)
1890                                 return true;
1891                         }
1892                     }
1893                     break;
1894 
1895                 default:
1896                     break;
1897                 }
1898 
1899                 result = false;
1900             }
1901             break;
1902 
1903 #ifndef Q_WS_WINCE
1904         case WM_NCHITTEST:
1905             if (widget->isWindow()) {
1906                 QPoint pos = widget->mapFromGlobal(QPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
1907                 // don't show resize-cursors for fixed-size widgets
1908                 QRect fs = widget->frameStrut();
1909                 if (!widget->isMinimized()) {
1910                     if (widget->minimumHeight() == widget->maximumHeight()) {
1911                         if (pos.y() < -(fs.top() - fs.left()))
1912                             return HTCAPTION;
1913                         if (pos.y() >= widget->height())
1914                             return HTBORDER;
1915                     }
1916                     if (widget->minimumWidth() == widget->maximumWidth() && (pos.x() < 0 || pos.x() >= widget->width()))
1917                         return HTBORDER;
1918                 }
1919             }
1920 
1921             result = false;
1922             break;
1923 #endif
1924 
1925         case WM_SYSCOMMAND: {
1926 #ifndef Q_WS_WINCE
1927             bool window_state_change = false;
1928             Qt::WindowStates oldstate = Qt::WindowStates(widget->dataPtr()->window_state);
1929             // MSDN:In WM_SYSCOMMAND messages, the four low-order bits of the wParam parameter are
1930             // used internally by the system. To obtain the correct result when testing the value of
1931             // wParam, an application must combine the value 0xFFF0 with the wParam value by using
1932             // the bitwise AND operator.
1933             switch(0xfff0 & wParam) {
1934             case SC_CONTEXTHELP:
1935 #ifndef QT_NO_WHATSTHIS
1936                 QWhatsThis::enterWhatsThisMode();
1937 #endif
1938                 DefWindowProc(hwnd, WM_NCPAINT, 1, 0);
1939                 break;
1940 #if defined(QT_NON_COMMERCIAL)
1941                 QT_NC_SYSCOMMAND
1942 #endif
1943             case SC_MINIMIZE:
1944                 window_state_change = true;
1945                 widget->dataPtr()->window_state |= Qt::WindowMinimized;
1946                 if (widget->isVisible()) {
1947                     QHideEvent e;
1948                     qt_sendSpontaneousEvent(widget, &e);
1949                     widget->hideChildren(true);
1950                     const QString title = widget->windowIconText();
1951                     if (!title.isEmpty())
1952                         widget->setWindowTitle_helper(title);
1953                 }
1954                 result = false;
1955                 break;
1956             case SC_MAXIMIZE:
1957                 if(widget->isWindow())
1958                     widget->topData()->normalGeometry = widget->geometry();
1959             case SC_RESTORE:
1960                 window_state_change = true;
1961                 if ((0xfff0 & wParam) == SC_MAXIMIZE)
1962                     widget->dataPtr()->window_state |= Qt::WindowMaximized;
1963                 else if (!widget->isMinimized())
1964                     widget->dataPtr()->window_state &= ~Qt::WindowMaximized;
1965 
1966                 if (widget->isMinimized()) {
1967                     widget->dataPtr()->window_state &= ~Qt::WindowMinimized;
1968                     widget->showChildren(true);
1969                     QShowEvent e;
1970                     qt_sendSpontaneousEvent(widget, &e);
1971                     const QString title = widget->windowTitle();
1972                     if (!title.isEmpty())
1973                         widget->setWindowTitle_helper(title);
1974                 }
1975                 result = false;
1976                 break;
1977             default:
1978                 result = false;
1979                 break;
1980             }
1981 
1982             if (window_state_change) {
1983                 QWindowStateChangeEvent e(oldstate);
1984                 qt_sendSpontaneousEvent(widget, &e);
1985             }
1986 #endif // #ifndef Q_OS_WINCE
1987 
1988             break;
1989         }
1990 
1991         case WM_SETTINGCHANGE:
1992             if ( QApplication::type() == QApplication::Tty )
1993                 break;
1994 
1995             if (!msg.wParam) {
1996 #ifdef Q_WS_WINCE
1997                 // On Windows CE, lParam parameter is a constant, not a char pointer.
1998                 if (msg.lParam == INI_INTL) {
1999 #else
2000                 QString area = QString::fromWCharArray((wchar_t*)msg.lParam);
2001                 if (area == QLatin1String("intl")) {
2002 #endif
2003                     QLocalePrivate::updateSystemPrivate();
2004                     if (!widget->testAttribute(Qt::WA_SetLocale))
2005                         widget->dptr()->setLocale_helper(QLocale(), true);
2006                     QEvent e(QEvent::LocaleChange);
2007                     QApplication::sendEvent(qApp, &e);
2008                 }
2009             }
2010             else if (msg.wParam == SPI_SETICONTITLELOGFONT) {
2011                 if (QApplication::desktopSettingsAware()) {
2012                     widget = (QETWidget*)QWidget::find(hwnd);
2013                     if (widget && !widget->parentWidget()) {
2014                         qt_set_windows_font_resources();
2015                     }
2016                 }
2017             }
2018             else if (msg.wParam == SPI_SETNONCLIENTMETRICS) {
2019                 widget = (QETWidget*)QWidget::find(hwnd);
2020                 if (widget && !widget->parentWidget()) {
2021                     qt_set_windows_updateScrollBar(widget);
2022                     QEvent e(QEvent::LayoutRequest);
2023                     QApplication::sendEvent(widget, &e);
2024                 }
2025         }
2026 
2027             break;
2028 
2029         case WM_PAINT:                                // paint event
2030         case WM_ERASEBKGND:                        // erase window background
2031             result = widget->translatePaintEvent(msg);
2032             break;
2033 
2034 #ifndef Q_WS_WINCE
2035         case WM_ENTERSIZEMOVE:
2036             autoCaptureWnd = hwnd;
2037             break;
2038         case WM_EXITSIZEMOVE:
2039             autoCaptureWnd = 0;
2040             break;
2041 #endif
2042         case WM_MOVE:                                // move window
2043         case WM_SIZE:                                // resize window
2044             result = widget->translateConfigEvent(msg);
2045             break;
2046 
2047         case WM_ACTIVATEAPP:
2048             if (wParam == FALSE) {
2049                 QApplication::setActiveWindow(0);
2050                 // Another application was activated while our popups are open,
2051                 // then close all popups.  In case some popup refuses to close,
2052                 // we give up after 1024 attempts (to avoid an infinite loop).
2053                 int maxiter = 1024;
2054                 QWidget *popup;
2055                 while ((popup=QApplication::activePopupWidget()) && maxiter--)
2056                     popup->close();
2057             }
2058             break;
2059 
2060         case WM_ACTIVATE:
2061             if ( QApplication::type() == QApplication::Tty )
2062                 break;
2063 
2064             if (ptrWTOverlap && ptrWTEnable) {
2065                 // cooperate with other tablet applications, but when
2066                 // we get focus, I want to use the tablet...
2067                 if (qt_tablet_context && GET_WM_ACTIVATE_STATE(wParam, lParam)) {
2068                     if (ptrWTEnable(qt_tablet_context, true))
2069                         ptrWTOverlap(qt_tablet_context, true);
2070                 }
2071             }
2072             if (QApplication::activePopupWidget() && LOWORD(wParam) == WA_INACTIVE &&
2073                 QWidget::find((HWND)lParam) == 0) {
2074                 // Another application was activated while our popups are open,
2075                 // then close all popups.  In case some popup refuses to close,
2076                 // we give up after 1024 attempts (to avoid an infinite loop).
2077                 int maxiter = 1024;
2078                 QWidget *popup;
2079                 while ((popup=QApplication::activePopupWidget()) && maxiter--)
2080                     popup->close();
2081             }
2082 
2083             if (LOWORD(wParam) != WA_INACTIVE) {
2084                 // WM_ACTIVATEAPP handles the "true" false case, as this is only when the application
2085                 // loses focus. Doing it here would result in the widget getting focus to not know
2086                 // where it got it from; it would simply get a 0 value as the old focus widget.
2087 #ifdef Q_WS_WINCE
2088                 {
2089 #ifdef Q_WS_WINCE_WM
2090                     // On Windows mobile we do not receive WM_SYSCOMMAND / SC_MINIMIZE messages.
2091                     // Thus we have to unset the minimized state explicitly. We must do this for all
2092                     // top-level widgets, because we get the HWND of a random widget here.
2093                     foreach (QWidget* tlw, QApplication::topLevelWidgets()) {
2094                         if (tlw->isMinimized())
2095                             tlw->setWindowState(tlw->windowState() & ~Qt::WindowMinimized);
2096                     }
2097 #else
2098                     // On Windows CE we do not receive WM_SYSCOMMAND / SC_MINIMIZE messages.
2099                     // Thus we have to unset the minimized state explicitly.
2100                     if (widget->windowState() & Qt::WindowMinimized)
2101                         widget->setWindowState(widget->windowState() & ~Qt::WindowMinimized);
2102 #endif  // Q_WS_WINCE_WM
2103 
2104 #else
2105                 if (!(widget->windowState() & Qt::WindowMinimized)) {
2106 #endif
2107                     // Ignore the activate message send by WindowsXP to a minimized window
2108 #ifdef Q_WS_WINCE_WM
2109                     if  (widget->windowState() & Qt::WindowFullScreen)
2110                         qt_wince_hide_taskbar(widget->winId());
2111 #endif
2112                     qApp->winFocus(widget, true);
2113                     // reset any window alert flashes
2114                     alert_widget(widget, -1);
2115                 }
2116             }
2117 
2118             // Windows tries to activate a modally blocked window.
2119             // This happens when restoring an application after "Show Desktop"
2120             if (app_do_modal && LOWORD(wParam) == WA_ACTIVE) {
2121                 QWidget *top = 0;
2122                 if (!QApplicationPrivate::tryModalHelper(widget, &top) && top && widget != top) {
2123                     if (top->isVisible()) {
2124                         top->activateWindow();
2125                     } else {
2126                         // This is the case when native file dialogs are shown
2127                         QWidget *p = (top->parentWidget() ? top->parentWidget()->window() : 0);
2128                         if (p && p->isVisible())
2129                             p->activateWindow();
2130                     }
2131                 }
2132             }
2133             break;
2134 
2135 #ifndef Q_WS_WINCE
2136             case WM_MOUSEACTIVATE:
2137                 if (widget->window()->windowType() == Qt::Tool) {
2138                     QWidget *w = widget;
2139                     if (!w->window()->focusWidget()) {
2140                         while (w && (w->focusPolicy() & Qt::ClickFocus) == 0) {
2141                             if (w->isWindow()) {
2142                                 QWidget *fw = w;
2143                                 while ((fw = fw->nextInFocusChain()) != w && fw->focusPolicy() == Qt::NoFocus)
2144                                     ;
2145                                 if (fw != w)
2146                                    break;
2147                                 QWidget *pw = w->parentWidget();
2148                                 while (pw) {
2149                                     pw = pw->window();
2150                                     if (pw && pw->isVisible() && pw->focusWidget()) {
2151                                         Q_ASSERT(pw->testAttribute(Qt::WA_WState_Created));
2152                                         SetWindowPos(pw->internalWinId(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
2153                                         break;
2154                                     }
2155                                     pw = pw->parentWidget();
2156                                 }
2157                                 RETURN(MA_NOACTIVATE);
2158                             }
2159                             w = w->parentWidget();
2160                         }
2161                     }
2162                 }
2163                 RETURN(MA_ACTIVATE);
2164                 break;
2165 #endif
2166             case WM_SHOWWINDOW:
2167                 if (lParam == SW_PARENTOPENING) {
2168                     if (widget->testAttribute(Qt::WA_WState_Hidden))
2169                         RETURN(0);
2170                 }
2171                 if (widget->isWindow() && widget->testAttribute(Qt::WA_WState_Visible)
2172                     && !widget->testWindowState(Qt::WindowMinimized)) {
2173                     if (lParam == SW_PARENTOPENING) {
2174                         QShowEvent e;
2175                         qt_sendSpontaneousEvent(widget, &e);
2176                         widget->showChildren(true);
2177                     } else if (lParam == SW_PARENTCLOSING) {
2178                         QHideEvent e;
2179                         qt_sendSpontaneousEvent(widget, &e);
2180                         widget->hideChildren(true);
2181                     }
2182                 }
2183                 if  (!wParam && autoCaptureWnd == widget->internalWinId())
2184                     releaseAutoCapture();
2185                 result = false;
2186                 break;
2187 
2188         case WM_PALETTECHANGED:                        // our window changed palette
2189             if (QColormap::hPal() && (WId)wParam == widget->internalWinId())
2190                 RETURN(0);                        // otherwise: FALL THROUGH!
2191             // FALL THROUGH
2192         case WM_QUERYNEWPALETTE:                // realize own palette
2193             if (QColormap::hPal()) {
2194                 Q_ASSERT(widget->testAttribute(Qt::WA_WState_Created));
2195                 HDC hdc = GetDC(widget->internalWinId());
2196                 HPALETTE hpalOld = SelectPalette(hdc, QColormap::hPal(), FALSE);
2197                 uint n = RealizePalette(hdc);
2198                 if (n)
2199                     InvalidateRect(widget->internalWinId(), 0, TRUE);
2200                 SelectPalette(hdc, hpalOld, TRUE);
2201                 RealizePalette(hdc);
2202                 ReleaseDC(widget->internalWinId(), hdc);
2203                 RETURN(n);
2204             }
2205             break;
2206         case WM_CLOSE:                                // close window
2207             widget->translateCloseEvent(msg);
2208             RETURN(0);                                // always handled
2209 
2210         case WM_DESTROY:                        // destroy window
2211             if (hwnd == curWin) {
2212                 QWidget *enter = QWidget::mouseGrabber();
2213                 if (enter == widget)
2214                     enter = 0;
2215                 QApplicationPrivate::dispatchEnterLeave(enter, widget);
2216                 curWin = enter ? enter->effectiveWinId() : 0;
2217                 qt_last_mouse_receiver = enter;
2218             }
2219             if (widget == popupButtonFocus)
2220                 popupButtonFocus = 0;
2221             result = false;
2222             break;
2223 
2224 #ifndef Q_WS_WINCE
2225         case WM_WINDOWPOSCHANGING:
2226             {
2227                 result = false;
2228                 if (widget->isWindow()) {
2229                     WINDOWPOS *winPos = (WINDOWPOS *)lParam;
2230                     if (widget->layout() && widget->layout()->hasHeightForWidth()
2231                         && !(winPos->flags & (SWP_NOCOPYBITS | SWP_NOSIZE))) {
2232                         QRect fs = widget->frameStrut();
2233                         QRect rect = widget->geometry();
2234                         QRect newRect = QRect(winPos->x + fs.left(),
2235                                               winPos->y + fs.top(),
2236                                               winPos->cx - fs.left() - fs.right(),
2237                                               winPos->cy - fs.top() - fs.bottom());
2238 
2239                         QSize newSize = QLayout::closestAcceptableSize(widget, newRect.size());
2240 
2241                         int dh = newSize.height() - newRect.height();
2242                         int dw = newSize.width() - newRect.width();
2243                         if (!dw && ! dh)
2244                             break; // Size OK
2245 
2246                         if (rect.y() != newRect.y()) {
2247                             newRect.setTop(newRect.top() - dh);
2248                         } else {
2249                             newRect.setBottom(newRect.bottom() + dh);
2250                         }
2251 
2252                         if (rect.x() != newRect.x()) {
2253                             newRect.setLeft(newRect.left() - dw);
2254                         } else {
2255                             newRect.setRight(newRect.right() + dw);
2256                         }
2257 
2258                         winPos->x = newRect.x() - fs.left();
2259                         winPos->y = newRect.y() - fs.top();
2260                         winPos->cx = newRect.width() + fs.left() + fs.right();
2261                         winPos->cy = newRect.height() + fs.top() + fs.bottom();
2262 
2263                         RETURN(0);
2264                     }
2265                     if (widget->windowFlags() & Qt::WindowStaysOnBottomHint) {
2266                         winPos->hwndInsertAfter = HWND_BOTTOM;
2267                     }
2268                 }
2269             }
2270             break;
2271 
2272         case WM_GETMINMAXINFO:
2273             if (widget->xtra()) {
2274                 MINMAXINFO *mmi = (MINMAXINFO *)lParam;
2275                 QWExtra *x = widget->xtra();
2276                 QRect fs = widget->frameStrut();
2277                 if ( x->minw > 0 )
2278                     mmi->ptMinTrackSize.x = x->minw + fs.right() + fs.left();
2279                 if ( x->minh > 0 )
2280                     mmi->ptMinTrackSize.y = x->minh + fs.top() + fs.bottom();
2281                 qint32 maxw = (x->maxw >= x->minw) ? x->maxw : x->minw;
2282                 qint32 maxh = (x->maxh >= x->minh) ? x->maxh : x->minh;
2283                 if ( maxw < QWIDGETSIZE_MAX ) {
2284                     mmi->ptMaxTrackSize.x = maxw + fs.right() + fs.left();
2285                     // windows with title bar have an implicit size limit of 112 pixels
2286                     if (widget->windowFlags() & Qt::WindowTitleHint)
2287                         mmi->ptMaxTrackSize.x = qMax<long>(mmi->ptMaxTrackSize.x, 112);
2288                 }
2289                 if ( maxh < QWIDGETSIZE_MAX )
2290                     mmi->ptMaxTrackSize.y = maxh + fs.top() + fs.bottom();
2291                 RETURN(0);
2292             }
2293             break;
2294 
2295 #ifndef QT_NO_CONTEXTMENU
2296             case WM_CONTEXTMENU:
2297             {
2298                 // it's not VK_APPS or Shift+F10, but a click in the NC area
2299                 if (lParam != (int)0xffffffff) {
2300                     result = false;
2301                     break;
2302                 }
2303 
2304                 QWidget *fw = QWidget::keyboardGrabber();
2305                 if (!fw) {
2306                     if (QApplication::activePopupWidget())
2307                         fw = (QApplication::activePopupWidget()->focusWidget()
2308                                                   ? QApplication::activePopupWidget()->focusWidget()
2309                                                   : QApplication::activePopupWidget());
2310                     else if (QApplication::focusWidget())
2311                         fw = QApplication::focusWidget();
2312                     else if (widget)
2313                         fw = widget->window();
2314                 }
2315                 if (fw && fw->isEnabled()) {
2316                     QPoint pos = fw->inputMethodQuery(Qt::ImMicroFocus).toRect().center();
2317                     QContextMenuEvent e(QContextMenuEvent::Keyboard, pos, fw->mapToGlobal(pos),
2318                                       qt_win_getKeyboardModifiers());
2319                     result = qt_sendSpontaneousEvent(fw, &e);
2320                 }
2321             }
2322             break;
2323 #endif
2324 #endif
2325 
2326 #ifndef QT_NO_IM
2327         case WM_IME_STARTCOMPOSITION:
2328         case WM_IME_ENDCOMPOSITION:
2329         case WM_IME_COMPOSITION: {
2330             QWidget *fw = QApplication::focusWidget();
2331             QWinInputContext *im = fw ? qobject_cast<QWinInputContext *>(fw->inputContext()) : 0;
2332             if (fw && im) {
2333                 if(message == WM_IME_STARTCOMPOSITION)
2334                     result = im->startComposition();
2335                 else if (message == WM_IME_ENDCOMPOSITION)
2336                     result = im->endComposition();
2337                 else if (message == WM_IME_COMPOSITION)
2338                     result = im->composition(lParam);
2339             }
2340             break;
2341         }
2342         case WM_IME_REQUEST: {
2343             QWidget *fw = QApplication::focusWidget();
2344             QWinInputContext *im = fw ? qobject_cast<QWinInputContext *>(fw->inputContext()) : 0;
2345             if (fw && im) {
2346                 if(wParam == IMR_RECONVERTSTRING) {
2347                     int ret = im->reconvertString((RECONVERTSTRING *)lParam);
2348                     if (ret == -1) {
2349                         result = false;
2350                     } else {
2351                         return ret;
2352                     }
2353                 } else if (wParam == IMR_CONFIRMRECONVERTSTRING) {
2354                     RETURN(TRUE);
2355                 } else {
2356                     // in all other cases, call DefWindowProc()
2357                     result = false;
2358                 }
2359             }
2360             break;
2361         }
2362 #endif // QT_NO_IM
2363 #ifndef Q_WS_WINCE
2364         case WM_CHANGECBCHAIN:
2365         case WM_DRAWCLIPBOARD:
2366 #endif
2367         case WM_RENDERFORMAT:
2368         case WM_RENDERALLFORMATS:
2369 #ifndef QT_NO_CLIPBOARD
2370         case WM_DESTROYCLIPBOARD:
2371             if (qt_clipboard) {
2372                 QClipboardEvent e(reinterpret_cast<QEventPrivate *>(&msg));
2373                 qt_sendSpontaneousEvent(qt_clipboard, &e);
2374                 RETURN(0);
2375             }
2376             result = false;
2377             break;
2378 #endif //QT_NO_CLIPBOARD
2379 #ifndef QT_NO_ACCESSIBILITY
2380         case WM_GETOBJECT:
2381             {
2382 #if !defined(Q_OS_WINCE)
2383                 /* On Win64, lParam can be 0x00000000fffffffc or 0xfffffffffffffffc (!),
2384                    but MSDN says that lParam should be converted to a DWORD
2385                    before its compared against OBJID_CLIENT
2386                 */
2387                 const DWORD dwObjId = (DWORD)lParam;
2388                 // Ignoring all requests while starting up
2389                 if (QApplication::startingUp() || QApplication::closingDown() || dwObjId != OBJID_CLIENT) {
2390                     result = false;
2391                     break;
2392                 }
2393 
2394                 typedef LRESULT (WINAPI *PtrLresultFromObject)(REFIID, WPARAM, LPUNKNOWN);
2395                 static PtrLresultFromObject ptrLresultFromObject = 0;
2396                 static bool oleaccChecked = false;
2397                 if (!oleaccChecked) {
2398                     QSystemLibrary oleacclib(QLatin1String("oleacc"));
2399                     ptrLresultFromObject = (PtrLresultFromObject)oleacclib.resolve("LresultFromObject");
2400                     oleaccChecked = true;
2401                 }
2402                 if (ptrLresultFromObject) {
2403                     QAccessibleInterface *acc = QAccessible::queryAccessibleInterface(widget);
2404                     if (!acc) {
2405                         result = false;
2406                         break;
2407                     }
2408 
2409                     // and get an instance of the IAccessibile implementation
2410                     IAccessible *iface = qt_createWindowsAccessible(acc);
2411                     res = ptrLresultFromObject(IID_IAccessible, wParam, iface);  // ref == 2
2412                     iface->Release(); // the client will release the object again, and then it will destroy itself
2413 
2414                     if (res > 0)
2415                         RETURN(res);
2416                 }
2417 #endif
2418             }
2419             result = false;
2420             break;
2421         case WM_GETTEXT:
2422             if (!widget->isWindow()) {
2423                 int ret = 0;
2424                 QAccessibleInterface *acc = QAccessible::queryAccessibleInterface(widget);
2425                 if (acc) {
2426                     QString text = acc->text(QAccessible::Name, 0);
2427                     if (text.isEmpty())
2428                         text = widget->objectName();
2429                     ret = qMin<int>(wParam - 1, text.size());
2430                     text.resize(ret);
2431                     memcpy((void *)lParam, text.utf16(), (text.size() + 1) * sizeof(ushort));
2432                     delete acc;
2433                 }
2434                 if (!ret) {
2435                     result = false;
2436                     break;
2437                 }
2438                 RETURN(ret);
2439             }
2440             result = false;
2441             break;
2442 #endif
2443         case WT_PACKET:
2444             if (ptrWTPacketsGet) {
2445                 if ((nPackets = ptrWTPacketsGet(qt_tablet_context, QT_TABLET_NPACKETQSIZE, &localPacketBuf))) {
2446                     result = widget->translateTabletEvent(msg, localPacketBuf, nPackets);
2447                 }
2448             }
2449             break;
2450         case WT_PROXIMITY:
2451 
2452             #ifndef QT_NO_TABLETEVENT
2453             if (ptrWTPacketsGet && ptrWTInfo) {
2454                 const bool enteredProximity = LOWORD(lParam) != 0;
2455                 PACKET proximityBuffer[1]; // we are only interested in the first packet in this case
2456                 const int totalPacks = ptrWTPacketsGet(qt_tablet_context, 1, proximityBuffer);
2457                 if (totalPacks > 0) {
2458                     const UINT currentCursor = proximityBuffer[0].pkCursor;
2459 
2460                     UINT csr_physid;
2461                     ptrWTInfo(WTI_CURSORS + currentCursor, CSR_PHYSID, &csr_physid);
2462                     UINT csr_type;
2463                     ptrWTInfo(WTI_CURSORS + currentCursor, CSR_TYPE, &csr_type);
2464                     const UINT deviceIdMask = 0xFF6; // device type mask && device color mask
2465                     quint64 uniqueId = (csr_type & deviceIdMask);
2466                     uniqueId = (uniqueId << 32) | csr_physid;
2467 
2468                     // initialising and updating the cursor should be done in response to
2469                     // WT_CSRCHANGE. We do it in WT_PROXIMITY because some wintab never send
2470                     // the event WT_CSRCHANGE even if asked with CXO_CSRMESSAGES
2471                     const QTabletCursorInfo *const globalCursorInfo = tCursorInfo();
2472                     if (!globalCursorInfo->contains(uniqueId))
2473                         tabletInit(uniqueId, csr_type, qt_tablet_context);
2474 
2475                     currentTabletPointer = globalCursorInfo->value(uniqueId);
2476                     tabletUpdateCursor(currentTabletPointer, currentCursor);
2477                 }
2478                 qt_tabletChokeMouse = false;
2479 
2480                 QTabletEvent tabletProximity(enteredProximity ? QEvent::TabletEnterProximity
2481                                                               : QEvent::TabletLeaveProximity,
2482                                              QPoint(), QPoint(), QPointF(), currentTabletPointer.currentDevice, currentTabletPointer.currentPointerType, 0, 0,
2483                                              0, 0, 0, 0, 0, currentTabletPointer.llId);
2484                 QApplication::sendEvent(qApp, &tabletProximity);
2485             }
2486             #endif // QT_NO_TABLETEVENT
2487 
2488             break;
2489 #ifdef Q_WS_WINCE_WM
2490         case WM_SETFOCUS: {
2491             HIMC hC;
2492             hC = ImmGetContext(hwnd);
2493             ImmSetOpenStatus(hC, TRUE);
2494             ImmEscape(NULL, hC, IME_ESC_SET_MODE, (LPVOID)IM_SPELL);
2495             result = false;
2496         }
2497         break;
2498 #endif
2499         case WM_KILLFOCUS:
2500             if (!QWidget::find((HWND)wParam)) { // we don't get focus, so unset it now
2501                 if (!widget->hasFocus()) // work around Windows bug after minimizing/restoring
2502                     widget = (QETWidget*)QApplication::focusWidget();
2503                 HWND focus = ::GetFocus();
2504                 //if there is a current widget and the new widget belongs to the same toplevel window
2505                 //or if the current widget was embedded into non-qt window (i.e. we won't get WM_ACTIVATEAPP)
2506                 //then we clear the focus on the widget
2507                 //in case the new widget belongs to a different widget hierarchy, clearing the focus
2508                 //will be handled because the active window will change
2509                 const bool embedded = widget && ((QETWidget*)widget->window())->topData()->embedded;
2510                 if (widget && (embedded || ::IsChild(widget->window()->internalWinId(), focus))) {
2511                     widget->clearFocus();
2512                     result = true;
2513                 } else {
2514                     result = false;
2515                 }
2516             } else {
2517                 result = false;
2518             }
2519             break;
2520         case WM_THEMECHANGED:
2521             if ((widget->windowType() == Qt::Desktop) || !qApp || QApplication::closingDown()
2522                                                          || QApplication::type() == QApplication::Tty)
2523                 break;
2524 
2525             if (widget->testAttribute(Qt::WA_WState_Polished))
2526                 QApplication::style()->unpolish(widget);
2527 
2528             if (widget->testAttribute(Qt::WA_WState_Polished))
2529                 QApplication::style()->polish(widget);
2530             widget->repolishStyle(*QApplication::style());
2531             if (widget->isVisible())
2532                 widget->update();
2533             break;
2534 
2535 #ifndef Q_WS_WINCE
2536         case WM_INPUTLANGCHANGE: {
2537             wchar_t info[7];
2538             if (!GetLocaleInfo(MAKELCID(lParam, SORT_DEFAULT), LOCALE_IDEFAULTANSICODEPAGE, info, 6)) {
2539                 inputcharset = CP_ACP;
2540             } else {
2541                 inputcharset = QString::fromWCharArray(info).toInt();
2542             }
2543             QKeyMapper::changeKeyboard();
2544             break;
2545         }
2546 #else
2547         case WM_COMMAND: {
2548             bool OkCommand = (LOWORD(wParam) == 0x1);
2549             bool CancelCommand = (LOWORD(wParam) == 0x2);
2550             if (OkCommand)
2551                 QApplication::postEvent(widget, new QEvent(QEvent::OkRequest));
2552             if (CancelCommand)
2553                 widget->showMinimized();
2554             else
2555 #ifndef QT_NO_MENUBAR
2556                 QMenuBar::wceCommands(LOWORD(wParam));
2557 #endif
2558             result = true;
2559         }
2560             break;
2561         case WM_HELP:
2562             QApplication::postEvent(widget, new QEvent(QEvent::HelpRequest));
2563             result = true;
2564             break;
2565 #endif
2566 
2567         case WM_MOUSELEAVE:
2568             // We receive a mouse leave for curWin, meaning
2569             // the mouse was moved outside our widgets
2570             if (widget->internalWinId() == curWin) {
2571                 bool dispatch = !widget->underMouse();
2572                 // hasMouse is updated when dispatching enter/leave,
2573                 // so test if it is actually up-to-date
2574                 if (!dispatch) {
2575                     QRect geom = widget->geometry();
2576                     if (widget->parentWidget() && !widget->isWindow()) {
2577                         QPoint gp = widget->parentWidget()->mapToGlobal(widget->pos());
2578                         geom.setX(gp.x());
2579                         geom.setY(gp.y());
2580                     }
2581                     QPoint cpos = QCursor::pos();
2582                     dispatch = !geom.contains(cpos);
2583                     if ( !dispatch && !QWidget::mouseGrabber()) {
2584                         QWidget *hittest = QApplication::widgetAt(cpos);
2585                         dispatch = !hittest || hittest->internalWinId() != curWin;
2586                     }
2587                     if (!dispatch) {
2588                         HRGN hrgn = qt_tryCreateRegion(QRegion::Rectangle, 0,0,0,0);
2589                         if (GetWindowRgn(curWin, hrgn) != ERROR) {
2590                             QPoint lcpos = widget->mapFromGlobal(cpos);
2591                             dispatch = !PtInRegion(hrgn, lcpos.x(), lcpos.y());
2592                         }
2593                         DeleteObject(hrgn);
2594                     }
2595                 }
2596                 if (dispatch) {
2597                     if (qt_last_mouse_receiver && !qt_last_mouse_receiver->internalWinId())
2598                         QApplicationPrivate::dispatchEnterLeave(0, qt_last_mouse_receiver);
2599                     else
2600                         QApplicationPrivate::dispatchEnterLeave(0, QWidget::find((WId)curWin));
2601                     curWin = 0;
2602                     qt_last_mouse_receiver = 0;
2603                 }
2604             }
2605             break;
2606 
2607         case WM_CANCELMODE:
2608             {
2609                 // this goes through QMenuBar's event filter
2610                 QEvent e(QEvent::ActivationChange);
2611                 QApplication::sendEvent(qApp, &e);
2612             }
2613             break;
2614 
2615         case WM_IME_NOTIFY:
2616             // special handling for ime, only for widgets in a popup
2617             if (wParam  == IMN_OPENCANDIDATE) {
2618                 imeParentWnd = hwnd;
2619                 if (QApplication::activePopupWidget()) {
2620                     // temporarily disable the mouse grab to allow mouse input in
2621                     // the ime candidate window. The actual handle is untouched
2622                     if (autoCaptureWnd)
2623                         ReleaseCapture();
2624                 }
2625             } else if (wParam  == IMN_CLOSECANDIDATE) {
2626                 imeParentWnd = 0;
2627                 if (QApplication::activePopupWidget()) {
2628                     // undo the action above, when candidate window is closed
2629                     if (autoCaptureWnd)
2630                         SetCapture(autoCaptureWnd);
2631                 }
2632             }
2633             result = false;
2634             break;
2635 #ifndef QT_NO_GESTURES
2636 #if !defined(Q_WS_WINCE) || defined(QT_WINCE_GESTURES)
2637         case WM_GESTURE: {
2638             GESTUREINFO gi;
2639             memset(&gi, 0, sizeof(GESTUREINFO));
2640             gi.cbSize = sizeof(GESTUREINFO);
2641 
2642             QApplicationPrivate *qAppPriv = QApplicationPrivate::instance();
2643             BOOL bResult = false;
2644             if (qAppPriv->GetGestureInfo)
2645                 bResult = qAppPriv->GetGestureInfo((HANDLE)msg.lParam, &gi);
2646             if (bResult) {
2647                 if (gi.dwID == GID_BEGIN) {
2648                     // find the alien widget for the gesture position.
2649                     // This might not be accurate as the position is the center
2650                     // point of two fingers for multi-finger gestures.
2651                     QPoint pt(gi.ptsLocation.x, gi.ptsLocation.y);
2652                     QWidget *w = widget->childAt(widget->mapFromGlobal(pt));
2653                     qAppPriv->gestureWidget = w ? w : widget;
2654                 }
2655                 if (qAppPriv->gestureWidget)
2656                     static_cast<QETWidget*>(qAppPriv->gestureWidget)->translateGestureEvent(msg, gi);
2657                 if (qAppPriv->CloseGestureInfoHandle)
2658                     qAppPriv->CloseGestureInfoHandle((HANDLE)msg.lParam);
2659                 if (gi.dwID == GID_END)
2660                     qAppPriv->gestureWidget = 0;
2661             } else {
2662                 DWORD dwErr = GetLastError();
2663                 if (dwErr > 0)
2664                     qWarning() << "translateGestureEvent: error = " << dwErr;
2665             }
2666             result = true;
2667             break;
2668         }
2669 #endif // !defined(Q_WS_WINCE) || defined(QT_WINCE_GESTURES)
2670 #endif // QT_NO_GESTURES
2671 #ifndef QT_NO_CURSOR
2672         case WM_SETCURSOR: {
2673             QCursor *ovr = QApplication::overrideCursor();
2674             if (ovr) {
2675                 SetCursor(ovr->handle());
2676                 RETURN(TRUE);
2677             }
2678             result = false;
2679             break;
2680         }
2681 #endif
2682         default:
2683             result = false;                        // event was not processed
2684             break;
2685         }
2686     }
2687 
2688     if (evt_type != QEvent::None) {                // simple event
2689         QEvent e(evt_type);
2690         result = qt_sendSpontaneousEvent(widget, &e);
2691     }
2692 
2693     if (result)
2694         RETURN(false);
2695 
2696 do_default:
2697 #ifndef QT_NO_IM
2698     RETURN(QWinInputContext::DefWindowProc(hwnd,message,wParam,lParam))
2699 #else
2700     RETURN(TRUE);
2701 #endif
2702 }
2703 
2704 
2705 /*****************************************************************************
2706   Modal widgets; We have implemented our own modal widget mechanism
2707   to get total control.
2708   A modal widget without a parent becomes application-modal.
2709   A modal widget with a parent becomes modal to its parent and grandparents..
2710 
2711   QApplicationPrivate::enterModal()
2712         Enters modal state
2713         Arguments:
2714             QWidget *widget        A modal widget
2715 
2716   QApplicationPrivate::leaveModal()
2717         Leaves modal state for a widget
2718         Arguments:
2719             QWidget *widget        A modal widget
2720  *****************************************************************************/
2721 
2722 bool QApplicationPrivate::modalState()
2723 {
2724     return app_do_modal;
2725 }
2726 
2727 void QApplicationPrivate::enterModal_sys(QWidget *widget)
2728 {
2729     if (!qt_modal_stack)
2730         qt_modal_stack = new QWidgetList;
2731 
2732     releaseAutoCapture();
2733     ClipCursor(0);
2734     QWidget *leave = qt_last_mouse_receiver;
2735     if (!leave)
2736         leave = QWidget::find((WId)curWin);
2737     QApplicationPrivate::dispatchEnterLeave(0, leave);
2738     qt_modal_stack->insert(0, widget);
2739     app_do_modal = true;
2740     curWin = 0;
2741     qt_last_mouse_receiver = 0;
2742     qt_win_ignoreNextMouseReleaseEvent = false;
2743 }
2744 
2745 void QApplicationPrivate::leaveModal_sys(QWidget *widget)
2746 {
2747     if (qt_modal_stack && qt_modal_stack->removeAll(widget)) {
2748         if (qt_modal_stack->isEmpty()) {
2749             delete qt_modal_stack;
2750             qt_modal_stack = 0;
2751             QPoint p(QCursor::pos());
2752             app_do_modal = false; // necessary, we may get recursively into qt_try_modal below
2753             QWidget* w = QApplication::widgetAt(p.x(), p.y());
2754             QWidget *leave = qt_last_mouse_receiver;
2755             if (!leave)
2756                 leave = QWidget::find((WId)curWin);
2757             if (QWidget *grabber = QWidget::mouseGrabber()) {
2758                 w = grabber;
2759                 if (leave == w)
2760                     leave = 0;
2761             }
2762             QApplicationPrivate::dispatchEnterLeave(w, leave); // send synthetic enter event
2763             curWin = w ? w->effectiveWinId() : 0;
2764             qt_last_mouse_receiver = w;
2765         }
2766         qt_win_ignoreNextMouseReleaseEvent = true;
2767     }
2768     app_do_modal = qt_modal_stack != 0;
2769 }
2770 
2771 bool qt_try_modal(QWidget *widget, MSG *msg, int& ret)
2772 {
2773 #if defined(Q_OS_WINCE)
2774     Q_UNUSED(ret);
2775 #endif
2776     QWidget * top = 0;
2777 
2778     if (QApplicationPrivate::tryModalHelper(widget, &top))
2779         return true;
2780 
2781     int type = msg->message;
2782 
2783     bool block_event = false;
2784 #ifndef Q_WS_WINCE
2785     if (type != WM_NCHITTEST) {
2786 #endif
2787         if ((type >= WM_MOUSEFIRST && type <= WM_MOUSELAST) ||
2788              type == WM_MOUSEWHEEL || type == WM_MOUSEHWHEEL ||
2789              type == WM_MOUSELEAVE ||
2790              (type >= WM_KEYFIRST && type <= WM_KEYLAST)
2791 #ifndef Q_WS_WINCE
2792             || type == WM_NCMOUSEMOVE
2793 #endif
2794          ) {
2795             if (type == WM_MOUSEMOVE
2796 #ifndef Q_WS_WINCE
2797                  || type == WM_NCMOUSEMOVE
2798 #endif
2799             ) {
2800 #ifndef QT_NO_CURSOR
2801                 QCursor *c = qt_grab_cursor();
2802                 if (!c)
2803                     c = QApplication::overrideCursor();
2804                 if (c)                                // application cursor defined
2805                     SetCursor(c->handle());
2806                 else
2807                     SetCursor(QCursor(Qt::ArrowCursor).handle());
2808 #endif // QT_NO_CURSOR
2809             }
2810             block_event = true;
2811         } else if (type == WM_CLOSE) {
2812             block_event = true;
2813         }
2814 #ifndef Q_WS_WINCE
2815         else if (type == WM_MOUSEACTIVATE || type == WM_NCLBUTTONDOWN){
2816             if (!top->isActiveWindow()) {
2817                 top->activateWindow();
2818             } else {
2819                 QApplication::beep();
2820             }
2821             block_event = true;
2822             ret = MA_NOACTIVATEANDEAT;
2823         } else if (type == WM_SYSCOMMAND) {
2824             if (!(msg->wParam == SC_RESTORE && widget->isMinimized()))
2825                 block_event = true;
2826         }
2827     }
2828 #endif
2829 
2830     return !block_event;
2831 }
2832 
2833 
2834 /*****************************************************************************
2835   Popup widget mechanism
2836 
2837   openPopup()
2838         Adds a widget to the list of popup widgets
2839         Arguments:
2840             QWidget *widget        The popup widget to be added
2841 
2842   closePopup()
2843         Removes a widget from the list of popup widgets
2844         Arguments:
2845             QWidget *widget        The popup widget to be removed
2846  *****************************************************************************/
2847 
2848 void QApplicationPrivate::openPopup(QWidget *popup)
2849 {
2850     if (!QApplicationPrivate::popupWidgets)
2851         QApplicationPrivate::popupWidgets = new QWidgetList;
2852     QApplicationPrivate::popupWidgets->append(popup);
2853     if (!popup->isEnabled())
2854         return;
2855 
2856     // close any opened 'ime candidate window'
2857     if (imeParentWnd)
2858         ::SendMessage(imeParentWnd, WM_IME_ENDCOMPOSITION, 0, 0);
2859 
2860     if (QApplicationPrivate::popupWidgets->count() == 1 && !qt_nograb()) {
2861         Q_ASSERT(popup->testAttribute(Qt::WA_WState_Created));
2862         setAutoCapture(popup->internalWinId());        // grab mouse/keyboard
2863     }
2864     // Popups are not focus-handled by the window system (the first
2865     // popup grabbed the keyboard), so we have to do that manually: A
2866     // new popup gets the focus
2867     if (popup->focusWidget()) {
2868         popup->focusWidget()->setFocus(Qt::PopupFocusReason);
2869     } else if (QApplicationPrivate::popupWidgets->count() == 1) { // this was the first popup
2870         if (QWidget *fw = QApplication::focusWidget()) {
2871             QFocusEvent e(QEvent::FocusOut, Qt::PopupFocusReason);
2872             QApplication::sendEvent(fw, &e);
2873         }
2874     }
2875 }
2876 
2877 void QApplicationPrivate::closePopup(QWidget *popup)
2878 {
2879     if (!QApplicationPrivate::popupWidgets)
2880         return;
2881     QApplicationPrivate::popupWidgets->removeAll(popup);
2882     POINT curPos;
2883     GetCursorPos(&curPos);
2884 
2885     // close any opened 'ime candidate window'
2886     if (imeParentWnd)
2887         ::SendMessage(imeParentWnd, WM_IME_ENDCOMPOSITION, 0, 0);
2888 
2889     if (QApplicationPrivate::popupWidgets->isEmpty()) { // this was the last popup
2890         delete QApplicationPrivate::popupWidgets;
2891         QApplicationPrivate::popupWidgets = 0;
2892         replayPopupMouseEvent = (!popup->geometry().contains(QPoint(curPos.x, curPos.y))
2893                                 && !popup->testAttribute(Qt::WA_NoMouseReplay));
2894         if (!popup->isEnabled())
2895             return;
2896         if (!qt_nograb())                        // grabbing not disabled
2897             releaseAutoCapture();
2898         QWidget *fw = QApplicationPrivate::active_window ? QApplicationPrivate::active_window->focusWidget()
2899             : QApplication::focusWidget();
2900         if (fw) {
2901             if (fw != QApplication::focusWidget()) {
2902                 fw->setFocus(Qt::PopupFocusReason);
2903             } else {
2904                 QFocusEvent e(QEvent::FocusIn, Qt::PopupFocusReason);
2905                 QApplication::sendEvent(fw, &e);
2906             }
2907         }
2908     } else {
2909         // Popups are not focus-handled by the window system (the
2910         // first popup grabbed the keyboard), so we have to do that
2911         // manually: A popup was closed, so the previous popup gets
2912         // the focus.
2913         QWidget* aw = QApplicationPrivate::popupWidgets->last();
2914         if (QApplicationPrivate::popupWidgets->count() == 1) {
2915             Q_ASSERT(aw->testAttribute(Qt::WA_WState_Created));
2916             setAutoCapture(aw->internalWinId());
2917         }
2918         if (QWidget *fw = aw->focusWidget())
2919             fw->setFocus(Qt::PopupFocusReason);
2920     }
2921 }
2922 
2923 
2924 
2925 
2926 /*****************************************************************************
2927   Event translation; translates Windows events to Qt events
2928  *****************************************************************************/
2929 
2930 //
2931 // Auto-capturing for mouse press and mouse release
2932 //
2933 
2934 static void setAutoCapture(HWND h)
2935 {
2936     if (autoCaptureWnd)
2937         releaseAutoCapture();
2938     autoCaptureWnd = h;
2939     SetCapture(h);
2940 }
2941 
2942 static void releaseAutoCapture()
2943 {
2944     if (autoCaptureWnd) {
2945         ReleaseCapture();
2946         autoCaptureWnd = 0;
2947     }
2948 }
2949 
2950 
2951 //
2952 // Mouse event translation
2953 //
2954 // Non-client mouse messages are not translated
2955 //
2956 
2957 static const ushort mouseTbl[] = {
2958     WM_MOUSEMOVE,        QEvent::MouseMove,               0,
2959     WM_LBUTTONDOWN,      QEvent::MouseButtonPress,        Qt::LeftButton,
2960     WM_LBUTTONUP,        QEvent::MouseButtonRelease,      Qt::LeftButton,
2961     WM_LBUTTONDBLCLK,    QEvent::MouseButtonDblClick,     Qt::LeftButton,
2962     WM_RBUTTONDOWN,      QEvent::MouseButtonPress,        Qt::RightButton,
2963     WM_RBUTTONUP,        QEvent::MouseButtonRelease,      Qt::RightButton,
2964     WM_RBUTTONDBLCLK,    QEvent::MouseButtonDblClick,     Qt::RightButton,
2965     WM_MBUTTONDOWN,      QEvent::MouseButtonPress,        Qt::MidButton,
2966     WM_MBUTTONUP,        QEvent::MouseButtonRelease,      Qt::MidButton,
2967     WM_MBUTTONDBLCLK,    QEvent::MouseButtonDblClick,     Qt::MidButton,
2968     // use XButton1 for now, the real X button is decided later
2969     WM_XBUTTONDOWN,      QEvent::MouseButtonPress,        Qt::XButton1,
2970     WM_XBUTTONUP,        QEvent::MouseButtonRelease,      Qt::XButton1,
2971     WM_XBUTTONDBLCLK,    QEvent::MouseButtonDblClick,     Qt::XButton1,
2972 
2973 #ifndef Q_WS_WINCE
2974     WM_NCMOUSEMOVE,      QEvent::NonClientAreaMouseMove,           0,
2975     WM_NCLBUTTONDOWN,    QEvent::NonClientAreaMouseButtonPress,    Qt::LeftButton,
2976     WM_NCLBUTTONUP,      QEvent::NonClientAreaMouseButtonRelease,  Qt::LeftButton,
2977     WM_NCLBUTTONDBLCLK,  QEvent::NonClientAreaMouseButtonDblClick, Qt::LeftButton,
2978     WM_NCRBUTTONDOWN,    QEvent::NonClientAreaMouseButtonPress,    Qt::RightButton,
2979     WM_NCRBUTTONUP,      QEvent::NonClientAreaMouseButtonRelease,  Qt::RightButton,
2980     WM_NCRBUTTONDBLCLK,  QEvent::NonClientAreaMouseButtonDblClick, Qt::RightButton,
2981     WM_NCMBUTTONDOWN,    QEvent::NonClientAreaMouseButtonPress,    Qt::MidButton,
2982     WM_NCMBUTTONUP,      QEvent::NonClientAreaMouseButtonRelease,  Qt::MidButton,
2983     WM_NCMBUTTONDBLCLK,  QEvent::NonClientAreaMouseButtonDblClick, Qt::MidButton,
2984 #endif
2985 
2986     0,                        0,                                0
2987 };
2988 
2989 static int translateButtonState(int s, int type, int button)
2990 {
2991     Q_UNUSED(type);
2992     Q_UNUSED(button);
2993     int bst = 0;
2994     if (s & MK_LBUTTON)
2995         bst |= Qt::LeftButton;
2996     if (s & MK_MBUTTON)
2997         bst |= Qt::MidButton;
2998     if (s & MK_RBUTTON)
2999         bst |= Qt::RightButton;
3000     if (s & MK_SHIFT)
3001         bst |= Qt::ShiftModifier;
3002     if (s & MK_CONTROL)
3003         bst |= Qt::ControlModifier;
3004 
3005     if (s & MK_XBUTTON1)
3006         bst |= Qt::XButton1;
3007     if (s & MK_XBUTTON2)
3008         bst |= Qt::XButton2;
3009 
3010     if (GetKeyState(VK_MENU) < 0)
3011         bst |= Qt::AltModifier;
3012 
3013     if ((GetKeyState(VK_LWIN) < 0) ||
3014          (GetKeyState(VK_RWIN) < 0))
3015         bst |= Qt::MetaModifier;
3016 
3017     return bst;
3018 }
3019 
3020 void qt_win_eatMouseMove()
3021 {
3022     // after closing a windows dialog with a double click (i.e. open a file)
3023     // the message queue still contains a dubious WM_MOUSEMOVE message where
3024     // the left button is reported to be down (wParam != 0).
3025     // remove all those messages (usually 1) and post the last one with a
3026     // reset button state
3027 
3028     MSG msg = {0, 0, 0, 0, 0, {0, 0} };
3029     while (PeekMessage(&msg, 0, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE))
3030         ;
3031     if (msg.message == WM_MOUSEMOVE)
3032         PostMessage(msg.hwnd, msg.message, 0, msg.lParam);
3033 }
3034 
3035 // In DnD, the mouse release event never appears, so the
3036 // mouse button state machine must be manually reset
3037 void QApplication::winMouseButtonUp()
3038 {
3039     qt_button_down = 0;
3040     releaseAutoCapture();
3041 }
3042 
3043 void QETWidget::repolishStyle(QStyle &)
3044 {
3045     QEvent e(QEvent::StyleChange);
3046     QApplication::sendEvent(this, &e);
3047 }
3048 
3049 bool QETWidget::translateMouseEvent(const MSG &msg)
3050 {
3051     if (!isWindow() && testAttribute(Qt::WA_NativeWindow))
3052         Q_ASSERT(internalWinId());
3053 
3054     static QPoint pos;
3055     static POINT gpos={-1,-1};
3056     QEvent::Type type;                                // event parameters
3057     int           button;
3058     int           state;
3059     int           i;
3060 
3061     if (sm_blockUserInput) //block user interaction during session management
3062         return true;
3063 
3064     // Compress mouse move events
3065     if (msg.message == WM_MOUSEMOVE) {
3066         MSG mouseMsg;
3067         while (PeekMessage(&mouseMsg, msg.hwnd, WM_MOUSEFIRST,
3068                WM_MOUSELAST, PM_NOREMOVE)) {
3069             if (mouseMsg.message == WM_MOUSEMOVE) {
3070 #define PEEKMESSAGE_IS_BROKEN 1
3071 #ifdef PEEKMESSAGE_IS_BROKEN
3072                 // Since the Windows PeekMessage() function doesn't
3073                 // correctly return the wParam for WM_MOUSEMOVE events
3074                 // if there is a key release event in the queue
3075                 // _before_ the mouse event, we have to also consider
3076                 // key release events (kls 2003-05-13):
3077                 MSG keyMsg;
3078                 bool done = false;
3079                 while (PeekMessage(&keyMsg, 0, WM_KEYFIRST, WM_KEYLAST,
3080                        PM_NOREMOVE)) {
3081                     if (keyMsg.time < mouseMsg.time) {
3082                         if ((keyMsg.lParam & 0xC0000000) == 0x40000000) {
3083                             PeekMessage(&keyMsg, 0, keyMsg.message,
3084                                         keyMsg.message, PM_REMOVE);
3085                         } else {
3086                             done = true;
3087                             break;
3088                         }
3089                     } else {
3090                         break; // no key event before the WM_MOUSEMOVE event
3091                     }
3092                 }
3093                 if (done)
3094                     break;
3095 #else
3096                 // Actually the following 'if' should work instead of
3097                 // the above key event checking, but apparently
3098                 // PeekMessage() is broken :-(
3099                 if (mouseMsg.wParam != msg.wParam)
3100                     break; // leave the message in the queue because
3101                            // the key state has changed
3102 #endif
3103                 MSG *msgPtr = (MSG *)(&msg);
3104                 // Update the passed in MSG structure with the
3105                 // most recent one.
3106                 msgPtr->lParam = mouseMsg.lParam;
3107                 msgPtr->wParam = mouseMsg.wParam;
3108                 // Extract the x,y coordinates from the lParam as we do in the WndProc
3109                 msgPtr->pt.x = GET_X_LPARAM(mouseMsg.lParam);
3110                 msgPtr->pt.y = GET_Y_LPARAM(mouseMsg.lParam);
3111                 ClientToScreen(msg.hwnd, &(msgPtr->pt));
3112                 // Remove the mouse move message
3113                 PeekMessage(&mouseMsg, msg.hwnd, WM_MOUSEMOVE,
3114                             WM_MOUSEMOVE, PM_REMOVE);
3115             } else {
3116                 break; // there was no more WM_MOUSEMOVE event
3117             }
3118         }
3119     }
3120 
3121     for (i=0; (UINT)mouseTbl[i] != msg.message && mouseTbl[i]; i += 3)
3122         ;
3123     if (!mouseTbl[i])
3124         return false;
3125     type   = (QEvent::Type)mouseTbl[++i];        // event type
3126     button = mouseTbl[++i];                        // which button
3127     if (button == Qt::XButton1) {
3128         switch(GET_XBUTTON_WPARAM(msg.wParam)) {
3129         case XBUTTON1:
3130             button = Qt::XButton1;
3131             break;
3132         case XBUTTON2:
3133             button = Qt::XButton2;
3134             break;
3135         }
3136     }
3137 #ifndef Q_OS_WINCE
3138     static bool trackMouseEventLookup = false;
3139     typedef BOOL (WINAPI *PtrTrackMouseEvent)(LPTRACKMOUSEEVENT);
3140     static PtrTrackMouseEvent ptrTrackMouseEvent = 0;
3141 #endif
3142     state  = translateButtonState(msg.wParam, type, button); // button state
3143     const QPoint widgetPos = mapFromGlobal(QPoint(msg.pt.x, msg.pt.y));
3144     QWidget *alienWidget = !internalWinId() ? this : childAt(widgetPos);
3145     if (alienWidget && alienWidget->internalWinId())
3146         alienWidget = 0;
3147 
3148     if (type == QEvent::MouseMove || type == QEvent::NonClientAreaMouseMove
3149             || type == QEvent::TabletMove) {
3150 
3151         if (!(state & Qt::MouseButtonMask))
3152             qt_button_down = 0;
3153 #ifndef QT_NO_CURSOR
3154         QCursor *c = qt_grab_cursor();
3155         if (!c)
3156             c = QApplication::overrideCursor();
3157         if (c)                                // application cursor defined
3158             SetCursor(c->handle());
3159         else if (type != QEvent::NonClientAreaMouseMove && !qt_button_down) {
3160             // use  widget cursor if widget is enabled
3161             QWidget *w = alienWidget ? alienWidget : this;
3162             while (!w->isWindow() && !w->isEnabled())
3163                 w = w->parentWidget();
3164             SetCursor(w->cursor().handle());
3165         }
3166 #endif // QT_NO_CURSOR
3167 
3168         HWND id = effectiveWinId();
3169         QWidget *mouseGrabber = QWidget::mouseGrabber();
3170         QWidget *activePopupWidget = QApplication::activePopupWidget();
3171         if (mouseGrabber) {
3172             if (!activePopupWidget || (activePopupWidget == this && !rect().contains(widgetPos)))
3173                 id = mouseGrabber->effectiveWinId();
3174         } else if (type == QEvent::NonClientAreaMouseMove) {
3175             id = 0;
3176         }
3177 
3178         if (curWin != id) {                // new current window
3179             if (id == 0) {
3180                 QWidget *leave = qt_last_mouse_receiver;
3181                 if (!leave)
3182                     leave = QWidget::find(curWin);
3183                 QApplicationPrivate::dispatchEnterLeave(0, leave);
3184                 qt_last_mouse_receiver = 0;
3185                 curWin = 0;
3186             } else {
3187                 QWidget *leave = 0;
3188                 if (curWin && qt_last_mouse_receiver)
3189                     leave = qt_last_mouse_receiver;
3190                 else
3191                     leave = QWidget::find(curWin);
3192                 QWidget *enter = alienWidget ? alienWidget : this;
3193                 if (mouseGrabber && activePopupWidget) {
3194                     if (leave != mouseGrabber)
3195                         enter = mouseGrabber;
3196                     else
3197                         enter = activePopupWidget == this ? this : mouseGrabber;
3198                 }
3199                 QApplicationPrivate::dispatchEnterLeave(enter, leave);
3200                 qt_last_mouse_receiver = enter;
3201                 curWin = enter ? enter->effectiveWinId() : 0;
3202             }
3203 #ifndef Q_OS_WINCE
3204 
3205             if (curWin != 0) {
3206                 if (!trackMouseEventLookup) {
3207                     ptrTrackMouseEvent = (PtrTrackMouseEvent)QSystemLibrary::resolve(QLatin1String("comctl32"), "_TrackMouseEvent");
3208                     trackMouseEventLookup = true;
3209                 }
3210                 if (ptrTrackMouseEvent && !qApp->d_func()->inPopupMode()) {
3211                     // We always have to set the tracking, since
3212                     // Windows detects more leaves than we do..
3213                     TRACKMOUSEEVENT tme;
3214                     tme.cbSize = sizeof(TRACKMOUSEEVENT);
3215                     tme.dwFlags = 0x00000002;    // TME_LEAVE
3216                     tme.hwndTrack = curWin;      // Track on window receiving msgs
3217                     tme.dwHoverTime = (DWORD)-1; // HOVER_DEFAULT
3218                     ptrTrackMouseEvent(&tme);
3219                 }
3220             }
3221 #endif // Q_OS_WINCE
3222         }
3223 
3224         POINT curPos = msg.pt;
3225         if (curPos.x == gpos.x && curPos.y == gpos.y)
3226             return true;                        // same global position
3227         gpos = curPos;
3228 
3229         Q_ASSERT(testAttribute(Qt::WA_WState_Created));
3230         ScreenToClient(internalWinId(), &curPos);
3231 
3232         pos.rx() = curPos.x;
3233         pos.ry() = curPos.y;
3234         pos = d_func()->mapFromWS(pos);
3235     } else {
3236         gpos = msg.pt;
3237         pos = mapFromGlobal(QPoint(gpos.x, gpos.y));
3238 
3239         // mouse button pressed
3240         if (!qt_button_down && (type == QEvent::MouseButtonPress || type == QEvent::MouseButtonDblClick)) {
3241             QWidget *tlw = window();
3242             if (QWidget *child = tlw->childAt(mapTo(tlw, pos)))
3243                 qt_button_down = child;
3244             else
3245                 qt_button_down = this;
3246         }
3247     }
3248 
3249     bool res = false;
3250 
3251     bool nonClientAreaEvent = type >= QEvent::NonClientAreaMouseMove
3252                                 && type <= QEvent::NonClientAreaMouseButtonDblClick;
3253 
3254     if (qApp->d_func()->inPopupMode()) {                        // in popup mode
3255 
3256         if (nonClientAreaEvent)
3257             return false;
3258 
3259         replayPopupMouseEvent = false;
3260         QWidget* activePopupWidget = QApplication::activePopupWidget();
3261         QWidget *target = activePopupWidget;
3262         const QPoint globalPos(gpos.x, gpos.y);
3263 
3264         if (target != this) {
3265             if ((windowType() == Qt::Popup) && rect().contains(pos) && 0)
3266                 target = this;
3267             else                                // send to last popup
3268                 pos = target->mapFromGlobal(globalPos);
3269         }
3270         QWidget *popupChild = target->childAt(pos);
3271         bool releaseAfter = false;
3272         switch (type) {
3273             case QEvent::MouseButtonPress:
3274             case QEvent::MouseButtonDblClick:
3275                 popupButtonFocus = popupChild;
3276                 break;
3277             case QEvent::MouseButtonRelease:
3278             case QEvent::TabletRelease:
3279 
3280                 releaseAfter = true;
3281                 break;
3282             default:
3283                 break;                                // nothing for mouse move
3284         }
3285 
3286         if (target->isEnabled()) {
3287             if (popupButtonFocus) {
3288                 target = popupButtonFocus;
3289             } else if (popupChild) {
3290                 target = popupChild;
3291             }
3292 
3293             pos = target->mapFromGlobal(globalPos);
3294                 QMouseEvent e(type, pos, globalPos,
3295                             Qt::MouseButton(button),
3296                             Qt::MouseButtons(state & Qt::MouseButtonMask),
3297                             Qt::KeyboardModifiers(state & Qt::KeyboardModifierMask));
3298                 res = QApplicationPrivate::sendMouseEvent(target, &e, alienWidget, this, &qt_button_down,
3299                                                           qt_last_mouse_receiver);
3300             res = res && e.isAccepted();
3301         } else {
3302             // close disabled popups when a mouse button is pressed or released
3303             switch (type) {
3304             case QEvent::MouseButtonPress:
3305             case QEvent::MouseButtonDblClick:
3306             case QEvent::MouseButtonRelease:
3307                 target->close();
3308                 break;
3309             default:
3310                 break;
3311             }
3312         }
3313 
3314         if (releaseAfter) {
3315             popupButtonFocus = 0;
3316             qt_button_down = 0;
3317         }
3318 
3319 #ifndef Q_OS_WINCE
3320         if (type == QEvent::MouseButtonPress
3321             && QApplication::activePopupWidget() != activePopupWidget
3322             && ptrTrackMouseEvent
3323             && curWin) {
3324             // Since curWin is already the window we clicked on,
3325             // we have to setup the mouse tracking here.
3326             TRACKMOUSEEVENT tme;
3327             tme.cbSize = sizeof(TRACKMOUSEEVENT);
3328             tme.dwFlags = 0x00000002;    // TME_LEAVE
3329             tme.hwndTrack = curWin;      // Track on window receiving msgs
3330             tme.dwHoverTime = (DWORD)-1; // HOVER_DEFAULT
3331             ptrTrackMouseEvent(&tme);
3332         }
3333 #endif
3334         if (type == QEvent::MouseButtonPress
3335             && QApplication::activePopupWidget() != activePopupWidget
3336             && replayPopupMouseEvent) {
3337             // the popup disappeared. Replay the event
3338             QWidget* w = QApplication::widgetAt(gpos.x, gpos.y);
3339             if (w && !QApplicationPrivate::isBlockedByModal(w)) {
3340                 Q_ASSERT(w->testAttribute(Qt::WA_WState_Created));
3341                 HWND hwndTarget = w->effectiveWinId();
3342                 if (QWidget::mouseGrabber() == 0)
3343                     setAutoCapture(hwndTarget);
3344                 if (!w->isActiveWindow())
3345                     w->activateWindow();
3346                 POINT widgetpt = gpos;
3347                 ScreenToClient(hwndTarget, &widgetpt);
3348                 LPARAM lParam = MAKELPARAM(widgetpt.x, widgetpt.y);
3349                 PostMessage(hwndTarget, msg.message, msg.wParam, lParam);
3350             }
3351         } else if (type == QEvent::MouseButtonRelease && button == Qt::RightButton
3352                 && QApplication::activePopupWidget() == activePopupWidget) {
3353             // popup still alive and received right-button-release
3354 #if !defined(QT_NO_CONTEXTMENU)
3355             QContextMenuEvent e2(QContextMenuEvent::Mouse, pos, globalPos,
3356                               qt_win_getKeyboardModifiers());
3357             bool res2 = QApplication::sendSpontaneousEvent( target, &e2 );
3358             if (!res) // RMB not accepted
3359                 res = res2 && e2.isAccepted();
3360 #endif
3361         }
3362     } else {                                        // not popup mode
3363         int bs = state & Qt::MouseButtonMask;
3364         if ((type == QEvent::MouseButtonPress ||
3365               type == QEvent::MouseButtonDblClick) && bs == button) {
3366             Q_ASSERT(testAttribute(Qt::WA_WState_Created));
3367             if (QWidget::mouseGrabber() == 0)
3368                 setAutoCapture(internalWinId());
3369         } else if (type == QEvent::MouseButtonRelease && bs == 0) {
3370             if (QWidget::mouseGrabber() == 0)
3371                 releaseAutoCapture();
3372         }
3373 
3374         const QPoint globalPos(gpos.x,gpos.y);
3375         QWidget *widget = QApplicationPrivate::pickMouseReceiver(this, globalPos, pos, type,
3376                                                                  Qt::MouseButtons(bs),
3377                                                                  qt_button_down, alienWidget);
3378         if (!widget)
3379             return false; // don't send event
3380 
3381         QMouseEvent e(type, pos, globalPos, Qt::MouseButton(button),
3382                       Qt::MouseButtons(state & Qt::MouseButtonMask),
3383                       Qt::KeyboardModifiers(state & Qt::KeyboardModifierMask));
3384 
3385         res = QApplicationPrivate::sendMouseEvent(widget, &e, alienWidget, this, &qt_button_down,
3386                                                   qt_last_mouse_receiver);
3387 
3388         // non client area events are only informational, you cannot "handle" them
3389         res = res && e.isAccepted() && !nonClientAreaEvent;
3390 #if !defined(QT_NO_CONTEXTMENU)
3391         if (type == QEvent::MouseButtonRelease && button == Qt::RightButton) {
3392             QContextMenuEvent e2(QContextMenuEvent::Mouse, pos, globalPos,
3393                               qt_win_getKeyboardModifiers());
3394             bool res2 = QApplication::sendSpontaneousEvent(widget, &e2);
3395             if (!res)
3396                 res = res2 && e2.isAccepted();
3397         }
3398 #endif
3399 
3400         if (type != QEvent::MouseMove)
3401             pos.rx() = pos.ry() = -9999;        // init for move compression
3402     }
3403     return res;
3404 }
3405 
3406 bool QETWidget::translateWheelEvent(const MSG &msg)
3407 {
3408     int  state = 0;
3409 
3410     if (sm_blockUserInput) // block user interaction during session management
3411         return true;
3412 
3413     state = translateButtonState(GET_KEYSTATE_WPARAM(msg.wParam), 0, 0);
3414 
3415     int delta;
3416     if (msg.message == WM_MOUSEWHEEL || msg.message == WM_MOUSEHWHEEL)
3417         delta = (short) HIWORD (msg.wParam);
3418     else
3419         delta = (int) msg.wParam;
3420 
3421     Qt::Orientation orient = (msg.message == WM_MOUSEHWHEEL || state&Qt::AltModifier
3422 #if 0
3423     // disabled for now - Trenton's one-wheel mouse makes trouble...
3424     // "delta" for usual wheels is +-120. +-240 seems to indicate
3425     // the second wheel see more recent MSDN for WM_MOUSEWHEEL
3426 
3427     ( // <- parantheses added to make update happy, remove if the
3428       // #if 0 is removed
3429         || delta == 240 || delta == -240)?Qt::Horizontal:Vertical;
3430     if (delta == 240 || delta == -240)
3431         delta /= 2;
3432 #endif
3433        ) ? Qt::Horizontal : Qt::Vertical;
3434 
3435     // according to the MSDN documentation on WM_MOUSEHWHEEL:
3436     // a positive value indicates that the wheel was rotated to the right;
3437     // a negative value indicates that the wheel was rotated to the left.
3438     // Qt defines this value as the exact opposite, so we have to flip the value!
3439     if (msg.message == WM_MOUSEHWHEEL)
3440         delta = -delta;
3441 
3442     QPoint globalPos;
3443 
3444     globalPos.rx() = (short)LOWORD (msg.lParam);
3445     globalPos.ry() = (short)HIWORD (msg.lParam);
3446 
3447 
3448     // if there is a widget under the mouse and it is not shadowed
3449     // by modality, we send the event to it first
3450     int ret = 0;
3451     QWidget* w = QApplication::widgetAt(globalPos);
3452     if (!w || !qt_try_modal(w, (MSG*)&msg, ret)) {
3453         //synaptics touchpad shows its own widget at this position
3454         //so widgetAt() will fail with that HWND, try child of this widget
3455         w = this->childAt(this->mapFromGlobal(globalPos));
3456         if (!w)
3457             w = this;
3458     }
3459 
3460     // send the event to the widget or its ancestors
3461     {
3462         QWidget* popup = QApplication::activePopupWidget();
3463         if (popup && w->window() != popup)
3464             popup->close();
3465 #ifndef QT_NO_WHEELEVENT
3466         QWheelEvent e(w->mapFromGlobal(globalPos), globalPos, delta,
3467                       Qt::MouseButtons(state & Qt::MouseButtonMask),
3468                       Qt::KeyboardModifier(state & Qt::KeyboardModifierMask), orient);
3469 
3470         if (QApplication::sendSpontaneousEvent(w, &e))
3471 #else
3472         Q_UNUSED(orient);
3473 #endif //QT_NO_WHEELEVENT
3474             return true;
3475     }
3476 
3477     // send the event to the widget that has the focus or its ancestors, if different
3478     if (w != QApplication::focusWidget() && (w = QApplication::focusWidget())) {
3479         QWidget* popup = QApplication::activePopupWidget();
3480         if (popup && w->window() != popup)
3481             popup->close();
3482 #ifndef QT_NO_WHEELEVENT
3483         QWheelEvent e(w->mapFromGlobal(globalPos), globalPos, delta,
3484                       Qt::MouseButtons(state & Qt::MouseButtonMask),
3485                       Qt::KeyboardModifier(state & Qt::KeyboardModifierMask), orient);
3486         if (QApplication::sendSpontaneousEvent(w, &e))
3487 #endif //QT_NO_WHEELEVENT
3488             return true;
3489     }
3490     return false;
3491 }
3492 
3493 
3494 //
3495 // Windows Wintab to QTabletEvent translation
3496 //
3497 
3498 // the following is adapted from the wintab syspress example (public domain)
3499 /* -------------------------------------------------------------------------- */
3500 // Initialize the "static" information of a cursor device (pen, airbrush, etc).
3501 // The QTabletDeviceData is initialized with the data that do not change in time
3502 // (number of button, type of device, etc) but do not initialize the variable data
3503 // (e.g.: pen or eraser)
3504 #ifndef QT_NO_TABLETEVENT
3505 
3506 static void tabletInit(const quint64 uniqueId, const UINT csr_type, HCTX hTab)
3507 {
3508     Q_ASSERT(ptrWTInfo);
3509     Q_ASSERT(ptrWTGet);
3510 
3511     Q_ASSERT(!tCursorInfo()->contains(uniqueId));
3512 
3513     /* browse WinTab's many info items to discover pressure handling. */
3514     AXIS np;
3515     LOGCONTEXT lc;
3516 
3517     /* get the current context for its device variable. */
3518     ptrWTGet(hTab, &lc);
3519 
3520     /* get the size of the pressure axis. */
3521     QTabletDeviceData tdd;
3522     tdd.llId = uniqueId;
3523 
3524     ptrWTInfo(WTI_DEVICES + lc.lcDevice, DVC_NPRESSURE, &np);
3525     tdd.minPressure = int(np.axMin);
3526     tdd.maxPressure = int(np.axMax);
3527 
3528     ptrWTInfo(WTI_DEVICES + lc.lcDevice, DVC_TPRESSURE, &np);
3529     tdd.minTanPressure = int(np.axMin);
3530     tdd.maxTanPressure = int(np.axMax);
3531 
3532     LOGCONTEXT lcMine;
3533 
3534     /* get default region */
3535     ptrWTInfo(WTI_DEFCONTEXT, 0, &lcMine);
3536 
3537     tdd.minX = 0;
3538     tdd.maxX = int(lcMine.lcInExtX) - int(lcMine.lcInOrgX);
3539 
3540     tdd.minY = 0;
3541     tdd.maxY = int(lcMine.lcInExtY) - int(lcMine.lcInOrgY);
3542 
3543     tdd.minZ = 0;
3544     tdd.maxZ = int(lcMine.lcInExtZ) - int(lcMine.lcInOrgZ);
3545 
3546     const uint cursorTypeBitMask = 0x0F06; // bitmask to find the specific cursor type (see Wacom FAQ)
3547     if (((csr_type & 0x0006) == 0x0002) && ((csr_type & cursorTypeBitMask) != 0x0902)) {
3548         tdd.currentDevice = QTabletEvent::Stylus;
3549     } else {
3550         switch (csr_type & cursorTypeBitMask) {
3551             case 0x0802:
3552                 tdd.currentDevice = QTabletEvent::Stylus;
3553                 break;
3554             case 0x0902:
3555                 tdd.currentDevice = QTabletEvent::Airbrush;
3556                 break;
3557             case 0x0004:
3558                 tdd.currentDevice = QTabletEvent::FourDMouse;
3559                 break;
3560             case 0x0006:
3561                 tdd.currentDevice = QTabletEvent::Puck;
3562                 break;
3563             case 0x0804:
3564                 tdd.currentDevice = QTabletEvent::RotationStylus;
3565                 break;
3566             default:
3567                 tdd.currentDevice = QTabletEvent::NoDevice;
3568         }
3569     }
3570     tCursorInfo()->insert(uniqueId, tdd);
3571 }
3572 #endif // QT_NO_TABLETEVENT
3573 
3574 // Update the "dynamic" information of a cursor device (pen, airbrush, etc).
3575 // The dynamic information is the information of QTabletDeviceData that can change
3576 // in time (eraser or pen if a device is turned around).
3577 #ifndef QT_NO_TABLETEVENT
3578 
3579 static void tabletUpdateCursor(QTabletDeviceData &tdd, const UINT currentCursor)
3580 {
3581     switch (currentCursor % 3) { // %3 for dual track
3582     case 0:
3583         tdd.currentPointerType = QTabletEvent::Cursor;
3584         break;
3585     case 1:
3586         tdd.currentPointerType = QTabletEvent::Pen;
3587         break;
3588     case 2:
3589         tdd.currentPointerType = QTabletEvent::Eraser;
3590         break;
3591     default:
3592         tdd.currentPointerType = QTabletEvent::UnknownPointer;
3593     }
3594 }
3595 #endif // QT_NO_TABLETEVENT
3596 
3597 bool QETWidget::translateTabletEvent(const MSG &msg, PACKET *localPacketBuf,
3598                                       int numPackets)
3599 {
3600     Q_UNUSED(msg);
3601     POINT ptNew;
3602     static DWORD btnNew, btnOld, btnChange;
3603     qreal prsNew;
3604     ORIENTATION ort;
3605     static bool button_pressed = false;
3606     int i,
3607         tiltX,
3608         tiltY;
3609     bool sendEvent = false;
3610     QEvent::Type t;
3611     int z = 0;
3612     qreal rotation = 0.0;
3613     qreal tangentialPressure;
3614     // The tablet can be used in 2 different modes, depending on it settings:
3615     // 1) Absolute (pen) mode:
3616     //    The coordinates are scaled to the virtual desktop (by default). The user
3617     //    can also choose to scale to the monitor or a region of the screen.
3618     //    When entering proximity, the tablet driver snaps the mouse pointer to the
3619     //    tablet position scaled to that area and keeps it in sync.
3620     // 2) Relative (mouse) mode:
3621     //    The pen follows the mouse. The constant 'absoluteRange' specifies the
3622     //    manhattanLength difference for detecting if a tablet input device is in this mode,
3623     //    in which case we snap the position to the mouse position.
3624     // It seems there is no way to find out the mode programmatically, the LOGCONTEXT orgX/Y/Ext
3625     // area is always the virtual desktop.
3626     enum { absoluteRange = 20 };
3627 
3628     // the most common event that we get...
3629     t = QEvent::TabletMove;
3630     for (i = 0; i < numPackets; i++) {
3631         // get the unique ID of the device...
3632         btnOld = btnNew;
3633         btnNew = localPacketBuf[i].pkButtons;
3634         btnChange = btnOld ^ btnNew;
3635 
3636         if (btnNew & btnChange) {
3637             button_pressed = true;
3638             t = QEvent::TabletPress;
3639         }
3640         ptNew.x = UINT(localPacketBuf[i].pkX);
3641         ptNew.y = UINT(localPacketBuf[i].pkY);
3642 #ifndef QT_NO_TABLETEVENT
3643         z = (currentTabletPointer.currentDevice == QTabletEvent::FourDMouse) ? UINT(localPacketBuf[i].pkZ) : 0;
3644 #else
3645         Q_UNUSED(z);
3646 #endif // QT_NO_TABLETEVENT
3647         prsNew = 0.0;
3648         QRect desktopArea = QApplication::desktop()->geometry();
3649 
3650         // This code is to delay the tablet data one cycle to sync with the mouse location.
3651         QPointF hiResTabletGlobalPosF = oldHiResTabletGlobalPosF;
3652         oldHiResTabletGlobalPosF =
3653             currentTabletPointer.scaleCoord(ptNew.x, ptNew.y, desktopArea.left(),
3654                                             desktopArea.width(), desktopArea.top(),
3655                                             desktopArea.height());
3656 
3657         if (btnNew) {
3658 #ifndef QT_NO_TABLETEVENT
3659             if (currentTabletPointer.currentPointerType == QTabletEvent::Pen || currentTabletPointer.currentPointerType == QTabletEvent::Eraser)
3660                 prsNew = localPacketBuf[i].pkNormalPressure
3661                             / qreal(currentTabletPointer.maxPressure
3662                                     - currentTabletPointer.minPressure);
3663             else
3664 #endif // QT_NO_TABLETEVENT
3665                 prsNew = 0;
3666         } else if (button_pressed) {
3667             // One button press, should only give one button release
3668             t = QEvent::TabletRelease;
3669             button_pressed = false;
3670         }
3671         QPoint globalPos = hiResTabletGlobalPosF.toPoint();
3672 
3673         // Get Mouse Position and compare to tablet info
3674         // Positions should be almost the same if we are in absolute
3675         //  mode. If they are not, use the mouse location.
3676 #ifndef Q_WS_WINCE
3677         POINT mouseLocationP;
3678         if (GetCursorPos(&mouseLocationP)) {
3679             const QPoint mouseLocation(mouseLocationP.x, mouseLocationP.y);
3680             if ((mouseLocation - globalPos).manhattanLength() > absoluteRange) {
3681                 globalPos = mouseLocation;
3682                 hiResTabletGlobalPosF = globalPos;
3683             }
3684         }
3685 #endif // !Q_WS_WINCE
3686 
3687         if (t == QEvent::TabletPress)
3688         {
3689             qt_button_down = QApplication::widgetAt(globalPos);
3690         }
3691 
3692         // make sure the tablet event get's sent to the proper widget...
3693         QWidget *w = 0;
3694 
3695         if (qt_button_down)
3696             w = qt_button_down; // Pass it to the thing that's grabbed it.
3697         else
3698             w = QApplication::widgetAt(globalPos);
3699 
3700         if (!w)
3701             w = this;
3702 
3703         if (t == QEvent::TabletRelease)
3704         {
3705             if (qt_win_ignoreNextMouseReleaseEvent) {
3706                 qt_win_ignoreNextMouseReleaseEvent = false;
3707                 if (qt_button_down && qt_button_down->internalWinId() == autoCaptureWnd) {
3708                     releaseAutoCapture();
3709                     qt_button_down = 0;
3710                 }
3711             }
3712 
3713         }
3714 
3715         QPoint localPos = w->mapFromGlobal(globalPos);
3716 #ifndef QT_NO_TABLETEVENT
3717         if (currentTabletPointer.currentDevice == QTabletEvent::Airbrush) {
3718             tangentialPressure = localPacketBuf[i].pkTangentPressure
3719                                 / qreal(currentTabletPointer.maxTanPressure
3720                                         - currentTabletPointer.minTanPressure);
3721         } else {
3722             tangentialPressure = 0.0;
3723         }
3724 #else
3725         tangentialPressure = 0.0;
3726 #endif // QT_NO_TABLETEVENT
3727 
3728         if (!qt_tablet_tilt_support) {
3729             tiltX = tiltY = 0;
3730             rotation = 0.0;
3731         } else {
3732             ort = localPacketBuf[i].pkOrientation;
3733             // convert from azimuth and altitude to x tilt and y tilt
3734             // what follows is the optimized version.  Here are the equations
3735             // I used to get to this point (in case things change :)
3736             // X = sin(azimuth) * cos(altitude)
3737             // Y = cos(azimuth) * cos(altitude)
3738             // Z = sin(altitude)
3739             // X Tilt = arctan(X / Z)
3740             // Y Tilt = arctan(Y / Z)
3741             double radAzim = (ort.orAzimuth / 10) * (Q_PI / 180);
3742             //double radAlt = abs(ort.orAltitude / 10) * (Q_PI / 180);
3743             double tanAlt = tan((abs(ort.orAltitude / 10)) * (Q_PI / 180));
3744 
3745             double degX = atan(sin(radAzim) / tanAlt);
3746             double degY = atan(cos(radAzim) / tanAlt);
3747             tiltX = int(degX * (180 / Q_PI));
3748             tiltY = int(-degY * (180 / Q_PI));
3749             rotation = ort.orTwist;
3750         }
3751 #ifndef QT_NO_TABLETEVENT
3752         QTabletEvent e(t, localPos, globalPos, hiResTabletGlobalPosF, currentTabletPointer.currentDevice,
3753                        currentTabletPointer.currentPointerType, prsNew, tiltX, tiltY,
3754                        tangentialPressure, rotation, z, QApplication::keyboardModifiers(), currentTabletPointer.llId);
3755         sendEvent = QApplication::sendSpontaneousEvent(w, &e);
3756 #endif // QT_NO_TABLETEVENT
3757     }
3758     return sendEvent;
3759 }
3760 
3761 extern bool qt_is_gui_used;
3762 
3763 
3764 #ifndef QT_NO_TABLETEVENT
3765 
3766 static void initWinTabFunctions()
3767 {
3768 #if defined(Q_OS_WINCE)
3769     return;
3770 #else
3771     if (!qt_is_gui_used)
3772         return;
3773 
3774     QSystemLibrary library(QLatin1String("wintab32"));
3775     ptrWTInfo = (PtrWTInfo)library.resolve("WTInfoW");
3776     ptrWTGet = (PtrWTGet)library.resolve("WTGetW");
3777     ptrWTEnable = (PtrWTEnable)library.resolve("WTEnable");
3778     ptrWTOverlap = (PtrWTEnable)library.resolve("WTOverlap");
3779     ptrWTPacketsGet = (PtrWTPacketsGet)library.resolve("WTPacketsGet");
3780 #endif // Q_OS_WINCE
3781 }
3782 #endif // QT_NO_TABLETEVENT
3783 
3784 
3785 //
3786 // Paint event translation
3787 //
3788 bool QETWidget::translatePaintEvent(const MSG &msg)
3789 {
3790     if (!isWindow() && testAttribute(Qt::WA_NativeWindow))
3791         Q_ASSERT(internalWinId());
3792 
3793     Q_ASSERT(testAttribute(Qt::WA_WState_Created));
3794     if (!GetUpdateRect(internalWinId(), 0, FALSE)) { // The update bounding rect is invalid
3795         d_func()->hd = 0;
3796         setAttribute(Qt::WA_PendingUpdate, false);
3797         return false;
3798     }
3799 
3800     if (msg.message == WM_ERASEBKGND)
3801         return true;
3802 
3803     setAttribute(Qt::WA_PendingUpdate, false);
3804 
3805     if (d_func()->isGLWidget) {
3806         if (d_func()->usesDoubleBufferedGLContext)
3807             InvalidateRect(internalWinId(), 0, false);
3808     } else {
3809         const QRegion dirtyInBackingStore(qt_dirtyRegion(this));
3810         // Make sure the invalidated region contains the region we're about to repaint.
3811         // BeginPaint will set the clip to the invalidated region and it is impossible
3812         // to enlarge it afterwards (only shrink it). Using GetDCEx is not suffient
3813         // as it may return an invalid context (especially on Windows Vista).
3814         if (!dirtyInBackingStore.isEmpty())
3815             InvalidateRgn(internalWinId(), dirtyInBackingStore.handle(), false);
3816     }
3817     PAINTSTRUCT ps;
3818     d_func()->hd = BeginPaint(internalWinId(), &ps);
3819 
3820     const QRect updateRect(QPoint(ps.rcPaint.left, ps.rcPaint.top),
3821                            QPoint(ps.rcPaint.right, ps.rcPaint.bottom));
3822 
3823     // Mapping region from system to qt (32 bit) coordinate system.
3824     d_func()->syncBackingStore(updateRect.translated(data->wrect.topLeft()));
3825 
3826     d_func()->hd = 0;
3827     EndPaint(internalWinId(), &ps);
3828 
3829     return true;
3830 }
3831 
3832 //
3833 // Window move and resize (configure) events
3834 //
3835 
3836 bool QETWidget::translateConfigEvent(const MSG &msg)
3837 {
3838     if (!testAttribute(Qt::WA_WState_Created))                // in QWidget::create()
3839         return true;
3840     if (testAttribute(Qt::WA_WState_ConfigPending))
3841         return true;
3842     if (testAttribute(Qt::WA_DontShowOnScreen))
3843         return true;
3844     if (!isWindow())
3845         return true;
3846     setAttribute(Qt::WA_WState_ConfigPending);                // set config flag
3847     QRect cr = geometry();
3848     if (msg.message == WM_SIZE) {                // resize event
3849         WORD a = LOWORD(msg.lParam);
3850         WORD b = HIWORD(msg.lParam);
3851         QSize oldSize = size();
3852         QSize newSize(a, b);
3853 #ifdef Q_WS_WINCE_WM
3854         if (isFullScreen() && (oldSize.width() == newSize.height()) && (oldSize.height() == newSize.width()))
3855             qt_wince_hide_taskbar(internalWinId());
3856 #endif
3857         cr.setSize(newSize);
3858         if (msg.wParam != SIZE_MINIMIZED)
3859             data->crect = cr;
3860         if (isWindow()) {                        // update title/icon text
3861             d_func()->createTLExtra();
3862             // Capture SIZE_MINIMIZED without preceding WM_SYSCOMMAND
3863             // (like Windows+M)
3864             if (msg.wParam == SIZE_MINIMIZED && !isMinimized()) {
3865 #ifndef Q_WS_WINCE
3866                 const QString title = windowIconText();
3867                 if (!title.isEmpty())
3868                     d_func()->setWindowTitle_helper(title);
3869 #endif
3870                 data->window_state |= Qt::WindowMinimized;
3871                 if (isVisible()) {
3872                     QHideEvent e;
3873                     QApplication::sendSpontaneousEvent(this, &e);
3874                     hideChildren(true);
3875                 }
3876             } else if (msg.wParam != SIZE_MINIMIZED) {
3877                 bool window_state_changed = false;
3878                 Qt::WindowStates oldstate = Qt::WindowStates(dataPtr()->window_state);
3879                 if (isMinimized()) {
3880 #ifndef Q_WS_WINCE
3881                     const QString title = windowTitle();
3882                     if (!title.isEmpty())
3883                         d_func()->setWindowTitle_helper(title);
3884 #endif
3885                     data->window_state &= ~Qt::WindowMinimized;
3886                     showChildren(true);
3887                     QShowEvent e;
3888                     QApplication::sendSpontaneousEvent(this, &e);
3889                 // Capture SIZE_MAXIMIZED and SIZE_RESTORED without preceding WM_SYSCOMMAND
3890                 // (Aero Snap on Win7)
3891                 } else if (msg.wParam == SIZE_MAXIMIZED && !isMaximized()) {
3892                     data->window_state |= Qt::WindowMaximized;
3893                     window_state_changed = true;
3894                 } else if (msg.wParam == SIZE_RESTORED && isMaximized()) {
3895                     data->window_state &= ~(Qt::WindowMaximized);
3896                     window_state_changed = true;
3897                 }
3898                 if (window_state_changed) {
3899                     QWindowStateChangeEvent e(oldstate);
3900                     QApplication::sendSpontaneousEvent(this, &e);
3901                 }
3902             }
3903         }
3904         if (msg.wParam != SIZE_MINIMIZED && oldSize != newSize) {
3905             if (isVisible()) {
3906                 QTLWExtra *tlwExtra = maybeTopData();
3907                 static bool slowResize = qgetenv("QT_SLOW_TOPLEVEL_RESIZE").toInt();
3908                 const bool hasStaticContents = tlwExtra && tlwExtra->backingStore
3909                                                && tlwExtra->backingStore->hasStaticContents();
3910                 // If we have a backing store with static contents, we have to disable the top-level
3911                 // resize optimization in order to get invalidated regions for resized widgets.
3912                 // The optimization discards all invalidateBuffer() calls since we're going to
3913                 // repaint everything anyways, but that's not the case with static contents.
3914                 if (!slowResize && tlwExtra && !hasStaticContents)
3915                     tlwExtra->inTopLevelResize = true;
3916                 QResizeEvent e(newSize, oldSize);
3917                 QApplication::sendSpontaneousEvent(this, &e);
3918                 if (d_func()->paintOnScreen()) {
3919                     QRegion updateRegion(rect());
3920                     if (testAttribute(Qt::WA_StaticContents))
3921                         updateRegion -= QRect(0, 0, oldSize.width(), oldSize.height());
3922                     d_func()->syncBackingStore(updateRegion);
3923                 } else {
3924                     d_func()->syncBackingStore();
3925                 }
3926                 if (!slowResize && tlwExtra)
3927                     tlwExtra->inTopLevelResize = false;
3928             } else {
3929                 QResizeEvent *e = new QResizeEvent(newSize, oldSize);
3930                 QApplication::postEvent(this, e);
3931             }
3932         }
3933     } else if (msg.message == WM_MOVE) {        // move event
3934         int a = (int) (short) LOWORD(msg.lParam);
3935         int b = (int) (short) HIWORD(msg.lParam);
3936         QPoint oldPos = geometry().topLeft();
3937         QPoint newCPos(a, b);
3938         // Ignore silly Windows move event to wild pos after iconify.
3939 #if !defined(Q_WS_WINCE)
3940         if (!IsIconic(internalWinId()) && newCPos != oldPos) {
3941 #endif
3942             cr.moveTopLeft(newCPos);
3943             data->crect = cr;
3944             if (isVisible()) {
3945                 QMoveEvent e(newCPos, oldPos);  // cpos (client position)
3946                 QApplication::sendSpontaneousEvent(this, &e);
3947             } else {
3948                 QMoveEvent * e = new QMoveEvent(newCPos, oldPos);
3949                 QApplication::postEvent(this, e);
3950             }
3951 #if !defined(Q_WS_WINCE)
3952         }
3953 #endif
3954     }
3955     setAttribute(Qt::WA_WState_ConfigPending, false);                // clear config flag
3956     return true;
3957 }
3958 
3959 
3960 //
3961 // Close window event translation.
3962 //
3963 // This class is a friend of QApplication because it needs to emit the
3964 // lastWindowClosed() signal when the last top level widget is closed.
3965 //
3966 
3967 bool QETWidget::translateCloseEvent(const MSG &)
3968 {
3969     return d_func()->close_helper(QWidgetPrivate::CloseWithSpontaneousEvent);
3970 }
3971 
3972 #ifndef QT_NO_GESTURES
3973 bool QETWidget::translateGestureEvent(const MSG &, const GESTUREINFO &gi)
3974 {
3975     const QPoint widgetPos = QPoint(gi.ptsLocation.x, gi.ptsLocation.y);
3976     QWidget *alienWidget = !internalWinId() ? this : childAt(widgetPos);
3977     if (alienWidget && alienWidget->internalWinId())
3978         alienWidget = 0;
3979     QWidget *widget = alienWidget ? alienWidget : this;
3980 
3981     QNativeGestureEvent event;
3982     event.sequenceId = gi.dwSequenceID;
3983     event.position = QPoint(gi.ptsLocation.x, gi.ptsLocation.y);
3984     event.argument = gi.ullArguments;
3985 
3986     switch (gi.dwID) {
3987     case GID_BEGIN:
3988         event.gestureType = QNativeGestureEvent::GestureBegin;
3989         break;
3990     case GID_END:
3991         event.gestureType = QNativeGestureEvent::GestureEnd;
3992         break;
3993     case GID_ZOOM:
3994         event.gestureType = QNativeGestureEvent::Zoom;
3995         break;
3996     case GID_PAN:
3997         event.gestureType = QNativeGestureEvent::Pan;
3998         break;
3999     case GID_ROTATE:
4000         event.gestureType = QNativeGestureEvent::Rotate;
4001         break;
4002     case GID_TWOFINGERTAP:
4003     case GID_ROLLOVER:
4004     default:
4005         break;
4006     }
4007     if (event.gestureType != QNativeGestureEvent::None)
4008         qt_sendSpontaneousEvent(widget, &event);
4009     return true;
4010 }
4011 #endif // QT_NO_GESTURES
4012 
4013 void  QApplication::setCursorFlashTime(int msecs)
4014 {
4015     SetCaretBlinkTime(msecs / 2);
4016     QApplicationPrivate::cursor_flash_time = msecs;
4017 }
4018 
4019 
4020 int QApplication::cursorFlashTime()
4021 {
4022     int blink = (int)GetCaretBlinkTime();
4023     if (!blink)
4024         return QApplicationPrivate::cursor_flash_time;
4025     if (blink > 0)
4026         return 2*blink;
4027     return 0;
4028 }
4029 
4030 
4031 void QApplication::setDoubleClickInterval(int ms)
4032 {
4033 #ifndef Q_WS_WINCE
4034     SetDoubleClickTime(ms);
4035 #endif
4036     QApplicationPrivate::mouse_double_click_time = ms;
4037 }
4038 
4039 int QApplication::doubleClickInterval()
4040 {
4041     int ms = GetDoubleClickTime();
4042     if (ms != 0)
4043         return ms;
4044     return QApplicationPrivate::mouse_double_click_time;
4045 }
4046 
4047 
4048 void QApplication::setKeyboardInputInterval(int ms)
4049 {
4050     QApplicationPrivate::keyboard_input_time = ms;
4051 }
4052 
4053 int QApplication::keyboardInputInterval()
4054 {
4055     // FIXME: get from the system
4056     return QApplicationPrivate::keyboard_input_time;
4057 }
4058 
4059 #ifndef QT_NO_WHEELEVENT
4060 void QApplication::setWheelScrollLines(int n)
4061 {
4062 #ifdef SPI_SETWHEELSCROLLLINES
4063     if (n < 0)
4064         n = 0;
4065     SystemParametersInfo(SPI_SETWHEELSCROLLLINES, (uint)n, 0, 0);
4066 #else
4067     QApplicationPrivate::wheel_scroll_lines = n;
4068 #endif
4069 }
4070 
4071 int QApplication::wheelScrollLines()
4072 {
4073 #ifdef SPI_GETWHEELSCROLLLINES
4074     uint i = 3;
4075     SystemParametersInfo(SPI_GETWHEELSCROLLLINES, sizeof(uint), &i, 0);
4076     if (i > INT_MAX)
4077         i = INT_MAX;
4078     return i;
4079 #else
4080     return QApplicationPrivate::wheel_scroll_lines;
4081 #endif
4082 }
4083 #endif //QT_NO_WHEELEVENT
4084 
4085 static bool effect_override = false;
4086 
4087 void QApplication::setEffectEnabled(Qt::UIEffect effect, bool enable)
4088 {
4089     effect_override = true;
4090     switch (effect) {
4091     case Qt::UI_AnimateMenu:
4092         QApplicationPrivate::animate_menu = enable;
4093         break;
4094     case Qt::UI_FadeMenu:
4095         QApplicationPrivate::fade_menu = enable;
4096         break;
4097     case Qt::UI_AnimateCombo:
4098         QApplicationPrivate::animate_combo = enable;
4099         break;
4100     case Qt::UI_AnimateTooltip:
4101         QApplicationPrivate::animate_tooltip = enable;
4102         break;
4103     case Qt::UI_FadeTooltip:
4104         QApplicationPrivate::fade_tooltip = enable;
4105         break;
4106     case Qt::UI_AnimateToolBox:
4107         QApplicationPrivate::animate_toolbox = enable;
4108         break;
4109     default:
4110         QApplicationPrivate::animate_ui = enable;
4111         break;
4112     }
4113 }
4114 
4115 bool QApplication::isEffectEnabled(Qt::UIEffect effect)
4116 {
4117     if (QColormap::instance().depth() < 16)
4118         return false;
4119 
4120     if (!effect_override && desktopSettingsAware()) {
4121         // we know that they can be used when we are here
4122         BOOL enabled = false;
4123         UINT api;
4124         switch (effect) {
4125         case Qt::UI_AnimateMenu:
4126             api = SPI_GETMENUANIMATION;
4127             break;
4128         case Qt::UI_FadeMenu:
4129             api = SPI_GETMENUFADE;
4130             break;
4131         case Qt::UI_AnimateCombo:
4132             api = SPI_GETCOMBOBOXANIMATION;
4133             break;
4134         case Qt::UI_AnimateTooltip:
4135             api = SPI_GETTOOLTIPANIMATION;
4136             break;
4137         case Qt::UI_FadeTooltip:
4138             api = SPI_GETTOOLTIPFADE;
4139             break;
4140         default:
4141             api = SPI_GETUIEFFECTS;
4142             break;
4143         }
4144         SystemParametersInfo(api, 0, &enabled, 0);
4145         return enabled;
4146     }
4147 
4148     switch(effect) {
4149     case Qt::UI_AnimateMenu:
4150         return QApplicationPrivate::animate_menu;
4151     case Qt::UI_FadeMenu:
4152         return QApplicationPrivate::fade_menu;
4153     case Qt::UI_AnimateCombo:
4154         return QApplicationPrivate::animate_combo;
4155     case Qt::UI_AnimateTooltip:
4156         return QApplicationPrivate::animate_tooltip;
4157     case Qt::UI_FadeTooltip:
4158         return QApplicationPrivate::fade_tooltip;
4159     case Qt::UI_AnimateToolBox:
4160         return QApplicationPrivate::animate_toolbox;
4161     default:
4162         return QApplicationPrivate::animate_ui;
4163     }
4164 }
4165 
4166 #ifndef QT_NO_SESSIONMANAGER
4167 
4168 bool QSessionManager::allowsInteraction()
4169 {
4170     sm_blockUserInput = false;
4171     return true;
4172 }
4173 
4174 bool QSessionManager::allowsErrorInteraction()
4175 {
4176     sm_blockUserInput = false;
4177     return true;
4178 }
4179 
4180 void QSessionManager::release()
4181 {
4182     if (sm_smActive)
4183         sm_blockUserInput = true;
4184 }
4185 
4186 void QSessionManager::cancel()
4187 {
4188     sm_cancel = true;
4189 }
4190 
4191 #endif //QT_NO_SESSIONMANAGER
4192 
4193 
4194 bool QApplicationPrivate::HasTouchSupport = false;
4195 PtrRegisterTouchWindow QApplicationPrivate::RegisterTouchWindow = 0;
4196 PtrGetTouchInputInfo QApplicationPrivate::GetTouchInputInfo = 0;
4197 PtrCloseTouchInputHandle QApplicationPrivate::CloseTouchInputHandle = 0;
4198 
4199 void QApplicationPrivate::initializeMultitouch_sys()
4200 {
4201     if (QSysInfo::windowsVersion() >= QSysInfo::WV_WINDOWS7
4202         && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)) {
4203         static const int QT_SM_DIGITIZER = 94;
4204         int value = GetSystemMetrics(QT_SM_DIGITIZER);
4205         static const int QT_NID_INTEGRATED_TOUCH = 0x01;
4206         static const int QT_NID_EXTERNAL_TOUCH   = 0x02;
4207         static const int QT_NID_MULTI_INPUT      = 0x40;
4208         QApplicationPrivate::HasTouchSupport =
4209                 value & (QT_NID_INTEGRATED_TOUCH | QT_NID_EXTERNAL_TOUCH | QT_NID_MULTI_INPUT);
4210     }
4211 
4212     QSystemLibrary library(QLatin1String("user32"));
4213     // MinGW (g++ 3.4.5) accepts only C casts.
4214     RegisterTouchWindow = (PtrRegisterTouchWindow)(library.resolve("RegisterTouchWindow"));
4215     GetTouchInputInfo = (PtrGetTouchInputInfo)(library.resolve("GetTouchInputInfo"));
4216     CloseTouchInputHandle = (PtrCloseTouchInputHandle)(library.resolve("CloseTouchInputHandle"));
4217 
4218     touchInputIDToTouchPointID.clear();
4219 }
4220 
4221 void QApplicationPrivate::cleanupMultitouch_sys()
4222 {
4223     touchInputIDToTouchPointID.clear();
4224 }
4225 
4226 bool QApplicationPrivate::translateTouchEvent(const MSG &msg)
4227 {
4228     QWidget *widgetForHwnd = QWidget::find(msg.hwnd);
4229     if (!widgetForHwnd)
4230         return false;
4231 
4232     QRect screenGeometry = QApplication::desktop()->screenGeometry(widgetForHwnd);
4233 
4234     QList<QTouchEvent::TouchPoint> touchPoints;
4235 
4236     QVector<TOUCHINPUT> winTouchInputs(msg.wParam);
4237     memset(winTouchInputs.data(), 0, sizeof(TOUCHINPUT) * winTouchInputs.count());
4238     Qt::TouchPointStates allStates = 0;
4239     QApplicationPrivate::GetTouchInputInfo((HANDLE) msg.lParam, msg.wParam, winTouchInputs.data(), sizeof(TOUCHINPUT));
4240     for (int i = 0; i < winTouchInputs.count(); ++i) {
4241         const TOUCHINPUT &touchInput = winTouchInputs.at(i);
4242 
4243         int touchPointID = touchInputIDToTouchPointID.value(touchInput.dwID, -1);
4244         if (touchPointID == -1) {
4245             touchPointID = touchInputIDToTouchPointID.count();
4246             touchInputIDToTouchPointID.insert(touchInput.dwID, touchPointID);
4247         }
4248 
4249         QTouchEvent::TouchPoint touchPoint(touchPointID);
4250 
4251         // update state
4252         QPointF screenPos(qreal(touchInput.x) / qreal(100.), qreal(touchInput.y) / qreal(100.));
4253         QRectF screenRect;
4254         if (touchInput.dwMask & TOUCHINPUTMASKF_CONTACTAREA)
4255             screenRect.setSize(QSizeF(qreal(touchInput.cxContact) / qreal(100.),
4256                                       qreal(touchInput.cyContact) / qreal(100.)));
4257         screenRect.moveCenter(screenPos);
4258 
4259         Qt::TouchPointStates state;
4260         if (touchInput.dwFlags & TOUCHEVENTF_DOWN) {
4261             state = Qt::TouchPointPressed;
4262         } else if (touchInput.dwFlags & TOUCHEVENTF_UP) {
4263             state = Qt::TouchPointReleased;
4264         } else {
4265             state = (screenPos == touchPoint.screenPos()
4266                      ? Qt::TouchPointStationary
4267                      : Qt::TouchPointMoved);
4268         }
4269         if (touchInput.dwFlags & TOUCHEVENTF_PRIMARY)
4270             state |= Qt::TouchPointPrimary;
4271         touchPoint.setState(state);
4272         touchPoint.setScreenRect(screenRect);
4273         touchPoint.setNormalizedPos(QPointF(screenPos.x() / screenGeometry.width(),
4274                                             screenPos.y() / screenGeometry.height()));
4275 
4276         allStates |= state;
4277 
4278         touchPoints.append(touchPoint);
4279     }
4280     QApplicationPrivate::CloseTouchInputHandle((HANDLE) msg.lParam);
4281 
4282     if ((allStates & Qt::TouchPointStateMask) == Qt::TouchPointReleased) {
4283         // all touch points released, forget the ids we've seen, they may not be reused
4284         touchInputIDToTouchPointID.clear();
4285     }
4286 
4287     translateRawTouchEvent(widgetForHwnd, QTouchEvent::TouchScreen, touchPoints);
4288     return true;
4289 }
4290 
4291 QT_END_NAMESPACE
4292