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