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