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