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