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