Suppress QWindowSystemInterface inclusion warnings.
[profile/ivi/qtbase.git] / src / plugins / platforms / xcb / qxcbwindow.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the plugins of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qxcbwindow.h"
43
44 #include <QtDebug>
45 #include <QScreen>
46 #include <QtGui/QIcon>
47 #include <QtGui/QRegion>
48
49 #include "qxcbconnection.h"
50 #include "qxcbscreen.h"
51 #include "qxcbdrag.h"
52 #include "qxcbkeyboard.h"
53 #include "qxcbwmsupport.h"
54 #include "qxcbimage.h"
55
56 #include <qpa/qplatformintegration.h>
57
58 #ifdef XCB_USE_DRI2
59 #include "qdri2context.h"
60 #endif
61
62 // FIXME This workaround can be removed for xcb-icccm > 3.8
63 #define class class_name
64 #include <xcb/xcb_icccm.h>
65 #undef class
66 #include <xcb/xfixes.h>
67
68 // xcb-icccm 3.8 support
69 #ifdef XCB_ICCCM_NUM_WM_SIZE_HINTS_ELEMENTS
70 #define xcb_get_wm_hints_reply xcb_icccm_get_wm_hints_reply
71 #define xcb_get_wm_hints xcb_icccm_get_wm_hints
72 #define xcb_get_wm_hints_unchecked xcb_icccm_get_wm_hints_unchecked
73 #define xcb_set_wm_hints xcb_icccm_set_wm_hints
74 #define xcb_set_wm_normal_hints xcb_icccm_set_wm_normal_hints
75 #define xcb_size_hints_set_base_size xcb_icccm_size_hints_set_base_size
76 #define xcb_size_hints_set_max_size xcb_icccm_size_hints_set_max_size
77 #define xcb_size_hints_set_min_size xcb_icccm_size_hints_set_min_size
78 #define xcb_size_hints_set_position xcb_icccm_size_hints_set_position
79 #define xcb_size_hints_set_resize_inc xcb_icccm_size_hints_set_resize_inc
80 #define xcb_size_hints_set_size xcb_icccm_size_hints_set_size
81 #define xcb_size_hints_set_win_gravity xcb_icccm_size_hints_set_win_gravity
82 #define xcb_wm_hints_set_iconic xcb_icccm_wm_hints_set_iconic
83 #define xcb_wm_hints_set_normal xcb_icccm_wm_hints_set_normal
84 #define xcb_wm_hints_set_input xcb_icccm_wm_hints_set_input
85 #define xcb_wm_hints_t xcb_icccm_wm_hints_t
86 #define XCB_WM_STATE_ICONIC XCB_ICCCM_WM_STATE_ICONIC
87 #define XCB_WM_STATE_WITHDRAWN XCB_ICCCM_WM_STATE_WITHDRAWN
88 #endif
89
90 #include <private/qguiapplication_p.h>
91 #include <private/qwindow_p.h>
92
93 #include <qpa/qplatformbackingstore.h>
94 #include <qpa/qwindowsysteminterface.h>
95
96 #include <stdio.h>
97
98 #ifdef XCB_USE_XLIB
99 #include <X11/Xlib.h>
100 #include <X11/Xutil.h>
101 #ifndef QT_NO_SHAPE
102 #  include <X11/extensions/shape.h>
103 #endif // QT_NO_SHAPE
104 #endif
105
106 #if defined(XCB_USE_XINPUT2_MAEMO) || defined(XCB_USE_XINPUT2)
107 #include <X11/extensions/XInput2.h>
108 #endif
109
110 #if defined(XCB_USE_GLX)
111 #include "qglxintegration.h"
112 #include <QtPlatformSupport/private/qglxconvenience_p.h>
113 #elif defined(XCB_USE_EGL)
114 #include "qxcbeglsurface.h"
115 #include <QtPlatformSupport/private/qeglconvenience_p.h>
116 #include <QtPlatformSupport/private/qxlibeglintegration_p.h>
117 #endif
118
119 #define XCOORD_MAX 16383
120
121 //#ifdef NET_WM_STATE_DEBUG
122
123 QT_BEGIN_NAMESPACE
124
125 // Returns true if we should set WM_TRANSIENT_FOR on \a w
126 static inline bool isTransient(const QWindow *w)
127 {
128     return w->windowType() == Qt::Dialog
129            || w->windowType() == Qt::Sheet
130            || w->windowType() == Qt::Tool
131            || w->windowType() == Qt::SplashScreen
132            || w->windowType() == Qt::ToolTip
133            || w->windowType() == Qt::Drawer
134            || w->windowType() == Qt::Popup;
135 }
136
137 static inline QImage::Format imageFormatForDepth(int depth)
138 {
139     switch (depth) {
140         case 32: return QImage::Format_ARGB32_Premultiplied;
141         case 24: return QImage::Format_RGB32;
142         case 16: return QImage::Format_RGB16;
143         default: return QImage::Format_Invalid;
144     }
145 }
146
147 static inline bool positionIncludesFrame(QWindow *w)
148 {
149     return qt_window_private(w)->positionPolicy == QWindowPrivate::WindowFrameInclusive;
150 }
151
152 QXcbWindow::QXcbWindow(QWindow *window)
153     : QPlatformWindow(window)
154     , m_window(0)
155     , m_syncCounter(0)
156     , m_gravity(XCB_GRAVITY_STATIC)
157     , m_mapped(false)
158     , m_transparent(false)
159     , m_deferredActivation(false)
160     , m_netWmUserTimeWindow(XCB_NONE)
161     , m_dirtyFrameMargins(false)
162 #if defined(XCB_USE_EGL)
163     , m_eglSurface(0)
164 #endif
165     , m_lastWindowStateEvent(-1)
166 {
167     m_screen = static_cast<QXcbScreen *>(window->screen()->handle());
168
169     setConnection(m_screen->connection());
170
171     create();
172 }
173
174 void QXcbWindow::create()
175 {
176     destroy();
177
178     m_deferredExpose = false;
179     m_configureNotifyPending = true;
180     m_windowState = Qt::WindowNoState;
181
182     Qt::WindowType type = window()->windowType();
183
184     if (type == Qt::Desktop) {
185         m_window = m_screen->root();
186         m_depth = m_screen->screen()->root_depth;
187         m_imageFormat = imageFormatForDepth(m_depth);
188         connection()->addWindow(m_window, this);
189         return;
190     }
191
192     // Determine gravity from initial position. Do not change
193     // later as it will cause the window to move uncontrollably.
194     m_gravity = positionIncludesFrame(window()) ?
195                 XCB_GRAVITY_NORTH_WEST : XCB_GRAVITY_STATIC;
196
197     const quint32 mask = XCB_CW_BACK_PIXMAP | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_SAVE_UNDER | XCB_CW_EVENT_MASK;
198     const quint32 values[] = {
199         // XCB_CW_BACK_PIXMAP
200         XCB_NONE,
201         // XCB_CW_OVERRIDE_REDIRECT
202         type == Qt::Popup || type == Qt::ToolTip,
203         // XCB_CW_SAVE_UNDER
204         type == Qt::Popup || type == Qt::Tool || type == Qt::SplashScreen || type == Qt::ToolTip || type == Qt::Drawer,
205         // XCB_CW_EVENT_MASK
206         XCB_EVENT_MASK_EXPOSURE
207         | XCB_EVENT_MASK_STRUCTURE_NOTIFY
208         | XCB_EVENT_MASK_KEY_PRESS
209         | XCB_EVENT_MASK_KEY_RELEASE
210         | XCB_EVENT_MASK_BUTTON_PRESS
211         | XCB_EVENT_MASK_BUTTON_RELEASE
212         | XCB_EVENT_MASK_BUTTON_MOTION
213         | XCB_EVENT_MASK_ENTER_WINDOW
214         | XCB_EVENT_MASK_LEAVE_WINDOW
215         | XCB_EVENT_MASK_POINTER_MOTION
216         | XCB_EVENT_MASK_PROPERTY_CHANGE
217         | XCB_EVENT_MASK_FOCUS_CHANGE
218     };
219
220     // Parameters to XCreateWindow() are frame corner + inner size.
221     // This fits in case position policy is frame inclusive. There is
222     // currently no way to implement it for frame-exclusive geometries.
223     QRect rect = window()->geometry();
224     QPlatformWindow::setGeometry(rect);
225
226     rect.setWidth(qBound(1, rect.width(), XCOORD_MAX));
227     rect.setHeight(qBound(1, rect.height(), XCOORD_MAX));
228
229     xcb_window_t xcb_parent_id = m_screen->root();
230     if (parent())
231         xcb_parent_id = static_cast<QXcbWindow *>(parent())->xcb_window();
232
233     m_format = window()->requestedFormat();
234
235 #if (defined(XCB_USE_GLX) || defined(XCB_USE_EGL)) && defined(XCB_USE_XLIB)
236     if (QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::OpenGL)
237         || m_format.hasAlpha())
238     {
239 #if defined(XCB_USE_GLX)
240         XVisualInfo *visualInfo = qglx_findVisualInfo(DISPLAY_FROM_XCB(m_screen), m_screen->screenNumber(), &m_format);
241         if (!visualInfo)
242             qFatal("Could not initialize GLX");
243 #elif defined(XCB_USE_EGL)
244         EGLDisplay eglDisplay = connection()->egl_display();
245         EGLConfig eglConfig = q_configFromGLFormat(eglDisplay, m_format, true);
246         m_format = q_glFormatFromConfig(eglDisplay, eglConfig);
247
248         VisualID id = QXlibEglIntegration::getCompatibleVisualId(DISPLAY_FROM_XCB(this), eglDisplay, eglConfig);
249
250         XVisualInfo visualInfoTemplate;
251         memset(&visualInfoTemplate, 0, sizeof(XVisualInfo));
252         visualInfoTemplate.visualid = id;
253
254         XVisualInfo *visualInfo;
255         int matchingCount = 0;
256         visualInfo = XGetVisualInfo(DISPLAY_FROM_XCB(this), VisualIDMask, &visualInfoTemplate, &matchingCount);
257         if (!visualInfo)
258             qFatal("Could not initialize EGL");
259 #endif //XCB_USE_GLX
260         m_depth = visualInfo->depth;
261         m_imageFormat = imageFormatForDepth(m_depth);
262         Colormap cmap = XCreateColormap(DISPLAY_FROM_XCB(this), xcb_parent_id, visualInfo->visual, AllocNone);
263
264         XSetWindowAttributes a;
265         a.background_pixel = WhitePixel(DISPLAY_FROM_XCB(this), m_screen->screenNumber());
266         a.border_pixel = BlackPixel(DISPLAY_FROM_XCB(this), m_screen->screenNumber());
267         a.colormap = cmap;
268
269         m_visualId = visualInfo->visualid;
270
271         m_window = XCreateWindow(DISPLAY_FROM_XCB(this), xcb_parent_id, rect.x(), rect.y(), rect.width(), rect.height(),
272                                   0, visualInfo->depth, InputOutput, visualInfo->visual,
273                                   CWBackPixel|CWBorderPixel|CWColormap, &a);
274
275         XFree(visualInfo);
276     } else
277 #endif //defined(XCB_USE_GLX) || defined(XCB_USE_EGL)
278     {
279         m_window = xcb_generate_id(xcb_connection());
280         m_depth = m_screen->screen()->root_depth;
281         m_imageFormat = imageFormatForDepth(m_depth);
282         m_visualId = m_screen->screen()->root_visual;
283
284         Q_XCB_CALL(xcb_create_window(xcb_connection(),
285                                      XCB_COPY_FROM_PARENT,            // depth -- same as root
286                                      m_window,                        // window id
287                                      xcb_parent_id,                   // parent window id
288                                      rect.x(),
289                                      rect.y(),
290                                      rect.width(),
291                                      rect.height(),
292                                      0,                               // border width
293                                      XCB_WINDOW_CLASS_INPUT_OUTPUT,   // window class
294                                      m_visualId,                      // visual
295                                      0,                               // value mask
296                                      0));                             // value list
297     }
298
299     connection()->addWindow(m_window, this);
300
301     Q_XCB_CALL(xcb_change_window_attributes(xcb_connection(), m_window, mask, values));
302
303     propagateSizeHints();
304
305     xcb_atom_t properties[4];
306     int propertyCount = 0;
307     properties[propertyCount++] = atom(QXcbAtom::WM_DELETE_WINDOW);
308     properties[propertyCount++] = atom(QXcbAtom::WM_TAKE_FOCUS);
309     properties[propertyCount++] = atom(QXcbAtom::_NET_WM_PING);
310
311     if (m_screen->syncRequestSupported())
312         properties[propertyCount++] = atom(QXcbAtom::_NET_WM_SYNC_REQUEST);
313
314     if (window()->windowFlags() & Qt::WindowContextHelpButtonHint)
315         properties[propertyCount++] = atom(QXcbAtom::_NET_WM_CONTEXT_HELP);
316
317     Q_XCB_CALL(xcb_change_property(xcb_connection(),
318                                    XCB_PROP_MODE_REPLACE,
319                                    m_window,
320                                    atom(QXcbAtom::WM_PROTOCOLS),
321                                    XCB_ATOM_ATOM,
322                                    32,
323                                    propertyCount,
324                                    properties));
325     m_syncValue.hi = 0;
326     m_syncValue.lo = 0;
327
328     if (m_screen->syncRequestSupported()) {
329         m_syncCounter = xcb_generate_id(xcb_connection());
330         Q_XCB_CALL(xcb_sync_create_counter(xcb_connection(), m_syncCounter, m_syncValue));
331
332         Q_XCB_CALL(xcb_change_property(xcb_connection(),
333                                        XCB_PROP_MODE_REPLACE,
334                                        m_window,
335                                        atom(QXcbAtom::_NET_WM_SYNC_REQUEST_COUNTER),
336                                        XCB_ATOM_CARDINAL,
337                                        32,
338                                        1,
339                                        &m_syncCounter));
340     }
341
342     // set the PID to let the WM kill the application if unresponsive
343     long pid = getpid();
344     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
345                                    atom(QXcbAtom::_NET_WM_PID), XCB_ATOM_CARDINAL, 32,
346                                    1, &pid));
347
348     xcb_wm_hints_t hints;
349     memset(&hints, 0, sizeof(hints));
350     xcb_wm_hints_set_normal(&hints);
351
352     xcb_wm_hints_set_input(&hints, !(window()->windowFlags() & Qt::WindowDoesNotAcceptFocus));
353
354     xcb_set_wm_hints(xcb_connection(), m_window, &hints);
355
356     xcb_window_t leader = m_screen->clientLeader();
357     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
358                                    atom(QXcbAtom::WM_CLIENT_LEADER), XCB_ATOM_WINDOW, 32,
359                                    1, &leader));
360
361 #ifdef XCB_USE_XINPUT2_MAEMO
362     if (connection()->isUsingXInput2Maemo()) {
363         XIEventMask xieventmask;
364         uchar bitmask[2] = { 0, 0 };
365
366         xieventmask.deviceid = XIAllMasterDevices;
367         xieventmask.mask = bitmask;
368         xieventmask.mask_len = sizeof(bitmask);
369
370         XISetMask(bitmask, XI_ButtonPress);
371         XISetMask(bitmask, XI_ButtonRelease);
372         XISetMask(bitmask, XI_Motion);
373
374         XISelectEvents(DISPLAY_FROM_XCB(this), m_window, &xieventmask, 1);
375     }
376 #elif defined(XCB_USE_XINPUT2)
377     connection()->xi2Select(m_window);
378 #endif
379
380     setWindowFlags(window()->windowFlags());
381     setWindowTitle(window()->windowTitle());
382     setWindowState(window()->windowState());
383
384     if (window()->windowFlags() & Qt::WindowTransparentForInput)
385         setTransparentForMouseEvents(true);
386
387 #ifndef QT_NO_DRAGANDDROP
388     connection()->drag()->dndEnable(this, true);
389 #endif
390 }
391
392 QXcbWindow::~QXcbWindow()
393 {
394     destroy();
395 }
396
397 void QXcbWindow::destroy()
398 {
399     if (m_syncCounter && m_screen->syncRequestSupported())
400         Q_XCB_CALL(xcb_sync_destroy_counter(xcb_connection(), m_syncCounter));
401     if (m_window) {
402         if (m_netWmUserTimeWindow) {
403             xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW));
404             // Some window managers, like metacity, do XSelectInput on the _NET_WM_USER_TIME_WINDOW window,
405             // without trapping BadWindow (which crashes when the user time window is destroyed).
406             connection()->sync();
407             xcb_destroy_window(xcb_connection(), m_netWmUserTimeWindow);
408             m_netWmUserTimeWindow = XCB_NONE;
409         }
410         connection()->removeWindow(m_window);
411         Q_XCB_CALL(xcb_destroy_window(xcb_connection(), m_window));
412     }
413     m_mapped = false;
414
415 #if defined(XCB_USE_EGL)
416     delete m_eglSurface;
417     m_eglSurface = 0;
418 #endif
419 }
420
421 void QXcbWindow::setGeometry(const QRect &rect)
422 {
423     QPlatformWindow::setGeometry(rect);
424
425     propagateSizeHints();
426     const QRect wmGeometry = windowToWmGeometry(rect);
427
428     const quint32 mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y | XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
429     const qint32 values[] = {
430         qBound<qint32>(-XCOORD_MAX, wmGeometry.x(),      XCOORD_MAX),
431         qBound<qint32>(-XCOORD_MAX, wmGeometry.y(),      XCOORD_MAX),
432         qBound<qint32>(1,           wmGeometry.width(),  XCOORD_MAX),
433         qBound<qint32>(1,           wmGeometry.height(), XCOORD_MAX),
434     };
435
436     Q_XCB_CALL(xcb_configure_window(xcb_connection(), m_window, mask, reinterpret_cast<const quint32*>(values)));
437
438     xcb_flush(xcb_connection());
439 }
440
441 QMargins QXcbWindow::frameMargins() const
442 {
443     if (m_dirtyFrameMargins) {
444         xcb_window_t window = m_window;
445         xcb_window_t parent = m_window;
446
447         bool foundRoot = false;
448
449         const QVector<xcb_window_t> &virtualRoots =
450             connection()->wmSupport()->virtualRoots();
451
452         while (!foundRoot) {
453             xcb_query_tree_cookie_t cookie = xcb_query_tree_unchecked(xcb_connection(), parent);
454
455             xcb_query_tree_reply_t *reply = xcb_query_tree_reply(xcb_connection(), cookie, NULL);
456             if (reply) {
457                 if (reply->root == reply->parent || virtualRoots.indexOf(reply->parent) != -1) {
458                     foundRoot = true;
459                 } else {
460                     window = parent;
461                     parent = reply->parent;
462                 }
463
464                 free(reply);
465             } else {
466                 m_dirtyFrameMargins = false;
467                 m_frameMargins = QMargins();
468                 return m_frameMargins;
469             }
470         }
471
472         QPoint offset;
473
474         xcb_translate_coordinates_reply_t *reply =
475             xcb_translate_coordinates_reply(
476                 xcb_connection(),
477                 xcb_translate_coordinates(xcb_connection(), window, parent, 0, 0),
478                 NULL);
479
480         if (reply) {
481             offset = QPoint(reply->dst_x, reply->dst_y);
482             free(reply);
483         }
484
485         xcb_get_geometry_reply_t *geom =
486             xcb_get_geometry_reply(
487                 xcb_connection(),
488                 xcb_get_geometry(xcb_connection(), parent),
489                 NULL);
490
491         if (geom) {
492             // --
493             // add the border_width for the window managers frame... some window managers
494             // do not use a border_width of zero for their frames, and if we the left and
495             // top strut, we ensure that pos() is absolutely correct.  frameGeometry()
496             // will still be incorrect though... perhaps i should have foffset as well, to
497             // indicate the frame offset (equal to the border_width on X).
498             // - Brad
499             // -- copied from qwidget_x11.cpp
500
501             int left = offset.x() + geom->border_width;
502             int top = offset.y() + geom->border_width;
503             int right = geom->width + geom->border_width - geometry().width() - offset.x();
504             int bottom = geom->height + geom->border_width - geometry().height() - offset.y();
505
506             m_frameMargins = QMargins(left, top, right, bottom);
507
508             free(geom);
509         }
510
511         m_dirtyFrameMargins = false;
512     }
513
514     return m_frameMargins;
515 }
516
517 void QXcbWindow::setVisible(bool visible)
518 {
519     if (visible)
520         show();
521     else
522         hide();
523 }
524
525 void QXcbWindow::show()
526 {
527     if (window()->isTopLevel()) {
528         xcb_get_property_cookie_t cookie = xcb_get_wm_hints_unchecked(xcb_connection(), m_window);
529
530         xcb_wm_hints_t hints;
531         xcb_get_wm_hints_reply(xcb_connection(), cookie, &hints, NULL);
532
533         if (window()->windowState() & Qt::WindowMinimized)
534             xcb_wm_hints_set_iconic(&hints);
535         else
536             xcb_wm_hints_set_normal(&hints);
537
538         xcb_wm_hints_set_input(&hints, !(window()->windowFlags() & Qt::WindowDoesNotAcceptFocus));
539
540         xcb_set_wm_hints(xcb_connection(), m_window, &hints);
541
542         // update WM_NORMAL_HINTS
543         propagateSizeHints();
544
545         // update WM_TRANSIENT_FOR
546         if (window()->transientParent() && isTransient(window())) {
547             QXcbWindow *transientXcbParent = static_cast<QXcbWindow *>(window()->transientParent()->handle());
548             if (transientXcbParent) {
549                 // ICCCM 4.1.2.6
550                 xcb_window_t parentWindow = transientXcbParent->xcb_window();
551
552                 // todo: set transient for group (wm_client_leader) if no parent, a la qwidget_x11.cpp
553                 Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
554                                                XCB_ATOM_WM_TRANSIENT_FOR, XCB_ATOM_WINDOW, 32,
555                                                1, &parentWindow));
556             }
557         }
558
559         // update _MOTIF_WM_HINTS
560         updateMotifWmHintsBeforeMap();
561
562         // update _NET_WM_STATE
563         updateNetWmStateBeforeMap();
564     }
565
566     if (connection()->time() != XCB_TIME_CURRENT_TIME)
567         updateNetWmUserTime(connection()->time());
568
569     Q_XCB_CALL(xcb_map_window(xcb_connection(), m_window));
570     xcb_flush(xcb_connection());
571
572     connection()->sync();
573 }
574
575 void QXcbWindow::hide()
576 {
577     Q_XCB_CALL(xcb_unmap_window(xcb_connection(), m_window));
578
579     // send synthetic UnmapNotify event according to icccm 4.1.4
580     xcb_unmap_notify_event_t event;
581     event.response_type = XCB_UNMAP_NOTIFY;
582     event.event = m_screen->root();
583     event.window = m_window;
584     event.from_configure = false;
585     Q_XCB_CALL(xcb_send_event(xcb_connection(), false, m_screen->root(),
586                               XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (const char *)&event));
587
588     xcb_flush(xcb_connection());
589
590     m_mapped = false;
591 }
592
593 struct QtMotifWmHints {
594     quint32 flags, functions, decorations;
595     qint32 input_mode;
596     quint32 status;
597 };
598
599 enum {
600     MWM_HINTS_FUNCTIONS   = (1L << 0),
601
602     MWM_FUNC_ALL      = (1L << 0),
603     MWM_FUNC_RESIZE   = (1L << 1),
604     MWM_FUNC_MOVE     = (1L << 2),
605     MWM_FUNC_MINIMIZE = (1L << 3),
606     MWM_FUNC_MAXIMIZE = (1L << 4),
607     MWM_FUNC_CLOSE    = (1L << 5),
608
609     MWM_HINTS_DECORATIONS = (1L << 1),
610
611     MWM_DECOR_ALL      = (1L << 0),
612     MWM_DECOR_BORDER   = (1L << 1),
613     MWM_DECOR_RESIZEH  = (1L << 2),
614     MWM_DECOR_TITLE    = (1L << 3),
615     MWM_DECOR_MENU     = (1L << 4),
616     MWM_DECOR_MINIMIZE = (1L << 5),
617     MWM_DECOR_MAXIMIZE = (1L << 6),
618
619     MWM_HINTS_INPUT_MODE = (1L << 2),
620
621     MWM_INPUT_MODELESS                  = 0L,
622     MWM_INPUT_PRIMARY_APPLICATION_MODAL = 1L,
623     MWM_INPUT_FULL_APPLICATION_MODAL    = 3L
624 };
625
626 static QtMotifWmHints getMotifWmHints(QXcbConnection *c, xcb_window_t window)
627 {
628     QtMotifWmHints hints;
629
630     xcb_get_property_cookie_t get_cookie =
631         xcb_get_property_unchecked(c->xcb_connection(), 0, window, c->atom(QXcbAtom::_MOTIF_WM_HINTS),
632                          c->atom(QXcbAtom::_MOTIF_WM_HINTS), 0, 20);
633
634     xcb_get_property_reply_t *reply =
635         xcb_get_property_reply(c->xcb_connection(), get_cookie, NULL);
636
637     if (reply && reply->format == 32 && reply->type == c->atom(QXcbAtom::_MOTIF_WM_HINTS)) {
638         hints = *((QtMotifWmHints *)xcb_get_property_value(reply));
639     } else {
640         hints.flags = 0L;
641         hints.functions = MWM_FUNC_ALL;
642         hints.decorations = MWM_DECOR_ALL;
643         hints.input_mode = 0L;
644         hints.status = 0L;
645     }
646
647     free(reply);
648
649     return hints;
650 }
651
652 static void setMotifWmHints(QXcbConnection *c, xcb_window_t window, const QtMotifWmHints &hints)
653 {
654     if (hints.flags != 0l) {
655         Q_XCB_CALL2(xcb_change_property(c->xcb_connection(),
656                                        XCB_PROP_MODE_REPLACE,
657                                        window,
658                                        c->atom(QXcbAtom::_MOTIF_WM_HINTS),
659                                        c->atom(QXcbAtom::_MOTIF_WM_HINTS),
660                                        32,
661                                        5,
662                                        &hints), c);
663     } else {
664         Q_XCB_CALL2(xcb_delete_property(c->xcb_connection(), window, c->atom(QXcbAtom::_MOTIF_WM_HINTS)), c);
665     }
666 }
667
668 QXcbWindow::NetWmStates QXcbWindow::netWmStates()
669 {
670     NetWmStates result(0);
671
672     xcb_get_property_cookie_t get_cookie =
673         xcb_get_property_unchecked(xcb_connection(), 0, m_window, atom(QXcbAtom::_NET_WM_STATE),
674                          XCB_ATOM_ATOM, 0, 1024);
675
676     xcb_get_property_reply_t *reply =
677         xcb_get_property_reply(xcb_connection(), get_cookie, NULL);
678
679     if (reply && reply->format == 32 && reply->type == XCB_ATOM_ATOM) {
680         const xcb_atom_t *states = static_cast<const xcb_atom_t *>(xcb_get_property_value(reply));
681         const xcb_atom_t *statesEnd = states + reply->length;
682         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_ABOVE)))
683             result |= NetWmStateAbove;
684         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_BELOW)))
685             result |= NetWmStateBelow;
686         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN)))
687             result |= NetWmStateFullScreen;
688         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ)))
689             result |= NetWmStateMaximizedHorz;
690         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT)))
691             result |= NetWmStateMaximizedVert;
692         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_MODAL)))
693             result |= NetWmStateModal;
694         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_STAYS_ON_TOP)))
695             result |= NetWmStateStaysOnTop;
696         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_DEMANDS_ATTENTION)))
697             result |= NetWmStateDemandsAttention;
698         free(reply);
699     } else {
700 #ifdef NET_WM_STATE_DEBUG
701         printf("getting net wm state (%x), empty\n", m_window);
702 #endif
703     }
704
705     return result;
706 }
707
708 void QXcbWindow::setNetWmStates(NetWmStates states)
709 {
710     QVector<xcb_atom_t> atoms;
711     if (states & NetWmStateAbove)
712         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_ABOVE));
713     if (states & NetWmStateBelow)
714         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_BELOW));
715     if (states & NetWmStateFullScreen)
716         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
717     if (states & NetWmStateMaximizedHorz)
718         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ));
719     if (states & NetWmStateMaximizedVert)
720         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
721     if (states & NetWmStateModal)
722         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_MODAL));
723     if (states & NetWmStateStaysOnTop)
724         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_STAYS_ON_TOP));
725     if (states & NetWmStateDemandsAttention)
726         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_DEMANDS_ATTENTION));
727
728     if (atoms.isEmpty()) {
729         Q_XCB_CALL(xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_STATE)));
730     } else {
731         Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
732                                        atom(QXcbAtom::_NET_WM_STATE), XCB_ATOM_ATOM, 32,
733                                        atoms.count(), atoms.constData()));
734     }
735     xcb_flush(xcb_connection());
736 }
737
738 Qt::WindowFlags QXcbWindow::setWindowFlags(Qt::WindowFlags flags)
739 {
740     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
741
742     if (type == Qt::ToolTip)
743         flags |= Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint;
744     if (type == Qt::Popup)
745         flags |= Qt::X11BypassWindowManagerHint;
746
747     if (flags & Qt::WindowTransparentForInput) {
748         uint32_t mask = XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_VISIBILITY_CHANGE
749                  | XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_RESIZE_REDIRECT
750                 | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT
751                 | XCB_EVENT_MASK_FOCUS_CHANGE  | XCB_EVENT_MASK_PROPERTY_CHANGE
752                 | XCB_EVENT_MASK_COLOR_MAP_CHANGE | XCB_EVENT_MASK_OWNER_GRAB_BUTTON;
753         xcb_change_window_attributes(xcb_connection(), xcb_window(), XCB_CW_EVENT_MASK, &mask);
754     }
755
756     setNetWmWindowFlags(flags);
757     setMotifWindowFlags(flags);
758
759     setTransparentForMouseEvents(flags & Qt::WindowTransparentForInput);
760     updateDoesNotAcceptFocus(flags & Qt::WindowDoesNotAcceptFocus);
761
762     return flags;
763 }
764
765 void QXcbWindow::setMotifWindowFlags(Qt::WindowFlags flags)
766 {
767     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
768
769     QtMotifWmHints mwmhints;
770     mwmhints.flags = 0L;
771     mwmhints.functions = 0L;
772     mwmhints.decorations = 0;
773     mwmhints.input_mode = 0L;
774     mwmhints.status = 0L;
775
776     if (type != Qt::SplashScreen) {
777         mwmhints.flags |= MWM_HINTS_DECORATIONS;
778
779         bool customize = flags & Qt::CustomizeWindowHint;
780         if (!(flags & Qt::FramelessWindowHint) && !(customize && !(flags & Qt::WindowTitleHint))) {
781             mwmhints.decorations |= MWM_DECOR_BORDER;
782             mwmhints.decorations |= MWM_DECOR_RESIZEH;
783
784             if (flags & Qt::WindowTitleHint)
785                 mwmhints.decorations |= MWM_DECOR_TITLE;
786
787             if (flags & Qt::WindowSystemMenuHint)
788                 mwmhints.decorations |= MWM_DECOR_MENU;
789
790             if (flags & Qt::WindowMinimizeButtonHint) {
791                 mwmhints.decorations |= MWM_DECOR_MINIMIZE;
792                 mwmhints.functions |= MWM_FUNC_MINIMIZE;
793             }
794
795             if (flags & Qt::WindowMaximizeButtonHint) {
796                 mwmhints.decorations |= MWM_DECOR_MAXIMIZE;
797                 mwmhints.functions |= MWM_FUNC_MAXIMIZE;
798             }
799
800             if (flags & Qt::WindowCloseButtonHint)
801                 mwmhints.functions |= MWM_FUNC_CLOSE;
802         }
803     } else {
804         // if type == Qt::SplashScreen
805         mwmhints.decorations = MWM_DECOR_ALL;
806     }
807
808     if (mwmhints.functions != 0) {
809         mwmhints.flags |= MWM_HINTS_FUNCTIONS;
810         mwmhints.functions |= MWM_FUNC_MOVE | MWM_FUNC_RESIZE;
811     } else {
812         mwmhints.functions = MWM_FUNC_ALL;
813     }
814
815     if (!(flags & Qt::FramelessWindowHint)
816         && flags & Qt::CustomizeWindowHint
817         && flags & Qt::WindowTitleHint
818         && !(flags &
819              (Qt::WindowMinimizeButtonHint
820               | Qt::WindowMaximizeButtonHint
821               | Qt::WindowCloseButtonHint)))
822     {
823         // a special case - only the titlebar without any button
824         mwmhints.flags = MWM_HINTS_FUNCTIONS;
825         mwmhints.functions = MWM_FUNC_MOVE | MWM_FUNC_RESIZE;
826         mwmhints.decorations = 0;
827     }
828
829     setMotifWmHints(connection(), m_window, mwmhints);
830 }
831
832 void QXcbWindow::changeNetWmState(bool set, xcb_atom_t one, xcb_atom_t two)
833 {
834     xcb_client_message_event_t event;
835
836     event.response_type = XCB_CLIENT_MESSAGE;
837     event.format = 32;
838     event.window = m_window;
839     event.type = atom(QXcbAtom::_NET_WM_STATE);
840     event.data.data32[0] = set ? 1 : 0;
841     event.data.data32[1] = one;
842     event.data.data32[2] = two;
843     event.data.data32[3] = 0;
844     event.data.data32[4] = 0;
845
846     Q_XCB_CALL(xcb_send_event(xcb_connection(), 0, m_screen->root(), XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (const char *)&event));
847 }
848
849 Qt::WindowState QXcbWindow::setWindowState(Qt::WindowState state)
850 {
851     if (state == m_windowState)
852         return state;
853
854     // unset old state
855     switch (m_windowState) {
856     case Qt::WindowMinimized:
857         Q_XCB_CALL(xcb_map_window(xcb_connection(), m_window));
858         break;
859     case Qt::WindowMaximized:
860         changeNetWmState(false,
861                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ),
862                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
863         break;
864     case Qt::WindowFullScreen:
865         changeNetWmState(false, atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
866         break;
867     default:
868         break;
869     }
870
871     // set new state
872     switch (state) {
873     case Qt::WindowMinimized:
874         {
875             xcb_client_message_event_t event;
876
877             event.response_type = XCB_CLIENT_MESSAGE;
878             event.format = 32;
879             event.window = m_window;
880             event.type = atom(QXcbAtom::WM_CHANGE_STATE);
881             event.data.data32[0] = XCB_WM_STATE_ICONIC;
882             event.data.data32[1] = 0;
883             event.data.data32[2] = 0;
884             event.data.data32[3] = 0;
885             event.data.data32[4] = 0;
886
887             Q_XCB_CALL(xcb_send_event(xcb_connection(), 0, m_screen->root(), XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (const char *)&event));
888         }
889         break;
890     case Qt::WindowMaximized:
891         changeNetWmState(true,
892                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ),
893                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
894         break;
895     case Qt::WindowFullScreen:
896         changeNetWmState(true, atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
897         break;
898     case Qt::WindowNoState:
899         break;
900     default:
901         break;
902     }
903
904     connection()->sync();
905
906     m_windowState = state;
907     return m_windowState;
908 }
909
910 void QXcbWindow::setNetWmWindowFlags(Qt::WindowFlags flags)
911 {
912     // in order of decreasing priority
913     QVector<uint> windowTypes;
914
915     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
916
917     switch (type) {
918     case Qt::Dialog:
919     case Qt::Sheet:
920         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_DIALOG));
921         break;
922     case Qt::Tool:
923     case Qt::Drawer:
924         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_UTILITY));
925         break;
926     case Qt::ToolTip:
927         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_TOOLTIP));
928         break;
929     case Qt::SplashScreen:
930         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_SPLASH));
931         break;
932     default:
933         break;
934     }
935
936     if (flags & Qt::FramelessWindowHint)
937         windowTypes.append(atom(QXcbAtom::_KDE_NET_WM_WINDOW_TYPE_OVERRIDE));
938
939     windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_NORMAL));
940
941     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
942                                    atom(QXcbAtom::_NET_WM_WINDOW_TYPE), XCB_ATOM_ATOM, 32,
943                                    windowTypes.count(), windowTypes.constData()));
944 }
945
946 void QXcbWindow::updateMotifWmHintsBeforeMap()
947 {
948     QtMotifWmHints mwmhints = getMotifWmHints(connection(), m_window);
949
950     if (window()->windowModality() != Qt::NonModal) {
951         switch (window()->windowModality()) {
952         case Qt::WindowModal:
953             mwmhints.input_mode = MWM_INPUT_PRIMARY_APPLICATION_MODAL;
954             break;
955         case Qt::ApplicationModal:
956         default:
957             mwmhints.input_mode = MWM_INPUT_FULL_APPLICATION_MODAL;
958             break;
959         }
960         mwmhints.flags |= MWM_HINTS_INPUT_MODE;
961     } else {
962         mwmhints.input_mode = MWM_INPUT_MODELESS;
963         mwmhints.flags &= ~MWM_HINTS_INPUT_MODE;
964     }
965
966     if (window()->minimumSize() == window()->maximumSize()) {
967         // fixed size, remove the resize handle (since mwm/dtwm
968         // isn't smart enough to do it itself)
969         mwmhints.flags |= MWM_HINTS_FUNCTIONS;
970         if (mwmhints.functions == MWM_FUNC_ALL) {
971             mwmhints.functions = MWM_FUNC_MOVE;
972         } else {
973             mwmhints.functions &= ~MWM_FUNC_RESIZE;
974         }
975
976         if (mwmhints.decorations == MWM_DECOR_ALL) {
977             mwmhints.flags |= MWM_HINTS_DECORATIONS;
978             mwmhints.decorations = (MWM_DECOR_BORDER
979                                     | MWM_DECOR_TITLE
980                                     | MWM_DECOR_MENU);
981         } else {
982             mwmhints.decorations &= ~MWM_DECOR_RESIZEH;
983         }
984     }
985
986     if (window()->windowFlags() & Qt::WindowMinimizeButtonHint) {
987         mwmhints.flags |= MWM_HINTS_DECORATIONS;
988         mwmhints.decorations |= MWM_DECOR_MINIMIZE;
989         mwmhints.functions |= MWM_FUNC_MINIMIZE;
990     }
991     if (window()->windowFlags() & Qt::WindowMaximizeButtonHint) {
992         mwmhints.flags |= MWM_HINTS_DECORATIONS;
993         mwmhints.decorations |= MWM_DECOR_MAXIMIZE;
994         mwmhints.functions |= MWM_FUNC_MAXIMIZE;
995     }
996     if (window()->windowFlags() & Qt::WindowCloseButtonHint)
997         mwmhints.functions |= MWM_FUNC_CLOSE;
998
999     setMotifWmHints(connection(), m_window, mwmhints);
1000 }
1001
1002 void QXcbWindow::updateNetWmStateBeforeMap()
1003 {
1004     NetWmStates states(0);
1005
1006     const Qt::WindowFlags flags = window()->windowFlags();
1007     if (flags & Qt::WindowStaysOnTopHint) {
1008         states |= NetWmStateAbove;
1009         states |= NetWmStateStaysOnTop;
1010     } else if (flags & Qt::WindowStaysOnBottomHint) {
1011         states |= NetWmStateBelow;
1012     }
1013
1014     if (window()->windowState() & Qt::WindowFullScreen)
1015         states |= NetWmStateFullScreen;
1016
1017     if (window()->windowState() & Qt::WindowMaximized) {
1018         states |= NetWmStateMaximizedHorz;
1019         states |= NetWmStateMaximizedVert;
1020     }
1021
1022     if (window()->windowModality() != Qt::NonModal)
1023         states |= NetWmStateModal;
1024
1025     setNetWmStates(states);
1026 }
1027
1028 void QXcbWindow::updateNetWmUserTime(xcb_timestamp_t timestamp)
1029 {
1030     xcb_window_t wid = m_window;
1031
1032     const bool isSupportedByWM = connection()->wmSupport()->isSupportedByWM(atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW));
1033     if (m_netWmUserTimeWindow || isSupportedByWM) {
1034         if (!m_netWmUserTimeWindow) {
1035             m_netWmUserTimeWindow = xcb_generate_id(xcb_connection());
1036             Q_XCB_CALL(xcb_create_window(xcb_connection(),
1037                                          XCB_COPY_FROM_PARENT,            // depth -- same as root
1038                                          m_netWmUserTimeWindow,                        // window id
1039                                          m_window,                   // parent window id
1040                                          -1, -1, 1, 1,
1041                                          0,                               // border width
1042                                          XCB_WINDOW_CLASS_INPUT_OUTPUT,   // window class
1043                                          m_visualId,                      // visual
1044                                          0,                               // value mask
1045                                          0));                             // value list
1046             wid = m_netWmUserTimeWindow;
1047             xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window, atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW),
1048                                 XCB_ATOM_WINDOW, 32, 1, &m_netWmUserTimeWindow);
1049             xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_USER_TIME));
1050         } else if (!isSupportedByWM) {
1051             // WM no longer supports it, then we should remove the
1052             // _NET_WM_USER_TIME_WINDOW atom.
1053             xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW));
1054             xcb_destroy_window(xcb_connection(), m_netWmUserTimeWindow);
1055             m_netWmUserTimeWindow = XCB_NONE;
1056         } else {
1057             wid = m_netWmUserTimeWindow;
1058         }
1059     }
1060     xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, wid, atom(QXcbAtom::_NET_WM_USER_TIME),
1061                         XCB_ATOM_CARDINAL, 32, 1, &timestamp);
1062 }
1063
1064 void QXcbWindow::setTransparentForMouseEvents(bool transparent)
1065 {
1066     if (transparent == m_transparent)
1067         return;
1068
1069     xcb_rectangle_t rectangle;
1070
1071     xcb_rectangle_t *rect = 0;
1072     int nrect = 0;
1073
1074     if (!transparent) {
1075         rectangle.x = 0;
1076         rectangle.y = 0;
1077         rectangle.width = geometry().width();
1078         rectangle.height = geometry().height();
1079         rect = &rectangle;
1080         nrect = 1;
1081     }
1082
1083     xcb_xfixes_region_t region = xcb_generate_id(xcb_connection());
1084     xcb_xfixes_create_region(xcb_connection(), region, nrect, rect);
1085     xcb_xfixes_set_window_shape_region_checked(xcb_connection(), m_window, XCB_SHAPE_SK_INPUT, 0, 0, region);
1086     xcb_xfixes_destroy_region(xcb_connection(), region);
1087
1088     m_transparent = transparent;
1089 }
1090
1091 void QXcbWindow::updateDoesNotAcceptFocus(bool doesNotAcceptFocus)
1092 {
1093     xcb_get_property_cookie_t cookie = xcb_get_wm_hints_unchecked(xcb_connection(), m_window);
1094
1095     xcb_wm_hints_t hints;
1096     if (!xcb_get_wm_hints_reply(xcb_connection(), cookie, &hints, NULL)) {
1097         return;
1098     }
1099
1100     xcb_wm_hints_set_input(&hints, !doesNotAcceptFocus);
1101     xcb_set_wm_hints(xcb_connection(), m_window, &hints);
1102 }
1103
1104 WId QXcbWindow::winId() const
1105 {
1106     return m_window;
1107 }
1108
1109 void QXcbWindow::setParent(const QPlatformWindow *parent)
1110 {
1111     // re-create for compatibility
1112     create();
1113
1114     QPoint topLeft = geometry().topLeft();
1115
1116     xcb_window_t xcb_parent_id = parent ? static_cast<const QXcbWindow *>(parent)->xcb_window() : m_screen->root();
1117     Q_XCB_CALL(xcb_reparent_window(xcb_connection(), xcb_window(), xcb_parent_id, topLeft.x(), topLeft.y()));
1118 }
1119
1120 void QXcbWindow::setWindowTitle(const QString &title)
1121 {
1122     QByteArray ba = title.toUtf8();
1123     Q_XCB_CALL(xcb_change_property(xcb_connection(),
1124                                    XCB_PROP_MODE_REPLACE,
1125                                    m_window,
1126                                    atom(QXcbAtom::_NET_WM_NAME),
1127                                    atom(QXcbAtom::UTF8_STRING),
1128                                    8,
1129                                    ba.length(),
1130                                    ba.constData()));
1131 }
1132
1133 void QXcbWindow::setWindowIcon(const QIcon &icon)
1134 {
1135     QVector<quint32> icon_data;
1136
1137     if (!icon.isNull()) {
1138         QList<QSize> availableSizes = icon.availableSizes();
1139         if (availableSizes.isEmpty()) {
1140             // try to use default sizes since the icon can be a scalable image like svg.
1141             availableSizes.push_back(QSize(16,16));
1142             availableSizes.push_back(QSize(32,32));
1143             availableSizes.push_back(QSize(64,64));
1144             availableSizes.push_back(QSize(128,128));
1145         }
1146         for (int i = 0; i < availableSizes.size(); ++i) {
1147             QSize size = availableSizes.at(i);
1148             QPixmap pixmap = icon.pixmap(size);
1149             if (!pixmap.isNull()) {
1150                 QImage image = pixmap.toImage().convertToFormat(QImage::Format_ARGB32);
1151                 int pos = icon_data.size();
1152                 icon_data.resize(pos + 2 + image.width()*image.height());
1153                 icon_data[pos++] = image.width();
1154                 icon_data[pos++] = image.height();
1155                 memcpy(icon_data.data() + pos, image.bits(), image.width()*image.height()*4);
1156             }
1157         }
1158     }
1159
1160     if (!icon_data.isEmpty()) {
1161         Q_XCB_CALL(xcb_change_property(xcb_connection(),
1162                                        XCB_PROP_MODE_REPLACE,
1163                                        m_window,
1164                                        atom(QXcbAtom::_NET_WM_ICON),
1165                                        atom(QXcbAtom::CARDINAL),
1166                                        32,
1167                                        icon_data.size(),
1168                                        (unsigned char *) icon_data.data()));
1169     } else {
1170         Q_XCB_CALL(xcb_delete_property(xcb_connection(),
1171                                        m_window,
1172                                        atom(QXcbAtom::_NET_WM_ICON)));
1173     }
1174 }
1175
1176 void QXcbWindow::raise()
1177 {
1178     const quint32 mask = XCB_CONFIG_WINDOW_STACK_MODE;
1179     const quint32 values[] = { XCB_STACK_MODE_ABOVE };
1180     Q_XCB_CALL(xcb_configure_window(xcb_connection(), m_window, mask, values));
1181 }
1182
1183 void QXcbWindow::lower()
1184 {
1185     const quint32 mask = XCB_CONFIG_WINDOW_STACK_MODE;
1186     const quint32 values[] = { XCB_STACK_MODE_BELOW };
1187     Q_XCB_CALL(xcb_configure_window(xcb_connection(), m_window, mask, values));
1188 }
1189
1190 // Adapt the geometry to match the WM expection with regards
1191 // to gravity.
1192 QRect QXcbWindow::windowToWmGeometry(QRect r) const
1193 {
1194     if (m_dirtyFrameMargins || m_frameMargins.isNull())
1195         return r;
1196     const bool frameInclusive = positionIncludesFrame(window());
1197     // XCB_GRAVITY_STATIC requires the inner geometry, whereas
1198     // XCB_GRAVITY_NORTH_WEST requires the frame geometry
1199     if (frameInclusive && m_gravity == XCB_GRAVITY_STATIC) {
1200         r.translate(m_frameMargins.left(), m_frameMargins.top());
1201     } else if (!frameInclusive && m_gravity == XCB_GRAVITY_NORTH_WEST) {
1202         r.translate(-m_frameMargins.left(), -m_frameMargins.top());
1203     }
1204     return r;
1205 }
1206
1207 void QXcbWindow::propagateSizeHints()
1208 {
1209     // update WM_NORMAL_HINTS
1210     xcb_size_hints_t hints;
1211     memset(&hints, 0, sizeof(hints));
1212
1213     const QRect rect = windowToWmGeometry(geometry());
1214
1215     QWindow *win = window();
1216
1217     xcb_size_hints_set_position(&hints, true, rect.x(), rect.y());
1218     xcb_size_hints_set_size(&hints, true, rect.width(), rect.height());
1219     xcb_size_hints_set_win_gravity(&hints, m_gravity);
1220
1221     QSize minimumSize = win->minimumSize();
1222     QSize maximumSize = win->maximumSize();
1223     QSize baseSize = win->baseSize();
1224     QSize sizeIncrement = win->sizeIncrement();
1225
1226     if (minimumSize.width() > 0 || minimumSize.height() > 0)
1227         xcb_size_hints_set_min_size(&hints, minimumSize.width(), minimumSize.height());
1228
1229     if (maximumSize.width() < QWINDOWSIZE_MAX || maximumSize.height() < QWINDOWSIZE_MAX)
1230         xcb_size_hints_set_max_size(&hints,
1231                                     qMin(XCOORD_MAX, maximumSize.width()),
1232                                     qMin(XCOORD_MAX, maximumSize.height()));
1233
1234     if (sizeIncrement.width() > 0 || sizeIncrement.height() > 0) {
1235         xcb_size_hints_set_base_size(&hints, baseSize.width(), baseSize.height());
1236         xcb_size_hints_set_resize_inc(&hints, sizeIncrement.width(), sizeIncrement.height());
1237     }
1238
1239     xcb_set_wm_normal_hints(xcb_connection(), m_window, &hints);
1240 }
1241
1242 void QXcbWindow::requestActivateWindow()
1243 {
1244     if (!m_mapped) {
1245         m_deferredActivation = true;
1246         return;
1247     }
1248     m_deferredActivation = false;
1249
1250     updateNetWmUserTime(connection()->time());
1251
1252     if (window()->isTopLevel()
1253         && connection()->wmSupport()->isSupportedByWM(atom(QXcbAtom::_NET_ACTIVE_WINDOW))) {
1254         xcb_client_message_event_t event;
1255
1256         event.response_type = XCB_CLIENT_MESSAGE;
1257         event.format = 32;
1258         event.window = m_window;
1259         event.type = atom(QXcbAtom::_NET_ACTIVE_WINDOW);
1260         event.data.data32[0] = 1;
1261         event.data.data32[1] = connection()->time();
1262         QWindow *focusWindow = QGuiApplication::focusWindow();
1263         event.data.data32[2] = focusWindow ? focusWindow->winId() : XCB_NONE;
1264         event.data.data32[3] = 0;
1265         event.data.data32[4] = 0;
1266
1267         Q_XCB_CALL(xcb_send_event(xcb_connection(), 0, m_screen->root(), XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (const char *)&event));
1268     } else {
1269         Q_XCB_CALL(xcb_set_input_focus(xcb_connection(), XCB_INPUT_FOCUS_PARENT, m_window, connection()->time()));
1270     }
1271
1272     connection()->sync();
1273 }
1274
1275 #if XCB_USE_MAEMO_WINDOW_PROPERTIES
1276 void QXcbWindow::handleContentOrientationChange(Qt::ScreenOrientation orientation)
1277 {
1278     int angle = 0;
1279     switch (orientation) {
1280         case Qt::PortraitOrientation: angle = 270; break;
1281         case Qt::LandscapeOrientation: angle = 0; break;
1282         case Qt::InvertedPortraitOrientation: angle = 90; break;
1283         case Qt::InvertedLandscapeOrientation: angle = 180; break;
1284         case Qt::PrimaryOrientation: break;
1285     }
1286     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
1287                                    atom(QXcbAtom::MeegoTouchOrientationAngle), XCB_ATOM_CARDINAL, 32,
1288                                    1, &angle));
1289 }
1290 #endif
1291
1292 QSurfaceFormat QXcbWindow::format() const
1293 {
1294     // ### return actual format
1295     return m_format;
1296 }
1297
1298 #if defined(XCB_USE_EGL)
1299 QXcbEGLSurface *QXcbWindow::eglSurface() const
1300 {
1301     if (!m_eglSurface) {
1302         EGLDisplay display = connection()->egl_display();
1303         EGLConfig config = q_configFromGLFormat(display, window()->requestedFormat(), true);
1304         EGLSurface surface = eglCreateWindowSurface(display, config, (EGLNativeWindowType)m_window, 0);
1305
1306         m_eglSurface = new QXcbEGLSurface(display, surface);
1307     }
1308
1309     return m_eglSurface;
1310 }
1311 #endif
1312
1313 void QXcbWindow::handleExposeEvent(const xcb_expose_event_t *event)
1314 {
1315     QRect rect(event->x, event->y, event->width, event->height);
1316
1317     if (m_exposeRegion.isEmpty())
1318         m_exposeRegion = rect;
1319     else
1320         m_exposeRegion |= rect;
1321
1322     // if count is non-zero there are more expose events pending
1323     if (event->count == 0) {
1324         QWindowSystemInterface::handleExposeEvent(window(), m_exposeRegion);
1325         m_exposeRegion = QRegion();
1326     }
1327 }
1328
1329 void QXcbWindow::handleClientMessageEvent(const xcb_client_message_event_t *event)
1330 {
1331     if (event->format != 32)
1332         return;
1333
1334     if (event->type == atom(QXcbAtom::WM_PROTOCOLS)) {
1335         if (event->data.data32[0] == atom(QXcbAtom::WM_DELETE_WINDOW)) {
1336             QWindowSystemInterface::handleCloseEvent(window());
1337         } else if (event->data.data32[0] == atom(QXcbAtom::WM_TAKE_FOCUS)) {
1338             connection()->setTime(event->data.data32[1]);
1339         } else if (event->data.data32[0] == atom(QXcbAtom::_NET_WM_PING)) {
1340             xcb_client_message_event_t reply = *event;
1341
1342             reply.response_type = XCB_CLIENT_MESSAGE;
1343             reply.window = m_screen->root();
1344
1345             xcb_send_event(xcb_connection(), 0, m_screen->root(), XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (const char *)&reply);
1346             xcb_flush(xcb_connection());
1347         } else if (event->data.data32[0] == atom(QXcbAtom::_NET_WM_SYNC_REQUEST)) {
1348             connection()->setTime(event->data.data32[1]);
1349             m_syncValue.lo = event->data.data32[2];
1350             m_syncValue.hi = event->data.data32[3];
1351         } else {
1352             qWarning() << "QXcbWindow: Unhandled WM_PROTOCOLS message:" << connection()->atomName(event->data.data32[0]);
1353         }
1354 #ifndef QT_NO_DRAGANDDROP
1355     } else if (event->type == atom(QXcbAtom::XdndEnter)) {
1356         connection()->drag()->handleEnter(window(), event);
1357     } else if (event->type == atom(QXcbAtom::XdndPosition)) {
1358         connection()->drag()->handlePosition(window(), event);
1359     } else if (event->type == atom(QXcbAtom::XdndLeave)) {
1360         connection()->drag()->handleLeave(window(), event);
1361     } else if (event->type == atom(QXcbAtom::XdndDrop)) {
1362         connection()->drag()->handleDrop(window(), event);
1363 #endif
1364     } else if (event->type == atom(QXcbAtom::_XEMBED)) { // QSystemTrayIcon
1365     } else {
1366         qWarning() << "QXcbWindow: Unhandled client message:" << connection()->atomName(event->type);
1367     }
1368 }
1369
1370 void QXcbWindow::handleConfigureNotifyEvent(const xcb_configure_notify_event_t *event)
1371 {
1372     bool fromSendEvent = (event->response_type & 0x80);
1373     QPoint pos(event->x, event->y);
1374     if (!parent() && !fromSendEvent) {
1375         // Do not trust the position, query it instead.
1376         xcb_translate_coordinates_cookie_t cookie = xcb_translate_coordinates(xcb_connection(), xcb_window(),
1377                                                                               m_screen->root(), 0, 0);
1378         xcb_translate_coordinates_reply_t *reply = xcb_translate_coordinates_reply(xcb_connection(), cookie, NULL);
1379         if (reply) {
1380             pos.setX(reply->dst_x);
1381             pos.setY(reply->dst_y);
1382             free(reply);
1383         }
1384     }
1385
1386     QRect rect(pos, QSize(event->width, event->height));
1387
1388     QPlatformWindow::setGeometry(rect);
1389     QWindowSystemInterface::handleGeometryChange(window(), rect);
1390
1391     m_configureNotifyPending = false;
1392
1393     if (m_deferredExpose) {
1394         m_deferredExpose = false;
1395         QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size()));
1396     }
1397
1398     m_dirtyFrameMargins = true;
1399
1400 #if XCB_USE_DRI2
1401     if (m_context)
1402         static_cast<QDri2Context *>(m_context)->resize(rect.size());
1403 #endif
1404 }
1405
1406 bool QXcbWindow::isExposed() const
1407 {
1408     return m_mapped;
1409 }
1410
1411 void QXcbWindow::handleMapNotifyEvent(const xcb_map_notify_event_t *event)
1412 {
1413     if (event->window == m_window) {
1414         m_mapped = true;
1415         if (m_deferredActivation)
1416             requestActivateWindow();
1417         if (m_configureNotifyPending)
1418             m_deferredExpose = true;
1419         else
1420             QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size()));
1421     }
1422 }
1423
1424 void QXcbWindow::handleUnmapNotifyEvent(const xcb_unmap_notify_event_t *event)
1425 {
1426     if (event->window == m_window) {
1427         m_mapped = false;
1428         QWindowSystemInterface::handleExposeEvent(window(), QRegion());
1429     }
1430 }
1431
1432 static Qt::MouseButtons translateMouseButtons(int s)
1433 {
1434     Qt::MouseButtons ret = 0;
1435     if (s & XCB_BUTTON_MASK_1)
1436         ret |= Qt::LeftButton;
1437     if (s & XCB_BUTTON_MASK_2)
1438         ret |= Qt::MidButton;
1439     if (s & XCB_BUTTON_MASK_3)
1440         ret |= Qt::RightButton;
1441     return ret;
1442 }
1443
1444 static Qt::MouseButton translateMouseButton(xcb_button_t s)
1445 {
1446     switch (s) {
1447     case 1: return Qt::LeftButton;
1448     case 2: return Qt::MidButton;
1449     case 3: return Qt::RightButton;
1450     // Button values 4-7 were already handled as Wheel events, and won't occur here.
1451     case 8: return Qt::BackButton;      // Also known as Qt::ExtraButton1
1452     case 9: return Qt::ForwardButton;   // Also known as Qt::ExtraButton2
1453     case 10: return Qt::ExtraButton3;
1454     case 11: return Qt::ExtraButton4;
1455     case 12: return Qt::ExtraButton5;
1456     case 13: return Qt::ExtraButton6;
1457     case 14: return Qt::ExtraButton7;
1458     case 15: return Qt::ExtraButton8;
1459     case 16: return Qt::ExtraButton9;
1460     case 17: return Qt::ExtraButton10;
1461     case 18: return Qt::ExtraButton11;
1462     case 19: return Qt::ExtraButton12;
1463     case 20: return Qt::ExtraButton13;
1464     case 21: return Qt::ExtraButton14;
1465     case 22: return Qt::ExtraButton15;
1466     case 23: return Qt::ExtraButton16;
1467     case 24: return Qt::ExtraButton17;
1468     case 25: return Qt::ExtraButton18;
1469     case 26: return Qt::ExtraButton19;
1470     case 27: return Qt::ExtraButton20;
1471     case 28: return Qt::ExtraButton21;
1472     case 29: return Qt::ExtraButton22;
1473     case 30: return Qt::ExtraButton23;
1474     case 31: return Qt::ExtraButton24;
1475     default: return Qt::NoButton;
1476     }
1477 }
1478
1479 void QXcbWindow::handleButtonPressEvent(const xcb_button_press_event_t *event)
1480 {
1481     updateNetWmUserTime(event->time);
1482
1483     QPoint local(event->event_x, event->event_y);
1484     QPoint global(event->root_x, event->root_y);
1485
1486     Qt::KeyboardModifiers modifiers = connection()->keyboard()->translateModifiers(event->state);
1487
1488     if (event->detail >= 4 && event->detail <= 7) {
1489         // Logic borrowed from qapplication_x11.cpp
1490         int delta = 120 * ((event->detail == 4 || event->detail == 6) ? 1 : -1);
1491         bool hor = (((event->detail == 4 || event->detail == 5)
1492                      && (modifiers & Qt::AltModifier))
1493                     || (event->detail == 6 || event->detail == 7));
1494
1495         QWindowSystemInterface::handleWheelEvent(window(), event->time,
1496                                                  local, global, delta, hor ? Qt::Horizontal : Qt::Vertical, modifiers);
1497         return;
1498     }
1499
1500     handleMouseEvent(event->detail, event->state, event->time, local, global, modifiers);
1501 }
1502
1503 void QXcbWindow::handleButtonReleaseEvent(const xcb_button_release_event_t *event)
1504 {
1505     QPoint local(event->event_x, event->event_y);
1506     QPoint global(event->root_x, event->root_y);
1507     Qt::KeyboardModifiers modifiers = connection()->keyboard()->translateModifiers(event->state);
1508
1509     handleMouseEvent(event->detail, event->state, event->time, local, global, modifiers);
1510 }
1511
1512 void QXcbWindow::handleMotionNotifyEvent(const xcb_motion_notify_event_t *event)
1513 {
1514     QPoint local(event->event_x, event->event_y);
1515     QPoint global(event->root_x, event->root_y);
1516     Qt::KeyboardModifiers modifiers = connection()->keyboard()->translateModifiers(event->state);
1517
1518     handleMouseEvent(event->detail, event->state, event->time, local, global, modifiers);
1519 }
1520
1521 void QXcbWindow::handleMouseEvent(xcb_button_t detail, uint16_t state, xcb_timestamp_t time, const QPoint &local, const QPoint &global, Qt::KeyboardModifiers modifiers)
1522 {
1523     connection()->setTime(time);
1524
1525     Qt::MouseButtons buttons = translateMouseButtons(state);
1526     Qt::MouseButton button = translateMouseButton(detail);
1527
1528     buttons ^= button; // X event uses state *before*, Qt uses state *after*
1529
1530     QWindowSystemInterface::handleMouseEvent(window(), time, local, global, buttons, modifiers);
1531 }
1532
1533 void QXcbWindow::handleEnterNotifyEvent(const xcb_enter_notify_event_t *event)
1534 {
1535     connection()->setTime(event->time);
1536
1537     if ((event->mode != XCB_NOTIFY_MODE_NORMAL && event->mode != XCB_NOTIFY_MODE_UNGRAB)
1538         || event->detail == XCB_NOTIFY_DETAIL_VIRTUAL
1539         || event->detail == XCB_NOTIFY_DETAIL_NONLINEAR_VIRTUAL)
1540     {
1541         return;
1542     }
1543
1544     QWindowSystemInterface::handleEnterEvent(window());
1545 }
1546
1547 void QXcbWindow::handleLeaveNotifyEvent(const xcb_leave_notify_event_t *event)
1548 {
1549     connection()->setTime(event->time);
1550
1551     if ((event->mode != XCB_NOTIFY_MODE_NORMAL && event->mode != XCB_NOTIFY_MODE_UNGRAB)
1552         || event->detail == XCB_NOTIFY_DETAIL_INFERIOR)
1553     {
1554         return;
1555     }
1556
1557     QWindowSystemInterface::handleLeaveEvent(window());
1558 }
1559
1560 void QXcbWindow::handlePropertyNotifyEvent(const xcb_property_notify_event_t *event)
1561 {
1562     connection()->setTime(event->time);
1563
1564     const bool propertyDeleted = event->state == XCB_PROPERTY_DELETE;
1565     const xcb_atom_t netWmStateAtom = atom(QXcbAtom::_NET_WM_STATE);
1566     const xcb_atom_t wmStateAtom = atom(QXcbAtom::WM_STATE);
1567
1568     if (event->atom == netWmStateAtom || event->atom == wmStateAtom) {
1569         if (propertyDeleted)
1570             return;
1571
1572         Qt::WindowState newState = Qt::WindowNoState;
1573         if (event->atom == wmStateAtom) { // WM_STATE: Quick check for 'Minimize'.
1574             const xcb_get_property_cookie_t get_cookie =
1575                 xcb_get_property(xcb_connection(), 0, m_window, wmStateAtom,
1576                                  XCB_ATOM_ANY, 0, 1024);
1577
1578             xcb_get_property_reply_t *reply =
1579                 xcb_get_property_reply(xcb_connection(), get_cookie, NULL);
1580
1581             if (reply && reply->format == 32 && reply->type == wmStateAtom) {
1582                 const long *data = (const long *)xcb_get_property_value(reply);
1583                 if (reply->length != 0 && XCB_WM_STATE_ICONIC == data[0])
1584                     newState = Qt::WindowMinimized;
1585                 free(reply);
1586             }
1587         } // WM_STATE: Quick check for 'Minimize'.
1588         if (newState != Qt::WindowMinimized) { // Something else changed, get _NET_WM_STATE.
1589             const NetWmStates states = netWmStates();
1590             if ((states & NetWmStateMaximizedHorz) && (states & NetWmStateMaximizedVert))
1591                 newState = Qt::WindowMaximized;
1592             else if (states & NetWmStateFullScreen)
1593                 newState = Qt::WindowFullScreen;
1594         }
1595         // Send Window state, compress events in case other flags (modality, etc) are changed.
1596         if (m_lastWindowStateEvent != newState) {
1597             QWindowSystemInterface::handleWindowStateChanged(window(), newState);
1598             m_lastWindowStateEvent = newState;
1599         }
1600     }
1601 }
1602
1603 void QXcbWindow::handleFocusInEvent(const xcb_focus_in_event_t *)
1604 {
1605     QWindowSystemInterface::handleWindowActivated(window());
1606 }
1607
1608 static bool focusInPeeker(xcb_generic_event_t *event)
1609 {
1610     if (!event) {
1611         // FocusIn event is not in the queue, proceed with FocusOut normally.
1612         QWindowSystemInterface::handleWindowActivated(0);
1613         return true;
1614     }
1615     uint response_type = event->response_type & ~0x80;
1616     return response_type == XCB_FOCUS_IN;
1617 }
1618
1619 void QXcbWindow::handleFocusOutEvent(const xcb_focus_out_event_t *)
1620 {
1621     // Do not set the active window to 0 if there is a FocusIn coming.
1622     // There is however no equivalent for XPutBackEvent so register a
1623     // callback for QXcbConnection instead.
1624     connection()->addPeekFunc(focusInPeeker);
1625 }
1626
1627 void QXcbWindow::updateSyncRequestCounter()
1628 {
1629     if (m_screen->syncRequestSupported() && (m_syncValue.lo != 0 || m_syncValue.hi != 0)) {
1630         Q_XCB_CALL(xcb_sync_set_counter(xcb_connection(), m_syncCounter, m_syncValue));
1631         xcb_flush(xcb_connection());
1632         connection()->sync();
1633
1634         m_syncValue.lo = 0;
1635         m_syncValue.hi = 0;
1636     }
1637 }
1638
1639 bool QXcbWindow::setKeyboardGrabEnabled(bool grab)
1640 {
1641     if (!grab) {
1642         xcb_ungrab_keyboard(xcb_connection(), XCB_TIME_CURRENT_TIME);
1643         return true;
1644     }
1645     xcb_grab_keyboard_cookie_t cookie = xcb_grab_keyboard(xcb_connection(), false,
1646                                                           m_window, XCB_TIME_CURRENT_TIME,
1647                                                           XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
1648     xcb_grab_keyboard_reply_t *reply = xcb_grab_keyboard_reply(xcb_connection(), cookie, NULL);
1649     bool result = !(!reply || reply->status != XCB_GRAB_STATUS_SUCCESS);
1650     free(reply);
1651     return result;
1652 }
1653
1654 bool QXcbWindow::setMouseGrabEnabled(bool grab)
1655 {
1656     if (!grab) {
1657         xcb_ungrab_pointer(xcb_connection(), XCB_TIME_CURRENT_TIME);
1658         return true;
1659     }
1660     xcb_grab_pointer_cookie_t cookie = xcb_grab_pointer(xcb_connection(), false, m_window,
1661                                                         (XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE
1662                                                          | XCB_EVENT_MASK_BUTTON_MOTION | XCB_EVENT_MASK_ENTER_WINDOW
1663                                                          | XCB_EVENT_MASK_LEAVE_WINDOW | XCB_EVENT_MASK_POINTER_MOTION),
1664                                                         XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC,
1665                                                         XCB_WINDOW_NONE, XCB_CURSOR_NONE,
1666                                                         XCB_TIME_CURRENT_TIME);
1667     xcb_grab_pointer_reply_t *reply = xcb_grab_pointer_reply(xcb_connection(), cookie, NULL);
1668     bool result = !(!reply || reply->status != XCB_GRAB_STATUS_SUCCESS);
1669     free(reply);
1670     return result;
1671 }
1672
1673 void QXcbWindow::setCursor(xcb_cursor_t cursor)
1674 {
1675     xcb_change_window_attributes(xcb_connection(), m_window, XCB_CW_CURSOR, &cursor);
1676     xcb_flush(xcb_connection());
1677 }
1678
1679 bool QXcbWindow::startSystemResize(const QPoint &pos, Qt::Corner corner)
1680 {
1681     const xcb_atom_t moveResize = connection()->atom(QXcbAtom::_NET_WM_MOVERESIZE);
1682     if (!connection()->wmSupport()->isSupportedByWM(moveResize))
1683         return false;
1684     xcb_client_message_event_t xev;
1685     xev.response_type = XCB_CLIENT_MESSAGE;
1686     xev.type = moveResize;
1687     xev.window = xcb_window();
1688     xev.format = 32;
1689     const QPoint globalPos = window()->mapToGlobal(pos);
1690     xev.data.data32[0] = globalPos.x();
1691     xev.data.data32[1] = globalPos.y();
1692     const bool bottom = corner == Qt::BottomRightCorner || corner == Qt::BottomLeftCorner;
1693     const bool left = corner == Qt::BottomLeftCorner || corner == Qt::TopLeftCorner;
1694     if (bottom)
1695         xev.data.data32[2] = left ? 6 : 4; // bottomleft/bottomright
1696     else
1697         xev.data.data32[2] = left ? 0 : 2; // topleft/topright
1698     xev.data.data32[3] = XCB_BUTTON_INDEX_1;
1699     xev.data.data32[4] = 0;
1700     xcb_ungrab_pointer(connection()->xcb_connection(), XCB_CURRENT_TIME);
1701     xcb_send_event(connection()->xcb_connection(), false, m_screen->root(),
1702                    XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY,
1703                    (const char *)&xev);
1704     return true;
1705 }
1706
1707 #if defined(XCB_USE_XLIB) && !defined(QT_NO_SHAPE)
1708
1709 static inline XRectangle qRectToX11Rectangle(const QRect &r)
1710 {
1711     XRectangle result;
1712     result.x = qMax(SHRT_MIN, r.x());
1713     result.y = qMax(SHRT_MIN, r.y());
1714     result.width = qMin((int)USHRT_MAX, r.width());
1715     result.height = qMin((int)USHRT_MAX, r.height());
1716     return result;
1717 }
1718
1719 static inline Region qRegionToX11Region(const QRegion &region)
1720 {
1721     if (region.isEmpty())
1722         return None;
1723     Region result = XCreateRegion();
1724     if (!result)
1725         return None;
1726     const QVector<QRect> rects = region.rects();
1727     if (rects.size() == 1) {
1728         XRectangle xrect = qRectToX11Rectangle(region.boundingRect());
1729         XUnionRectWithRegion(&xrect, result, result);
1730     } else {
1731         foreach (const QRect &r, rects) {
1732             XRectangle xrect = qRectToX11Rectangle(r);
1733             XUnionRectWithRegion(&xrect, result, result);
1734         }
1735     }
1736     return result;
1737 }
1738
1739
1740 void QXcbWindow::setMask(const QRegion &region)
1741 {
1742
1743     Display *display = (Display *)connection()->xlib_display();
1744     if (region.isEmpty()) {
1745         XShapeCombineMask(display, xcb_window(),
1746                           ShapeBounding, 0, 0,
1747                           None, ShapeSet);
1748     } else {
1749         XShapeCombineRegion(display, xcb_window(),
1750                             ShapeBounding, 0, 0,
1751                             qRegionToX11Region(region), ShapeSet);
1752     }
1753 }
1754
1755 #endif // XCB_USE_XLIB && !QT_NO_SHAPE
1756
1757 QT_END_NAMESPACE