Minor build fix for newer XCB versions
[profile/ivi/qtbase.git] / src / plugins / platforms / xcb / qxcbwindow.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the plugins of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 **
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 **
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
29 **
30 ** Other Usage
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qxcbwindow.h"
43
44 #include <QtDebug>
45 #include <QScreen>
46
47 #include "qxcbconnection.h"
48 #include "qxcbscreen.h"
49 #include "qxcbdrag.h"
50 #include "qxcbkeyboard.h"
51 #include "qxcbwmsupport.h"
52
53 #ifdef XCB_USE_DRI2
54 #include "qdri2context.h"
55 #endif
56
57 // FIXME This workaround can be removed for xcb-icccm > 3.8
58 #define class class_name
59 #include <xcb/xcb_icccm.h>
60 #undef class
61 #include <xcb/xfixes.h>
62
63 // xcb-icccm 3.8 support
64 #ifdef XCB_ICCCM_NUM_WM_SIZE_HINTS_ELEMENTS
65 #define xcb_get_wm_hints_reply xcb_icccm_get_wm_hints_reply
66 #define xcb_get_wm_hints xcb_icccm_get_wm_hints
67 #define xcb_set_wm_hints xcb_icccm_set_wm_hints
68 #define xcb_set_wm_normal_hints xcb_icccm_set_wm_normal_hints
69 #define xcb_size_hints_set_base_size xcb_icccm_size_hints_set_base_size
70 #define xcb_size_hints_set_max_size xcb_icccm_size_hints_set_max_size
71 #define xcb_size_hints_set_min_size xcb_icccm_size_hints_set_min_size
72 #define xcb_size_hints_set_position xcb_icccm_size_hints_set_position
73 #define xcb_size_hints_set_resize_inc xcb_icccm_size_hints_set_resize_inc
74 #define xcb_size_hints_set_size xcb_icccm_size_hints_set_size
75 #define xcb_size_hints_set_win_gravity xcb_icccm_size_hints_set_win_gravity
76 #define xcb_wm_hints_set_iconic xcb_icccm_wm_hints_set_iconic
77 #define xcb_wm_hints_set_normal xcb_icccm_wm_hints_set_normal
78 #define xcb_wm_hints_t xcb_icccm_wm_hints_t
79 #define XCB_WM_STATE_ICONIC XCB_ICCCM_WM_STATE_ICONIC
80 #define XCB_WM_STATE_WITHDRAWN XCB_ICCCM_WM_STATE_WITHDRAWN
81 #endif
82
83 #include <private/qguiapplication_p.h>
84 #include <private/qwindow_p.h>
85
86 #include <QtGui/QPlatformBackingStore>
87 #include <QtGui/QWindowSystemInterface>
88
89 #include <stdio.h>
90
91 #ifdef XCB_USE_XLIB
92 #include <X11/Xlib.h>
93 #include <X11/Xutil.h>
94 #endif
95
96 #if defined(XCB_USE_GLX)
97 #include "qglxintegration.h"
98 #include <QtPlatformSupport/private/qglxconvenience_p.h>
99 #elif defined(XCB_USE_EGL)
100 #include "qxcbeglsurface.h"
101 #include <QtPlatformSupport/private/qeglconvenience_p.h>
102 #include <QtPlatformSupport/private/qxlibeglintegration_p.h>
103 #endif
104
105 #define XCOORD_MAX 16383
106
107 //#ifdef NET_WM_STATE_DEBUG
108
109 QT_BEGIN_NAMESPACE
110
111 // Returns true if we should set WM_TRANSIENT_FOR on \a w
112 static inline bool isTransient(const QWindow *w)
113 {
114     return w->windowType() == Qt::Dialog
115            || w->windowType() == Qt::Sheet
116            || w->windowType() == Qt::Tool
117            || w->windowType() == Qt::SplashScreen
118            || w->windowType() == Qt::ToolTip
119            || w->windowType() == Qt::Drawer
120            || w->windowType() == Qt::Popup;
121 }
122
123 static inline QImage::Format imageFormatForDepth(int depth)
124 {
125     switch (depth) {
126         case 32: return QImage::Format_ARGB32_Premultiplied;
127         case 24: return QImage::Format_RGB32;
128         case 16: return QImage::Format_RGB16;
129         default: break;
130     }
131     qFatal("Unsupported display depth %d", depth);
132     return QImage::Format_Invalid;
133 }
134
135 QXcbWindow::QXcbWindow(QWindow *window)
136     : QPlatformWindow(window)
137     , m_window(0)
138     , m_syncCounter(0)
139     , m_mapped(false)
140     , m_transparent(false)
141     , m_netWmUserTimeWindow(XCB_NONE)
142 #if defined(XCB_USE_EGL)
143     , m_eglSurface(0)
144 #endif
145 {
146     m_screen = static_cast<QXcbScreen *>(window->screen()->handle());
147
148     setConnection(m_screen->connection());
149
150     create();
151 }
152
153 void QXcbWindow::create()
154 {
155     destroy();
156
157     m_windowState = Qt::WindowNoState;
158
159     Qt::WindowType type = window()->windowType();
160
161     if (type == Qt::Desktop) {
162         m_window = m_screen->root();
163         m_depth = m_screen->screen()->root_depth;
164         m_imageFormat = imageFormatForDepth(m_depth);
165         connection()->addWindow(m_window, this);
166         return;
167     }
168
169     const quint32 mask = XCB_CW_BACK_PIXMAP | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_SAVE_UNDER | XCB_CW_EVENT_MASK;
170     const quint32 values[] = {
171         // XCB_CW_BACK_PIXMAP
172         XCB_NONE,
173         // XCB_CW_OVERRIDE_REDIRECT
174         type == Qt::Popup || type == Qt::ToolTip,
175         // XCB_CW_SAVE_UNDER
176         type == Qt::Popup || type == Qt::Tool || type == Qt::SplashScreen || type == Qt::ToolTip || type == Qt::Drawer,
177         // XCB_CW_EVENT_MASK
178         XCB_EVENT_MASK_EXPOSURE
179         | XCB_EVENT_MASK_STRUCTURE_NOTIFY
180         | XCB_EVENT_MASK_KEY_PRESS
181         | XCB_EVENT_MASK_KEY_RELEASE
182         | XCB_EVENT_MASK_BUTTON_PRESS
183         | XCB_EVENT_MASK_BUTTON_RELEASE
184         | XCB_EVENT_MASK_BUTTON_MOTION
185         | XCB_EVENT_MASK_ENTER_WINDOW
186         | XCB_EVENT_MASK_LEAVE_WINDOW
187         | XCB_EVENT_MASK_POINTER_MOTION
188         | XCB_EVENT_MASK_PROPERTY_CHANGE
189         | XCB_EVENT_MASK_FOCUS_CHANGE
190     };
191
192     QRect rect = window()->geometry();
193     QPlatformWindow::setGeometry(rect);
194
195     rect.setWidth(qBound(1, rect.width(), XCOORD_MAX));
196     rect.setHeight(qBound(1, rect.height(), XCOORD_MAX));
197
198     xcb_window_t xcb_parent_id = m_screen->root();
199     if (parent())
200         xcb_parent_id = static_cast<QXcbWindow *>(parent())->xcb_window();
201
202     m_requestedFormat = window()->format();
203
204 #if (defined(XCB_USE_GLX) || defined(XCB_USE_EGL)) && defined(XCB_USE_XLIB)
205     if (QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::OpenGL)
206         || window()->format().hasAlpha())
207     {
208 #if defined(XCB_USE_GLX)
209         XVisualInfo *visualInfo = qglx_findVisualInfo(DISPLAY_FROM_XCB(m_screen),m_screen->screenNumber(), window()->format());
210
211 #elif defined(XCB_USE_EGL)
212         EGLDisplay eglDisplay = connection()->egl_display();
213         EGLConfig eglConfig = q_configFromGLFormat(eglDisplay, window()->format(), true);
214         VisualID id = QXlibEglIntegration::getCompatibleVisualId(DISPLAY_FROM_XCB(this), eglDisplay, eglConfig);
215
216         XVisualInfo visualInfoTemplate;
217         memset(&visualInfoTemplate, 0, sizeof(XVisualInfo));
218         visualInfoTemplate.visualid = id;
219
220         XVisualInfo *visualInfo;
221         int matchingCount = 0;
222         visualInfo = XGetVisualInfo(DISPLAY_FROM_XCB(this), VisualIDMask, &visualInfoTemplate, &matchingCount);
223 #endif //XCB_USE_GLX
224         if (visualInfo) {
225             m_depth = visualInfo->depth;
226             m_imageFormat = imageFormatForDepth(m_depth);
227             Colormap cmap = XCreateColormap(DISPLAY_FROM_XCB(this), xcb_parent_id, visualInfo->visual, AllocNone);
228
229             XSetWindowAttributes a;
230             a.background_pixel = WhitePixel(DISPLAY_FROM_XCB(this), m_screen->screenNumber());
231             a.border_pixel = BlackPixel(DISPLAY_FROM_XCB(this), m_screen->screenNumber());
232             a.colormap = cmap;
233             m_window = XCreateWindow(DISPLAY_FROM_XCB(this), xcb_parent_id, rect.x(), rect.y(), rect.width(), rect.height(),
234                                       0, visualInfo->depth, InputOutput, visualInfo->visual,
235                                       CWBackPixel|CWBorderPixel|CWColormap, &a);
236         } else {
237             qFatal("no window!");
238         }
239     } else
240 #endif //defined(XCB_USE_GLX) || defined(XCB_USE_EGL)
241     {
242         m_window = xcb_generate_id(xcb_connection());
243         m_depth = m_screen->screen()->root_depth;
244         m_imageFormat = imageFormatForDepth(m_depth);
245
246         Q_XCB_CALL(xcb_create_window(xcb_connection(),
247                                      XCB_COPY_FROM_PARENT,            // depth -- same as root
248                                      m_window,                        // window id
249                                      xcb_parent_id,                   // parent window id
250                                      rect.x(),
251                                      rect.y(),
252                                      rect.width(),
253                                      rect.height(),
254                                      0,                               // border width
255                                      XCB_WINDOW_CLASS_INPUT_OUTPUT,   // window class
256                                      m_screen->screen()->root_visual, // visual
257                                      0,                               // value mask
258                                      0));                             // value list
259     }
260
261     connection()->addWindow(m_window, this);
262
263     Q_XCB_CALL(xcb_change_window_attributes(xcb_connection(), m_window, mask, values));
264
265     propagateSizeHints();
266
267     xcb_atom_t properties[4];
268     int propertyCount = 0;
269     properties[propertyCount++] = atom(QXcbAtom::WM_DELETE_WINDOW);
270     properties[propertyCount++] = atom(QXcbAtom::WM_TAKE_FOCUS);
271     properties[propertyCount++] = atom(QXcbAtom::_NET_WM_PING);
272
273     if (m_screen->syncRequestSupported())
274         properties[propertyCount++] = atom(QXcbAtom::_NET_WM_SYNC_REQUEST);
275
276     if (window()->windowFlags() & Qt::WindowContextHelpButtonHint)
277         properties[propertyCount++] = atom(QXcbAtom::_NET_WM_CONTEXT_HELP);
278
279     Q_XCB_CALL(xcb_change_property(xcb_connection(),
280                                    XCB_PROP_MODE_REPLACE,
281                                    m_window,
282                                    atom(QXcbAtom::WM_PROTOCOLS),
283                                    XCB_ATOM_ATOM,
284                                    32,
285                                    propertyCount,
286                                    properties));
287     m_syncValue.hi = 0;
288     m_syncValue.lo = 0;
289
290     if (m_screen->syncRequestSupported()) {
291         m_syncCounter = xcb_generate_id(xcb_connection());
292         Q_XCB_CALL(xcb_sync_create_counter(xcb_connection(), m_syncCounter, m_syncValue));
293
294         Q_XCB_CALL(xcb_change_property(xcb_connection(),
295                                        XCB_PROP_MODE_REPLACE,
296                                        m_window,
297                                        atom(QXcbAtom::_NET_WM_SYNC_REQUEST_COUNTER),
298                                        XCB_ATOM_CARDINAL,
299                                        32,
300                                        1,
301                                        &m_syncCounter));
302     }
303
304     // set the PID to let the WM kill the application if unresponsive
305     long pid = getpid();
306     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
307                                    atom(QXcbAtom::_NET_WM_PID), XCB_ATOM_CARDINAL, 32,
308                                    1, &pid));
309
310     xcb_wm_hints_t hints;
311     memset(&hints, 0, sizeof(hints));
312     xcb_wm_hints_set_normal(&hints);
313
314     xcb_set_wm_hints(xcb_connection(), m_window, &hints);
315
316     xcb_window_t leader = m_screen->clientLeader();
317     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
318                                    atom(QXcbAtom::WM_CLIENT_LEADER), XCB_ATOM_WINDOW, 32,
319                                    1, &leader));
320
321     setWindowFlags(window()->windowFlags());
322     setWindowTitle(window()->windowTitle());
323     setWindowState(window()->windowState());
324
325     if (window()->windowFlags() & Qt::WindowTransparentForInput)
326         setTransparentForMouseEvents(true);
327
328     connection()->drag()->dndEnable(this, true);
329 }
330
331 QXcbWindow::~QXcbWindow()
332 {
333     destroy();
334 }
335
336 void QXcbWindow::destroy()
337 {
338     if (m_syncCounter && m_screen->syncRequestSupported())
339         Q_XCB_CALL(xcb_sync_destroy_counter(xcb_connection(), m_syncCounter));
340     if (m_window) {
341         connection()->removeWindow(m_window);
342         Q_XCB_CALL(xcb_destroy_window(xcb_connection(), m_window));
343     }
344     m_mapped = false;
345
346 #if defined(XCB_USE_EGL)
347     delete m_eglSurface;
348     m_eglSurface = 0;
349 #endif
350 }
351
352 void QXcbWindow::setGeometry(const QRect &rect)
353 {
354     QPlatformWindow::setGeometry(rect);
355
356     propagateSizeHints();
357
358     const quint32 mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y | XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
359     const quint32 values[] = { rect.x(),
360                                rect.y(),
361                                qBound(1, rect.width(), XCOORD_MAX),
362                                qBound(1, rect.height(), XCOORD_MAX) };
363
364     Q_XCB_CALL(xcb_configure_window(xcb_connection(), m_window, mask, values));
365
366     xcb_flush(xcb_connection());
367 }
368
369 QMargins QXcbWindow::frameMargins() const
370 {
371     if (m_dirtyFrameMargins) {
372         xcb_window_t window = m_window;
373         xcb_window_t parent = m_window;
374
375         bool foundRoot = false;
376
377         const QVector<xcb_window_t> &virtualRoots =
378             connection()->wmSupport()->virtualRoots();
379
380         while (!foundRoot) {
381             xcb_query_tree_cookie_t cookie = xcb_query_tree(xcb_connection(), parent);
382
383             xcb_generic_error_t *error;
384             xcb_query_tree_reply_t *reply = xcb_query_tree_reply(xcb_connection(), cookie, &error);
385             if (reply) {
386                 if (reply->root == reply->parent || virtualRoots.indexOf(reply->parent) != -1) {
387                     foundRoot = true;
388                 } else {
389                     window = parent;
390                     parent = reply->parent;
391                 }
392
393                 free(reply);
394             } else {
395                 if (error) {
396                     connection()->handleXcbError(error);
397                     free(error);
398                 }
399
400                 m_dirtyFrameMargins = false;
401                 m_frameMargins = QMargins();
402                 return m_frameMargins;
403             }
404         }
405
406         QPoint offset;
407
408         xcb_generic_error_t *error;
409         xcb_translate_coordinates_reply_t *reply =
410             xcb_translate_coordinates_reply(
411                 xcb_connection(),
412                 xcb_translate_coordinates(xcb_connection(), window, parent, 0, 0),
413                 &error);
414
415         if (reply) {
416             offset = QPoint(reply->dst_x, reply->dst_y);
417             free(reply);
418         } else if (error) {
419             free(error);
420         }
421
422         xcb_get_geometry_reply_t *geom =
423             xcb_get_geometry_reply(
424                 xcb_connection(),
425                 xcb_get_geometry(xcb_connection(), parent),
426                 &error);
427
428         if (geom) {
429             // --
430             // add the border_width for the window managers frame... some window managers
431             // do not use a border_width of zero for their frames, and if we the left and
432             // top strut, we ensure that pos() is absolutely correct.  frameGeometry()
433             // will still be incorrect though... perhaps i should have foffset as well, to
434             // indicate the frame offset (equal to the border_width on X).
435             // - Brad
436             // -- copied from qwidget_x11.cpp
437
438             int left = offset.x() + geom->border_width;
439             int top = offset.y() + geom->border_width;
440             int right = geom->width + geom->border_width - geometry().width() - offset.x();
441             int bottom = geom->height + geom->border_width - geometry().height() - offset.y();
442
443             m_frameMargins = QMargins(left, top, right, bottom);
444
445             free(geom);
446         } else if (error) {
447             free(error);
448         }
449
450         m_dirtyFrameMargins = false;
451     }
452
453     return m_frameMargins;
454 }
455
456 void QXcbWindow::setVisible(bool visible)
457 {
458     if (visible)
459         show();
460     else
461         hide();
462 }
463
464 void QXcbWindow::show()
465 {
466     if (window()->isTopLevel()) {
467         xcb_get_property_cookie_t cookie = xcb_get_wm_hints(xcb_connection(), m_window);
468
469         xcb_generic_error_t *error;
470
471         xcb_wm_hints_t hints;
472         xcb_get_wm_hints_reply(xcb_connection(), cookie, &hints, &error);
473
474         if (error) {
475             connection()->handleXcbError(error);
476             free(error);
477         }
478
479         if (window()->windowState() & Qt::WindowMinimized)
480             xcb_wm_hints_set_iconic(&hints);
481         else
482             xcb_wm_hints_set_normal(&hints);
483
484         xcb_set_wm_hints(xcb_connection(), m_window, &hints);
485
486         // update WM_NORMAL_HINTS
487         propagateSizeHints();
488
489         // update WM_TRANSIENT_FOR
490         if (window()->transientParent() && isTransient(window())) {
491             QXcbWindow *transientXcbParent = static_cast<QXcbWindow *>(window()->transientParent()->handle());
492             if (transientXcbParent) {
493                 // ICCCM 4.1.2.6
494                 xcb_window_t parentWindow = transientXcbParent->xcb_window();
495
496                 // todo: set transient for group (wm_client_leader) if no parent, a la qwidget_x11.cpp
497                 Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
498                                                XCB_ATOM_WM_TRANSIENT_FOR, XCB_ATOM_WINDOW, 32,
499                                                1, &parentWindow));
500             }
501         }
502
503         // update _MOTIF_WM_HINTS
504         updateMotifWmHintsBeforeMap();
505
506         // update _NET_WM_STATE
507         updateNetWmStateBeforeMap();
508     }
509
510     Q_XCB_CALL(xcb_map_window(xcb_connection(), m_window));
511     xcb_flush(xcb_connection());
512
513     connection()->sync();
514 }
515
516 void QXcbWindow::hide()
517 {
518     Q_XCB_CALL(xcb_unmap_window(xcb_connection(), m_window));
519
520     // send synthetic UnmapNotify event according to icccm 4.1.4
521     xcb_unmap_notify_event_t event;
522     event.response_type = XCB_UNMAP_NOTIFY;
523     event.event = m_screen->root();
524     event.window = m_window;
525     event.from_configure = false;
526     Q_XCB_CALL(xcb_send_event(xcb_connection(), false, m_screen->root(),
527                               XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (const char *)&event));
528
529     xcb_flush(xcb_connection());
530
531     m_mapped = false;
532 }
533
534 struct QtMotifWmHints {
535     quint32 flags, functions, decorations;
536     qint32 input_mode;
537     quint32 status;
538 };
539
540 enum {
541     MWM_HINTS_FUNCTIONS   = (1L << 0),
542
543     MWM_FUNC_ALL      = (1L << 0),
544     MWM_FUNC_RESIZE   = (1L << 1),
545     MWM_FUNC_MOVE     = (1L << 2),
546     MWM_FUNC_MINIMIZE = (1L << 3),
547     MWM_FUNC_MAXIMIZE = (1L << 4),
548     MWM_FUNC_CLOSE    = (1L << 5),
549
550     MWM_HINTS_DECORATIONS = (1L << 1),
551
552     MWM_DECOR_ALL      = (1L << 0),
553     MWM_DECOR_BORDER   = (1L << 1),
554     MWM_DECOR_RESIZEH  = (1L << 2),
555     MWM_DECOR_TITLE    = (1L << 3),
556     MWM_DECOR_MENU     = (1L << 4),
557     MWM_DECOR_MINIMIZE = (1L << 5),
558     MWM_DECOR_MAXIMIZE = (1L << 6),
559
560     MWM_HINTS_INPUT_MODE = (1L << 2),
561
562     MWM_INPUT_MODELESS                  = 0L,
563     MWM_INPUT_PRIMARY_APPLICATION_MODAL = 1L,
564     MWM_INPUT_FULL_APPLICATION_MODAL    = 3L
565 };
566
567 static QtMotifWmHints getMotifWmHints(QXcbConnection *c, xcb_window_t window)
568 {
569     QtMotifWmHints hints;
570
571     xcb_get_property_cookie_t get_cookie =
572         xcb_get_property(c->xcb_connection(), 0, window, c->atom(QXcbAtom::_MOTIF_WM_HINTS),
573                          c->atom(QXcbAtom::_MOTIF_WM_HINTS), 0, 20);
574
575     xcb_generic_error_t *error;
576
577     xcb_get_property_reply_t *reply =
578         xcb_get_property_reply(c->xcb_connection(), get_cookie, &error);
579
580     if (reply && reply->format == 32 && reply->type == c->atom(QXcbAtom::_MOTIF_WM_HINTS)) {
581         hints = *((QtMotifWmHints *)xcb_get_property_value(reply));
582     } else if (error) {
583         c->handleXcbError(error);
584         free(error);
585
586         hints.flags = 0L;
587         hints.functions = MWM_FUNC_ALL;
588         hints.decorations = MWM_DECOR_ALL;
589         hints.input_mode = 0L;
590         hints.status = 0L;
591     }
592
593     free(reply);
594
595     return hints;
596 }
597
598 static void setMotifWmHints(QXcbConnection *c, xcb_window_t window, const QtMotifWmHints &hints)
599 {
600     if (hints.flags != 0l) {
601         Q_XCB_CALL2(xcb_change_property(c->xcb_connection(),
602                                        XCB_PROP_MODE_REPLACE,
603                                        window,
604                                        c->atom(QXcbAtom::_MOTIF_WM_HINTS),
605                                        c->atom(QXcbAtom::_MOTIF_WM_HINTS),
606                                        32,
607                                        5,
608                                        &hints), c);
609     } else {
610         Q_XCB_CALL2(xcb_delete_property(c->xcb_connection(), window, c->atom(QXcbAtom::_MOTIF_WM_HINTS)), c);
611     }
612 }
613
614 void QXcbWindow::printNetWmState(const QVector<xcb_atom_t> &state)
615 {
616     printf("_NET_WM_STATE (%d): ", state.size());
617     for (int i = 0; i < state.size(); ++i) {
618 #define CHECK_WM_STATE(state_atom) \
619         if (state.at(i) == atom(QXcbAtom::state_atom))\
620             printf(#state_atom " ");
621         CHECK_WM_STATE(_NET_WM_STATE_ABOVE)
622         CHECK_WM_STATE(_NET_WM_STATE_BELOW)
623         CHECK_WM_STATE(_NET_WM_STATE_FULLSCREEN)
624         CHECK_WM_STATE(_NET_WM_STATE_MAXIMIZED_HORZ)
625         CHECK_WM_STATE(_NET_WM_STATE_MAXIMIZED_VERT)
626         CHECK_WM_STATE(_NET_WM_STATE_MODAL)
627         CHECK_WM_STATE(_NET_WM_STATE_STAYS_ON_TOP)
628         CHECK_WM_STATE(_NET_WM_STATE_DEMANDS_ATTENTION)
629 #undef CHECK_WM_STATE
630     }
631     printf("\n");
632 }
633
634 QVector<xcb_atom_t> QXcbWindow::getNetWmState()
635 {
636     QVector<xcb_atom_t> result;
637
638     xcb_get_property_cookie_t get_cookie =
639         xcb_get_property(xcb_connection(), 0, m_window, atom(QXcbAtom::_NET_WM_STATE),
640                          XCB_ATOM_ATOM, 0, 1024);
641
642     xcb_generic_error_t *error;
643
644     xcb_get_property_reply_t *reply =
645         xcb_get_property_reply(xcb_connection(), get_cookie, &error);
646
647     if (reply && reply->format == 32 && reply->type == XCB_ATOM_ATOM) {
648         result.resize(reply->length);
649
650         memcpy(result.data(), xcb_get_property_value(reply), reply->length * sizeof(xcb_atom_t));
651
652 #ifdef NET_WM_STATE_DEBUG
653         printf("getting net wm state (%x)\n", m_window);
654         printNetWmState(result);
655 #endif
656
657         free(reply);
658     } else if (error) {
659         connection()->handleXcbError(error);
660         free(error);
661     } else {
662 #ifdef NET_WM_STATE_DEBUG
663         printf("getting net wm state (%x), empty\n", m_window);
664 #endif
665     }
666
667     return result;
668 }
669
670 void QXcbWindow::setNetWmState(const QVector<xcb_atom_t> &atoms)
671 {
672     if (atoms.isEmpty()) {
673         Q_XCB_CALL(xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_STATE)));
674     } else {
675         Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
676                                        atom(QXcbAtom::_NET_WM_STATE), XCB_ATOM_ATOM, 32,
677                                        atoms.count(), atoms.constData()));
678     }
679     xcb_flush(xcb_connection());
680 }
681
682
683 Qt::WindowFlags QXcbWindow::setWindowFlags(Qt::WindowFlags flags)
684 {
685     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
686
687     if (type == Qt::ToolTip)
688         flags |= Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint;
689     if (type == Qt::Popup)
690         flags |= Qt::X11BypassWindowManagerHint;
691
692     if (flags & Qt::WindowTransparentForInput) {
693         uint32_t mask = XCB_EVENT_MASK_NO_EVENT;
694         xcb_change_window_attributes(xcb_connection(), xcb_window(), XCB_CW_EVENT_MASK, &mask);
695     }
696
697     setNetWmWindowFlags(flags);
698     setMotifWindowFlags(flags);
699
700     setTransparentForMouseEvents(flags & Qt::WindowTransparentForInput);
701
702     return flags;
703 }
704
705 void QXcbWindow::setMotifWindowFlags(Qt::WindowFlags flags)
706 {
707     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
708
709     QtMotifWmHints mwmhints;
710     mwmhints.flags = 0L;
711     mwmhints.functions = 0L;
712     mwmhints.decorations = 0;
713     mwmhints.input_mode = 0L;
714     mwmhints.status = 0L;
715
716     if (type != Qt::SplashScreen) {
717         mwmhints.flags |= MWM_HINTS_DECORATIONS;
718
719         bool customize = flags & Qt::CustomizeWindowHint;
720         if (!(flags & Qt::FramelessWindowHint) && !(customize && !(flags & Qt::WindowTitleHint))) {
721             mwmhints.decorations |= MWM_DECOR_BORDER;
722             mwmhints.decorations |= MWM_DECOR_RESIZEH;
723
724             if (flags & Qt::WindowTitleHint)
725                 mwmhints.decorations |= MWM_DECOR_TITLE;
726
727             if (flags & Qt::WindowSystemMenuHint)
728                 mwmhints.decorations |= MWM_DECOR_MENU;
729
730             if (flags & Qt::WindowMinimizeButtonHint) {
731                 mwmhints.decorations |= MWM_DECOR_MINIMIZE;
732                 mwmhints.functions |= MWM_FUNC_MINIMIZE;
733             }
734
735             if (flags & Qt::WindowMaximizeButtonHint) {
736                 mwmhints.decorations |= MWM_DECOR_MAXIMIZE;
737                 mwmhints.functions |= MWM_FUNC_MAXIMIZE;
738             }
739
740             if (flags & Qt::WindowCloseButtonHint)
741                 mwmhints.functions |= MWM_FUNC_CLOSE;
742         }
743     } else {
744         // if type == Qt::SplashScreen
745         mwmhints.decorations = MWM_DECOR_ALL;
746     }
747
748     if (mwmhints.functions != 0) {
749         mwmhints.flags |= MWM_HINTS_FUNCTIONS;
750         mwmhints.functions |= MWM_FUNC_MOVE | MWM_FUNC_RESIZE;
751     } else {
752         mwmhints.functions = MWM_FUNC_ALL;
753     }
754
755     if (!(flags & Qt::FramelessWindowHint)
756         && flags & Qt::CustomizeWindowHint
757         && flags & Qt::WindowTitleHint
758         && !(flags &
759              (Qt::WindowMinimizeButtonHint
760               | Qt::WindowMaximizeButtonHint
761               | Qt::WindowCloseButtonHint)))
762     {
763         // a special case - only the titlebar without any button
764         mwmhints.flags = MWM_HINTS_FUNCTIONS;
765         mwmhints.functions = MWM_FUNC_MOVE | MWM_FUNC_RESIZE;
766         mwmhints.decorations = 0;
767     }
768
769     setMotifWmHints(connection(), m_window, mwmhints);
770 }
771
772 void QXcbWindow::changeNetWmState(bool set, xcb_atom_t one, xcb_atom_t two)
773 {
774     xcb_client_message_event_t event;
775
776     event.response_type = XCB_CLIENT_MESSAGE;
777     event.format = 32;
778     event.window = m_window;
779     event.type = atom(QXcbAtom::_NET_WM_STATE);
780     event.data.data32[0] = set ? 1 : 0;
781     event.data.data32[1] = one;
782     event.data.data32[2] = two;
783     event.data.data32[3] = 0;
784     event.data.data32[4] = 0;
785
786     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));
787 }
788
789 Qt::WindowState QXcbWindow::setWindowState(Qt::WindowState state)
790 {
791     if (state == m_windowState)
792         return state;
793
794     // unset old state
795     switch (m_windowState) {
796     case Qt::WindowMinimized:
797         Q_XCB_CALL(xcb_map_window(xcb_connection(), m_window));
798         break;
799     case Qt::WindowMaximized:
800         changeNetWmState(false,
801                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ),
802                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
803         break;
804     case Qt::WindowFullScreen:
805         changeNetWmState(false, atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
806         break;
807     default:
808         break;
809     }
810
811     // set new state
812     switch (state) {
813     case Qt::WindowMinimized:
814         {
815             xcb_client_message_event_t event;
816
817             event.response_type = XCB_CLIENT_MESSAGE;
818             event.format = 32;
819             event.window = m_window;
820             event.type = atom(QXcbAtom::WM_CHANGE_STATE);
821             event.data.data32[0] = XCB_WM_STATE_ICONIC;
822             event.data.data32[1] = 0;
823             event.data.data32[2] = 0;
824             event.data.data32[3] = 0;
825             event.data.data32[4] = 0;
826
827             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));
828         }
829         break;
830     case Qt::WindowMaximized:
831         changeNetWmState(true,
832                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ),
833                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
834         break;
835     case Qt::WindowFullScreen:
836         changeNetWmState(true, atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
837         break;
838     case Qt::WindowNoState:
839         break;
840     default:
841         break;
842     }
843
844     connection()->sync();
845
846     m_windowState = state;
847     return m_windowState;
848 }
849
850 void QXcbWindow::setNetWmWindowFlags(Qt::WindowFlags flags)
851 {
852     // in order of decreasing priority
853     QVector<uint> windowTypes;
854
855     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
856
857     switch (type) {
858     case Qt::Dialog:
859     case Qt::Sheet:
860         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_DIALOG));
861         break;
862     case Qt::Tool:
863     case Qt::Drawer:
864         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_UTILITY));
865         break;
866     case Qt::ToolTip:
867         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_TOOLTIP));
868         break;
869     case Qt::SplashScreen:
870         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_SPLASH));
871         break;
872     default:
873         break;
874     }
875
876     if (flags & Qt::FramelessWindowHint)
877         windowTypes.append(atom(QXcbAtom::_KDE_NET_WM_WINDOW_TYPE_OVERRIDE));
878
879     windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_NORMAL));
880
881     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
882                                    atom(QXcbAtom::_NET_WM_WINDOW_TYPE), XCB_ATOM_ATOM, 32,
883                                    windowTypes.count(), windowTypes.constData()));
884 }
885
886 void QXcbWindow::updateMotifWmHintsBeforeMap()
887 {
888     QtMotifWmHints mwmhints = getMotifWmHints(connection(), m_window);
889
890     if (window()->windowModality() != Qt::NonModal) {
891         switch (window()->windowModality()) {
892         case Qt::WindowModal:
893             mwmhints.input_mode = MWM_INPUT_PRIMARY_APPLICATION_MODAL;
894             break;
895         case Qt::ApplicationModal:
896         default:
897             mwmhints.input_mode = MWM_INPUT_FULL_APPLICATION_MODAL;
898             break;
899         }
900         mwmhints.flags |= MWM_HINTS_INPUT_MODE;
901     } else {
902         mwmhints.input_mode = MWM_INPUT_MODELESS;
903         mwmhints.flags &= ~MWM_HINTS_INPUT_MODE;
904     }
905
906     if (window()->minimumSize() == window()->maximumSize()) {
907         // fixed size, remove the resize handle (since mwm/dtwm
908         // isn't smart enough to do it itself)
909         mwmhints.flags |= MWM_HINTS_FUNCTIONS;
910         if (mwmhints.functions == MWM_FUNC_ALL) {
911             mwmhints.functions = MWM_FUNC_MOVE;
912         } else {
913             mwmhints.functions &= ~MWM_FUNC_RESIZE;
914         }
915
916         if (mwmhints.decorations == MWM_DECOR_ALL) {
917             mwmhints.flags |= MWM_HINTS_DECORATIONS;
918             mwmhints.decorations = (MWM_DECOR_BORDER
919                                     | MWM_DECOR_TITLE
920                                     | MWM_DECOR_MENU);
921         } else {
922             mwmhints.decorations &= ~MWM_DECOR_RESIZEH;
923         }
924     }
925
926     if (window()->windowFlags() & Qt::WindowMinimizeButtonHint) {
927         mwmhints.flags |= MWM_HINTS_DECORATIONS;
928         mwmhints.decorations |= MWM_DECOR_MINIMIZE;
929         mwmhints.functions |= MWM_FUNC_MINIMIZE;
930     }
931     if (window()->windowFlags() & Qt::WindowMaximizeButtonHint) {
932         mwmhints.flags |= MWM_HINTS_DECORATIONS;
933         mwmhints.decorations |= MWM_DECOR_MAXIMIZE;
934         mwmhints.functions |= MWM_FUNC_MAXIMIZE;
935     }
936     if (window()->windowFlags() & Qt::WindowCloseButtonHint)
937         mwmhints.functions |= MWM_FUNC_CLOSE;
938
939     setMotifWmHints(connection(), m_window, mwmhints);
940 }
941
942 void QXcbWindow::updateNetWmStateBeforeMap()
943 {
944     QVector<xcb_atom_t> netWmState;
945
946     Qt::WindowFlags flags = window()->windowFlags();
947     if (flags & Qt::WindowStaysOnTopHint) {
948         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_ABOVE));
949         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_STAYS_ON_TOP));
950     } else if (flags & Qt::WindowStaysOnBottomHint) {
951         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_BELOW));
952     }
953
954     if (window()->windowState() & Qt::WindowFullScreen) {
955         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
956     }
957
958     if (window()->windowState() & Qt::WindowMaximized) {
959         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ));
960         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
961     }
962
963     if (window()->windowModality() != Qt::NonModal) {
964         netWmState.append(atom(QXcbAtom::_NET_WM_STATE_MODAL));
965     }
966
967     setNetWmState(netWmState);
968 }
969
970 void QXcbWindow::updateNetWmUserTime(xcb_timestamp_t timestamp)
971 {
972     xcb_window_t wid = m_window;
973
974     const bool isSupportedByWM = connection()->wmSupport()->isSupportedByWM(atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW));
975     if (m_netWmUserTimeWindow || isSupportedByWM) {
976         if (!m_netWmUserTimeWindow) {
977             m_netWmUserTimeWindow = xcb_generate_id(xcb_connection());
978             Q_XCB_CALL(xcb_create_window(xcb_connection(),
979                                          XCB_COPY_FROM_PARENT,            // depth -- same as root
980                                          m_netWmUserTimeWindow,                        // window id
981                                          m_window,                   // parent window id
982                                          -1, -1, 1, 1,
983                                          0,                               // border width
984                                          XCB_WINDOW_CLASS_INPUT_OUTPUT,   // window class
985                                          m_screen->screen()->root_visual, // visual
986                                          0,                               // value mask
987                                          0));                             // value list
988             wid = m_netWmUserTimeWindow;
989             xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window, atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW),
990                                 XCB_ATOM_WINDOW, 32, 1, &m_netWmUserTimeWindow);
991             xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_USER_TIME));
992         } else if (!isSupportedByWM) {
993             // WM no longer supports it, then we should remove the
994             // _NET_WM_USER_TIME_WINDOW atom.
995             xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW));
996             xcb_destroy_window(xcb_connection(), m_netWmUserTimeWindow);
997             m_netWmUserTimeWindow = XCB_NONE;
998         } else {
999             wid = m_netWmUserTimeWindow;
1000         }
1001     }
1002     xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, wid, atom(QXcbAtom::_NET_WM_USER_TIME),
1003                         XCB_ATOM_CARDINAL, 32, 1, &timestamp);
1004 }
1005
1006 void QXcbWindow::setTransparentForMouseEvents(bool transparent)
1007 {
1008     if (transparent == m_transparent)
1009         return;
1010
1011     xcb_rectangle_t rectangle;
1012
1013     xcb_rectangle_t *rect = 0;
1014     int nrect = 0;
1015
1016     if (!transparent) {
1017         rectangle.x = 0;
1018         rectangle.y = 0;
1019         rectangle.width = geometry().width();
1020         rectangle.height = geometry().height();
1021         rect = &rectangle;
1022         nrect = 1;
1023     }
1024
1025     xcb_xfixes_region_t region = xcb_generate_id(xcb_connection());
1026     xcb_xfixes_create_region(xcb_connection(), region, nrect, rect);
1027     xcb_xfixes_set_window_shape_region_checked(xcb_connection(), m_window, XCB_SHAPE_SK_INPUT, 0, 0, region);
1028     xcb_xfixes_destroy_region(xcb_connection(), region);
1029
1030     m_transparent = transparent;
1031 }
1032
1033
1034 WId QXcbWindow::winId() const
1035 {
1036     return m_window;
1037 }
1038
1039 void QXcbWindow::setParent(const QPlatformWindow *parent)
1040 {
1041     // re-create for compatibility
1042     create();
1043
1044     QPoint topLeft = geometry().topLeft();
1045
1046     xcb_window_t xcb_parent_id = parent ? static_cast<const QXcbWindow *>(parent)->xcb_window() : m_screen->root();
1047     Q_XCB_CALL(xcb_reparent_window(xcb_connection(), xcb_window(), xcb_parent_id, topLeft.x(), topLeft.y()));
1048 }
1049
1050 void QXcbWindow::setWindowTitle(const QString &title)
1051 {
1052     QByteArray ba = title.toUtf8();
1053     Q_XCB_CALL(xcb_change_property(xcb_connection(),
1054                                    XCB_PROP_MODE_REPLACE,
1055                                    m_window,
1056                                    atom(QXcbAtom::_NET_WM_NAME),
1057                                    atom(QXcbAtom::UTF8_STRING),
1058                                    8,
1059                                    ba.length(),
1060                                    ba.constData()));
1061 }
1062
1063 void QXcbWindow::raise()
1064 {
1065     const quint32 mask = XCB_CONFIG_WINDOW_STACK_MODE;
1066     const quint32 values[] = { XCB_STACK_MODE_ABOVE };
1067     Q_XCB_CALL(xcb_configure_window(xcb_connection(), m_window, mask, values));
1068 }
1069
1070 void QXcbWindow::lower()
1071 {
1072     const quint32 mask = XCB_CONFIG_WINDOW_STACK_MODE;
1073     const quint32 values[] = { XCB_STACK_MODE_BELOW };
1074     Q_XCB_CALL(xcb_configure_window(xcb_connection(), m_window, mask, values));
1075 }
1076
1077 void QXcbWindow::propagateSizeHints()
1078 {
1079     // update WM_NORMAL_HINTS
1080     xcb_size_hints_t hints;
1081     memset(&hints, 0, sizeof(hints));
1082
1083     QRect rect = geometry();
1084
1085     QWindow *win = window();
1086
1087     xcb_size_hints_set_position(&hints, true, rect.x(), rect.y());
1088     xcb_size_hints_set_size(&hints, true, rect.width(), rect.height());
1089     xcb_size_hints_set_win_gravity(&hints, qt_window_private(win)->positionPolicy == QWindowPrivate::WindowFrameInclusive
1090                                            ? XCB_GRAVITY_NORTH_WEST : XCB_GRAVITY_STATIC);
1091
1092     QSize minimumSize = win->minimumSize();
1093     QSize maximumSize = win->maximumSize();
1094     QSize baseSize = win->baseSize();
1095     QSize sizeIncrement = win->sizeIncrement();
1096
1097     if (minimumSize.width() > 0 || minimumSize.height() > 0)
1098         xcb_size_hints_set_min_size(&hints, minimumSize.width(), minimumSize.height());
1099
1100     if (maximumSize.width() < QWINDOWSIZE_MAX || maximumSize.height() < QWINDOWSIZE_MAX)
1101         xcb_size_hints_set_max_size(&hints,
1102                                     qMin(XCOORD_MAX, maximumSize.width()),
1103                                     qMin(XCOORD_MAX, maximumSize.height()));
1104
1105     if (sizeIncrement.width() > 0 || sizeIncrement.height() > 0) {
1106         xcb_size_hints_set_base_size(&hints, baseSize.width(), baseSize.height());
1107         xcb_size_hints_set_resize_inc(&hints, sizeIncrement.width(), sizeIncrement.height());
1108     }
1109
1110     xcb_set_wm_normal_hints(xcb_connection(), m_window, &hints);
1111 }
1112
1113 void QXcbWindow::requestActivateWindow()
1114 {
1115     if (m_mapped){
1116         updateNetWmUserTime(connection()->time());
1117         Q_XCB_CALL(xcb_set_input_focus(xcb_connection(), XCB_INPUT_FOCUS_PARENT, m_window, connection()->time()));
1118     }
1119     connection()->sync();
1120 }
1121
1122 QSurfaceFormat QXcbWindow::format() const
1123 {
1124     // ### return actual format
1125     return m_requestedFormat;
1126 }
1127
1128 #if defined(XCB_USE_EGL)
1129 QXcbEGLSurface *QXcbWindow::eglSurface() const
1130 {
1131     if (!m_eglSurface) {
1132         EGLDisplay display = connection()->egl_display();
1133         EGLConfig config = q_configFromGLFormat(display, window()->format(), true);
1134         EGLSurface surface = eglCreateWindowSurface(display, config, (EGLNativeWindowType)m_window, 0);
1135
1136         m_eglSurface = new QXcbEGLSurface(display, surface);
1137     }
1138
1139     return m_eglSurface;
1140 }
1141 #endif
1142
1143 void QXcbWindow::handleExposeEvent(const xcb_expose_event_t *event)
1144 {
1145     QRect rect(event->x, event->y, event->width, event->height);
1146
1147     if (m_exposeRegion.isEmpty())
1148         m_exposeRegion = rect;
1149     else
1150         m_exposeRegion |= rect;
1151
1152     // if count is non-zero there are more expose events pending
1153     if (event->count == 0) {
1154         QWindowSystemInterface::handleSynchronousExposeEvent(window(), m_exposeRegion);
1155         m_exposeRegion = QRegion();
1156     }
1157 }
1158
1159 void QXcbWindow::handleClientMessageEvent(const xcb_client_message_event_t *event)
1160 {
1161     if (event->format != 32)
1162         return;
1163
1164     if (event->type == atom(QXcbAtom::WM_PROTOCOLS)) {
1165         if (event->data.data32[0] == atom(QXcbAtom::WM_DELETE_WINDOW)) {
1166             QWindowSystemInterface::handleCloseEvent(window());
1167         } else if (event->data.data32[0] == atom(QXcbAtom::WM_TAKE_FOCUS)) {
1168             connection()->setTime(event->data.data32[1]);
1169         } else if (event->data.data32[0] == atom(QXcbAtom::_NET_WM_PING)) {
1170             xcb_client_message_event_t reply = *event;
1171
1172             reply.response_type = XCB_CLIENT_MESSAGE;
1173             reply.window = m_screen->root();
1174
1175             xcb_send_event(xcb_connection(), 0, m_screen->root(), XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (const char *)&reply);
1176             xcb_flush(xcb_connection());
1177         } else if (event->data.data32[0] == atom(QXcbAtom::_NET_WM_SYNC_REQUEST)) {
1178             connection()->setTime(event->data.data32[1]);
1179             m_syncValue.lo = event->data.data32[2];
1180             m_syncValue.hi = event->data.data32[3];
1181         } else {
1182             qWarning() << "unhandled WM_PROTOCOLS message:" << connection()->atomName(event->data.data32[0]);
1183         }
1184     } else if (event->type == atom(QXcbAtom::XdndEnter)) {
1185         connection()->drag()->handleEnter(window(), event);
1186     } else if (event->type == atom(QXcbAtom::XdndPosition)) {
1187         connection()->drag()->handlePosition(window(), event, false);
1188     } else if (event->type == atom(QXcbAtom::XdndLeave)) {
1189         connection()->drag()->handleLeave(window(), event, false);
1190     } else if (event->type == atom(QXcbAtom::XdndDrop)) {
1191         connection()->drag()->handleDrop(window(), event, false);
1192     } else {
1193         qWarning() << "unhandled client message:" << connection()->atomName(event->type);
1194     }
1195 }
1196
1197 void QXcbWindow::handleConfigureNotifyEvent(const xcb_configure_notify_event_t *event)
1198 {
1199     QRect rect(event->x, event->y, event->width, event->height);
1200
1201     QPlatformWindow::setGeometry(rect);
1202     QWindowSystemInterface::handleGeometryChange(window(), rect);
1203
1204     m_dirtyFrameMargins = true;
1205
1206 #if XCB_USE_DRI2
1207     if (m_context)
1208         static_cast<QDri2Context *>(m_context)->resize(rect.size());
1209 #endif
1210 }
1211
1212 void QXcbWindow::handleMapNotifyEvent(const xcb_map_notify_event_t *event)
1213 {
1214     if (event->window == m_window) {
1215         m_mapped = true;
1216         QWindowSystemInterface::handleMapEvent(window());
1217     }
1218 }
1219
1220 void QXcbWindow::handleUnmapNotifyEvent(const xcb_unmap_notify_event_t *event)
1221 {
1222     if (event->window == m_window) {
1223         m_mapped = false;
1224         QWindowSystemInterface::handleUnmapEvent(window());
1225     }
1226 }
1227
1228 static Qt::MouseButtons translateMouseButtons(int s)
1229 {
1230     Qt::MouseButtons ret = 0;
1231     if (s & XCB_BUTTON_MASK_1)
1232         ret |= Qt::LeftButton;
1233     if (s & XCB_BUTTON_MASK_2)
1234         ret |= Qt::MidButton;
1235     if (s & XCB_BUTTON_MASK_3)
1236         ret |= Qt::RightButton;
1237     return ret;
1238 }
1239
1240 static Qt::MouseButton translateMouseButton(xcb_button_t s)
1241 {
1242     switch (s) {
1243     case 1:
1244         return Qt::LeftButton;
1245     case 2:
1246         return Qt::MidButton;
1247     case 3:
1248         return Qt::RightButton;
1249     default:
1250         return Qt::NoButton;
1251     }
1252 }
1253
1254 void QXcbWindow::handleButtonPressEvent(const xcb_button_press_event_t *event)
1255 {
1256     updateNetWmUserTime(event->time);
1257
1258     QPoint local(event->event_x, event->event_y);
1259     QPoint global(event->root_x, event->root_y);
1260
1261     Qt::KeyboardModifiers modifiers = connection()->keyboard()->translateModifiers(event->state);
1262
1263     if (event->detail >= 4 && event->detail <= 7) {
1264         //logic borrowed from qapplication_x11.cpp
1265         int delta = 120 * ((event->detail == 4 || event->detail == 6) ? 1 : -1);
1266         bool hor = (((event->detail == 4 || event->detail == 5)
1267                      && (modifiers & Qt::AltModifier))
1268                     || (event->detail == 6 || event->detail == 7));
1269
1270         QWindowSystemInterface::handleWheelEvent(window(), event->time,
1271                                                  local, global, delta, hor ? Qt::Horizontal : Qt::Vertical, modifiers);
1272         return;
1273     }
1274
1275     handleMouseEvent(event->detail, event->state, event->time, local, global, modifiers);
1276 }
1277
1278 void QXcbWindow::handleButtonReleaseEvent(const xcb_button_release_event_t *event)
1279 {
1280     QPoint local(event->event_x, event->event_y);
1281     QPoint global(event->root_x, event->root_y);
1282     Qt::KeyboardModifiers modifiers = connection()->keyboard()->translateModifiers(event->state);
1283
1284     handleMouseEvent(event->detail, event->state, event->time, local, global, modifiers);
1285 }
1286
1287 void QXcbWindow::handleMotionNotifyEvent(const xcb_motion_notify_event_t *event)
1288 {
1289     QPoint local(event->event_x, event->event_y);
1290     QPoint global(event->root_x, event->root_y);
1291     Qt::KeyboardModifiers modifiers = connection()->keyboard()->translateModifiers(event->state);
1292
1293     handleMouseEvent(event->detail, event->state, event->time, local, global, modifiers);
1294 }
1295
1296 void QXcbWindow::handleMouseEvent(xcb_button_t detail, uint16_t state, xcb_timestamp_t time, const QPoint &local, const QPoint &global, Qt::KeyboardModifiers modifiers)
1297 {
1298     connection()->setTime(time);
1299
1300     Qt::MouseButtons buttons = translateMouseButtons(state);
1301     Qt::MouseButton button = translateMouseButton(detail);
1302
1303     buttons ^= button; // X event uses state *before*, Qt uses state *after*
1304
1305     QWindowSystemInterface::handleMouseEvent(window(), time, local, global, buttons, modifiers);
1306 }
1307
1308 void QXcbWindow::handleEnterNotifyEvent(const xcb_enter_notify_event_t *event)
1309 {
1310     connection()->setTime(event->time);
1311
1312     if ((event->mode != XCB_NOTIFY_MODE_NORMAL && event->mode != XCB_NOTIFY_MODE_UNGRAB)
1313         || event->detail == XCB_NOTIFY_DETAIL_VIRTUAL
1314         || event->detail == XCB_NOTIFY_DETAIL_NONLINEAR_VIRTUAL)
1315     {
1316         return;
1317     }
1318
1319     QWindowSystemInterface::handleEnterEvent(window());
1320 }
1321
1322 void QXcbWindow::handleLeaveNotifyEvent(const xcb_leave_notify_event_t *event)
1323 {
1324     connection()->setTime(event->time);
1325
1326     if ((event->mode != XCB_NOTIFY_MODE_NORMAL && event->mode != XCB_NOTIFY_MODE_UNGRAB)
1327         || event->detail == XCB_NOTIFY_DETAIL_INFERIOR)
1328     {
1329         return;
1330     }
1331
1332     QWindowSystemInterface::handleLeaveEvent(window());
1333 }
1334
1335 void QXcbWindow::handlePropertyNotifyEvent(const xcb_property_notify_event_t *event)
1336 {
1337     connection()->setTime(event->time);
1338
1339     bool propertyDeleted = event->state == XCB_PROPERTY_DELETE;
1340
1341     if (event->atom == atom(QXcbAtom::_NET_WM_STATE) || event->atom == atom(QXcbAtom::WM_STATE)) {
1342         if (propertyDeleted)
1343             return;
1344
1345         xcb_get_property_cookie_t get_cookie =
1346             xcb_get_property(xcb_connection(), 0, m_window, atom(QXcbAtom::WM_STATE),
1347                              XCB_ATOM_ANY, 0, 1024);
1348
1349         xcb_generic_error_t *error;
1350
1351         xcb_get_property_reply_t *reply =
1352             xcb_get_property_reply(xcb_connection(), get_cookie, &error);
1353
1354         xcb_atom_t wm_state = XCB_WM_STATE_WITHDRAWN;
1355         if (reply && reply->format == 32 && reply->type == atom(QXcbAtom::WM_STATE)) {
1356             if (reply->length != 0)
1357                 wm_state = ((long *)xcb_get_property_value(reply))[0];
1358             free(reply);
1359         } else if (error) {
1360             connection()->handleXcbError(error);
1361             free(error);
1362         }
1363
1364         QVector<xcb_atom_t> netWmState = getNetWmState();
1365
1366         bool maximized = netWmState.contains(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ))
1367             && netWmState.contains(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
1368         bool fullscreen = netWmState.contains(atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
1369
1370         Qt::WindowState state = Qt::WindowNoState;
1371         if (wm_state == XCB_WM_STATE_ICONIC)
1372             state = Qt::WindowMinimized;
1373         else if (maximized)
1374             state = Qt::WindowMaximized;
1375         else if (fullscreen)
1376             state = Qt::WindowFullScreen;
1377
1378         QWindowSystemInterface::handleWindowStateChanged(window(), state);
1379     }
1380 }
1381
1382 void QXcbWindow::handleFocusInEvent(const xcb_focus_in_event_t *)
1383 {
1384     QWindowSystemInterface::handleWindowActivated(window());
1385 }
1386
1387 static bool focusInPeeker(xcb_generic_event_t *event)
1388 {
1389     if (!event) {
1390         // FocusIn event is not in the queue, proceed with FocusOut normally.
1391         QWindowSystemInterface::handleWindowActivated(0);
1392         return true;
1393     }
1394     uint response_type = event->response_type & ~0x80;
1395     return response_type == XCB_FOCUS_IN;
1396 }
1397
1398 void QXcbWindow::handleFocusOutEvent(const xcb_focus_out_event_t *)
1399 {
1400     // Do not set the active window to 0 if there is a FocusIn coming.
1401     // There is however no equivalent for XPutBackEvent so register a
1402     // callback for QXcbConnection instead.
1403     connection()->addPeekFunc(focusInPeeker);
1404 }
1405
1406 void QXcbWindow::updateSyncRequestCounter()
1407 {
1408     if (m_screen->syncRequestSupported() && (m_syncValue.lo != 0 || m_syncValue.hi != 0)) {
1409         Q_XCB_CALL(xcb_sync_set_counter(xcb_connection(), m_syncCounter, m_syncValue));
1410         xcb_flush(xcb_connection());
1411         connection()->sync();
1412
1413         m_syncValue.lo = 0;
1414         m_syncValue.hi = 0;
1415     }
1416 }
1417
1418 bool QXcbWindow::setKeyboardGrabEnabled(bool grab)
1419 {
1420     if (!grab) {
1421         xcb_ungrab_keyboard(xcb_connection(), XCB_TIME_CURRENT_TIME);
1422         return true;
1423     }
1424     xcb_grab_keyboard_cookie_t cookie = xcb_grab_keyboard(xcb_connection(), false,
1425                                                           m_window, XCB_TIME_CURRENT_TIME,
1426                                                           XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
1427     xcb_generic_error_t *err;
1428     xcb_grab_keyboard_reply_t *reply = xcb_grab_keyboard_reply(xcb_connection(), cookie, &err);
1429     bool result = !(err || !reply || reply->status != XCB_GRAB_STATUS_SUCCESS);
1430     free(reply);
1431     free(err);
1432     return result;
1433 }
1434
1435 bool QXcbWindow::setMouseGrabEnabled(bool grab)
1436 {
1437     if (!grab) {
1438         xcb_ungrab_pointer(xcb_connection(), XCB_TIME_CURRENT_TIME);
1439         return true;
1440     }
1441     xcb_grab_pointer_cookie_t cookie = xcb_grab_pointer(xcb_connection(), false, m_window,
1442                                                         (XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE
1443                                                          | XCB_EVENT_MASK_BUTTON_MOTION | XCB_EVENT_MASK_ENTER_WINDOW
1444                                                          | XCB_EVENT_MASK_LEAVE_WINDOW | XCB_EVENT_MASK_POINTER_MOTION),
1445                                                         XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC,
1446                                                         XCB_WINDOW_NONE, XCB_CURSOR_NONE,
1447                                                         XCB_TIME_CURRENT_TIME);
1448     xcb_generic_error_t *err;
1449     xcb_grab_pointer_reply_t *reply = xcb_grab_pointer_reply(xcb_connection(), cookie, &err);
1450     bool result = !(err || !reply || reply->status != XCB_GRAB_STATUS_SUCCESS);
1451     free(reply);
1452     free(err);
1453     return result;
1454 }
1455
1456 void QXcbWindow::setCursor(xcb_cursor_t cursor)
1457 {
1458     xcb_change_window_attributes(xcb_connection(), m_window, XCB_CW_CURSOR, &cursor);
1459     xcb_flush(xcb_connection());
1460 }
1461
1462 QT_END_NAMESPACE