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