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