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