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