7020e63b0efa70d07c4565dfeb3748dfcae05f24
[profile/ivi/qtbase.git] / src / plugins / platforms / xcb / qxcbwindow.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the plugins of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qxcbwindow.h"
43
44 #include <QtDebug>
45 #include <QScreen>
46 #include <QtGui/QIcon>
47 #include <QtGui/QRegion>
48
49 #include "qxcbconnection.h"
50 #include "qxcbscreen.h"
51 #include "qxcbdrag.h"
52 #include "qxcbkeyboard.h"
53 #include "qxcbwmsupport.h"
54 #include "qxcbimage.h"
55
56 #include <qpa/qplatformintegration.h>
57
58 #ifdef XCB_USE_DRI2
59 #include "qdri2context.h"
60 #endif
61
62 // FIXME This workaround can be removed for xcb-icccm > 3.8
63 #define class class_name
64 #include <xcb/xcb_icccm.h>
65 #undef class
66 #include <xcb/xfixes.h>
67 #ifndef QT_NO_SHAPE
68 #  include <xcb/shape.h>
69 #endif // QT_NO_SHAPE
70
71 // xcb-icccm 3.8 support
72 #ifdef XCB_ICCCM_NUM_WM_SIZE_HINTS_ELEMENTS
73 #define xcb_get_wm_hints_reply xcb_icccm_get_wm_hints_reply
74 #define xcb_get_wm_hints xcb_icccm_get_wm_hints
75 #define xcb_get_wm_hints_unchecked xcb_icccm_get_wm_hints_unchecked
76 #define xcb_set_wm_hints xcb_icccm_set_wm_hints
77 #define xcb_set_wm_normal_hints xcb_icccm_set_wm_normal_hints
78 #define xcb_size_hints_set_base_size xcb_icccm_size_hints_set_base_size
79 #define xcb_size_hints_set_max_size xcb_icccm_size_hints_set_max_size
80 #define xcb_size_hints_set_min_size xcb_icccm_size_hints_set_min_size
81 #define xcb_size_hints_set_position xcb_icccm_size_hints_set_position
82 #define xcb_size_hints_set_resize_inc xcb_icccm_size_hints_set_resize_inc
83 #define xcb_size_hints_set_size xcb_icccm_size_hints_set_size
84 #define xcb_size_hints_set_win_gravity xcb_icccm_size_hints_set_win_gravity
85 #define xcb_wm_hints_set_iconic xcb_icccm_wm_hints_set_iconic
86 #define xcb_wm_hints_set_normal xcb_icccm_wm_hints_set_normal
87 #define xcb_wm_hints_set_input xcb_icccm_wm_hints_set_input
88 #define xcb_wm_hints_t xcb_icccm_wm_hints_t
89 #define XCB_WM_STATE_ICONIC XCB_ICCCM_WM_STATE_ICONIC
90 #define XCB_WM_STATE_WITHDRAWN XCB_ICCCM_WM_STATE_WITHDRAWN
91 #endif
92
93 #include <private/qguiapplication_p.h>
94 #include <private/qwindow_p.h>
95
96 #include <qpa/qplatformbackingstore.h>
97 #include <qpa/qwindowsysteminterface.h>
98
99 #include <stdio.h>
100
101 #ifdef XCB_USE_XLIB
102 #include <X11/Xlib.h>
103 #include <X11/Xutil.h>
104 #endif
105
106 #if defined(XCB_USE_XINPUT2_MAEMO) || defined(XCB_USE_XINPUT2)
107 #include <X11/extensions/XInput2.h>
108 #endif
109
110 #if defined(XCB_USE_GLX)
111 #include "qglxintegration.h"
112 #include <QtPlatformSupport/private/qglxconvenience_p.h>
113 #elif defined(XCB_USE_EGL)
114 #include "qxcbeglsurface.h"
115 #include <QtPlatformSupport/private/qeglconvenience_p.h>
116 #include <QtPlatformSupport/private/qxlibeglintegration_p.h>
117 #endif
118
119 #define XCOORD_MAX 16383
120
121 //#ifdef NET_WM_STATE_DEBUG
122
123 QT_BEGIN_NAMESPACE
124
125 // Returns true if we should set WM_TRANSIENT_FOR on \a w
126 static inline bool isTransient(const QWindow *w)
127 {
128     return w->windowType() == Qt::Dialog
129            || w->windowType() == Qt::Sheet
130            || w->windowType() == Qt::Tool
131            || w->windowType() == Qt::SplashScreen
132            || w->windowType() == Qt::ToolTip
133            || w->windowType() == Qt::Drawer
134            || w->windowType() == Qt::Popup;
135 }
136
137 static inline QImage::Format imageFormatForDepth(int depth)
138 {
139     switch (depth) {
140         case 32: return QImage::Format_ARGB32_Premultiplied;
141         case 24: return QImage::Format_RGB32;
142         case 16: return QImage::Format_RGB16;
143         default: return QImage::Format_Invalid;
144     }
145 }
146
147 static inline bool positionIncludesFrame(QWindow *w)
148 {
149     return qt_window_private(w)->positionPolicy == QWindowPrivate::WindowFrameInclusive;
150 }
151
152 QXcbWindow::QXcbWindow(QWindow *window)
153     : QPlatformWindow(window)
154     , m_window(0)
155     , m_syncCounter(0)
156     , m_gravity(XCB_GRAVITY_STATIC)
157     , m_mapped(false)
158     , m_transparent(false)
159     , m_deferredActivation(false)
160     , m_netWmUserTimeWindow(XCB_NONE)
161     , m_dirtyFrameMargins(false)
162 #if defined(XCB_USE_EGL)
163     , m_eglSurface(0)
164 #endif
165     , m_lastWindowStateEvent(-1)
166 {
167     m_screen = static_cast<QXcbScreen *>(window->screen()->handle());
168
169     setConnection(m_screen->connection());
170
171     create();
172 }
173
174 void QXcbWindow::create()
175 {
176     destroy();
177
178     m_deferredExpose = false;
179     m_configureNotifyPending = true;
180     m_windowState = Qt::WindowNoState;
181
182     Qt::WindowType type = window()->windowType();
183
184     if (type == Qt::Desktop) {
185         m_window = m_screen->root();
186         m_depth = m_screen->screen()->root_depth;
187         m_imageFormat = imageFormatForDepth(m_depth);
188         connection()->addWindow(m_window, this);
189         return;
190     }
191
192     // Determine gravity from initial position. Do not change
193     // later as it will cause the window to move uncontrollably.
194     m_gravity = positionIncludesFrame(window()) ?
195                 XCB_GRAVITY_NORTH_WEST : XCB_GRAVITY_STATIC;
196
197     const quint32 mask = XCB_CW_BACK_PIXMAP | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_SAVE_UNDER | XCB_CW_EVENT_MASK;
198     const quint32 values[] = {
199         // XCB_CW_BACK_PIXMAP
200         XCB_NONE,
201         // XCB_CW_OVERRIDE_REDIRECT
202         type == Qt::Popup || type == Qt::ToolTip,
203         // XCB_CW_SAVE_UNDER
204         type == Qt::Popup || type == Qt::Tool || type == Qt::SplashScreen || type == Qt::ToolTip || type == Qt::Drawer,
205         // XCB_CW_EVENT_MASK
206         XCB_EVENT_MASK_EXPOSURE
207         | XCB_EVENT_MASK_STRUCTURE_NOTIFY
208         | XCB_EVENT_MASK_KEY_PRESS
209         | XCB_EVENT_MASK_KEY_RELEASE
210         | XCB_EVENT_MASK_BUTTON_PRESS
211         | XCB_EVENT_MASK_BUTTON_RELEASE
212         | XCB_EVENT_MASK_BUTTON_MOTION
213         | XCB_EVENT_MASK_ENTER_WINDOW
214         | XCB_EVENT_MASK_LEAVE_WINDOW
215         | XCB_EVENT_MASK_POINTER_MOTION
216         | XCB_EVENT_MASK_PROPERTY_CHANGE
217         | XCB_EVENT_MASK_FOCUS_CHANGE
218     };
219
220     // Parameters to XCreateWindow() are frame corner + inner size.
221     // This fits in case position policy is frame inclusive. There is
222     // currently no way to implement it for frame-exclusive geometries.
223     QRect rect = window()->geometry();
224     QPlatformWindow::setGeometry(rect);
225
226     rect.setWidth(qBound(1, rect.width(), XCOORD_MAX));
227     rect.setHeight(qBound(1, rect.height(), XCOORD_MAX));
228
229     xcb_window_t xcb_parent_id = m_screen->root();
230     if (parent())
231         xcb_parent_id = static_cast<QXcbWindow *>(parent())->xcb_window();
232
233     m_format = window()->requestedFormat();
234
235 #if (defined(XCB_USE_GLX) || defined(XCB_USE_EGL)) && defined(XCB_USE_XLIB)
236     if (QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::OpenGL)
237         || m_format.hasAlpha())
238     {
239 #if defined(XCB_USE_GLX)
240         XVisualInfo *visualInfo = qglx_findVisualInfo(DISPLAY_FROM_XCB(m_screen), m_screen->screenNumber(), &m_format);
241         if (!visualInfo && window()->surfaceType() == QSurface::OpenGLSurface)
242             qFatal("Could not initialize GLX");
243 #elif defined(XCB_USE_EGL)
244         EGLDisplay eglDisplay = connection()->egl_display();
245         EGLConfig eglConfig = q_configFromGLFormat(eglDisplay, m_format, true);
246         m_format = q_glFormatFromConfig(eglDisplay, eglConfig);
247
248         VisualID id = QXlibEglIntegration::getCompatibleVisualId(DISPLAY_FROM_XCB(this), eglDisplay, eglConfig);
249
250         XVisualInfo visualInfoTemplate;
251         memset(&visualInfoTemplate, 0, sizeof(XVisualInfo));
252         visualInfoTemplate.visualid = id;
253
254         XVisualInfo *visualInfo;
255         int matchingCount = 0;
256         visualInfo = XGetVisualInfo(DISPLAY_FROM_XCB(this), VisualIDMask, &visualInfoTemplate, &matchingCount);
257         if (!visualInfo && window()->surfaceType() == QSurface::OpenGLSurface)
258             qFatal("Could not initialize EGL");
259 #endif //XCB_USE_GLX
260         if (visualInfo) {
261             m_depth = visualInfo->depth;
262             m_imageFormat = imageFormatForDepth(m_depth);
263             Colormap cmap = XCreateColormap(DISPLAY_FROM_XCB(this), xcb_parent_id, visualInfo->visual, AllocNone);
264
265             XSetWindowAttributes a;
266             a.background_pixel = WhitePixel(DISPLAY_FROM_XCB(this), m_screen->screenNumber());
267             a.border_pixel = BlackPixel(DISPLAY_FROM_XCB(this), m_screen->screenNumber());
268             a.colormap = cmap;
269
270             m_visualId = visualInfo->visualid;
271
272             m_window = XCreateWindow(DISPLAY_FROM_XCB(this), xcb_parent_id, rect.x(), rect.y(), rect.width(), rect.height(),
273                                       0, visualInfo->depth, InputOutput, visualInfo->visual,
274                                       CWBackPixel|CWBorderPixel|CWColormap, &a);
275
276             XFree(visualInfo);
277         }
278     }
279
280     if (!m_window)
281 #endif //defined(XCB_USE_GLX) || defined(XCB_USE_EGL)
282     {
283         m_window = xcb_generate_id(xcb_connection());
284         m_depth = m_screen->screen()->root_depth;
285         m_imageFormat = imageFormatForDepth(m_depth);
286         m_visualId = m_screen->screen()->root_visual;
287
288         Q_XCB_CALL(xcb_create_window(xcb_connection(),
289                                      XCB_COPY_FROM_PARENT,            // depth -- same as root
290                                      m_window,                        // window id
291                                      xcb_parent_id,                   // parent window id
292                                      rect.x(),
293                                      rect.y(),
294                                      rect.width(),
295                                      rect.height(),
296                                      0,                               // border width
297                                      XCB_WINDOW_CLASS_INPUT_OUTPUT,   // window class
298                                      m_visualId,                      // visual
299                                      0,                               // value mask
300                                      0));                             // value list
301     }
302
303     connection()->addWindow(m_window, this);
304
305     Q_XCB_CALL(xcb_change_window_attributes(xcb_connection(), m_window, mask, values));
306
307     propagateSizeHints();
308
309     xcb_atom_t properties[4];
310     int propertyCount = 0;
311     properties[propertyCount++] = atom(QXcbAtom::WM_DELETE_WINDOW);
312     properties[propertyCount++] = atom(QXcbAtom::WM_TAKE_FOCUS);
313     properties[propertyCount++] = atom(QXcbAtom::_NET_WM_PING);
314
315     if (m_screen->syncRequestSupported())
316         properties[propertyCount++] = atom(QXcbAtom::_NET_WM_SYNC_REQUEST);
317
318     if (window()->windowFlags() & Qt::WindowContextHelpButtonHint)
319         properties[propertyCount++] = atom(QXcbAtom::_NET_WM_CONTEXT_HELP);
320
321     Q_XCB_CALL(xcb_change_property(xcb_connection(),
322                                    XCB_PROP_MODE_REPLACE,
323                                    m_window,
324                                    atom(QXcbAtom::WM_PROTOCOLS),
325                                    XCB_ATOM_ATOM,
326                                    32,
327                                    propertyCount,
328                                    properties));
329     m_syncValue.hi = 0;
330     m_syncValue.lo = 0;
331
332     if (m_screen->syncRequestSupported()) {
333         m_syncCounter = xcb_generate_id(xcb_connection());
334         Q_XCB_CALL(xcb_sync_create_counter(xcb_connection(), m_syncCounter, m_syncValue));
335
336         Q_XCB_CALL(xcb_change_property(xcb_connection(),
337                                        XCB_PROP_MODE_REPLACE,
338                                        m_window,
339                                        atom(QXcbAtom::_NET_WM_SYNC_REQUEST_COUNTER),
340                                        XCB_ATOM_CARDINAL,
341                                        32,
342                                        1,
343                                        &m_syncCounter));
344     }
345
346     // set the PID to let the WM kill the application if unresponsive
347     long pid = getpid();
348     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
349                                    atom(QXcbAtom::_NET_WM_PID), XCB_ATOM_CARDINAL, 32,
350                                    1, &pid));
351
352     xcb_wm_hints_t hints;
353     memset(&hints, 0, sizeof(hints));
354     xcb_wm_hints_set_normal(&hints);
355
356     xcb_wm_hints_set_input(&hints, !(window()->windowFlags() & Qt::WindowDoesNotAcceptFocus));
357
358     xcb_set_wm_hints(xcb_connection(), m_window, &hints);
359
360     xcb_window_t leader = m_screen->clientLeader();
361     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
362                                    atom(QXcbAtom::WM_CLIENT_LEADER), XCB_ATOM_WINDOW, 32,
363                                    1, &leader));
364
365 #ifdef XCB_USE_XINPUT2_MAEMO
366     if (connection()->isUsingXInput2Maemo()) {
367         XIEventMask xieventmask;
368         uchar bitmask[2] = { 0, 0 };
369
370         xieventmask.deviceid = XIAllMasterDevices;
371         xieventmask.mask = bitmask;
372         xieventmask.mask_len = sizeof(bitmask);
373
374         XISetMask(bitmask, XI_ButtonPress);
375         XISetMask(bitmask, XI_ButtonRelease);
376         XISetMask(bitmask, XI_Motion);
377
378         XISelectEvents(DISPLAY_FROM_XCB(this), m_window, &xieventmask, 1);
379     }
380 #elif defined(XCB_USE_XINPUT2)
381     connection()->xi2Select(m_window);
382 #endif
383
384     setWindowFlags(window()->windowFlags());
385     setWindowTitle(window()->windowTitle());
386     setWindowState(window()->windowState());
387
388     if (window()->windowFlags() & Qt::WindowTransparentForInput)
389         setTransparentForMouseEvents(true);
390
391 #ifndef QT_NO_DRAGANDDROP
392     connection()->drag()->dndEnable(this, true);
393 #endif
394 }
395
396 QXcbWindow::~QXcbWindow()
397 {
398     destroy();
399 }
400
401 void QXcbWindow::destroy()
402 {
403     if (m_syncCounter && m_screen->syncRequestSupported())
404         Q_XCB_CALL(xcb_sync_destroy_counter(xcb_connection(), m_syncCounter));
405     if (m_window) {
406         if (m_netWmUserTimeWindow) {
407             xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW));
408             // Some window managers, like metacity, do XSelectInput on the _NET_WM_USER_TIME_WINDOW window,
409             // without trapping BadWindow (which crashes when the user time window is destroyed).
410             connection()->sync();
411             xcb_destroy_window(xcb_connection(), m_netWmUserTimeWindow);
412             m_netWmUserTimeWindow = XCB_NONE;
413         }
414         connection()->removeWindow(m_window);
415         Q_XCB_CALL(xcb_destroy_window(xcb_connection(), m_window));
416         m_window = 0;
417     }
418     m_mapped = false;
419
420 #if defined(XCB_USE_EGL)
421     delete m_eglSurface;
422     m_eglSurface = 0;
423 #endif
424 }
425
426 void QXcbWindow::setGeometry(const QRect &rect)
427 {
428     QPlatformWindow::setGeometry(rect);
429
430     propagateSizeHints();
431     const QRect wmGeometry = windowToWmGeometry(rect);
432
433     const quint32 mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y | XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
434     const qint32 values[] = {
435         qBound<qint32>(-XCOORD_MAX, wmGeometry.x(),      XCOORD_MAX),
436         qBound<qint32>(-XCOORD_MAX, wmGeometry.y(),      XCOORD_MAX),
437         qBound<qint32>(1,           wmGeometry.width(),  XCOORD_MAX),
438         qBound<qint32>(1,           wmGeometry.height(), XCOORD_MAX),
439     };
440
441     Q_XCB_CALL(xcb_configure_window(xcb_connection(), m_window, mask, reinterpret_cast<const quint32*>(values)));
442
443     xcb_flush(xcb_connection());
444 }
445
446 QMargins QXcbWindow::frameMargins() const
447 {
448     if (m_dirtyFrameMargins) {
449         xcb_window_t window = m_window;
450         xcb_window_t parent = m_window;
451
452         bool foundRoot = false;
453
454         const QVector<xcb_window_t> &virtualRoots =
455             connection()->wmSupport()->virtualRoots();
456
457         while (!foundRoot) {
458             xcb_query_tree_cookie_t cookie = xcb_query_tree_unchecked(xcb_connection(), parent);
459
460             xcb_query_tree_reply_t *reply = xcb_query_tree_reply(xcb_connection(), cookie, NULL);
461             if (reply) {
462                 if (reply->root == reply->parent || virtualRoots.indexOf(reply->parent) != -1) {
463                     foundRoot = true;
464                 } else {
465                     window = parent;
466                     parent = reply->parent;
467                 }
468
469                 free(reply);
470             } else {
471                 m_dirtyFrameMargins = false;
472                 m_frameMargins = QMargins();
473                 return m_frameMargins;
474             }
475         }
476
477         QPoint offset;
478
479         xcb_translate_coordinates_reply_t *reply =
480             xcb_translate_coordinates_reply(
481                 xcb_connection(),
482                 xcb_translate_coordinates(xcb_connection(), window, parent, 0, 0),
483                 NULL);
484
485         if (reply) {
486             offset = QPoint(reply->dst_x, reply->dst_y);
487             free(reply);
488         }
489
490         xcb_get_geometry_reply_t *geom =
491             xcb_get_geometry_reply(
492                 xcb_connection(),
493                 xcb_get_geometry(xcb_connection(), parent),
494                 NULL);
495
496         if (geom) {
497             // --
498             // add the border_width for the window managers frame... some window managers
499             // do not use a border_width of zero for their frames, and if we the left and
500             // top strut, we ensure that pos() is absolutely correct.  frameGeometry()
501             // will still be incorrect though... perhaps i should have foffset as well, to
502             // indicate the frame offset (equal to the border_width on X).
503             // - Brad
504             // -- copied from qwidget_x11.cpp
505
506             int left = offset.x() + geom->border_width;
507             int top = offset.y() + geom->border_width;
508             int right = geom->width + geom->border_width - geometry().width() - offset.x();
509             int bottom = geom->height + geom->border_width - geometry().height() - offset.y();
510
511             m_frameMargins = QMargins(left, top, right, bottom);
512
513             free(geom);
514         }
515
516         m_dirtyFrameMargins = false;
517     }
518
519     return m_frameMargins;
520 }
521
522 void QXcbWindow::setVisible(bool visible)
523 {
524     if (visible)
525         show();
526     else
527         hide();
528 }
529
530 void QXcbWindow::show()
531 {
532     if (window()->isTopLevel()) {
533         xcb_get_property_cookie_t cookie = xcb_get_wm_hints_unchecked(xcb_connection(), m_window);
534
535         xcb_wm_hints_t hints;
536         xcb_get_wm_hints_reply(xcb_connection(), cookie, &hints, NULL);
537
538         if (window()->windowState() & Qt::WindowMinimized)
539             xcb_wm_hints_set_iconic(&hints);
540         else
541             xcb_wm_hints_set_normal(&hints);
542
543         xcb_wm_hints_set_input(&hints, !(window()->windowFlags() & Qt::WindowDoesNotAcceptFocus));
544
545         xcb_set_wm_hints(xcb_connection(), m_window, &hints);
546
547         // update WM_NORMAL_HINTS
548         propagateSizeHints();
549
550         // update WM_TRANSIENT_FOR
551         if (window()->transientParent() && isTransient(window())) {
552             QXcbWindow *transientXcbParent = static_cast<QXcbWindow *>(window()->transientParent()->handle());
553             if (transientXcbParent) {
554                 // ICCCM 4.1.2.6
555                 xcb_window_t parentWindow = transientXcbParent->xcb_window();
556
557                 // todo: set transient for group (wm_client_leader) if no parent, a la qwidget_x11.cpp
558                 Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
559                                                XCB_ATOM_WM_TRANSIENT_FOR, XCB_ATOM_WINDOW, 32,
560                                                1, &parentWindow));
561             }
562         }
563
564         // update _MOTIF_WM_HINTS
565         updateMotifWmHintsBeforeMap();
566
567         // update _NET_WM_STATE
568         updateNetWmStateBeforeMap();
569     }
570
571     if (connection()->time() != XCB_TIME_CURRENT_TIME)
572         updateNetWmUserTime(connection()->time());
573
574     Q_XCB_CALL(xcb_map_window(xcb_connection(), m_window));
575     xcb_flush(xcb_connection());
576
577     connection()->sync();
578 }
579
580 void QXcbWindow::hide()
581 {
582     Q_XCB_CALL(xcb_unmap_window(xcb_connection(), m_window));
583
584     // send synthetic UnmapNotify event according to icccm 4.1.4
585     xcb_unmap_notify_event_t event;
586     event.response_type = XCB_UNMAP_NOTIFY;
587     event.event = m_screen->root();
588     event.window = m_window;
589     event.from_configure = false;
590     Q_XCB_CALL(xcb_send_event(xcb_connection(), false, m_screen->root(),
591                               XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (const char *)&event));
592
593     xcb_flush(xcb_connection());
594
595     m_mapped = false;
596 }
597
598 struct QtMotifWmHints {
599     quint32 flags, functions, decorations;
600     qint32 input_mode;
601     quint32 status;
602 };
603
604 enum {
605     MWM_HINTS_FUNCTIONS   = (1L << 0),
606
607     MWM_FUNC_ALL      = (1L << 0),
608     MWM_FUNC_RESIZE   = (1L << 1),
609     MWM_FUNC_MOVE     = (1L << 2),
610     MWM_FUNC_MINIMIZE = (1L << 3),
611     MWM_FUNC_MAXIMIZE = (1L << 4),
612     MWM_FUNC_CLOSE    = (1L << 5),
613
614     MWM_HINTS_DECORATIONS = (1L << 1),
615
616     MWM_DECOR_ALL      = (1L << 0),
617     MWM_DECOR_BORDER   = (1L << 1),
618     MWM_DECOR_RESIZEH  = (1L << 2),
619     MWM_DECOR_TITLE    = (1L << 3),
620     MWM_DECOR_MENU     = (1L << 4),
621     MWM_DECOR_MINIMIZE = (1L << 5),
622     MWM_DECOR_MAXIMIZE = (1L << 6),
623
624     MWM_HINTS_INPUT_MODE = (1L << 2),
625
626     MWM_INPUT_MODELESS                  = 0L,
627     MWM_INPUT_PRIMARY_APPLICATION_MODAL = 1L,
628     MWM_INPUT_FULL_APPLICATION_MODAL    = 3L
629 };
630
631 static QtMotifWmHints getMotifWmHints(QXcbConnection *c, xcb_window_t window)
632 {
633     QtMotifWmHints hints;
634
635     xcb_get_property_cookie_t get_cookie =
636         xcb_get_property_unchecked(c->xcb_connection(), 0, window, c->atom(QXcbAtom::_MOTIF_WM_HINTS),
637                          c->atom(QXcbAtom::_MOTIF_WM_HINTS), 0, 20);
638
639     xcb_get_property_reply_t *reply =
640         xcb_get_property_reply(c->xcb_connection(), get_cookie, NULL);
641
642     if (reply && reply->format == 32 && reply->type == c->atom(QXcbAtom::_MOTIF_WM_HINTS)) {
643         hints = *((QtMotifWmHints *)xcb_get_property_value(reply));
644     } else {
645         hints.flags = 0L;
646         hints.functions = MWM_FUNC_ALL;
647         hints.decorations = MWM_DECOR_ALL;
648         hints.input_mode = 0L;
649         hints.status = 0L;
650     }
651
652     free(reply);
653
654     return hints;
655 }
656
657 static void setMotifWmHints(QXcbConnection *c, xcb_window_t window, const QtMotifWmHints &hints)
658 {
659     if (hints.flags != 0l) {
660         Q_XCB_CALL2(xcb_change_property(c->xcb_connection(),
661                                        XCB_PROP_MODE_REPLACE,
662                                        window,
663                                        c->atom(QXcbAtom::_MOTIF_WM_HINTS),
664                                        c->atom(QXcbAtom::_MOTIF_WM_HINTS),
665                                        32,
666                                        5,
667                                        &hints), c);
668     } else {
669         Q_XCB_CALL2(xcb_delete_property(c->xcb_connection(), window, c->atom(QXcbAtom::_MOTIF_WM_HINTS)), c);
670     }
671 }
672
673 QXcbWindow::NetWmStates QXcbWindow::netWmStates()
674 {
675     NetWmStates result(0);
676
677     xcb_get_property_cookie_t get_cookie =
678         xcb_get_property_unchecked(xcb_connection(), 0, m_window, atom(QXcbAtom::_NET_WM_STATE),
679                          XCB_ATOM_ATOM, 0, 1024);
680
681     xcb_get_property_reply_t *reply =
682         xcb_get_property_reply(xcb_connection(), get_cookie, NULL);
683
684     if (reply && reply->format == 32 && reply->type == XCB_ATOM_ATOM) {
685         const xcb_atom_t *states = static_cast<const xcb_atom_t *>(xcb_get_property_value(reply));
686         const xcb_atom_t *statesEnd = states + reply->length;
687         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_ABOVE)))
688             result |= NetWmStateAbove;
689         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_BELOW)))
690             result |= NetWmStateBelow;
691         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN)))
692             result |= NetWmStateFullScreen;
693         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ)))
694             result |= NetWmStateMaximizedHorz;
695         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT)))
696             result |= NetWmStateMaximizedVert;
697         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_MODAL)))
698             result |= NetWmStateModal;
699         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_STAYS_ON_TOP)))
700             result |= NetWmStateStaysOnTop;
701         if (statesEnd != qFind(states, statesEnd, atom(QXcbAtom::_NET_WM_STATE_DEMANDS_ATTENTION)))
702             result |= NetWmStateDemandsAttention;
703         free(reply);
704     } else {
705 #ifdef NET_WM_STATE_DEBUG
706         printf("getting net wm state (%x), empty\n", m_window);
707 #endif
708     }
709
710     return result;
711 }
712
713 void QXcbWindow::setNetWmStates(NetWmStates states)
714 {
715     QVector<xcb_atom_t> atoms;
716     if (states & NetWmStateAbove)
717         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_ABOVE));
718     if (states & NetWmStateBelow)
719         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_BELOW));
720     if (states & NetWmStateFullScreen)
721         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
722     if (states & NetWmStateMaximizedHorz)
723         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ));
724     if (states & NetWmStateMaximizedVert)
725         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
726     if (states & NetWmStateModal)
727         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_MODAL));
728     if (states & NetWmStateStaysOnTop)
729         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_STAYS_ON_TOP));
730     if (states & NetWmStateDemandsAttention)
731         atoms.push_back(atom(QXcbAtom::_NET_WM_STATE_DEMANDS_ATTENTION));
732
733     if (atoms.isEmpty()) {
734         Q_XCB_CALL(xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_STATE)));
735     } else {
736         Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
737                                        atom(QXcbAtom::_NET_WM_STATE), XCB_ATOM_ATOM, 32,
738                                        atoms.count(), atoms.constData()));
739     }
740     xcb_flush(xcb_connection());
741 }
742
743 Qt::WindowFlags QXcbWindow::setWindowFlags(Qt::WindowFlags flags)
744 {
745     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
746
747     if (type == Qt::ToolTip)
748         flags |= Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint;
749     if (type == Qt::Popup)
750         flags |= Qt::X11BypassWindowManagerHint;
751
752     if (flags & Qt::WindowTransparentForInput) {
753         uint32_t mask = XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_VISIBILITY_CHANGE
754                  | XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_RESIZE_REDIRECT
755                 | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT
756                 | XCB_EVENT_MASK_FOCUS_CHANGE  | XCB_EVENT_MASK_PROPERTY_CHANGE
757                 | XCB_EVENT_MASK_COLOR_MAP_CHANGE | XCB_EVENT_MASK_OWNER_GRAB_BUTTON;
758         xcb_change_window_attributes(xcb_connection(), xcb_window(), XCB_CW_EVENT_MASK, &mask);
759     }
760
761     setNetWmWindowFlags(flags);
762     setMotifWindowFlags(flags);
763
764     setTransparentForMouseEvents(flags & Qt::WindowTransparentForInput);
765     updateDoesNotAcceptFocus(flags & Qt::WindowDoesNotAcceptFocus);
766
767     return flags;
768 }
769
770 void QXcbWindow::setMotifWindowFlags(Qt::WindowFlags flags)
771 {
772     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
773
774     QtMotifWmHints mwmhints;
775     mwmhints.flags = 0L;
776     mwmhints.functions = 0L;
777     mwmhints.decorations = 0;
778     mwmhints.input_mode = 0L;
779     mwmhints.status = 0L;
780
781     if (type != Qt::SplashScreen) {
782         mwmhints.flags |= MWM_HINTS_DECORATIONS;
783
784         bool customize = flags & Qt::CustomizeWindowHint;
785         if (!(flags & Qt::FramelessWindowHint) && !(customize && !(flags & Qt::WindowTitleHint))) {
786             mwmhints.decorations |= MWM_DECOR_BORDER;
787             mwmhints.decorations |= MWM_DECOR_RESIZEH;
788
789             if (flags & Qt::WindowTitleHint)
790                 mwmhints.decorations |= MWM_DECOR_TITLE;
791
792             if (flags & Qt::WindowSystemMenuHint)
793                 mwmhints.decorations |= MWM_DECOR_MENU;
794
795             if (flags & Qt::WindowMinimizeButtonHint) {
796                 mwmhints.decorations |= MWM_DECOR_MINIMIZE;
797                 mwmhints.functions |= MWM_FUNC_MINIMIZE;
798             }
799
800             if (flags & Qt::WindowMaximizeButtonHint) {
801                 mwmhints.decorations |= MWM_DECOR_MAXIMIZE;
802                 mwmhints.functions |= MWM_FUNC_MAXIMIZE;
803             }
804
805             if (flags & Qt::WindowCloseButtonHint)
806                 mwmhints.functions |= MWM_FUNC_CLOSE;
807         }
808     } else {
809         // if type == Qt::SplashScreen
810         mwmhints.decorations = MWM_DECOR_ALL;
811     }
812
813     if (mwmhints.functions != 0) {
814         mwmhints.flags |= MWM_HINTS_FUNCTIONS;
815         mwmhints.functions |= MWM_FUNC_MOVE | MWM_FUNC_RESIZE;
816     } else {
817         mwmhints.functions = MWM_FUNC_ALL;
818     }
819
820     if (!(flags & Qt::FramelessWindowHint)
821         && flags & Qt::CustomizeWindowHint
822         && flags & Qt::WindowTitleHint
823         && !(flags &
824              (Qt::WindowMinimizeButtonHint
825               | Qt::WindowMaximizeButtonHint
826               | Qt::WindowCloseButtonHint)))
827     {
828         // a special case - only the titlebar without any button
829         mwmhints.flags = MWM_HINTS_FUNCTIONS;
830         mwmhints.functions = MWM_FUNC_MOVE | MWM_FUNC_RESIZE;
831         mwmhints.decorations = 0;
832     }
833
834     setMotifWmHints(connection(), m_window, mwmhints);
835 }
836
837 void QXcbWindow::changeNetWmState(bool set, xcb_atom_t one, xcb_atom_t two)
838 {
839     xcb_client_message_event_t event;
840
841     event.response_type = XCB_CLIENT_MESSAGE;
842     event.format = 32;
843     event.window = m_window;
844     event.type = atom(QXcbAtom::_NET_WM_STATE);
845     event.data.data32[0] = set ? 1 : 0;
846     event.data.data32[1] = one;
847     event.data.data32[2] = two;
848     event.data.data32[3] = 0;
849     event.data.data32[4] = 0;
850
851     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));
852 }
853
854 Qt::WindowState QXcbWindow::setWindowState(Qt::WindowState state)
855 {
856     if (state == m_windowState)
857         return state;
858
859     // unset old state
860     switch (m_windowState) {
861     case Qt::WindowMinimized:
862         Q_XCB_CALL(xcb_map_window(xcb_connection(), m_window));
863         break;
864     case Qt::WindowMaximized:
865         changeNetWmState(false,
866                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ),
867                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
868         break;
869     case Qt::WindowFullScreen:
870         changeNetWmState(false, atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
871         break;
872     default:
873         break;
874     }
875
876     // set new state
877     switch (state) {
878     case Qt::WindowMinimized:
879         {
880             xcb_client_message_event_t event;
881
882             event.response_type = XCB_CLIENT_MESSAGE;
883             event.format = 32;
884             event.window = m_window;
885             event.type = atom(QXcbAtom::WM_CHANGE_STATE);
886             event.data.data32[0] = XCB_WM_STATE_ICONIC;
887             event.data.data32[1] = 0;
888             event.data.data32[2] = 0;
889             event.data.data32[3] = 0;
890             event.data.data32[4] = 0;
891
892             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));
893         }
894         break;
895     case Qt::WindowMaximized:
896         changeNetWmState(true,
897                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_HORZ),
898                          atom(QXcbAtom::_NET_WM_STATE_MAXIMIZED_VERT));
899         break;
900     case Qt::WindowFullScreen:
901         changeNetWmState(true, atom(QXcbAtom::_NET_WM_STATE_FULLSCREEN));
902         break;
903     case Qt::WindowNoState:
904         break;
905     default:
906         break;
907     }
908
909     connection()->sync();
910
911     m_windowState = state;
912     return m_windowState;
913 }
914
915 void QXcbWindow::setNetWmWindowFlags(Qt::WindowFlags flags)
916 {
917     // in order of decreasing priority
918     QVector<uint> windowTypes;
919
920     Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));
921
922     switch (type) {
923     case Qt::Dialog:
924     case Qt::Sheet:
925         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_DIALOG));
926         break;
927     case Qt::Tool:
928     case Qt::Drawer:
929         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_UTILITY));
930         break;
931     case Qt::ToolTip:
932         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_TOOLTIP));
933         break;
934     case Qt::SplashScreen:
935         windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_SPLASH));
936         break;
937     default:
938         break;
939     }
940
941     if (flags & Qt::FramelessWindowHint)
942         windowTypes.append(atom(QXcbAtom::_KDE_NET_WM_WINDOW_TYPE_OVERRIDE));
943
944     windowTypes.append(atom(QXcbAtom::_NET_WM_WINDOW_TYPE_NORMAL));
945
946     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
947                                    atom(QXcbAtom::_NET_WM_WINDOW_TYPE), XCB_ATOM_ATOM, 32,
948                                    windowTypes.count(), windowTypes.constData()));
949 }
950
951 void QXcbWindow::updateMotifWmHintsBeforeMap()
952 {
953     QtMotifWmHints mwmhints = getMotifWmHints(connection(), m_window);
954
955     if (window()->windowModality() != Qt::NonModal) {
956         switch (window()->windowModality()) {
957         case Qt::WindowModal:
958             mwmhints.input_mode = MWM_INPUT_PRIMARY_APPLICATION_MODAL;
959             break;
960         case Qt::ApplicationModal:
961         default:
962             mwmhints.input_mode = MWM_INPUT_FULL_APPLICATION_MODAL;
963             break;
964         }
965         mwmhints.flags |= MWM_HINTS_INPUT_MODE;
966     } else {
967         mwmhints.input_mode = MWM_INPUT_MODELESS;
968         mwmhints.flags &= ~MWM_HINTS_INPUT_MODE;
969     }
970
971     if (window()->minimumSize() == window()->maximumSize()) {
972         // fixed size, remove the resize handle (since mwm/dtwm
973         // isn't smart enough to do it itself)
974         mwmhints.flags |= MWM_HINTS_FUNCTIONS;
975         if (mwmhints.functions == MWM_FUNC_ALL) {
976             mwmhints.functions = MWM_FUNC_MOVE;
977         } else {
978             mwmhints.functions &= ~MWM_FUNC_RESIZE;
979         }
980
981         if (mwmhints.decorations == MWM_DECOR_ALL) {
982             mwmhints.flags |= MWM_HINTS_DECORATIONS;
983             mwmhints.decorations = (MWM_DECOR_BORDER
984                                     | MWM_DECOR_TITLE
985                                     | MWM_DECOR_MENU);
986         } else {
987             mwmhints.decorations &= ~MWM_DECOR_RESIZEH;
988         }
989     }
990
991     if (window()->windowFlags() & Qt::WindowMinimizeButtonHint) {
992         mwmhints.flags |= MWM_HINTS_DECORATIONS;
993         mwmhints.decorations |= MWM_DECOR_MINIMIZE;
994         mwmhints.functions |= MWM_FUNC_MINIMIZE;
995     }
996     if (window()->windowFlags() & Qt::WindowMaximizeButtonHint) {
997         mwmhints.flags |= MWM_HINTS_DECORATIONS;
998         mwmhints.decorations |= MWM_DECOR_MAXIMIZE;
999         mwmhints.functions |= MWM_FUNC_MAXIMIZE;
1000     }
1001     if (window()->windowFlags() & Qt::WindowCloseButtonHint)
1002         mwmhints.functions |= MWM_FUNC_CLOSE;
1003
1004     setMotifWmHints(connection(), m_window, mwmhints);
1005 }
1006
1007 void QXcbWindow::updateNetWmStateBeforeMap()
1008 {
1009     NetWmStates states(0);
1010
1011     const Qt::WindowFlags flags = window()->windowFlags();
1012     if (flags & Qt::WindowStaysOnTopHint) {
1013         states |= NetWmStateAbove;
1014         states |= NetWmStateStaysOnTop;
1015     } else if (flags & Qt::WindowStaysOnBottomHint) {
1016         states |= NetWmStateBelow;
1017     }
1018
1019     if (window()->windowState() & Qt::WindowFullScreen)
1020         states |= NetWmStateFullScreen;
1021
1022     if (window()->windowState() & Qt::WindowMaximized) {
1023         states |= NetWmStateMaximizedHorz;
1024         states |= NetWmStateMaximizedVert;
1025     }
1026
1027     if (window()->windowModality() != Qt::NonModal)
1028         states |= NetWmStateModal;
1029
1030     setNetWmStates(states);
1031 }
1032
1033 void QXcbWindow::updateNetWmUserTime(xcb_timestamp_t timestamp)
1034 {
1035     xcb_window_t wid = m_window;
1036
1037     const bool isSupportedByWM = connection()->wmSupport()->isSupportedByWM(atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW));
1038     if (m_netWmUserTimeWindow || isSupportedByWM) {
1039         if (!m_netWmUserTimeWindow) {
1040             m_netWmUserTimeWindow = xcb_generate_id(xcb_connection());
1041             Q_XCB_CALL(xcb_create_window(xcb_connection(),
1042                                          XCB_COPY_FROM_PARENT,            // depth -- same as root
1043                                          m_netWmUserTimeWindow,                        // window id
1044                                          m_window,                   // parent window id
1045                                          -1, -1, 1, 1,
1046                                          0,                               // border width
1047                                          XCB_WINDOW_CLASS_INPUT_OUTPUT,   // window class
1048                                          m_visualId,                      // visual
1049                                          0,                               // value mask
1050                                          0));                             // value list
1051             wid = m_netWmUserTimeWindow;
1052             xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window, atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW),
1053                                 XCB_ATOM_WINDOW, 32, 1, &m_netWmUserTimeWindow);
1054             xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_USER_TIME));
1055         } else if (!isSupportedByWM) {
1056             // WM no longer supports it, then we should remove the
1057             // _NET_WM_USER_TIME_WINDOW atom.
1058             xcb_delete_property(xcb_connection(), m_window, atom(QXcbAtom::_NET_WM_USER_TIME_WINDOW));
1059             xcb_destroy_window(xcb_connection(), m_netWmUserTimeWindow);
1060             m_netWmUserTimeWindow = XCB_NONE;
1061         } else {
1062             wid = m_netWmUserTimeWindow;
1063         }
1064     }
1065     xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, wid, atom(QXcbAtom::_NET_WM_USER_TIME),
1066                         XCB_ATOM_CARDINAL, 32, 1, &timestamp);
1067 }
1068
1069 void QXcbWindow::setTransparentForMouseEvents(bool transparent)
1070 {
1071     if (transparent == m_transparent)
1072         return;
1073
1074     xcb_rectangle_t rectangle;
1075
1076     xcb_rectangle_t *rect = 0;
1077     int nrect = 0;
1078
1079     if (!transparent) {
1080         rectangle.x = 0;
1081         rectangle.y = 0;
1082         rectangle.width = geometry().width();
1083         rectangle.height = geometry().height();
1084         rect = &rectangle;
1085         nrect = 1;
1086     }
1087
1088     xcb_xfixes_region_t region = xcb_generate_id(xcb_connection());
1089     xcb_xfixes_create_region(xcb_connection(), region, nrect, rect);
1090     xcb_xfixes_set_window_shape_region_checked(xcb_connection(), m_window, XCB_SHAPE_SK_INPUT, 0, 0, region);
1091     xcb_xfixes_destroy_region(xcb_connection(), region);
1092
1093     m_transparent = transparent;
1094 }
1095
1096 void QXcbWindow::updateDoesNotAcceptFocus(bool doesNotAcceptFocus)
1097 {
1098     xcb_get_property_cookie_t cookie = xcb_get_wm_hints_unchecked(xcb_connection(), m_window);
1099
1100     xcb_wm_hints_t hints;
1101     if (!xcb_get_wm_hints_reply(xcb_connection(), cookie, &hints, NULL)) {
1102         return;
1103     }
1104
1105     xcb_wm_hints_set_input(&hints, !doesNotAcceptFocus);
1106     xcb_set_wm_hints(xcb_connection(), m_window, &hints);
1107 }
1108
1109 WId QXcbWindow::winId() const
1110 {
1111     return m_window;
1112 }
1113
1114 void QXcbWindow::setParent(const QPlatformWindow *parent)
1115 {
1116     // re-create for compatibility
1117     create();
1118
1119     QPoint topLeft = geometry().topLeft();
1120
1121     xcb_window_t xcb_parent_id = parent ? static_cast<const QXcbWindow *>(parent)->xcb_window() : m_screen->root();
1122     Q_XCB_CALL(xcb_reparent_window(xcb_connection(), xcb_window(), xcb_parent_id, topLeft.x(), topLeft.y()));
1123 }
1124
1125 void QXcbWindow::setWindowTitle(const QString &title)
1126 {
1127     QByteArray ba = title.toUtf8();
1128     Q_XCB_CALL(xcb_change_property(xcb_connection(),
1129                                    XCB_PROP_MODE_REPLACE,
1130                                    m_window,
1131                                    atom(QXcbAtom::_NET_WM_NAME),
1132                                    atom(QXcbAtom::UTF8_STRING),
1133                                    8,
1134                                    ba.length(),
1135                                    ba.constData()));
1136 }
1137
1138 void QXcbWindow::setWindowIcon(const QIcon &icon)
1139 {
1140     QVector<quint32> icon_data;
1141
1142     if (!icon.isNull()) {
1143         QList<QSize> availableSizes = icon.availableSizes();
1144         if (availableSizes.isEmpty()) {
1145             // try to use default sizes since the icon can be a scalable image like svg.
1146             availableSizes.push_back(QSize(16,16));
1147             availableSizes.push_back(QSize(32,32));
1148             availableSizes.push_back(QSize(64,64));
1149             availableSizes.push_back(QSize(128,128));
1150         }
1151         for (int i = 0; i < availableSizes.size(); ++i) {
1152             QSize size = availableSizes.at(i);
1153             QPixmap pixmap = icon.pixmap(size);
1154             if (!pixmap.isNull()) {
1155                 QImage image = pixmap.toImage().convertToFormat(QImage::Format_ARGB32);
1156                 int pos = icon_data.size();
1157                 icon_data.resize(pos + 2 + image.width()*image.height());
1158                 icon_data[pos++] = image.width();
1159                 icon_data[pos++] = image.height();
1160                 memcpy(icon_data.data() + pos, image.bits(), image.width()*image.height()*4);
1161             }
1162         }
1163     }
1164
1165     if (!icon_data.isEmpty()) {
1166         Q_XCB_CALL(xcb_change_property(xcb_connection(),
1167                                        XCB_PROP_MODE_REPLACE,
1168                                        m_window,
1169                                        atom(QXcbAtom::_NET_WM_ICON),
1170                                        atom(QXcbAtom::CARDINAL),
1171                                        32,
1172                                        icon_data.size(),
1173                                        (unsigned char *) icon_data.data()));
1174     } else {
1175         Q_XCB_CALL(xcb_delete_property(xcb_connection(),
1176                                        m_window,
1177                                        atom(QXcbAtom::_NET_WM_ICON)));
1178     }
1179 }
1180
1181 void QXcbWindow::raise()
1182 {
1183     const quint32 mask = XCB_CONFIG_WINDOW_STACK_MODE;
1184     const quint32 values[] = { XCB_STACK_MODE_ABOVE };
1185     Q_XCB_CALL(xcb_configure_window(xcb_connection(), m_window, mask, values));
1186 }
1187
1188 void QXcbWindow::lower()
1189 {
1190     const quint32 mask = XCB_CONFIG_WINDOW_STACK_MODE;
1191     const quint32 values[] = { XCB_STACK_MODE_BELOW };
1192     Q_XCB_CALL(xcb_configure_window(xcb_connection(), m_window, mask, values));
1193 }
1194
1195 // Adapt the geometry to match the WM expection with regards
1196 // to gravity.
1197 QRect QXcbWindow::windowToWmGeometry(QRect r) const
1198 {
1199     if (m_dirtyFrameMargins || m_frameMargins.isNull())
1200         return r;
1201     const bool frameInclusive = positionIncludesFrame(window());
1202     // XCB_GRAVITY_STATIC requires the inner geometry, whereas
1203     // XCB_GRAVITY_NORTH_WEST requires the frame geometry
1204     if (frameInclusive && m_gravity == XCB_GRAVITY_STATIC) {
1205         r.translate(m_frameMargins.left(), m_frameMargins.top());
1206     } else if (!frameInclusive && m_gravity == XCB_GRAVITY_NORTH_WEST) {
1207         r.translate(-m_frameMargins.left(), -m_frameMargins.top());
1208     }
1209     return r;
1210 }
1211
1212 void QXcbWindow::propagateSizeHints()
1213 {
1214     // update WM_NORMAL_HINTS
1215     xcb_size_hints_t hints;
1216     memset(&hints, 0, sizeof(hints));
1217
1218     const QRect rect = windowToWmGeometry(geometry());
1219
1220     QWindow *win = window();
1221
1222     xcb_size_hints_set_position(&hints, true, rect.x(), rect.y());
1223     xcb_size_hints_set_size(&hints, true, rect.width(), rect.height());
1224     xcb_size_hints_set_win_gravity(&hints, m_gravity);
1225
1226     QSize minimumSize = win->minimumSize();
1227     QSize maximumSize = win->maximumSize();
1228     QSize baseSize = win->baseSize();
1229     QSize sizeIncrement = win->sizeIncrement();
1230
1231     if (minimumSize.width() > 0 || minimumSize.height() > 0)
1232         xcb_size_hints_set_min_size(&hints, minimumSize.width(), minimumSize.height());
1233
1234     if (maximumSize.width() < QWINDOWSIZE_MAX || maximumSize.height() < QWINDOWSIZE_MAX)
1235         xcb_size_hints_set_max_size(&hints,
1236                                     qMin(XCOORD_MAX, maximumSize.width()),
1237                                     qMin(XCOORD_MAX, maximumSize.height()));
1238
1239     if (sizeIncrement.width() > 0 || sizeIncrement.height() > 0) {
1240         xcb_size_hints_set_base_size(&hints, baseSize.width(), baseSize.height());
1241         xcb_size_hints_set_resize_inc(&hints, sizeIncrement.width(), sizeIncrement.height());
1242     }
1243
1244     xcb_set_wm_normal_hints(xcb_connection(), m_window, &hints);
1245 }
1246
1247 void QXcbWindow::requestActivateWindow()
1248 {
1249     if (!m_mapped) {
1250         m_deferredActivation = true;
1251         return;
1252     }
1253     m_deferredActivation = false;
1254
1255     updateNetWmUserTime(connection()->time());
1256
1257     if (window()->isTopLevel()
1258         && connection()->wmSupport()->isSupportedByWM(atom(QXcbAtom::_NET_ACTIVE_WINDOW))) {
1259         xcb_client_message_event_t event;
1260
1261         event.response_type = XCB_CLIENT_MESSAGE;
1262         event.format = 32;
1263         event.window = m_window;
1264         event.type = atom(QXcbAtom::_NET_ACTIVE_WINDOW);
1265         event.data.data32[0] = 1;
1266         event.data.data32[1] = connection()->time();
1267         QWindow *focusWindow = QGuiApplication::focusWindow();
1268         event.data.data32[2] = focusWindow ? focusWindow->winId() : XCB_NONE;
1269         event.data.data32[3] = 0;
1270         event.data.data32[4] = 0;
1271
1272         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));
1273     } else {
1274         Q_XCB_CALL(xcb_set_input_focus(xcb_connection(), XCB_INPUT_FOCUS_PARENT, m_window, connection()->time()));
1275     }
1276
1277     connection()->sync();
1278 }
1279
1280 #if XCB_USE_MAEMO_WINDOW_PROPERTIES
1281 void QXcbWindow::handleContentOrientationChange(Qt::ScreenOrientation orientation)
1282 {
1283     int angle = 0;
1284     switch (orientation) {
1285         case Qt::PortraitOrientation: angle = 270; break;
1286         case Qt::LandscapeOrientation: angle = 0; break;
1287         case Qt::InvertedPortraitOrientation: angle = 90; break;
1288         case Qt::InvertedLandscapeOrientation: angle = 180; break;
1289         case Qt::PrimaryOrientation: break;
1290     }
1291     Q_XCB_CALL(xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, m_window,
1292                                    atom(QXcbAtom::MeegoTouchOrientationAngle), XCB_ATOM_CARDINAL, 32,
1293                                    1, &angle));
1294 }
1295 #endif
1296
1297 QSurfaceFormat QXcbWindow::format() const
1298 {
1299     // ### return actual format
1300     return m_format;
1301 }
1302
1303 #if defined(XCB_USE_EGL)
1304 QXcbEGLSurface *QXcbWindow::eglSurface() const
1305 {
1306     if (!m_eglSurface) {
1307         EGLDisplay display = connection()->egl_display();
1308         EGLConfig config = q_configFromGLFormat(display, window()->requestedFormat(), true);
1309         EGLSurface surface = eglCreateWindowSurface(display, config, (EGLNativeWindowType)m_window, 0);
1310
1311         m_eglSurface = new QXcbEGLSurface(display, surface);
1312     }
1313
1314     return m_eglSurface;
1315 }
1316 #endif
1317
1318 void QXcbWindow::handleExposeEvent(const xcb_expose_event_t *event)
1319 {
1320     QRect rect(event->x, event->y, event->width, event->height);
1321
1322     if (m_exposeRegion.isEmpty())
1323         m_exposeRegion = rect;
1324     else
1325         m_exposeRegion |= rect;
1326
1327     // if count is non-zero there are more expose events pending
1328     if (event->count == 0) {
1329         QWindowSystemInterface::handleExposeEvent(window(), m_exposeRegion);
1330         m_exposeRegion = QRegion();
1331     }
1332 }
1333
1334 void QXcbWindow::handleClientMessageEvent(const xcb_client_message_event_t *event)
1335 {
1336     if (event->format != 32)
1337         return;
1338
1339     if (event->type == atom(QXcbAtom::WM_PROTOCOLS)) {
1340         if (event->data.data32[0] == atom(QXcbAtom::WM_DELETE_WINDOW)) {
1341             QWindowSystemInterface::handleCloseEvent(window());
1342         } else if (event->data.data32[0] == atom(QXcbAtom::WM_TAKE_FOCUS)) {
1343             connection()->setTime(event->data.data32[1]);
1344         } else if (event->data.data32[0] == atom(QXcbAtom::_NET_WM_PING)) {
1345             xcb_client_message_event_t reply = *event;
1346
1347             reply.response_type = XCB_CLIENT_MESSAGE;
1348             reply.window = m_screen->root();
1349
1350             xcb_send_event(xcb_connection(), 0, m_screen->root(), XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (const char *)&reply);
1351             xcb_flush(xcb_connection());
1352         } else if (event->data.data32[0] == atom(QXcbAtom::_NET_WM_SYNC_REQUEST)) {
1353             connection()->setTime(event->data.data32[1]);
1354             m_syncValue.lo = event->data.data32[2];
1355             m_syncValue.hi = event->data.data32[3];
1356         } else {
1357             qWarning() << "QXcbWindow: Unhandled WM_PROTOCOLS message:" << connection()->atomName(event->data.data32[0]);
1358         }
1359 #ifndef QT_NO_DRAGANDDROP
1360     } else if (event->type == atom(QXcbAtom::XdndEnter)) {
1361         connection()->drag()->handleEnter(window(), event);
1362     } else if (event->type == atom(QXcbAtom::XdndPosition)) {
1363         connection()->drag()->handlePosition(window(), event);
1364     } else if (event->type == atom(QXcbAtom::XdndLeave)) {
1365         connection()->drag()->handleLeave(window(), event);
1366     } else if (event->type == atom(QXcbAtom::XdndDrop)) {
1367         connection()->drag()->handleDrop(window(), event);
1368 #endif
1369     } else if (event->type == atom(QXcbAtom::_XEMBED)) { // QSystemTrayIcon
1370     } else {
1371         qWarning() << "QXcbWindow: Unhandled client message:" << connection()->atomName(event->type);
1372     }
1373 }
1374
1375 void QXcbWindow::handleConfigureNotifyEvent(const xcb_configure_notify_event_t *event)
1376 {
1377     bool fromSendEvent = (event->response_type & 0x80);
1378     QPoint pos(event->x, event->y);
1379     if (!parent() && !fromSendEvent) {
1380         // Do not trust the position, query it instead.
1381         xcb_translate_coordinates_cookie_t cookie = xcb_translate_coordinates(xcb_connection(), xcb_window(),
1382                                                                               m_screen->root(), 0, 0);
1383         xcb_translate_coordinates_reply_t *reply = xcb_translate_coordinates_reply(xcb_connection(), cookie, NULL);
1384         if (reply) {
1385             pos.setX(reply->dst_x);
1386             pos.setY(reply->dst_y);
1387             free(reply);
1388         }
1389     }
1390
1391     QRect rect(pos, QSize(event->width, event->height));
1392
1393     QPlatformWindow::setGeometry(rect);
1394     QWindowSystemInterface::handleGeometryChange(window(), rect);
1395
1396     m_configureNotifyPending = false;
1397
1398     if (m_deferredExpose) {
1399         m_deferredExpose = false;
1400         QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size()));
1401     }
1402
1403     m_dirtyFrameMargins = true;
1404
1405 #if XCB_USE_DRI2
1406     if (m_context)
1407         static_cast<QDri2Context *>(m_context)->resize(rect.size());
1408 #endif
1409 }
1410
1411 bool QXcbWindow::isExposed() const
1412 {
1413     return m_mapped;
1414 }
1415
1416 void QXcbWindow::handleMapNotifyEvent(const xcb_map_notify_event_t *event)
1417 {
1418     if (event->window == m_window) {
1419         m_mapped = true;
1420         if (m_deferredActivation)
1421             requestActivateWindow();
1422         if (m_configureNotifyPending)
1423             m_deferredExpose = true;
1424         else
1425             QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size()));
1426     }
1427 }
1428
1429 void QXcbWindow::handleUnmapNotifyEvent(const xcb_unmap_notify_event_t *event)
1430 {
1431     if (event->window == m_window) {
1432         m_mapped = false;
1433         QWindowSystemInterface::handleExposeEvent(window(), QRegion());
1434     }
1435 }
1436
1437 static Qt::MouseButtons translateMouseButtons(int s)
1438 {
1439     Qt::MouseButtons ret = 0;
1440     if (s & XCB_BUTTON_MASK_1)
1441         ret |= Qt::LeftButton;
1442     if (s & XCB_BUTTON_MASK_2)
1443         ret |= Qt::MidButton;
1444     if (s & XCB_BUTTON_MASK_3)
1445         ret |= Qt::RightButton;
1446     return ret;
1447 }
1448
1449 static Qt::MouseButton translateMouseButton(xcb_button_t s)
1450 {
1451     switch (s) {
1452     case 1: return Qt::LeftButton;
1453     case 2: return Qt::MidButton;
1454     case 3: return Qt::RightButton;
1455     // Button values 4-7 were already handled as Wheel events, and won't occur here.
1456     case 8: return Qt::BackButton;      // Also known as Qt::ExtraButton1
1457     case 9: return Qt::ForwardButton;   // Also known as Qt::ExtraButton2
1458     case 10: return Qt::ExtraButton3;
1459     case 11: return Qt::ExtraButton4;
1460     case 12: return Qt::ExtraButton5;
1461     case 13: return Qt::ExtraButton6;
1462     case 14: return Qt::ExtraButton7;
1463     case 15: return Qt::ExtraButton8;
1464     case 16: return Qt::ExtraButton9;
1465     case 17: return Qt::ExtraButton10;
1466     case 18: return Qt::ExtraButton11;
1467     case 19: return Qt::ExtraButton12;
1468     case 20: return Qt::ExtraButton13;
1469     case 21: return Qt::ExtraButton14;
1470     case 22: return Qt::ExtraButton15;
1471     case 23: return Qt::ExtraButton16;
1472     case 24: return Qt::ExtraButton17;
1473     case 25: return Qt::ExtraButton18;
1474     case 26: return Qt::ExtraButton19;
1475     case 27: return Qt::ExtraButton20;
1476     case 28: return Qt::ExtraButton21;
1477     case 29: return Qt::ExtraButton22;
1478     case 30: return Qt::ExtraButton23;
1479     case 31: return Qt::ExtraButton24;
1480     default: return Qt::NoButton;
1481     }
1482 }
1483
1484 void QXcbWindow::handleButtonPressEvent(const xcb_button_press_event_t *event)
1485 {
1486     updateNetWmUserTime(event->time);
1487
1488     QPoint local(event->event_x, event->event_y);
1489     QPoint global(event->root_x, event->root_y);
1490
1491     Qt::KeyboardModifiers modifiers = connection()->keyboard()->translateModifiers(event->state);
1492
1493     if (event->detail >= 4 && event->detail <= 7) {
1494         // Logic borrowed from qapplication_x11.cpp
1495         int delta = 120 * ((event->detail == 4 || event->detail == 6) ? 1 : -1);
1496         bool hor = (((event->detail == 4 || event->detail == 5)
1497                      && (modifiers & Qt::AltModifier))
1498                     || (event->detail == 6 || event->detail == 7));
1499
1500         QWindowSystemInterface::handleWheelEvent(window(), event->time,
1501                                                  local, global, delta, hor ? Qt::Horizontal : Qt::Vertical, modifiers);
1502         return;
1503     }
1504
1505     handleMouseEvent(event->detail, event->state, event->time, local, global, modifiers);
1506 }
1507
1508 void QXcbWindow::handleButtonReleaseEvent(const xcb_button_release_event_t *event)
1509 {
1510     QPoint local(event->event_x, event->event_y);
1511     QPoint global(event->root_x, event->root_y);
1512     Qt::KeyboardModifiers modifiers = connection()->keyboard()->translateModifiers(event->state);
1513
1514     handleMouseEvent(event->detail, event->state, event->time, local, global, modifiers);
1515 }
1516
1517 void QXcbWindow::handleMotionNotifyEvent(const xcb_motion_notify_event_t *event)
1518 {
1519     QPoint local(event->event_x, event->event_y);
1520     QPoint global(event->root_x, event->root_y);
1521     Qt::KeyboardModifiers modifiers = connection()->keyboard()->translateModifiers(event->state);
1522
1523     handleMouseEvent(event->detail, event->state, event->time, local, global, modifiers);
1524 }
1525
1526 void QXcbWindow::handleMouseEvent(xcb_button_t detail, uint16_t state, xcb_timestamp_t time, const QPoint &local, const QPoint &global, Qt::KeyboardModifiers modifiers)
1527 {
1528     connection()->setTime(time);
1529
1530     Qt::MouseButtons buttons = translateMouseButtons(state);
1531     Qt::MouseButton button = translateMouseButton(detail);
1532
1533     buttons ^= button; // X event uses state *before*, Qt uses state *after*
1534
1535     QWindowSystemInterface::handleMouseEvent(window(), time, local, global, buttons, modifiers);
1536 }
1537
1538 void QXcbWindow::handleEnterNotifyEvent(const xcb_enter_notify_event_t *event)
1539 {
1540     connection()->setTime(event->time);
1541
1542     if ((event->mode != XCB_NOTIFY_MODE_NORMAL && event->mode != XCB_NOTIFY_MODE_UNGRAB)
1543         || event->detail == XCB_NOTIFY_DETAIL_VIRTUAL
1544         || event->detail == XCB_NOTIFY_DETAIL_NONLINEAR_VIRTUAL)
1545     {
1546         return;
1547     }
1548
1549     QWindowSystemInterface::handleEnterEvent(window());
1550 }
1551
1552 void QXcbWindow::handleLeaveNotifyEvent(const xcb_leave_notify_event_t *event)
1553 {
1554     connection()->setTime(event->time);
1555
1556     if ((event->mode != XCB_NOTIFY_MODE_NORMAL && event->mode != XCB_NOTIFY_MODE_UNGRAB)
1557         || event->detail == XCB_NOTIFY_DETAIL_INFERIOR)
1558     {
1559         return;
1560     }
1561
1562     QWindowSystemInterface::handleLeaveEvent(window());
1563 }
1564
1565 void QXcbWindow::handlePropertyNotifyEvent(const xcb_property_notify_event_t *event)
1566 {
1567     connection()->setTime(event->time);
1568
1569     const bool propertyDeleted = event->state == XCB_PROPERTY_DELETE;
1570     const xcb_atom_t netWmStateAtom = atom(QXcbAtom::_NET_WM_STATE);
1571     const xcb_atom_t wmStateAtom = atom(QXcbAtom::WM_STATE);
1572
1573     if (event->atom == netWmStateAtom || event->atom == wmStateAtom) {
1574         if (propertyDeleted)
1575             return;
1576
1577         Qt::WindowState newState = Qt::WindowNoState;
1578         if (event->atom == wmStateAtom) { // WM_STATE: Quick check for 'Minimize'.
1579             const xcb_get_property_cookie_t get_cookie =
1580                 xcb_get_property(xcb_connection(), 0, m_window, wmStateAtom,
1581                                  XCB_ATOM_ANY, 0, 1024);
1582
1583             xcb_get_property_reply_t *reply =
1584                 xcb_get_property_reply(xcb_connection(), get_cookie, NULL);
1585
1586             if (reply && reply->format == 32 && reply->type == wmStateAtom) {
1587                 const long *data = (const long *)xcb_get_property_value(reply);
1588                 if (reply->length != 0 && XCB_WM_STATE_ICONIC == data[0])
1589                     newState = Qt::WindowMinimized;
1590                 free(reply);
1591             }
1592         } // WM_STATE: Quick check for 'Minimize'.
1593         if (newState != Qt::WindowMinimized) { // Something else changed, get _NET_WM_STATE.
1594             const NetWmStates states = netWmStates();
1595             if ((states & NetWmStateMaximizedHorz) && (states & NetWmStateMaximizedVert))
1596                 newState = Qt::WindowMaximized;
1597             else if (states & NetWmStateFullScreen)
1598                 newState = Qt::WindowFullScreen;
1599         }
1600         // Send Window state, compress events in case other flags (modality, etc) are changed.
1601         if (m_lastWindowStateEvent != newState) {
1602             QWindowSystemInterface::handleWindowStateChanged(window(), newState);
1603             m_lastWindowStateEvent = newState;
1604         }
1605     }
1606 }
1607
1608 void QXcbWindow::handleFocusInEvent(const xcb_focus_in_event_t *)
1609 {
1610     QWindowSystemInterface::handleWindowActivated(window());
1611 }
1612
1613 static bool focusInPeeker(xcb_generic_event_t *event)
1614 {
1615     if (!event) {
1616         // FocusIn event is not in the queue, proceed with FocusOut normally.
1617         QWindowSystemInterface::handleWindowActivated(0);
1618         return true;
1619     }
1620     uint response_type = event->response_type & ~0x80;
1621     return response_type == XCB_FOCUS_IN;
1622 }
1623
1624 void QXcbWindow::handleFocusOutEvent(const xcb_focus_out_event_t *)
1625 {
1626     // Do not set the active window to 0 if there is a FocusIn coming.
1627     // There is however no equivalent for XPutBackEvent so register a
1628     // callback for QXcbConnection instead.
1629     connection()->addPeekFunc(focusInPeeker);
1630 }
1631
1632 void QXcbWindow::updateSyncRequestCounter()
1633 {
1634     if (m_screen->syncRequestSupported() && (m_syncValue.lo != 0 || m_syncValue.hi != 0)) {
1635         Q_XCB_CALL(xcb_sync_set_counter(xcb_connection(), m_syncCounter, m_syncValue));
1636         xcb_flush(xcb_connection());
1637         connection()->sync();
1638
1639         m_syncValue.lo = 0;
1640         m_syncValue.hi = 0;
1641     }
1642 }
1643
1644 bool QXcbWindow::setKeyboardGrabEnabled(bool grab)
1645 {
1646     if (!grab) {
1647         xcb_ungrab_keyboard(xcb_connection(), XCB_TIME_CURRENT_TIME);
1648         return true;
1649     }
1650     xcb_grab_keyboard_cookie_t cookie = xcb_grab_keyboard(xcb_connection(), false,
1651                                                           m_window, XCB_TIME_CURRENT_TIME,
1652                                                           XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
1653     xcb_grab_keyboard_reply_t *reply = xcb_grab_keyboard_reply(xcb_connection(), cookie, NULL);
1654     bool result = !(!reply || reply->status != XCB_GRAB_STATUS_SUCCESS);
1655     free(reply);
1656     return result;
1657 }
1658
1659 bool QXcbWindow::setMouseGrabEnabled(bool grab)
1660 {
1661     if (!grab) {
1662         xcb_ungrab_pointer(xcb_connection(), XCB_TIME_CURRENT_TIME);
1663         return true;
1664     }
1665     xcb_grab_pointer_cookie_t cookie = xcb_grab_pointer(xcb_connection(), false, m_window,
1666                                                         (XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE
1667                                                          | XCB_EVENT_MASK_BUTTON_MOTION | XCB_EVENT_MASK_ENTER_WINDOW
1668                                                          | XCB_EVENT_MASK_LEAVE_WINDOW | XCB_EVENT_MASK_POINTER_MOTION),
1669                                                         XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC,
1670                                                         XCB_WINDOW_NONE, XCB_CURSOR_NONE,
1671                                                         XCB_TIME_CURRENT_TIME);
1672     xcb_grab_pointer_reply_t *reply = xcb_grab_pointer_reply(xcb_connection(), cookie, NULL);
1673     bool result = !(!reply || reply->status != XCB_GRAB_STATUS_SUCCESS);
1674     free(reply);
1675     return result;
1676 }
1677
1678 void QXcbWindow::setCursor(xcb_cursor_t cursor)
1679 {
1680     xcb_change_window_attributes(xcb_connection(), m_window, XCB_CW_CURSOR, &cursor);
1681     xcb_flush(xcb_connection());
1682 }
1683
1684 bool QXcbWindow::startSystemResize(const QPoint &pos, Qt::Corner corner)
1685 {
1686     const xcb_atom_t moveResize = connection()->atom(QXcbAtom::_NET_WM_MOVERESIZE);
1687     if (!connection()->wmSupport()->isSupportedByWM(moveResize))
1688         return false;
1689     xcb_client_message_event_t xev;
1690     xev.response_type = XCB_CLIENT_MESSAGE;
1691     xev.type = moveResize;
1692     xev.window = xcb_window();
1693     xev.format = 32;
1694     const QPoint globalPos = window()->mapToGlobal(pos);
1695     xev.data.data32[0] = globalPos.x();
1696     xev.data.data32[1] = globalPos.y();
1697     const bool bottom = corner == Qt::BottomRightCorner || corner == Qt::BottomLeftCorner;
1698     const bool left = corner == Qt::BottomLeftCorner || corner == Qt::TopLeftCorner;
1699     if (bottom)
1700         xev.data.data32[2] = left ? 6 : 4; // bottomleft/bottomright
1701     else
1702         xev.data.data32[2] = left ? 0 : 2; // topleft/topright
1703     xev.data.data32[3] = XCB_BUTTON_INDEX_1;
1704     xev.data.data32[4] = 0;
1705     xcb_ungrab_pointer(connection()->xcb_connection(), XCB_CURRENT_TIME);
1706     xcb_send_event(connection()->xcb_connection(), false, m_screen->root(),
1707                    XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY,
1708                    (const char *)&xev);
1709     return true;
1710 }
1711
1712 #if !defined(QT_NO_SHAPE)
1713
1714 static inline xcb_rectangle_t qRectToXCBRectangle(const QRect &r)
1715 {
1716     xcb_rectangle_t result;
1717     result.x = qMax(SHRT_MIN, r.x());
1718     result.y = qMax(SHRT_MIN, r.y());
1719     result.width = qMin((int)USHRT_MAX, r.width());
1720     result.height = qMin((int)USHRT_MAX, r.height());
1721     return result;
1722 }
1723
1724 void QXcbWindow::setMask(const QRegion &region)
1725 {
1726     if (!connection()->hasXShape())
1727         return;
1728     if (region.isEmpty()) {
1729         xcb_shape_mask(connection()->xcb_connection(), XCB_SHAPE_SO_SET,
1730                        XCB_SHAPE_SK_BOUNDING, xcb_window(), 0, 0, XCB_NONE);
1731     } else {
1732         QVector<xcb_rectangle_t> rects;
1733         foreach (const QRect &r, region.rects())
1734             rects.push_back(qRectToXCBRectangle(r));
1735         xcb_shape_rectangles(connection()->xcb_connection(), XCB_SHAPE_SO_SET,
1736                              XCB_SHAPE_SK_BOUNDING, XCB_CLIP_ORDERING_UNSORTED,
1737                              xcb_window(), 0, 0, rects.size(), &rects[0]);
1738     }
1739 }
1740
1741 #endif // !QT_NO_SHAPE
1742
1743 QT_END_NAMESPACE