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