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