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