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