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